prompt
stringlengths 19
879k
| completion
stringlengths 3
53.8k
| api
stringlengths 8
59
|
---|---|---|
import warnings
import math as m
import numpy as nu
from scipy import integrate
from galpy.potential.Potential import _evaluateRforces, _evaluatezforces,\
evaluatePotentials, evaluateDensities, _check_c
from galpy.util import galpyWarning
import galpy.util.bovy_plot as plot
import galpy.util.bovy_symplecticode as symplecticode
from .FullOrbit import _integrateFullOrbit
from .integrateFullOrbit import _ext_loaded as ext_loaded
from galpy.util.bovy_conversion import physical_conversion
from galpy.util.leung_dop853 import dop853
from .OrbitTop import OrbitTop
class RZOrbit(OrbitTop):
"""Class that holds and integrates orbits in axisymetric potentials
in the (R,z) plane"""
def __init__(self,vxvv=[1.,0.,0.9,0.,0.1],vo=220.,ro=8.0,zo=0.025,
solarmotion=nu.array([-10.1,4.0,6.7])):
"""
NAME:
__init__
PURPOSE:
intialize an RZ-orbit
INPUT:
vxvv - initial condition [R,vR,vT,z,vz]
vo - circular velocity at ro (km/s)
ro - distance from vantage point to GC (kpc)
zo - offset toward the NGP of the Sun wrt the plane (kpc)
solarmotion - value in [-U,V,W] (km/s)
OUTPUT:
(none)
HISTORY:
2010-07-10 - Written - Bovy (NYU)
2014-06-11 - Added conversion kwargs to physical coordinates - Bovy (IAS)
"""
OrbitTop.__init__(self,vxvv=vxvv,
ro=ro,zo=zo,vo=vo,solarmotion=solarmotion)
return None
def integrate(self,t,pot,method='symplec4_c',dt=None):
"""
NAME:
integrate
PURPOSE:
integrate the orbit
INPUT:
t - list of times at which to output (0 has to be in this!)
pot - potential instance or list of instances
method= 'odeint' for scipy's odeint
'leapfrog' for a simple leapfrog implementation
'leapfrog_c' for a simple leapfrog implementation in C
'rk4_c' for a 4th-order Runge-Kutta integrator in C
'rk6_c' for a 6-th order Runge-Kutta integrator in C
'dopr54_c' for a Dormand-Prince integrator in C (generally the fastest)
dt= (None) if set, force the integrator to use this basic stepsize; must be an integer divisor of output stepsize
OUTPUT:
(none) (get the actual orbit using getOrbit()
HISTORY:
2010-07-10
"""
if hasattr(self,'_orbInterp'): delattr(self,'_orbInterp')
if hasattr(self,'rs'): delattr(self,'rs')
self.t= nu.array(t)
self._pot= pot
self.orbit= _integrateRZOrbit(self.vxvv,pot,t,method,dt)
@physical_conversion('energy')
def E(self,*args,**kwargs):
"""
NAME:
E
PURPOSE:
calculate the energy
INPUT:
t - (optional) time at which to get the radius
pot= RZPotential instance or list thereof
OUTPUT:
energy
HISTORY:
2010-09-15 - Written - Bovy (NYU)
"""
if not 'pot' in kwargs or kwargs['pot'] is None:
try:
pot= self._pot
except AttributeError:
raise AttributeError("Integrate orbit or specify pot=")
if 'pot' in kwargs and kwargs['pot'] is None:
kwargs.pop('pot')
else:
pot= kwargs.pop('pot')
if len(args) > 0:
t= args[0]
else:
t= 0.
#Get orbit
thiso= self(*args,**kwargs)
onet= (len(thiso.shape) == 1)
if onet:
return evaluatePotentials(pot,thiso[0],thiso[3],
t=t,use_physical=False)\
+thiso[1]**2./2.\
+thiso[2]**2./2.\
+thiso[4]**2./2.
else:
return nu.array([evaluatePotentials(pot,thiso[0,ii],thiso[3,ii],
t=t[ii],use_physical=False)\
+thiso[1,ii]**2./2.\
+thiso[2,ii]**2./2.\
+thiso[4,ii]**2./2. for ii in range(len(t))])
@physical_conversion('energy')
def ER(self,*args,**kwargs):
"""
NAME:
ER
PURPOSE:
calculate the radial energy
INPUT:
t - (optional) time at which to get the energy
pot= potential instance or list of such instances
OUTPUT:
radial energy
HISTORY:
2013-11-30 - Written - Bovy (IAS)
"""
if not 'pot' in kwargs or kwargs['pot'] is None:
try:
pot= self._pot
except AttributeError:
raise AttributeError("Integrate orbit or specify pot=")
if 'pot' in kwargs and kwargs['pot'] is None:
kwargs.pop('pot')
else:
pot= kwargs.pop('pot')
if len(args) > 0:
t= args[0]
else:
t= 0.
#Get orbit
thiso= self(*args,**kwargs)
onet= (len(thiso.shape) == 1)
if onet:
return evaluatePotentials(pot,thiso[0],0.,
t=t,use_physical=False)\
+thiso[1]**2./2.\
+thiso[2]**2./2.
else:
return nu.array([evaluatePotentials(pot,thiso[0,ii],0.,
t=t[ii],use_physical=False)\
+thiso[1,ii]**2./2.\
+thiso[2,ii]**2./2. for ii in range(len(t))])
@physical_conversion('energy')
def Ez(self,*args,**kwargs):
"""
NAME:
Ez
PURPOSE:
calculate the vertical energy
INPUT:
t - (optional) time at which to get the energy
pot= potential instance or list of such instances
OUTPUT:
vertical energy
HISTORY:
2013-11-30 - Written - Bovy (IAS)
"""
if not 'pot' in kwargs or kwargs['pot'] is None:
try:
pot= self._pot
except AttributeError:
raise AttributeError("Integrate orbit or specify pot=")
if 'pot' in kwargs and kwargs['pot'] is None:
kwargs.pop('pot')
else:
pot= kwargs.pop('pot')
if len(args) > 0:
t= args[0]
else:
t= 0.
#Get orbit
thiso= self(*args,**kwargs)
onet= (len(thiso.shape) == 1)
if onet:
return evaluatePotentials(pot,thiso[0],thiso[3],
t=t,use_physical=False)\
-evaluatePotentials(pot,thiso[0],0.,
t=t,
use_physical=False)\
+thiso[4]**2./2.
else:
return nu.array([evaluatePotentials(pot,thiso[0,ii],thiso[3,ii],
t=t[ii],use_physical=False)\
-evaluatePotentials(pot,thiso[0,ii],0.,
t=t[ii],use_physical=False)\
+thiso[4,ii]**2./2. for ii in range(len(t))])
@physical_conversion('energy')
def Jacobi(self,*args,**kwargs):
"""
NAME:
Jacobi
PURPOSE:
calculate the Jacobi integral of the motion
INPUT:
t - (optional) time at which to get the radius
OmegaP= pattern speed of rotating frame (scalar)
pot= potential instance or list of such instances
OUTPUT:
Jacobi integral
HISTORY:
2011-04-18 - Written - Bovy (NYU)
"""
if not 'OmegaP' in kwargs or kwargs['OmegaP'] is None:
OmegaP= 1.
if not 'pot' in kwargs or kwargs['pot'] is None:
try:
pot= self._pot
except AttributeError:
raise AttributeError("Integrate orbit or specify pot=")
else:
pot= kwargs['pot']
if isinstance(pot,list):
for p in pot:
if hasattr(p,'OmegaP'):
OmegaP= p.OmegaP()
break
else:
if hasattr(pot,'OmegaP'):
OmegaP= pot.OmegaP()
kwargs.pop('OmegaP',None)
else:
OmegaP= kwargs.pop('OmegaP')
#Make sure you are not using physical coordinates
old_physical= kwargs.get('use_physical',None)
kwargs['use_physical']= False
thiso= self(*args,**kwargs)
out= self.E(*args,**kwargs)-OmegaP*thiso[0]*thiso[2]
if not old_physical is None:
kwargs['use_physical']= old_physical
else:
kwargs.pop('use_physical')
return out
def e(self,analytic=False,pot=None,**kwargs):
"""
NAME:
e
PURPOSE:
calculate the eccentricity
INPUT:
analytic - compute this analytically
pot - potential to use for analytical calculation
OUTPUT:
eccentricity
HISTORY:
2010-09-15 - Written - Bovy (NYU)
"""
if analytic:
self._setupaA(pot=pot,**kwargs)
return float(self._aA.EccZmaxRperiRap(self)[0])
if not hasattr(self,'orbit'):
raise AttributeError("Integrate the orbit first or use analytic=True for approximate eccentricity")
if not hasattr(self,'rs'):
self.rs= nu.sqrt(self.orbit[:,0]**2.+self.orbit[:,3]**2.)
return (nu.amax(self.rs)-nu.amin(self.rs))/(nu.amax(self.rs)+nu.amin(self.rs))
@physical_conversion('position')
def rap(self,analytic=False,pot=None,**kwargs):
"""
NAME:
rap
PURPOSE:
return the apocenter radius
INPUT:
analytic - compute this analytically
pot - potential to use for analytical calculation
OUTPUT:
R_ap
HISTORY:
2010-09-20 - Written - Bovy (NYU)
"""
if analytic:
self._setupaA(pot=pot,**kwargs)
return float(self._aA.EccZmaxRperiRap(self)[3])
if not hasattr(self,'orbit'):
raise AttributeError("Integrate the orbit first or use analytic=True for approximate rap")
if not hasattr(self,'rs'):
self.rs= nu.sqrt(self.orbit[:,0]**2.+self.orbit[:,3]**2.)
return nu.amax(self.rs)
@physical_conversion('position')
def rperi(self,analytic=False,pot=None,**kwargs):
"""
NAME:
rperi
PURPOSE:
return the pericenter radius
INPUT:
analytic - compute this analytically
pot - potential to use for analytical calculation
OUTPUT:
R_peri
HISTORY:
2010-09-20 - Written - Bovy (NYU)
"""
if analytic:
self._setupaA(pot=pot,**kwargs)
return float(self._aA.EccZmaxRperiRap(self)[2])
if not hasattr(self,'orbit'):
raise AttributeError("Integrate the orbit first or use analytic=True for approximate rperi")
if not hasattr(self,'rs'):
self.rs= | nu.sqrt(self.orbit[:,0]**2.+self.orbit[:,3]**2.) | numpy.sqrt |
# standard libraries
import collections
import copy
import functools
import math
import numbers
import operator
import typing
# third party libraries
import numpy
import numpy.fft
import scipy
import scipy.fftpack
import scipy.ndimage
import scipy.ndimage.filters
import scipy.ndimage.fourier
import scipy.signal
# local libraries
from nion.data import Calibration
from nion.data import DataAndMetadata
from nion.data import Image
from nion.data import ImageRegistration
from nion.data import TemplateMatching
from nion.utils import Geometry
DataRangeType = typing.Tuple[float, float]
NormIntervalType = typing.Tuple[float, float]
NormChannelType = float
NormRectangleType = typing.Tuple[typing.Tuple[float, float], typing.Tuple[float, float]]
NormPointType = typing.Tuple[float, float]
NormSizeType = typing.Tuple[float, float]
NormVectorType = typing.Tuple[NormPointType, NormPointType]
def column(data_and_metadata: DataAndMetadata.DataAndMetadata, start: int, stop: int) -> DataAndMetadata.DataAndMetadata:
data_and_metadata = DataAndMetadata.promote_ndarray(data_and_metadata)
def calculate_data():
start_0 = start if start is not None else 0
stop_0 = stop if stop is not None else data_shape(data_and_metadata)[0]
start_1 = start if start is not None else 0
stop_1 = stop if stop is not None else data_shape(data_and_metadata)[1]
return numpy.meshgrid(numpy.linspace(start_1, stop_1, data_shape(data_and_metadata)[1]), numpy.linspace(start_0, stop_0, data_shape(data_and_metadata)[0]), sparse=True)[0]
return DataAndMetadata.new_data_and_metadata(calculate_data(), intensity_calibration=data_and_metadata.intensity_calibration, dimensional_calibrations=data_and_metadata.dimensional_calibrations)
def row(data_and_metadata: DataAndMetadata.DataAndMetadata, start: int, stop: int) -> DataAndMetadata.DataAndMetadata:
data_and_metadata = DataAndMetadata.promote_ndarray(data_and_metadata)
def calculate_data():
start_0 = start if start is not None else 0
stop_0 = stop if stop is not None else data_shape(data_and_metadata)[0]
start_1 = start if start is not None else 0
stop_1 = stop if stop is not None else data_shape(data_and_metadata)[1]
return numpy.meshgrid(numpy.linspace(start_1, stop_1, data_shape(data_and_metadata)[1]), numpy.linspace(start_0, stop_0, data_shape(data_and_metadata)[0]), sparse=True)[1]
return DataAndMetadata.new_data_and_metadata(calculate_data(), intensity_calibration=data_and_metadata.intensity_calibration, dimensional_calibrations=data_and_metadata.dimensional_calibrations)
def radius(data_and_metadata: DataAndMetadata.DataAndMetadata, normalize: bool=True) -> DataAndMetadata.DataAndMetadata:
data_and_metadata = DataAndMetadata.promote_ndarray(data_and_metadata)
def calculate_data():
start_0 = -1 if normalize else -data_shape(data_and_metadata)[0] * 0.5
stop_0 = -start_0
start_1 = -1 if normalize else -data_shape(data_and_metadata)[1] * 0.5
stop_1 = -start_1
icol, irow = numpy.meshgrid(numpy.linspace(start_1, stop_1, data_shape(data_and_metadata)[1]), numpy.linspace(start_0, stop_0, data_shape(data_and_metadata)[0]), sparse=True)
return numpy.sqrt(icol * icol + irow * irow)
return DataAndMetadata.new_data_and_metadata(calculate_data(), intensity_calibration=data_and_metadata.intensity_calibration, dimensional_calibrations=data_and_metadata.dimensional_calibrations)
def full(shape: DataAndMetadata.ShapeType, fill_value, dtype: numpy.dtype = None) -> DataAndMetadata.DataAndMetadata:
"""Generate a constant valued image with the given shape.
full(4, shape(4, 5))
full(0, data_shape(b))
"""
dtype = dtype if dtype else numpy.dtype(numpy.float64)
return DataAndMetadata.new_data_and_metadata(numpy.full(shape, DataAndMetadata.extract_data(fill_value), dtype))
def arange(start: int, stop: int=None, step: int=None) -> DataAndMetadata.DataAndMetadata:
if stop is None:
start = 0
stop = start
if step is None:
step = 1
return DataAndMetadata.new_data_and_metadata(numpy.linspace(int(start), int(stop), int(step)))
def linspace(start: float, stop: float, num: int, endpoint: bool=True) -> DataAndMetadata.DataAndMetadata:
return DataAndMetadata.new_data_and_metadata(numpy.linspace(start, stop, num, endpoint))
def logspace(start: float, stop: float, num: int, endpoint: bool=True, base: float=10.0) -> DataAndMetadata.DataAndMetadata:
return DataAndMetadata.new_data_and_metadata(numpy.logspace(start, stop, num, endpoint, base))
def apply_dist(data_and_metadata: DataAndMetadata.DataAndMetadata, mean: float, stddev: float, dist, fn) -> DataAndMetadata.DataAndMetadata:
data_and_metadata = DataAndMetadata.promote_ndarray(data_and_metadata)
return DataAndMetadata.new_data_and_metadata(getattr(dist(loc=mean, scale=stddev), fn)(data_and_metadata.data))
def take_item(data, key):
return data[key]
def data_shape(data_and_metadata: DataAndMetadata.DataAndMetadata) -> DataAndMetadata.ShapeType:
return data_and_metadata.data_shape
def astype(data: numpy.ndarray, dtype: numpy.dtype) -> numpy.ndarray:
return data.astype(dtype)
dtype_map: typing.Mapping[typing.Any, str] = {int: "int", float: "float", complex: "complex", numpy.int16: "int16",
numpy.int32: "int32", numpy.int64: "int64", numpy.uint8: "uint8",
numpy.uint16: "uint16", numpy.uint32: "uint32", numpy.uint64: "uint64",
numpy.float32: "float32", numpy.float64: "float64",
numpy.complex64: "complex64", numpy.complex128: "complex128"}
dtype_inverse_map = {dtype_map[k]: k for k in dtype_map}
def str_to_dtype(str: str) -> numpy.dtype:
return dtype_inverse_map.get(str, float)
def dtype_to_str(dtype: numpy.dtype) -> str:
return dtype_map.get(dtype, "float")
def function_fft(data_and_metadata: DataAndMetadata.DataAndMetadata) -> typing.Optional[DataAndMetadata.DataAndMetadata]:
data_and_metadata = DataAndMetadata.promote_ndarray(data_and_metadata)
data_shape = data_and_metadata.data_shape
data_dtype = data_and_metadata.data_dtype
def calculate_data():
data = data_and_metadata.data
if data is None or not Image.is_data_valid(data):
return None
# scaling: numpy.sqrt(numpy.mean(numpy.absolute(data_copy)**2)) == numpy.sqrt(numpy.mean(numpy.absolute(data_copy_fft)**2))
# see https://gist.github.com/endolith/1257010
if Image.is_data_1d(data):
scaling = 1.0 / numpy.sqrt(data_shape[0])
return scipy.fftpack.fftshift(numpy.multiply(scipy.fftpack.fft(data), scaling))
elif Image.is_data_2d(data):
if Image.is_data_rgb_type(data):
if Image.is_data_rgb(data):
data_copy = numpy.sum(data[..., :] * (0.2126, 0.7152, 0.0722), 2)
else:
data_copy = numpy.sum(data[..., :] * (0.2126, 0.7152, 0.0722, 0.0), 2)
else:
data_copy = data.copy() # let other threads use data while we're processing
scaling = 1.0 / numpy.sqrt(data_shape[1] * data_shape[0])
# note: the numpy.fft.fft2 is faster than scipy.fftpack.fft2, probably either because
# our conda distribution compiles numpy for multiprocessing, the numpy version releases
# the GIL, or both.
return scipy.fftpack.fftshift(numpy.multiply(numpy.fft.fft2(data_copy), scaling))
else:
raise NotImplementedError()
src_dimensional_calibrations = data_and_metadata.dimensional_calibrations
if not Image.is_shape_and_dtype_valid(data_shape, data_dtype) or src_dimensional_calibrations is None:
return None
assert len(src_dimensional_calibrations) == len(
Image.dimensional_shape_from_shape_and_dtype(data_shape, data_dtype))
dimensional_calibrations = [Calibration.Calibration((-0.5 - 0.5 * data_shape_n) / (dimensional_calibration.scale * data_shape_n), 1.0 / (dimensional_calibration.scale * data_shape_n),
"1/" + dimensional_calibration.units) for
dimensional_calibration, data_shape_n in zip(src_dimensional_calibrations, data_shape)]
return DataAndMetadata.new_data_and_metadata(calculate_data(), dimensional_calibrations=dimensional_calibrations)
def function_ifft(data_and_metadata: DataAndMetadata.DataAndMetadata) -> typing.Optional[DataAndMetadata.DataAndMetadata]:
data_and_metadata = DataAndMetadata.promote_ndarray(data_and_metadata)
data_shape = data_and_metadata.data_shape
data_dtype = data_and_metadata.data_dtype
def calculate_data():
data = data_and_metadata.data
if data is None or not Image.is_data_valid(data):
return None
# scaling: numpy.sqrt(numpy.mean(numpy.absolute(data_copy)**2)) == numpy.sqrt(numpy.mean(numpy.absolute(data_copy_fft)**2))
# see https://gist.github.com/endolith/1257010
if Image.is_data_1d(data):
scaling = numpy.sqrt(data_shape[0])
return scipy.fftpack.ifft(scipy.fftpack.ifftshift(data) * scaling)
elif Image.is_data_2d(data):
data_copy = data.copy() # let other threads use data while we're processing
scaling = numpy.sqrt(data_shape[1] * data_shape[0])
return scipy.fftpack.ifft2(scipy.fftpack.ifftshift(data_copy) * scaling)
else:
raise NotImplementedError()
src_dimensional_calibrations = data_and_metadata.dimensional_calibrations
if not Image.is_shape_and_dtype_valid(data_shape, data_dtype) or src_dimensional_calibrations is None:
return None
assert len(src_dimensional_calibrations) == len(
Image.dimensional_shape_from_shape_and_dtype(data_shape, data_dtype))
def remove_one_slash(s):
if s.startswith("1/"):
return s[2:]
else:
return "1/" + s
dimensional_calibrations = [Calibration.Calibration(0.0, 1.0 / (dimensional_calibration.scale * data_shape_n),
remove_one_slash(dimensional_calibration.units)) for
dimensional_calibration, data_shape_n in zip(src_dimensional_calibrations, data_shape)]
return DataAndMetadata.new_data_and_metadata(calculate_data(), dimensional_calibrations=dimensional_calibrations)
def function_autocorrelate(data_and_metadata: DataAndMetadata.DataAndMetadata) -> typing.Optional[DataAndMetadata.DataAndMetadata]:
data_and_metadata = DataAndMetadata.promote_ndarray(data_and_metadata)
def calculate_data():
data = data_and_metadata.data
if data is None or not Image.is_data_valid(data):
return None
if Image.is_data_2d(data):
data_copy = data.copy() # let other threads use data while we're processing
data_std = data_copy.std(dtype=numpy.float64)
if data_std != 0.0:
data_norm = (data_copy - data_copy.mean(dtype=numpy.float64)) / data_std
else:
data_norm = data_copy
scaling = 1.0 / (data_norm.shape[0] * data_norm.shape[1])
data_norm = numpy.fft.rfft2(data_norm)
return numpy.fft.fftshift(numpy.fft.irfft2(data_norm * numpy.conj(data_norm))) * scaling
# this gives different results. why? because for some reason scipy pads out to 1023 and does calculation.
# see https://github.com/scipy/scipy/blob/master/scipy/signal/signaltools.py
# return scipy.signal.fftconvolve(data_copy, numpy.conj(data_copy), mode='same')
return None
if data_and_metadata is None:
return None
return DataAndMetadata.new_data_and_metadata(calculate_data(), dimensional_calibrations=data_and_metadata.dimensional_calibrations)
def function_crosscorrelate(*args) -> typing.Optional[DataAndMetadata.DataAndMetadata]:
if len(args) != 2:
return None
data_and_metadata1, data_and_metadata2 = args[0], args[1]
data_and_metadata1 = DataAndMetadata.promote_ndarray(data_and_metadata1)
data_and_metadata2 = DataAndMetadata.promote_ndarray(data_and_metadata2)
shape = DataAndMetadata.determine_shape(data_and_metadata1, data_and_metadata2)
data_and_metadata1 = DataAndMetadata.promote_constant(data_and_metadata1, shape)
data_and_metadata2 = DataAndMetadata.promote_constant(data_and_metadata2, shape)
def calculate_data():
data1 = data_and_metadata1.data
data2 = data_and_metadata2.data
if data1 is None or data2 is None:
return None
if Image.is_data_2d(data1) and Image.is_data_2d(data2):
data_std1 = data1.std(dtype=numpy.float64)
if data_std1 != 0.0:
norm1 = (data1 - data1.mean(dtype=numpy.float64)) / data_std1
else:
norm1 = data1
data_std2 = data2.std(dtype=numpy.float64)
if data_std2 != 0.0:
norm2 = (data2 - data2.mean(dtype=numpy.float64)) / data_std2
else:
norm2 = data2
scaling = 1.0 / (norm1.shape[0] * norm1.shape[1])
return numpy.fft.fftshift(numpy.fft.irfft2(numpy.fft.rfft2(norm1) * numpy.conj(numpy.fft.rfft2(norm2)))) * scaling
# this gives different results. why? because for some reason scipy pads out to 1023 and does calculation.
# see https://github.com/scipy/scipy/blob/master/scipy/signal/signaltools.py
# return scipy.signal.fftconvolve(data1.copy(), numpy.conj(data2.copy()), mode='same')
return None
if data_and_metadata1 is None or data_and_metadata2 is None:
return None
return DataAndMetadata.new_data_and_metadata(calculate_data(), dimensional_calibrations=data_and_metadata1.dimensional_calibrations)
def function_register(xdata1: DataAndMetadata.DataAndMetadata, xdata2: DataAndMetadata.DataAndMetadata, upsample_factor: int, subtract_means: bool, bounds: typing.Union[NormRectangleType, NormIntervalType]=None) -> typing.Tuple[float, ...]:
# FUTURE: use scikit.image register_translation
xdata1 = DataAndMetadata.promote_ndarray(xdata1)
xdata2 = DataAndMetadata.promote_ndarray(xdata2)
# data shape and descriptors should match
assert xdata1.data_shape == xdata2.data_shape
assert xdata1.data_descriptor == xdata2.data_descriptor
# get the raw data
data1 = xdata1.data
data2 = xdata2.data
if data1 is None:
return tuple()
if data2 is None:
return tuple()
# take the slice if there is one
if bounds is not None:
d_rank = xdata1.datum_dimension_count
shape = data1.shape
bounds_pixels = numpy.rint(numpy.array(bounds) * numpy.array(shape)).astype(numpy.int_)
bounds_slice: typing.Optional[typing.Union[slice, typing.Tuple[slice, ...]]]
if d_rank == 1:
bounds_slice = slice(max(0, bounds_pixels[0]), min(shape[0], bounds_pixels[1]))
elif d_rank == 2:
bounds_slice = (slice(max(0, bounds_pixels[0][0]), min(shape[0], bounds_pixels[0][0]+bounds_pixels[1][0])),
slice(max(0, bounds_pixels[0][1]), min(shape[1], bounds_pixels[0][1]+bounds_pixels[1][1])))
else:
bounds_slice = None
data1 = data1[bounds_slice]
data2 = data2[bounds_slice]
# subtract the means if desired
if subtract_means:
data1 = data1 - numpy.average(data1)
data2 = data2 - numpy.average(data2)
assert data1 is not None
assert data2 is not None
# adjust the dimensions so 1D data is always nx1
add_before = 0
while len(data1.shape) > 1 and data1.shape[0] == 1:
data1 = numpy.squeeze(data1, axis=0)
data2 = numpy.squeeze(data2, axis=0)
add_before += 1
add_after = 0
while len(data1.shape) > 1 and data1.shape[-1] == 1:
data1 = numpy.squeeze(data1, axis=-1)
data2 = numpy.squeeze(data2, axis=-1)
add_after += 1
do_squeeze = False
if len(data1.shape) == 1:
data1 = data1[..., numpy.newaxis]
data2 = data2[..., numpy.newaxis]
do_squeeze = True
# carry out the registration
result = ImageRegistration.dftregistration(data1, data2, upsample_factor)#[0:d_rank]
# adjust results to match input data
if do_squeeze:
result = result[0:-1]
for _ in range(add_before):
result = (numpy.zeros_like(result[0]), ) + result
for _ in range(add_after):
result = result + (numpy.zeros_like(result[0]), )
return result
def function_match_template(image_xdata: DataAndMetadata.DataAndMetadata, template_xdata: DataAndMetadata.DataAndMetadata) -> typing.Optional[DataAndMetadata.DataAndMetadata]:
"""
Calculates the normalized cross-correlation for a template with an image. The returned xdata will have the same
shape as `image_xdata`.
Inputs can be 1D or 2D and the template must be smaller than or the same size as the image.
"""
image_xdata = DataAndMetadata.promote_ndarray(image_xdata)
template_xdata = DataAndMetadata.promote_ndarray(template_xdata)
assert image_xdata.is_data_2d or image_xdata.is_data_1d
assert template_xdata.is_data_2d or template_xdata.is_data_1d
assert image_xdata.data_descriptor == template_xdata.data_descriptor
# The template needs to be the smaller of the two if they have different shape
assert numpy.less_equal(template_xdata.data_shape, image_xdata.data_shape).all()
image = image_xdata.data
template = template_xdata.data
assert image is not None
assert template is not None
squeeze = False
if image_xdata.is_data_1d:
image = image[..., numpy.newaxis]
template = template[..., numpy.newaxis]
assert image is not None
assert template is not None
squeeze = True
ccorr = TemplateMatching.match_template(image, template)
if squeeze:
ccorr = numpy.squeeze(ccorr)
return DataAndMetadata.new_data_and_metadata(ccorr, dimensional_calibrations=image_xdata.dimensional_calibrations)
def function_register_template(image_xdata: DataAndMetadata.DataAndMetadata, template_xdata: DataAndMetadata.DataAndMetadata) -> typing.Tuple[float, typing.Tuple[float, ...]]:
"""
Calculates and returns the position of a template on an image. The returned values are the intensity if the
normalized cross-correlation peak (between -1 and 1) and the sub-pixel position of the template on the image.
The sub-pixel position is calculated by fitting a parabola to the tip of the cross-correlation peak.
Inputs can be 1D or 2D and the template must be smaller than or the same size as the image.
"""
image_xdata = DataAndMetadata.promote_ndarray(image_xdata)
template_xdata = DataAndMetadata.promote_ndarray(template_xdata)
ccorr_xdata = function_match_template(image_xdata, template_xdata)
if ccorr_xdata:
error, ccoeff, max_pos = TemplateMatching.find_ccorr_max(ccorr_xdata.data)
if not error:
return ccoeff, tuple(max_pos[i] - image_xdata.data_shape[i] * 0.5 for i in range(len(image_xdata.data_shape)))
return 0.0, (0.0, ) * len(image_xdata.data_shape)
def function_shift(src: DataAndMetadata.DataAndMetadata, shift: typing.Tuple[float, ...], *, order: int = 1) -> typing.Optional[DataAndMetadata.DataAndMetadata]:
src = DataAndMetadata.promote_ndarray(src)
if src:
src_data = src._data_ex
shifted = scipy.ndimage.shift(src_data, shift, order=order, cval=numpy.mean(src_data))
return DataAndMetadata.new_data_and_metadata(numpy.squeeze(shifted))
return None
def function_fourier_shift(src: DataAndMetadata.DataAndMetadata, shift: typing.Tuple[float, ...]) -> typing.Optional[DataAndMetadata.DataAndMetadata]:
src = DataAndMetadata.promote_ndarray(src)
src_data = numpy.fft.fftn(src.data)
do_squeeze = False
if len(src_data.shape) == 1:
src_data = src_data[..., numpy.newaxis]
shift = tuple(shift) + (1,)
do_squeeze = True
# NOTE: fourier_shift assumes non-fft-shifted data.
shifted = numpy.fft.ifftn(scipy.ndimage.fourier_shift(src_data, shift)).real
shifted = numpy.squeeze(shifted) if do_squeeze else shifted
return DataAndMetadata.new_data_and_metadata(shifted)
def function_align(src: DataAndMetadata.DataAndMetadata, target: DataAndMetadata.DataAndMetadata, upsample_factor: int, bounds: typing.Union[NormRectangleType, NormIntervalType] = None) -> typing.Optional[DataAndMetadata.DataAndMetadata]:
"""Aligns target to src and returns align target, using Fourier space."""
src = DataAndMetadata.promote_ndarray(src)
target = DataAndMetadata.promote_ndarray(target)
return function_shift(target, function_register(src, target, upsample_factor, True, bounds=bounds))
def function_fourier_align(src: DataAndMetadata.DataAndMetadata, target: DataAndMetadata.DataAndMetadata, upsample_factor: int, bounds: typing.Union[NormRectangleType, NormIntervalType] = None) -> typing.Optional[DataAndMetadata.DataAndMetadata]:
"""Aligns target to src and returns align target, using Fourier space."""
src = DataAndMetadata.promote_ndarray(src)
target = DataAndMetadata.promote_ndarray(target)
return function_fourier_shift(target, function_register(src, target, upsample_factor, True, bounds=bounds))
def function_sequence_register_translation(src: DataAndMetadata.DataAndMetadata, upsample_factor: int, subtract_means: bool, bounds: typing.Union[NormRectangleType, NormIntervalType] = None) -> typing.Optional[DataAndMetadata.DataAndMetadata]:
# measures shift relative to last position in sequence
# only works on sequences
src = DataAndMetadata.promote_ndarray(src)
assert src.is_sequence
d_rank = src.datum_dimension_count
if len(src.data_shape) <= d_rank:
return None
if d_rank < 1 or d_rank > 2:
return None
src_shape = tuple(src.data_shape)
s_shape = src_shape[0:-d_rank]
c = int(numpy.product(s_shape))
result = numpy.empty(s_shape + (d_rank, ))
previous_data = None
src_data = src._data_ex
for i in range(c):
ii = numpy.unravel_index(i, s_shape) + (Ellipsis, )
if previous_data is None:
previous_data = src_data[ii]
result[0, ...] = 0
else:
current_data = src_data[ii]
result[ii] = function_register(previous_data, current_data, upsample_factor, subtract_means, bounds=bounds)
previous_data = current_data
intensity_calibration = src.dimensional_calibrations[1] # not the sequence dimension
return DataAndMetadata.new_data_and_metadata(result, intensity_calibration=intensity_calibration, data_descriptor=DataAndMetadata.DataDescriptor(True, 0, 1))
def function_sequence_measure_relative_translation(src: DataAndMetadata.DataAndMetadata, ref: DataAndMetadata.DataAndMetadata, upsample_factor: int, subtract_means: bool, bounds: typing.Union[NormRectangleType, NormIntervalType] = None) -> typing.Optional[DataAndMetadata.DataAndMetadata]:
# measures shift at each point in sequence/collection relative to reference
src = DataAndMetadata.promote_ndarray(src)
d_rank = src.datum_dimension_count
if len(src.data_shape) <= d_rank:
return None
if d_rank < 1 or d_rank > 2:
return None
src_shape = tuple(src.data_shape)
s_shape = src_shape[0:-d_rank]
c = int(numpy.product(s_shape))
result = numpy.empty(s_shape + (d_rank, ))
src_data = src._data_ex
for i in range(c):
ii = numpy.unravel_index(i, s_shape)
current_data = src_data[ii]
result[ii] = function_register(ref, current_data, upsample_factor, subtract_means, bounds=bounds)
intensity_calibration = src.dimensional_calibrations[1] # not the sequence dimension
return DataAndMetadata.new_data_and_metadata(result, intensity_calibration=intensity_calibration, data_descriptor=DataAndMetadata.DataDescriptor(src.is_sequence, src.collection_dimension_count, 1))
def function_squeeze_measurement(src: DataAndMetadata.DataAndMetadata) -> typing.Optional[DataAndMetadata.DataAndMetadata]:
# squeezes a measurement of a sequence or collection so that it can be sensibly displayed
src = DataAndMetadata.promote_ndarray(src)
data = src._data_ex
descriptor = src.data_descriptor
calibrations = list(src.dimensional_calibrations)
if descriptor.is_sequence and data.shape[0] == 1:
data = numpy.squeeze(data, axis=0)
descriptor = DataAndMetadata.DataDescriptor(False, descriptor.collection_dimension_count, descriptor.datum_dimension_count)
calibrations.pop(0)
for index in reversed(descriptor.collection_dimension_indexes):
if data.shape[index] == 1:
data = numpy.squeeze(data, axis=index)
descriptor = DataAndMetadata.DataDescriptor(descriptor.is_sequence, descriptor.collection_dimension_count - 1, descriptor.datum_dimension_count)
calibrations.pop(index)
for index in reversed(descriptor.datum_dimension_indexes):
if data.shape[index] == 1:
if descriptor.datum_dimension_count > 1:
data = numpy.squeeze(data, axis=index)
descriptor = DataAndMetadata.DataDescriptor(descriptor.is_sequence, descriptor.collection_dimension_count, descriptor.datum_dimension_count - 1)
calibrations.pop(index)
elif descriptor.collection_dimension_count > 0:
data = numpy.squeeze(data, axis=index)
descriptor = DataAndMetadata.DataDescriptor(descriptor.is_sequence, 0, descriptor.collection_dimension_count)
calibrations.pop(index)
elif descriptor.is_sequence:
data = numpy.squeeze(data, axis=index)
descriptor = DataAndMetadata.DataDescriptor(False, 0, 1)
calibrations.pop(index)
intensity_calibration = src.intensity_calibration
intensity_calibration.offset = 0.0
return DataAndMetadata.new_data_and_metadata(data, intensity_calibration=intensity_calibration, dimensional_calibrations=calibrations, data_descriptor=descriptor)
def function_sequence_align(src: DataAndMetadata.DataAndMetadata, upsample_factor: int, bounds: typing.Union[NormRectangleType, NormIntervalType] = None) -> typing.Optional[DataAndMetadata.DataAndMetadata]:
src = DataAndMetadata.promote_ndarray(src)
d_rank = src.datum_dimension_count
if len(src.data_shape) <= d_rank:
return None
if d_rank < 1 or d_rank > 2:
return None
src_shape = list(src.data_shape)
s_shape = src_shape[0:-d_rank]
c = int(numpy.product(s_shape))
ref = src[numpy.unravel_index(0, s_shape) + (Ellipsis, )]
translations = function_sequence_measure_relative_translation(src, ref, upsample_factor, True, bounds=bounds)
if not translations:
return None
result_data = numpy.copy(src.data)
for i in range(1, c):
ii = numpy.unravel_index(i, s_shape) + (Ellipsis, )
current_xdata = DataAndMetadata.new_data_and_metadata(numpy.copy(result_data[ii]))
translation = translations._data_ex[numpy.unravel_index(i, s_shape)]
shift_xdata = function_shift(current_xdata, tuple(translation))
if shift_xdata:
result_data[ii] = shift_xdata.data
return DataAndMetadata.new_data_and_metadata(result_data, intensity_calibration=src.intensity_calibration, dimensional_calibrations=src.dimensional_calibrations, data_descriptor=src.data_descriptor)
def function_sequence_fourier_align(src: DataAndMetadata.DataAndMetadata, upsample_factor: int, bounds: typing.Union[NormRectangleType, NormIntervalType] = None) -> typing.Optional[DataAndMetadata.DataAndMetadata]:
src = DataAndMetadata.promote_ndarray(src)
d_rank = src.datum_dimension_count
if len(src.data_shape) <= d_rank:
return None
if d_rank < 1 or d_rank > 2:
return None
src_shape = list(src.data_shape)
s_shape = src_shape[0:-d_rank]
c = int(numpy.product(s_shape))
ref = src[numpy.unravel_index(0, s_shape) + (Ellipsis, )]
translations = function_sequence_measure_relative_translation(src, ref, upsample_factor, True, bounds=bounds)
if not translations:
return None
result_data = numpy.copy(src.data)
for i in range(1, c):
ii = numpy.unravel_index(i, s_shape) + (Ellipsis, )
current_xdata = DataAndMetadata.new_data_and_metadata(numpy.copy(result_data[ii]))
translation = translations._data_ex[numpy.unravel_index(i, s_shape)]
shift_xdata = function_fourier_shift(current_xdata, tuple(translation))
if shift_xdata:
result_data[ii] = shift_xdata.data
return DataAndMetadata.new_data_and_metadata(result_data, intensity_calibration=src.intensity_calibration, dimensional_calibrations=src.dimensional_calibrations, data_descriptor=src.data_descriptor)
def function_sequence_integrate(src: DataAndMetadata.DataAndMetadata) -> typing.Optional[DataAndMetadata.DataAndMetadata]:
src = DataAndMetadata.promote_ndarray(src)
if not src.is_sequence:
return None
dim = src.data_shape[1:]
if len(dim) < 1:
return None
result = numpy.sum(src._data_ex, axis=0)
intensity_calibration = src.intensity_calibration
dimensional_calibrations = src.dimensional_calibrations[1:]
data_descriptor = DataAndMetadata.DataDescriptor(False, src.data_descriptor.collection_dimension_count, src.data_descriptor.datum_dimension_count)
return DataAndMetadata.new_data_and_metadata(result, intensity_calibration=intensity_calibration, dimensional_calibrations=dimensional_calibrations, data_descriptor=data_descriptor)
def function_sequence_trim(src: DataAndMetadata.DataAndMetadata, trim_start: int, trim_end: int) -> typing.Optional[DataAndMetadata.DataAndMetadata]:
src = DataAndMetadata.promote_ndarray(src)
if not src.is_sequence:
return None
c = src.sequence_dimension_shape[0]
dim = src.data_shape[1:]
if len(dim) < 1:
return None
cs = max(0, int(trim_start))
ce = min(c, max(cs + 1, int(trim_end)))
return src[cs:ce]
def function_sequence_insert(src1: DataAndMetadata.DataAndMetadata, src2: DataAndMetadata.DataAndMetadata, position: int) -> typing.Optional[DataAndMetadata.DataAndMetadata]:
src1 = DataAndMetadata.promote_ndarray(src1)
src2 = DataAndMetadata.promote_ndarray(src2)
if not src1.is_sequence or not src2.is_sequence:
return None
if src1.data_shape[1:] != src2.data_shape[1:]:
return None
c = src1.sequence_dimension_shape[0]
dim = src1.data_shape[1:]
if len(dim) < 1 or len(dim) > 2:
return None
channel = max(0, min(c, int(position)))
result = numpy.vstack([src1._data_ex[:channel], src2._data_ex, src1._data_ex[channel:]])
intensity_calibration = src1.intensity_calibration
dimensional_calibrations = src1.dimensional_calibrations
data_descriptor = src1.data_descriptor
return DataAndMetadata.new_data_and_metadata(result, intensity_calibration=intensity_calibration, dimensional_calibrations=dimensional_calibrations, data_descriptor=data_descriptor)
def function_sequence_concatenate(src1: DataAndMetadata.DataAndMetadata, src2: DataAndMetadata.DataAndMetadata) -> typing.Optional[DataAndMetadata.DataAndMetadata]:
src1 = DataAndMetadata.promote_ndarray(src1)
src2 = DataAndMetadata.promote_ndarray(src2)
return function_sequence_insert(src1, src2, src1.data_shape[0])
def function_sequence_join(data_and_metadata_list: typing.Sequence[DataAndMetadata.DataAndMetadata]) -> typing.Optional[DataAndMetadata.DataAndMetadata]:
if not data_and_metadata_list:
return None
data_and_metadata_list = [DataAndMetadata.promote_ndarray(data_and_metadata) for data_and_metadata in data_and_metadata_list]
def ensure_sequence(xdata):
if xdata.is_sequence:
return xdata
sequence_data = numpy.reshape(xdata.data, (1,) + xdata.data.shape)
dimensional_calibrations = [Calibration.Calibration()] + xdata.dimensional_calibrations
data_descriptor = DataAndMetadata.DataDescriptor(True, xdata.collection_dimension_count, xdata.datum_dimension_count)
return DataAndMetadata.new_data_and_metadata(sequence_data, dimensional_calibrations=dimensional_calibrations, intensity_calibration=xdata.intensity_calibration, data_descriptor=data_descriptor)
sequence_xdata_list = [ensure_sequence(xdata) for xdata in data_and_metadata_list]
xdata_0 = sequence_xdata_list[0]
non_sequence_shape_0 = xdata_0.data_shape[1:]
for xdata in sequence_xdata_list[1:]:
if xdata.data_shape[1:] != non_sequence_shape_0:
return None
return function_concatenate(sequence_xdata_list)
def function_sequence_extract(src: DataAndMetadata.DataAndMetadata, position: int) -> typing.Optional[DataAndMetadata.DataAndMetadata]:
src = DataAndMetadata.promote_ndarray(src)
if not src.is_sequence:
return None
c = src.sequence_dimension_shape[0]
dim = src.data_shape[1:]
if len(dim) < 1:
return None
channel = max(0, min(c, int(position)))
return src[channel]
def function_sequence_split(src: DataAndMetadata.DataAndMetadata) -> typing.Optional[typing.List[DataAndMetadata.DataAndMetadata]]:
src = DataAndMetadata.promote_ndarray(src)
if not src.is_sequence:
return None
dim = src.data_shape[1:]
if len(dim) < 1:
return None
dimensional_calibrations = copy.deepcopy(src.dimensional_calibrations[1:])
data_descriptor = DataAndMetadata.DataDescriptor(False, src.collection_dimension_count, src.datum_dimension_count)
return [
DataAndMetadata.new_data_and_metadata(data, dimensional_calibrations=copy.deepcopy(dimensional_calibrations),
intensity_calibration=copy.deepcopy(src.intensity_calibration),
data_descriptor=copy.copy(data_descriptor)) for data in src._data_ex]
def function_make_elliptical_mask(data_shape: DataAndMetadata.ShapeType, center: NormPointType, size: NormSizeType, rotation: float) -> typing.Optional[DataAndMetadata.DataAndMetadata]:
data_size = Geometry.IntSize.make(data_shape)
data_rect = Geometry.FloatRect(origin=Geometry.FloatPoint(), size=Geometry.FloatSize.make(data_size))
center_point = Geometry.map_point(Geometry.FloatPoint.make(center), Geometry.FloatRect.unit_rect(), data_rect)
size_size = Geometry.map_size(Geometry.FloatSize.make(size), Geometry.FloatRect.unit_rect(), data_rect)
mask = numpy.zeros((data_size.height, data_size.width))
bounds = Geometry.FloatRect.from_center_and_size(center_point, size_size)
if bounds.height <= 0 or bounds.width <= 0:
return DataAndMetadata.new_data_and_metadata(mask)
a, b = bounds.center.y, bounds.center.x
y, x = numpy.ogrid[-a:data_size.height - a, -b:data_size.width - b]
if rotation:
angle_sin = math.sin(rotation)
angle_cos = math.cos(rotation)
mask_eq = ((x * angle_cos - y * angle_sin) ** 2) / ((bounds.width / 2) * (bounds.width / 2)) + ((y * angle_cos + x * angle_sin) ** 2) / ((bounds.height / 2) * (bounds.height / 2)) <= 1
else:
mask_eq = x * x / ((bounds.width / 2) * (bounds.width / 2)) + y * y / ((bounds.height / 2) * (bounds.height / 2)) <= 1
mask[mask_eq] = 1
return DataAndMetadata.new_data_and_metadata(mask)
def function_fourier_mask(data_and_metadata: DataAndMetadata.DataAndMetadata, mask_data_and_metadata: DataAndMetadata.DataAndMetadata) -> typing.Optional[DataAndMetadata.DataAndMetadata]:
data_and_metadata = DataAndMetadata.promote_ndarray(data_and_metadata)
mask_data_and_metadata = DataAndMetadata.promote_ndarray(mask_data_and_metadata)
shape = DataAndMetadata.determine_shape(data_and_metadata, mask_data_and_metadata)
data_and_metadata = DataAndMetadata.promote_constant(data_and_metadata, shape)
mask_data_and_metadata = DataAndMetadata.promote_constant(mask_data_and_metadata, shape)
def calculate_data():
data = data_and_metadata.data
mask_data = mask_data_and_metadata.data
if data is None or mask_data is None:
return None
if Image.is_data_2d(data) and Image.is_data_2d(mask_data):
try:
y_half = data.shape[0] // 2
y_half_p1 = y_half + 1
y_half_m1 = y_half - 1
y_low = 0 if data.shape[0] % 2 == 0 else None
x_half = data.shape[1] // 2
x_half_p1 = x_half + 1
x_half_m1 = x_half - 1
x_low = 0 if data.shape[1] % 2 == 0 else None
fourier_mask_data = numpy.empty_like(mask_data)
fourier_mask_data[y_half_p1:, x_half_p1:] = mask_data[y_half_p1:, x_half_p1:]
fourier_mask_data[y_half_p1:, x_half_m1:x_low:-1] = mask_data[y_half_p1:, x_half_m1:x_low:-1]
fourier_mask_data[y_half_m1:y_low:-1, x_half_m1:x_low:-1] = mask_data[y_half_p1:, x_half_p1:]
fourier_mask_data[y_half_m1:y_low:-1, x_half_p1:] = mask_data[y_half_p1:, x_half_m1:x_low:-1]
fourier_mask_data[0, :] = mask_data[0, :]
fourier_mask_data[:, 0] = mask_data[:, 0]
fourier_mask_data[y_half, :] = mask_data[y_half, :]
fourier_mask_data[:, x_half] = mask_data[:, x_half]
return data * fourier_mask_data
except Exception as e:
print(e)
raise
return None
return DataAndMetadata.new_data_and_metadata(calculate_data(), intensity_calibration=data_and_metadata.intensity_calibration, dimensional_calibrations=data_and_metadata.dimensional_calibrations)
def function_sobel(data_and_metadata: DataAndMetadata.DataAndMetadata) -> typing.Optional[DataAndMetadata.DataAndMetadata]:
data_and_metadata = DataAndMetadata.promote_ndarray(data_and_metadata)
def calculate_data():
data = data_and_metadata.data
if not Image.is_data_valid(data):
return None
if Image.is_shape_and_dtype_rgb(data.shape, data.dtype):
rgb = numpy.empty(data.shape[:-1] + (3,), numpy.uint8)
rgb[..., 0] = scipy.ndimage.sobel(data[..., 0])
rgb[..., 1] = scipy.ndimage.sobel(data[..., 1])
rgb[..., 2] = scipy.ndimage.sobel(data[..., 2])
return rgb
elif Image.is_shape_and_dtype_rgba(data.shape, data.dtype):
rgba = numpy.empty(data.shape[:-1] + (4,), numpy.uint8)
rgba[..., 0] = scipy.ndimage.sobel(data[..., 0])
rgba[..., 1] = scipy.ndimage.sobel(data[..., 1])
rgba[..., 2] = scipy.ndimage.sobel(data[..., 2])
rgba[..., 3] = data[..., 3]
return rgba
else:
return scipy.ndimage.sobel(data)
return DataAndMetadata.new_data_and_metadata(calculate_data(), intensity_calibration=data_and_metadata.intensity_calibration, dimensional_calibrations=data_and_metadata.dimensional_calibrations)
def function_laplace(data_and_metadata: DataAndMetadata.DataAndMetadata) -> typing.Optional[DataAndMetadata.DataAndMetadata]:
data_and_metadata = DataAndMetadata.promote_ndarray(data_and_metadata)
def calculate_data():
data = data_and_metadata.data
if not Image.is_data_valid(data):
return None
if Image.is_shape_and_dtype_rgb(data.shape, data.dtype):
rgb = numpy.empty(data.shape[:-1] + (3,), numpy.uint8)
rgb[..., 0] = scipy.ndimage.laplace(data[..., 0])
rgb[..., 1] = scipy.ndimage.laplace(data[..., 1])
rgb[..., 2] = scipy.ndimage.laplace(data[..., 2])
return rgb
elif Image.is_shape_and_dtype_rgba(data.shape, data.dtype):
rgba = numpy.empty(data.shape[:-1] + (4,), numpy.uint8)
rgba[..., 0] = scipy.ndimage.laplace(data[..., 0])
rgba[..., 1] = scipy.ndimage.laplace(data[..., 1])
rgba[..., 2] = scipy.ndimage.laplace(data[..., 2])
rgba[..., 3] = data[..., 3]
return rgba
else:
return scipy.ndimage.laplace(data)
return DataAndMetadata.new_data_and_metadata(calculate_data(), intensity_calibration=data_and_metadata.intensity_calibration, dimensional_calibrations=data_and_metadata.dimensional_calibrations)
def function_gaussian_blur(data_and_metadata: DataAndMetadata.DataAndMetadata, sigma: float) -> typing.Optional[DataAndMetadata.DataAndMetadata]:
data_and_metadata = DataAndMetadata.promote_ndarray(data_and_metadata)
sigma = float(sigma)
def calculate_data():
data = data_and_metadata.data
if not Image.is_data_valid(data):
return None
return scipy.ndimage.gaussian_filter(data, sigma=sigma)
return DataAndMetadata.new_data_and_metadata(calculate_data(), intensity_calibration=data_and_metadata.intensity_calibration, dimensional_calibrations=data_and_metadata.dimensional_calibrations)
def function_median_filter(data_and_metadata: DataAndMetadata.DataAndMetadata, size: int) -> typing.Optional[DataAndMetadata.DataAndMetadata]:
data_and_metadata = DataAndMetadata.promote_ndarray(data_and_metadata)
size = max(min(int(size), 999), 1)
def calculate_data():
data = data_and_metadata.data
if not Image.is_data_valid(data):
return None
if Image.is_shape_and_dtype_rgb(data.shape, data.dtype):
rgb = numpy.empty(data.shape[:-1] + (3,), numpy.uint8)
rgb[..., 0] = scipy.ndimage.median_filter(data[..., 0], size=size)
rgb[..., 1] = scipy.ndimage.median_filter(data[..., 1], size=size)
rgb[..., 2] = scipy.ndimage.median_filter(data[..., 2], size=size)
return rgb
elif Image.is_shape_and_dtype_rgba(data.shape, data.dtype):
rgba = numpy.empty(data.shape[:-1] + (4,), numpy.uint8)
rgba[..., 0] = scipy.ndimage.median_filter(data[..., 0], size=size)
rgba[..., 1] = scipy.ndimage.median_filter(data[..., 1], size=size)
rgba[..., 2] = scipy.ndimage.median_filter(data[..., 2], size=size)
rgba[..., 3] = data[..., 3]
return rgba
else:
return scipy.ndimage.median_filter(data, size=size)
return DataAndMetadata.new_data_and_metadata(calculate_data(), intensity_calibration=data_and_metadata.intensity_calibration, dimensional_calibrations=data_and_metadata.dimensional_calibrations)
def function_uniform_filter(data_and_metadata: DataAndMetadata.DataAndMetadata, size: int) -> typing.Optional[DataAndMetadata.DataAndMetadata]:
data_and_metadata = DataAndMetadata.promote_ndarray(data_and_metadata)
size = max(min(int(size), 999), 1)
def calculate_data():
data = data_and_metadata.data
if not Image.is_data_valid(data):
return None
if Image.is_shape_and_dtype_rgb(data.shape, data.dtype):
rgb = numpy.empty(data.shape[:-1] + (3,), numpy.uint8)
rgb[..., 0] = scipy.ndimage.uniform_filter(data[..., 0], size=size)
rgb[..., 1] = scipy.ndimage.uniform_filter(data[..., 1], size=size)
rgb[..., 2] = scipy.ndimage.uniform_filter(data[..., 2], size=size)
return rgb
elif Image.is_shape_and_dtype_rgba(data.shape, data.dtype):
rgba = numpy.empty(data.shape[:-1] + (4,), numpy.uint8)
rgba[..., 0] = scipy.ndimage.uniform_filter(data[..., 0], size=size)
rgba[..., 1] = scipy.ndimage.uniform_filter(data[..., 1], size=size)
rgba[..., 2] = scipy.ndimage.uniform_filter(data[..., 2], size=size)
rgba[..., 3] = data[..., 3]
return rgba
else:
return scipy.ndimage.uniform_filter(data, size=size)
return DataAndMetadata.new_data_and_metadata(calculate_data(), intensity_calibration=data_and_metadata.intensity_calibration, dimensional_calibrations=data_and_metadata.dimensional_calibrations)
def function_transpose_flip(data_and_metadata: DataAndMetadata.DataAndMetadata, transpose: bool=False, flip_v: bool=False, flip_h: bool=False) -> typing.Optional[DataAndMetadata.DataAndMetadata]:
data_and_metadata = DataAndMetadata.promote_ndarray(data_and_metadata)
def calculate_data():
data = data_and_metadata.data
data_id = id(data)
if not Image.is_data_valid(data):
return None
if transpose:
if Image.is_shape_and_dtype_rgb_type(data.shape, data.dtype):
data = numpy.transpose(data, [1, 0, 2])
elif len(data_and_metadata.data_shape) == 2:
data = numpy.transpose(data, [1, 0])
if flip_h and len(data_and_metadata.data_shape) == 2:
data = numpy.fliplr(data)
if flip_v and len(data_and_metadata.data_shape) == 2:
data = numpy.flipud(data)
if id(data) == data_id: # ensure real data, not a view
data = data.copy()
return data
data_shape = data_and_metadata.data_shape
data_dtype = data_and_metadata.data_dtype
if not Image.is_shape_and_dtype_valid(data_shape, data_dtype):
return None
if transpose:
dimensional_calibrations = list(reversed(data_and_metadata.dimensional_calibrations))
else:
dimensional_calibrations = list(data_and_metadata.dimensional_calibrations)
return DataAndMetadata.new_data_and_metadata(calculate_data(), intensity_calibration=data_and_metadata.intensity_calibration, dimensional_calibrations=dimensional_calibrations)
def function_invert(data_and_metadata: DataAndMetadata.DataAndMetadata) -> typing.Optional[DataAndMetadata.DataAndMetadata]:
data_and_metadata = DataAndMetadata.promote_ndarray(data_and_metadata)
def calculate_data():
data = data_and_metadata.data
if not Image.is_data_valid(data):
return None
if Image.is_shape_and_dtype_rgb_type(data.shape, data.dtype):
if Image.is_data_rgba(data):
inverted = 255 - data[:]
inverted[...,3] = data[...,3]
return inverted
else:
return 255 - data[:]
else:
return -data[:]
data_shape = data_and_metadata.data_shape
data_dtype = data_and_metadata.data_dtype
if not Image.is_shape_and_dtype_valid(data_shape, data_dtype):
return None
dimensional_calibrations = data_and_metadata.dimensional_calibrations
return DataAndMetadata.new_data_and_metadata(calculate_data(), intensity_calibration=data_and_metadata.intensity_calibration, dimensional_calibrations=dimensional_calibrations)
def function_crop(data_and_metadata: DataAndMetadata.DataAndMetadata, bounds: NormRectangleType) -> typing.Optional[DataAndMetadata.DataAndMetadata]:
bounds_rect = Geometry.FloatRect.make(bounds)
data_and_metadata = DataAndMetadata.promote_ndarray(data_and_metadata)
data_shape = Geometry.IntSize.make(data_and_metadata.data_shape)
data_dtype = data_and_metadata.data_dtype
dimensional_calibrations = data_and_metadata.dimensional_calibrations
data = data_and_metadata._data_ex
if not Image.is_shape_and_dtype_valid(list(data_shape), data_dtype) or dimensional_calibrations is None:
return None
if not Image.is_data_valid(data):
return None
oheight = int(data_shape.height * bounds_rect.height)
owidth = int(data_shape.width * bounds_rect.width)
top = int(data_shape.height * bounds_rect.top)
left = int(data_shape.width * bounds_rect.left)
height = int(data_shape.height * bounds_rect.height)
width = int(data_shape.width * bounds_rect.width)
dtop = 0
dleft = 0
dheight = height
dwidth = width
if top < 0:
dheight += top
dtop -= top
height += top
top = 0
if top + height > data_shape.height:
dheight -= (top + height - data_shape.height)
height = data_shape.height - top
if left < 0:
dwidth += left
dleft -= left
width += left
left = 0
if left + width > data_shape.width:
dwidth -= (left + width- data_shape.width)
width = data_shape.width - left
data_dtype = data.dtype
assert data_dtype is not None
if data_and_metadata.is_data_rgb:
new_data = numpy.zeros((oheight, owidth, 3), dtype=data_dtype)
if height > 0 and width > 0:
new_data[dtop:dtop + dheight, dleft:dleft + dwidth] = data[top:top + height, left:left + width]
elif data_and_metadata.is_data_rgba:
new_data = numpy.zeros((oheight, owidth, 4), dtype=data_dtype)
if height > 0 and width > 0:
new_data[dtop:dtop + dheight, dleft:dleft + dwidth] = data[top:top + height, left:left + width]
else:
new_data = numpy.zeros((oheight, owidth), dtype=data_dtype)
if height > 0 and width > 0:
new_data[dtop:dtop + dheight, dleft:dleft + dwidth] = data[top:top + height, left:left + width]
cropped_dimensional_calibrations = list()
for index, dimensional_calibration in enumerate(dimensional_calibrations):
cropped_calibration = Calibration.Calibration(
dimensional_calibration.offset + data_shape[index] * bounds_rect.origin[index] * dimensional_calibration.scale,
dimensional_calibration.scale, dimensional_calibration.units)
cropped_dimensional_calibrations.append(cropped_calibration)
return DataAndMetadata.new_data_and_metadata(new_data, intensity_calibration=data_and_metadata.intensity_calibration, dimensional_calibrations=cropped_dimensional_calibrations)
def function_crop_rotated(data_and_metadata: DataAndMetadata.DataAndMetadata, bounds: NormRectangleType, angle: float) -> typing.Optional[DataAndMetadata.DataAndMetadata]:
bounds_rect = Geometry.FloatRect.make(bounds)
data_and_metadata = DataAndMetadata.promote_ndarray(data_and_metadata)
data_shape = Geometry.IntSize.make(data_and_metadata.data_shape)
data_dtype = data_and_metadata.data_dtype
dimensional_calibrations = data_and_metadata.dimensional_calibrations
data = data_and_metadata._data_ex
if not Image.is_shape_and_dtype_valid(list(data_shape), data_dtype) or dimensional_calibrations is None:
return None
if not Image.is_data_valid(data):
return None
top = round(data_shape.height * bounds_rect.top)
left = round(data_shape.width * bounds_rect.left)
height = round(data_shape.height * bounds_rect.height)
width = round(data_shape.width * bounds_rect.width)
x, y = numpy.meshgrid(numpy.arange(-(width // 2), width - width // 2), numpy.arange(-(height // 2), height - height // 2))
angle_sin = math.sin(angle)
angle_cos = math.cos(angle)
coords = [top + height // 2 + (y * angle_cos - x * angle_sin), left + width // 2 + (x * angle_cos + y * angle_sin)]
if data_and_metadata.is_data_rgb:
new_data = numpy.zeros(coords[0].shape + (3,), numpy.uint8)
new_data[..., 0] = scipy.ndimage.interpolation.map_coordinates(data[..., 0], coords)
new_data[..., 1] = scipy.ndimage.interpolation.map_coordinates(data[..., 1], coords)
new_data[..., 2] = scipy.ndimage.interpolation.map_coordinates(data[..., 2], coords)
elif data_and_metadata.is_data_rgba:
new_data = numpy.zeros(coords[0].shape + (4,), numpy.uint8)
new_data[..., 0] = scipy.ndimage.interpolation.map_coordinates(data[..., 0], coords)
new_data[..., 1] = scipy.ndimage.interpolation.map_coordinates(data[..., 1], coords)
new_data[..., 2] = scipy.ndimage.interpolation.map_coordinates(data[..., 2], coords)
new_data[..., 3] = scipy.ndimage.interpolation.map_coordinates(data[..., 3], coords)
else:
new_data = scipy.ndimage.interpolation.map_coordinates(data, coords)
cropped_dimensional_calibrations = list()
for index, dimensional_calibration in enumerate(dimensional_calibrations):
cropped_calibration = Calibration.Calibration(
dimensional_calibration.offset + data_shape[index] * bounds_rect[0][index] * dimensional_calibration.scale,
dimensional_calibration.scale, dimensional_calibration.units)
cropped_dimensional_calibrations.append(cropped_calibration)
return DataAndMetadata.new_data_and_metadata(new_data, intensity_calibration=data_and_metadata.intensity_calibration, dimensional_calibrations=cropped_dimensional_calibrations)
def function_crop_interval(data_and_metadata: DataAndMetadata.DataAndMetadata, interval: NormIntervalType) -> typing.Optional[DataAndMetadata.DataAndMetadata]:
data_and_metadata = DataAndMetadata.promote_ndarray(data_and_metadata)
data_shape = data_and_metadata.data_shape
data_dtype = data_and_metadata.data_dtype
def calculate_data():
data = data_and_metadata.data
if not Image.is_data_valid(data):
return None
data_shape = data_and_metadata.data_shape
interval_int = int(data_shape[0] * interval[0]), int(data_shape[0] * interval[1])
return data[interval_int[0]:interval_int[1]].copy()
dimensional_calibrations = data_and_metadata.dimensional_calibrations
if not Image.is_shape_and_dtype_valid(data_shape, data_dtype) or dimensional_calibrations is None:
return None
interval_int = int(data_shape[0] * interval[0]), int(data_shape[0] * interval[1])
cropped_dimensional_calibrations = list()
dimensional_calibration = dimensional_calibrations[0]
cropped_calibration = Calibration.Calibration(
dimensional_calibration.offset + data_shape[0] * interval_int[0] * dimensional_calibration.scale,
dimensional_calibration.scale, dimensional_calibration.units)
cropped_dimensional_calibrations.append(cropped_calibration)
return DataAndMetadata.new_data_and_metadata(calculate_data(), intensity_calibration=data_and_metadata.intensity_calibration, dimensional_calibrations=cropped_dimensional_calibrations)
def function_slice_sum(data_and_metadata: DataAndMetadata.DataAndMetadata, slice_center: int, slice_width: int) -> typing.Optional[DataAndMetadata.DataAndMetadata]:
data_and_metadata = DataAndMetadata.promote_ndarray(data_and_metadata)
signal_index = -1
slice_center = int(slice_center)
slice_width = int(slice_width)
data_shape = data_and_metadata.data_shape
data_dtype = data_and_metadata.data_dtype
def calculate_data():
data = data_and_metadata.data
if not Image.is_data_valid(data):
return None
shape = data.shape
slice_start = int(slice_center - slice_width * 0.5 + 0.5)
slice_start = max(slice_start, 0)
slice_end = slice_start + slice_width
slice_end = min(shape[signal_index], slice_end)
return numpy.sum(data[..., slice_start:slice_end], signal_index)
dimensional_calibrations = data_and_metadata.dimensional_calibrations
if not Image.is_shape_and_dtype_valid(data_shape, data_dtype) or dimensional_calibrations is None:
return None
dimensional_calibrations = dimensional_calibrations[0:signal_index]
return DataAndMetadata.new_data_and_metadata(calculate_data(), intensity_calibration=data_and_metadata.intensity_calibration, dimensional_calibrations=dimensional_calibrations)
def function_pick(data_and_metadata: DataAndMetadata.DataAndMetadata, position: DataAndMetadata.PositionType) -> typing.Optional[DataAndMetadata.DataAndMetadata]:
data_and_metadata = DataAndMetadata.promote_ndarray(data_and_metadata)
data_shape = data_and_metadata.data_shape
data_dtype = data_and_metadata.data_dtype
def calculate_data():
data = data_and_metadata.data
collection_dimensions = data_and_metadata.dimensional_shape[data_and_metadata.collection_dimension_slice]
datum_dimensions = data_and_metadata.dimensional_shape[data_and_metadata.datum_dimension_slice]
assert len(collection_dimensions) == len(position)
position_i = list()
for collection_dimension, pos in zip(collection_dimensions, position):
pos_i = int(pos * collection_dimension)
if not (0 <= pos_i < collection_dimension):
return numpy.zeros(datum_dimensions, dtype=data.dtype)
position_i.append(pos_i)
if data_and_metadata.is_sequence:
return data[(slice(None),) + tuple(position_i + [...])].copy()
return data[tuple(position_i + [...])].copy()
dimensional_calibrations = data_and_metadata.dimensional_calibrations
data_descriptor = DataAndMetadata.DataDescriptor(data_and_metadata.is_sequence, 0, data_and_metadata.datum_dimension_count)
if not Image.is_shape_and_dtype_valid(data_shape, data_dtype) or dimensional_calibrations is None:
return None
if len(position) != data_and_metadata.collection_dimension_count:
return None
if data_and_metadata.datum_dimension_count == 0:
return None
if data_and_metadata.is_sequence:
dimensional_calibrations = [dimensional_calibrations[0]] + list(dimensional_calibrations[data_and_metadata.datum_dimension_slice])
else:
dimensional_calibrations = list(dimensional_calibrations[data_and_metadata.datum_dimension_slice])
return DataAndMetadata.new_data_and_metadata(calculate_data(), intensity_calibration=data_and_metadata.intensity_calibration, dimensional_calibrations=dimensional_calibrations, data_descriptor=data_descriptor)
def function_concatenate(data_and_metadata_list: typing.Sequence[DataAndMetadata.DataAndMetadata], axis: int=0) -> typing.Optional[DataAndMetadata.DataAndMetadata]:
"""Concatenate multiple data_and_metadatas.
concatenate((a, b, c), 1)
Function is called by passing a tuple of the list of source items, which matches the
form of the numpy function of the same name.
Keeps intensity calibration of first source item.
Keeps data descriptor of first source item.
Keeps dimensional calibration in axis dimension.
"""
if len(data_and_metadata_list) < 1:
return None
data_and_metadata_list = [DataAndMetadata.promote_ndarray(data_and_metadata) for data_and_metadata in data_and_metadata_list]
partial_shape = data_and_metadata_list[0].data_shape
def calculate_data():
if any([data_and_metadata.data is None for data_and_metadata in data_and_metadata_list]):
return None
if all([data_and_metadata.data_shape[1:] == partial_shape[1:] for data_and_metadata in data_and_metadata_list]):
data_list = list(data_and_metadata.data for data_and_metadata in data_and_metadata_list)
return numpy.concatenate(data_list, axis)
return None
if any([data_and_metadata.data is None for data_and_metadata in data_and_metadata_list]):
return None
if any([data_and_metadata.data_shape != partial_shape[1:] is None for data_and_metadata in data_and_metadata_list]):
return None
dimensional_calibrations: typing.List[Calibration.Calibration] = [typing.cast(Calibration.Calibration, None)] * len(data_and_metadata_list[0].dimensional_calibrations)
for data_and_metadata in data_and_metadata_list:
for index, calibration in enumerate(data_and_metadata.dimensional_calibrations):
if dimensional_calibrations[index] is None:
dimensional_calibrations[index] = calibration
elif dimensional_calibrations[index] != calibration:
dimensional_calibrations[index] = Calibration.Calibration()
intensity_calibration = data_and_metadata_list[0].intensity_calibration
data_descriptor = data_and_metadata_list[0].data_descriptor
return DataAndMetadata.new_data_and_metadata(calculate_data(), intensity_calibration=intensity_calibration, dimensional_calibrations=dimensional_calibrations, data_descriptor=data_descriptor)
def function_hstack(data_and_metadata_list: typing.Sequence[DataAndMetadata.DataAndMetadata]) -> typing.Optional[DataAndMetadata.DataAndMetadata]:
"""Stack multiple data_and_metadatas along axis 1.
hstack((a, b, c))
Function is called by passing a tuple of the list of source items, which matches the
form of the numpy function of the same name.
Keeps intensity calibration of first source item.
Keeps dimensional calibration in axis dimension.
"""
if len(data_and_metadata_list) < 1:
return None
data_and_metadata_list = [DataAndMetadata.promote_ndarray(data_and_metadata) for data_and_metadata in data_and_metadata_list]
partial_shape = data_and_metadata_list[0].data_shape
if len(partial_shape) >= 2:
return function_concatenate(data_and_metadata_list, 1)
else:
return function_concatenate(data_and_metadata_list, 0)
def function_vstack(data_and_metadata_list: typing.Sequence[DataAndMetadata.DataAndMetadata]) -> typing.Optional[DataAndMetadata.DataAndMetadata]:
"""Stack multiple data_and_metadatas along axis 0.
hstack((a, b, c))
Function is called by passing a tuple of the list of source items, which matches the
form of the numpy function of the same name.
Keeps intensity calibration of first source item.
Keeps dimensional calibration in axis dimension.
"""
if len(data_and_metadata_list) < 1:
return None
data_and_metadata_list = [DataAndMetadata.promote_ndarray(data_and_metadata) for data_and_metadata in data_and_metadata_list]
partial_shape = data_and_metadata_list[0].data_shape
if len(partial_shape) >= 2:
return function_concatenate(data_and_metadata_list, 0)
def calculate_data():
if any([data_and_metadata.data is None for data_and_metadata in data_and_metadata_list]):
return None
if all([data_and_metadata.data_shape[0] == partial_shape[0] for data_and_metadata in data_and_metadata_list]):
data_list = list(data_and_metadata.data for data_and_metadata in data_and_metadata_list)
return numpy.vstack(data_list)
return None
if any([data_and_metadata.data is None for data_and_metadata in data_and_metadata_list]):
return None
if any([data_and_metadata.data_shape[0] != partial_shape[0] is None for data_and_metadata in data_and_metadata_list]):
return None
dimensional_calibrations = list()
dimensional_calibrations.append(Calibration.Calibration())
dimensional_calibrations.append(data_and_metadata_list[0].dimensional_calibrations[0])
intensity_calibration = data_and_metadata_list[0].intensity_calibration
data_descriptor = data_and_metadata_list[0].data_descriptor
data_descriptor = DataAndMetadata.DataDescriptor(data_descriptor.is_sequence, data_descriptor.collection_dimension_count + 1, data_descriptor.datum_dimension_count)
return DataAndMetadata.new_data_and_metadata(calculate_data(), intensity_calibration=intensity_calibration, dimensional_calibrations=dimensional_calibrations, data_descriptor=data_descriptor)
def function_moveaxis(data_and_metadata: DataAndMetadata.DataAndMetadata, src_axis: int, dst_axis: int) -> typing.Optional[DataAndMetadata.DataAndMetadata]:
data_and_metadata = DataAndMetadata.promote_ndarray(data_and_metadata)
data = numpy.moveaxis(data_and_metadata._data_ex, src_axis, dst_axis)
dimensional_calibrations = list(copy.deepcopy(data_and_metadata.dimensional_calibrations))
dimensional_calibrations.insert(dst_axis, dimensional_calibrations.pop(src_axis))
return DataAndMetadata.new_data_and_metadata(data, intensity_calibration=data_and_metadata.intensity_calibration, dimensional_calibrations=dimensional_calibrations)
def function_sum(data_and_metadata: DataAndMetadata.DataAndMetadata, axis: typing.Optional[typing.Union[int, typing.Sequence[int]]] = None, keepdims: bool = False) -> typing.Optional[DataAndMetadata.DataAndMetadata]:
data_and_metadata = DataAndMetadata.promote_ndarray(data_and_metadata)
data_shape = data_and_metadata.data_shape
data_dtype = data_and_metadata.data_dtype
def calculate_data():
data = data_and_metadata.data
if not Image.is_data_valid(data):
return None
if Image.is_shape_and_dtype_rgb_type(data.shape, data.dtype):
if Image.is_shape_and_dtype_rgb(data.shape, data.dtype):
rgb_image = numpy.empty(data.shape[1:], numpy.uint8)
rgb_image[:,0] = numpy.average(data[...,0], axis)
rgb_image[:,1] = numpy.average(data[...,1], axis)
rgb_image[:,2] = numpy.average(data[...,2], axis)
return rgb_image
else:
rgba_image = numpy.empty(data.shape[1:], numpy.uint8)
rgba_image[:,0] = numpy.average(data[...,0], axis)
rgba_image[:,1] = numpy.average(data[...,1], axis)
rgba_image[:,2] = numpy.average(data[...,2], axis)
rgba_image[:,3] = numpy.average(data[...,3], axis)
return rgba_image
else:
return numpy.sum(data, axis, keepdims=keepdims)
dimensional_calibrations = data_and_metadata.dimensional_calibrations
if not Image.is_shape_and_dtype_valid(data_shape, data_dtype) or dimensional_calibrations is None:
return None
new_dimensional_calibrations = list()
if not keepdims or Image.is_shape_and_dtype_rgb_type(data_shape, data_dtype):
assert axis is not None
axes = numpy.atleast_1d(axis)
for i in range(len(axes)):
if axes[i] < 0:
axes[i] += len(dimensional_calibrations)
for i in range(len(dimensional_calibrations)):
if not i in axes:
new_dimensional_calibrations.append(dimensional_calibrations[i])
dimensional_calibrations = new_dimensional_calibrations
return DataAndMetadata.new_data_and_metadata(calculate_data(), intensity_calibration=data_and_metadata.intensity_calibration, dimensional_calibrations=dimensional_calibrations)
def function_mean(data_and_metadata: DataAndMetadata.DataAndMetadata, axis: typing.Optional[typing.Union[int, typing.Sequence[int]]] = None, keepdims: bool = False) -> typing.Optional[DataAndMetadata.DataAndMetadata]:
data_and_metadata = DataAndMetadata.promote_ndarray(data_and_metadata)
data_shape = data_and_metadata.data_shape
data_dtype = data_and_metadata.data_dtype
def calculate_data():
data = data_and_metadata.data
if not Image.is_data_valid(data):
return None
if Image.is_shape_and_dtype_rgb_type(data.shape, data.dtype):
if Image.is_shape_and_dtype_rgb(data.shape, data.dtype):
rgb_image = numpy.empty(data.shape[1:], numpy.uint8)
rgb_image[:,0] = numpy.average(data[...,0], axis)
rgb_image[:,1] = numpy.average(data[...,1], axis)
rgb_image[:,2] = numpy.average(data[...,2], axis)
return rgb_image
else:
rgba_image = numpy.empty(data.shape[1:], numpy.uint8)
rgba_image[:,0] = numpy.average(data[...,0], axis)
rgba_image[:,1] = numpy.average(data[...,1], axis)
rgba_image[:,2] = numpy.average(data[...,2], axis)
rgba_image[:,3] = numpy.average(data[...,3], axis)
return rgba_image
else:
return numpy.mean(data, axis, keepdims=keepdims)
dimensional_calibrations = data_and_metadata.dimensional_calibrations
if not Image.is_shape_and_dtype_valid(data_shape, data_dtype) or dimensional_calibrations is None:
return None
new_dimensional_calibrations = list()
if not keepdims or Image.is_shape_and_dtype_rgb_type(data_shape, data_dtype):
assert axis is not None
axes = numpy.atleast_1d(axis)
for i in range(len(axes)):
if axes[i] < 0:
axes[i] += len(dimensional_calibrations)
for i in range(len(dimensional_calibrations)):
if not i in axes:
new_dimensional_calibrations.append(dimensional_calibrations[i])
dimensional_calibrations = new_dimensional_calibrations
return DataAndMetadata.new_data_and_metadata(calculate_data(), intensity_calibration=data_and_metadata.intensity_calibration, dimensional_calibrations=dimensional_calibrations)
def function_sum_region(data_and_metadata: DataAndMetadata.DataAndMetadata, mask_data_and_metadata: DataAndMetadata.DataAndMetadata) -> typing.Optional[DataAndMetadata.DataAndMetadata]:
data_and_metadata = DataAndMetadata.promote_ndarray(data_and_metadata)
mask_data_and_metadata = DataAndMetadata.promote_ndarray(mask_data_and_metadata)
data_shape = data_and_metadata.data_shape
data_dtype = data_and_metadata.data_dtype
dimensional_calibrations = data_and_metadata.dimensional_calibrations
if not Image.is_shape_and_dtype_valid(data_shape, data_dtype) or dimensional_calibrations is None:
return None
if data_and_metadata.is_sequence:
assert len(data_and_metadata.dimensional_shape) == 4
else:
assert len(data_and_metadata.dimensional_shape) == 3
assert len(mask_data_and_metadata.dimensional_shape) == 2
data = data_and_metadata._data_ex
mask_data = mask_data_and_metadata._data_ex.astype(bool)
start_index = 1 if data_and_metadata.is_sequence else 0
result_data = numpy.sum(data, axis=tuple(range(start_index, len(data_and_metadata.dimensional_shape) - 1)), where=mask_data[..., numpy.newaxis])
data_descriptor = DataAndMetadata.DataDescriptor(data_and_metadata.is_sequence, 0, data_and_metadata.datum_dimension_count)
if data_and_metadata.is_sequence:
dimensional_calibrations = [dimensional_calibrations[0]] + list(dimensional_calibrations[data_and_metadata.datum_dimension_slice])
else:
dimensional_calibrations = list(dimensional_calibrations[data_and_metadata.datum_dimension_slice])
return DataAndMetadata.new_data_and_metadata(result_data, intensity_calibration=data_and_metadata.intensity_calibration, dimensional_calibrations=dimensional_calibrations, data_descriptor=data_descriptor)
def function_average_region(data_and_metadata: DataAndMetadata.DataAndMetadata, mask_data_and_metadata: DataAndMetadata.DataAndMetadata) -> typing.Optional[DataAndMetadata.DataAndMetadata]:
data_and_metadata = DataAndMetadata.promote_ndarray(data_and_metadata)
mask_data_and_metadata = DataAndMetadata.promote_ndarray(mask_data_and_metadata)
data_shape = data_and_metadata.data_shape
data_dtype = data_and_metadata.data_dtype
dimensional_calibrations = data_and_metadata.dimensional_calibrations
if not Image.is_shape_and_dtype_valid(data_shape, data_dtype) or dimensional_calibrations is None:
return None
if data_and_metadata.is_sequence:
assert len(data_and_metadata.dimensional_shape) == 4
else:
assert len(data_and_metadata.dimensional_shape) == 3
assert len(mask_data_and_metadata.dimensional_shape) == 2
data = data_and_metadata._data_ex
mask_data = mask_data_and_metadata._data_ex.astype(bool)
assert data is not None
mask_sum = max(1, numpy.sum(mask_data))
start_index = 1 if data_and_metadata.is_sequence else 0
result_data = numpy.sum(data, axis=tuple(range(start_index, len(data_and_metadata.dimensional_shape) - 1)), where=mask_data[..., numpy.newaxis]) / mask_sum
data_descriptor = DataAndMetadata.DataDescriptor(data_and_metadata.is_sequence, 0, data_and_metadata.datum_dimension_count)
if data_and_metadata.is_sequence:
dimensional_calibrations = [dimensional_calibrations[0]] + list(dimensional_calibrations[data_and_metadata.datum_dimension_slice])
else:
dimensional_calibrations = list(dimensional_calibrations[data_and_metadata.datum_dimension_slice])
return DataAndMetadata.new_data_and_metadata(result_data, intensity_calibration=data_and_metadata.intensity_calibration, dimensional_calibrations=dimensional_calibrations, data_descriptor=data_descriptor)
def function_reshape(data_and_metadata: DataAndMetadata.DataAndMetadata, shape: DataAndMetadata.ShapeType) -> typing.Optional[DataAndMetadata.DataAndMetadata]:
"""Reshape a data and metadata to shape.
reshape(a, shape(4, 5))
reshape(a, data_shape(b))
Handles special cases when going to one extra dimension and when going to one fewer
dimension -- namely to keep the calibrations intact.
When increasing dimension, a -1 can be passed for the new dimension and this function
will calculate the missing value.
"""
data_and_metadata = DataAndMetadata.promote_ndarray(data_and_metadata)
data_shape = data_and_metadata.data_shape
data_dtype = data_and_metadata.data_dtype
def calculate_data():
data = data_and_metadata.data
if not Image.is_data_valid(data):
return None
return numpy.reshape(data, shape)
dimensional_calibrations = data_and_metadata.dimensional_calibrations
if not Image.is_shape_and_dtype_valid(data_shape, data_dtype) or dimensional_calibrations is None:
return None
total_old_pixels = 1
for dimension in data_shape:
total_old_pixels *= dimension
total_new_pixels = 1
for dimension in shape:
total_new_pixels *= dimension if dimension > 0 else 1
new_dimensional_calibrations = list()
if len(data_shape) + 1 == len(shape) and -1 in shape:
# special case going to one more dimension
index = 0
for dimension in shape:
if dimension == -1:
new_dimensional_calibrations.append(Calibration.Calibration())
else:
new_dimensional_calibrations.append(dimensional_calibrations[index])
index += 1
elif len(data_shape) - 1 == len(shape) and 1 in data_shape:
# special case going to one fewer dimension
for dimension, dimensional_calibration in zip(data_shape, dimensional_calibrations):
if dimension == 1:
continue
else:
new_dimensional_calibrations.append(dimensional_calibration)
else:
for _ in range(len(shape)):
new_dimensional_calibrations.append(Calibration.Calibration())
return DataAndMetadata.new_data_and_metadata(calculate_data(), intensity_calibration=data_and_metadata.intensity_calibration, dimensional_calibrations=new_dimensional_calibrations)
def function_squeeze(data_and_metadata: DataAndMetadata.DataAndMetadata) -> typing.Optional[DataAndMetadata.DataAndMetadata]:
"""Remove dimensions with lengths of one."""
data_and_metadata = DataAndMetadata.promote_ndarray(data_and_metadata)
data_shape = data_and_metadata.data_shape
dimensional_calibrations = data_and_metadata.dimensional_calibrations
is_sequence = data_and_metadata.is_sequence
collection_dimension_count = data_and_metadata.collection_dimension_count
datum_dimension_count = data_and_metadata.datum_dimension_count
new_dimensional_calibrations = list()
dimensional_index = 0
# fix the data descriptor and the dimensions
indexes = list()
if is_sequence:
if data_shape[dimensional_index] <= 1:
is_sequence = False
indexes.append(dimensional_index)
else:
new_dimensional_calibrations.append(dimensional_calibrations[dimensional_index])
dimensional_index += 1
for collection_dimension_index in range(collection_dimension_count):
if data_shape[dimensional_index] <= 1:
collection_dimension_count -= 1
indexes.append(dimensional_index)
else:
new_dimensional_calibrations.append(dimensional_calibrations[dimensional_index])
dimensional_index += 1
for datum_dimension_index in range(datum_dimension_count):
if data_shape[dimensional_index] <= 1 and datum_dimension_count > 1:
datum_dimension_count -= 1
indexes.append(dimensional_index)
else:
new_dimensional_calibrations.append(dimensional_calibrations[dimensional_index])
dimensional_index += 1
data_descriptor = DataAndMetadata.DataDescriptor(is_sequence, collection_dimension_count, datum_dimension_count)
data = data_and_metadata._data_ex
if not Image.is_data_valid(data):
return None
data = numpy.squeeze(data, axis=tuple(indexes))
return DataAndMetadata.new_data_and_metadata(data, intensity_calibration=data_and_metadata.intensity_calibration, dimensional_calibrations=new_dimensional_calibrations, data_descriptor=data_descriptor)
def function_redimension(data_and_metadata: DataAndMetadata.DataAndMetadata, data_descriptor: DataAndMetadata.DataDescriptor) -> typing.Optional[DataAndMetadata.DataAndMetadata]:
data_and_metadata = DataAndMetadata.promote_ndarray(data_and_metadata)
if data_and_metadata.data_descriptor.expected_dimension_count != data_descriptor.expected_dimension_count:
return None
data = data_and_metadata.data
if not Image.is_data_valid(data):
return None
return DataAndMetadata.new_data_and_metadata(data, intensity_calibration=data_and_metadata.intensity_calibration, dimensional_calibrations=data_and_metadata.dimensional_calibrations, data_descriptor=data_descriptor)
def function_resize(data_and_metadata: DataAndMetadata.DataAndMetadata, shape: DataAndMetadata.ShapeType, mode: str=None) -> typing.Optional[DataAndMetadata.DataAndMetadata]:
"""Resize a data and metadata to shape, padding if larger, cropping if smaller.
resize(a, shape(4, 5))
resize(a, data_shape(b))
Shape must have same number of dimensions as original.
"""
data_and_metadata = DataAndMetadata.promote_ndarray(data_and_metadata)
data_shape = data_and_metadata.data_shape
data_dtype = data_and_metadata.data_dtype
def calculate_data():
data = data_and_metadata.data
if not Image.is_data_valid(data):
return None
c = numpy.mean(data)
data_shape = data_and_metadata.data_shape
slices = list()
for data_size, new_size in zip(data_shape, shape):
if new_size <= data_size:
left = data_size // 2 - new_size // 2
slices.append(slice(left, left + new_size))
else:
slices.append(slice(None))
data = data[tuple(slices)]
data_shape = data_and_metadata.data_shape
pads = list()
for data_size, new_size in zip(data_shape, shape):
if new_size > data_size:
left = new_size // 2 - data_size // 2
pads.append((left, new_size - left - data_size))
else:
pads.append((0, 0))
return numpy.pad(data, pads, 'constant', constant_values=c)
dimensional_calibrations = data_and_metadata.dimensional_calibrations
if not Image.is_shape_and_dtype_valid(data_shape, data_dtype) or dimensional_calibrations is None:
return None
resized_dimensional_calibrations = list()
for index, dimensional_calibration in enumerate(dimensional_calibrations):
offset = data_shape[index] // 2 - shape[index] // 2
cropped_calibration = Calibration.Calibration(
dimensional_calibration.offset + offset * dimensional_calibration.scale,
dimensional_calibration.scale, dimensional_calibration.units)
resized_dimensional_calibrations.append(cropped_calibration)
return DataAndMetadata.new_data_and_metadata(calculate_data(), intensity_calibration=data_and_metadata.intensity_calibration, dimensional_calibrations=resized_dimensional_calibrations)
def function_rescale(data_and_metadata: DataAndMetadata.DataAndMetadata, data_range: DataRangeType=None, in_range: DataRangeType=None) -> typing.Optional[DataAndMetadata.DataAndMetadata]:
"""Rescale data and update intensity calibration.
rescale(a, (0.0, 1.0))
"""
data_and_metadata = DataAndMetadata.promote_ndarray(data_and_metadata)
data_range = data_range if data_range is not None else (0.0, 1.0)
def calculate_data():
data = data_and_metadata.data
if not Image.is_data_valid(data):
return None
data_ptp = numpy.ptp(data) if in_range is None else in_range[1] - in_range[0]
data_ptp_i = 1.0 / data_ptp if data_ptp != 0.0 else 1.0
data_min = numpy.amin(data) if in_range is None else in_range[0]
data_span = data_range[1] - data_range[0]
if data_span == 1.0 and data_range[0] == 0.0:
return (data - data_min) * data_ptp_i
else:
m = data_span * data_ptp_i
return (data - data_min) * m + data_range[0]
data_shape = data_and_metadata.data_shape
data_dtype = data_and_metadata.data_dtype
if not Image.is_shape_and_dtype_valid(data_shape, data_dtype):
return None
intensity_calibration = Calibration.Calibration()
return DataAndMetadata.new_data_and_metadata(calculate_data(), intensity_calibration=intensity_calibration, dimensional_calibrations=data_and_metadata.dimensional_calibrations)
def function_rebin_2d(data_and_metadata: DataAndMetadata.DataAndMetadata, shape: DataAndMetadata.ShapeType) -> typing.Optional[DataAndMetadata.DataAndMetadata]:
data_and_metadata = DataAndMetadata.promote_ndarray(data_and_metadata)
height = int(shape[0])
width = int(shape[1])
data_shape = data_and_metadata.data_shape
data_dtype = data_and_metadata.data_dtype
dimensional_calibrations = data_and_metadata.dimensional_calibrations
if not Image.is_shape_and_dtype_valid(data_shape, data_dtype) or dimensional_calibrations is None:
return None
if not Image.is_shape_and_dtype_2d(data_shape, data_dtype):
return None
height = min(height, data_shape[0])
width = min(width, data_shape[1])
def calculate_data():
data = data_and_metadata.data
if not Image.is_data_valid(data):
return None
if not Image.is_data_2d(data):
return None
if data.shape[0] == height and data.shape[1] == width:
return data.copy()
shape = height, data.shape[0] // height, width, data.shape[1] // width
return data.reshape(shape).mean(-1).mean(1)
dimensions = height, width
rebinned_dimensional_calibrations = [Calibration.Calibration(dimensional_calibrations[i].offset, dimensional_calibrations[i].scale * data_shape[i] / dimensions[i], dimensional_calibrations[i].units) for i in range(len(dimensional_calibrations))]
return DataAndMetadata.new_data_and_metadata(calculate_data(), intensity_calibration=data_and_metadata.intensity_calibration, dimensional_calibrations=rebinned_dimensional_calibrations)
def function_resample_2d(data_and_metadata: DataAndMetadata.DataAndMetadata, shape: DataAndMetadata.ShapeType) -> typing.Optional[DataAndMetadata.DataAndMetadata]:
data_and_metadata = DataAndMetadata.promote_ndarray(data_and_metadata)
height = int(shape[0])
width = int(shape[1])
data_shape = data_and_metadata.data_shape
data_dtype = data_and_metadata.data_dtype
def calculate_data():
data = data_and_metadata.data
if not Image.is_data_valid(data):
return None
if not Image.is_data_2d(data):
return None
if data.shape[0] == height and data.shape[1] == width:
return data.copy()
return Image.scaled(data, (height, width))
dimensional_calibrations = data_and_metadata.dimensional_calibrations
if not Image.is_shape_and_dtype_valid(data_shape, data_dtype) or dimensional_calibrations is None:
return None
if not Image.is_shape_and_dtype_2d(data_shape, data_dtype):
return None
dimensions = height, width
resampled_dimensional_calibrations = [Calibration.Calibration(dimensional_calibrations[i].offset, dimensional_calibrations[i].scale * data_shape[i] / dimensions[i], dimensional_calibrations[i].units) for i in range(len(dimensional_calibrations))]
return DataAndMetadata.new_data_and_metadata(calculate_data(), intensity_calibration=data_and_metadata.intensity_calibration, dimensional_calibrations=resampled_dimensional_calibrations)
def function_warp(data_and_metadata: DataAndMetadata.DataAndMetadata, coordinates: typing.Sequence[DataAndMetadata.DataAndMetadata], order: int=1) -> typing.Optional[DataAndMetadata.DataAndMetadata]:
data_and_metadata = DataAndMetadata.promote_ndarray(data_and_metadata)
coords = numpy.moveaxis(numpy.dstack([coordinate.data for coordinate in coordinates]), -1, 0)
data = data_and_metadata._data_ex
if data_and_metadata.is_data_rgb:
rgb = numpy.zeros(tuple(data_and_metadata.dimensional_shape) + (3,), numpy.uint8)
rgb[..., 0] = scipy.ndimage.interpolation.map_coordinates(data[..., 0], coords, order=order)
rgb[..., 1] = scipy.ndimage.interpolation.map_coordinates(data[..., 1], coords, order=order)
rgb[..., 2] = scipy.ndimage.interpolation.map_coordinates(data[..., 2], coords, order=order)
return DataAndMetadata.new_data_and_metadata(rgb, dimensional_calibrations=data_and_metadata.dimensional_calibrations,
intensity_calibration=data_and_metadata.intensity_calibration)
elif data_and_metadata.is_data_rgba:
rgba = numpy.zeros(tuple(data_and_metadata.dimensional_shape) + (4,), numpy.uint8)
rgba[..., 0] = scipy.ndimage.interpolation.map_coordinates(data[..., 0], coords, order=order)
rgba[..., 1] = scipy.ndimage.interpolation.map_coordinates(data[..., 1], coords, order=order)
rgba[..., 2] = scipy.ndimage.interpolation.map_coordinates(data[..., 2], coords, order=order)
rgba[..., 3] = scipy.ndimage.interpolation.map_coordinates(data[..., 3], coords, order=order)
return DataAndMetadata.new_data_and_metadata(rgba, dimensional_calibrations=data_and_metadata.dimensional_calibrations,
intensity_calibration=data_and_metadata.intensity_calibration)
else:
return DataAndMetadata.new_data_and_metadata(scipy.ndimage.interpolation.map_coordinates(data, coords, order=order),
dimensional_calibrations=data_and_metadata.dimensional_calibrations,
intensity_calibration=data_and_metadata.intensity_calibration)
def calculate_coordinates_for_affine_transform(data_and_metadata: DataAndMetadata.DataAndMetadata, transformation_matrix: numpy.ndarray) -> typing.Sequence[DataAndMetadata.DataAndMetadata]:
data_and_metadata = DataAndMetadata.promote_ndarray(data_and_metadata)
if data_and_metadata.is_data_rgb_type:
assert len(data_and_metadata.data_shape) == 3
coords_shape = data_and_metadata.data_shape[:-1]
else:
assert len(data_and_metadata.data_shape) == 2
coords_shape = data_and_metadata.data_shape
assert transformation_matrix.ndim == 2
assert transformation_matrix.shape[0] == transformation_matrix.shape[1]
assert transformation_matrix.shape[0] in {len(coords_shape), len(coords_shape) + 1}
half_shape = (coords_shape[0] * 0.5, coords_shape[1] * 0.5)
coords = numpy.mgrid[0:coords_shape[0], 0:coords_shape[1]].astype(float)
coords[0] -= half_shape[0] - 0.5
coords[1] -= half_shape[1] - 0.5
if transformation_matrix.shape[0] == len(coords_shape) + 1:
coords = numpy.concatenate([numpy.ones((1,) + coords.shape[1:]), coords])
coords = coords[::-1, ...]
transformed = numpy.einsum('ij,ikm', transformation_matrix, coords)
transformed = transformed[::-1, ...]
if transformation_matrix.shape[0] == len(coords_shape) + 1:
transformed = transformed[1:, ...]
transformed[0] += half_shape[0] - 0.5
transformed[1] += half_shape[1] - 0.5
transformed = [DataAndMetadata.new_data_and_metadata(transformed[0]), DataAndMetadata.new_data_and_metadata(transformed[1])]
return transformed
def function_affine_transform(data_and_metadata: DataAndMetadata.DataAndMetadata, transformation_matrix: numpy.ndarray, order: int=1) -> typing.Optional[DataAndMetadata.DataAndMetadata]:
coordinates = calculate_coordinates_for_affine_transform(data_and_metadata, transformation_matrix)
return function_warp(data_and_metadata, coordinates, order=order)
def function_histogram(data_and_metadata: DataAndMetadata.DataAndMetadata, bins: int) -> typing.Optional[DataAndMetadata.DataAndMetadata]:
data_and_metadata = DataAndMetadata.promote_ndarray(data_and_metadata)
bins = int(bins)
data_shape = data_and_metadata.data_shape
data_dtype = data_and_metadata.data_dtype
dimensional_calibrations = data_and_metadata.dimensional_calibrations
if not Image.is_shape_and_dtype_valid(data_shape, data_dtype) or dimensional_calibrations is None:
return None
data = data_and_metadata.data
if not Image.is_data_valid(data):
return None
histogram_data = | numpy.histogram(data, bins=bins) | numpy.histogram |
import matplotlib
import code_stats as cs
import copy
import datetime
import matplotlib.pyplot as plt
import numpy as np
import os
import pandas
from code_stats import GithubStats, TravisStats
import pandas.plotting
pandas.plotting.register_matplotlib_converters()
# repos = {
# "prisms-center/phaseField": "PRISMS-PF",
# "prisms-center/plasticity": "Plasticity",
# "prisms-center/CASMcode": "CASM",
# "prisms-center/pbs": "PRISMS pbs",
# "prisms-center/prisms_jobs": "PRISMS Jobs",
# "prisms-center/IntegrationTools": "IntegrationTools",
# "dftfeDevelopers/dftfe": "DFT-FE"}
area_plot_fmt = [
#("prisms-center/IntegrationTools", "IntegrationTools", 'red'),
("prisms-center/prisms_jobs", "PRISMS Jobs", 'orange'),
("prisms-center/CASMcode", "CASM", 'yellow'),
("prisms-center/phaseField", "PRISMS-PF", 'green'),
("prisms-center/plasticity", "Plasticity", 'blue'),
("dftfeDevelopers/dftfe", "DFT-FE", 'purple')
]
legend_values = [val[1] for val in area_plot_fmt]
legend_values.reverse()
reference_weeks = [ datetime.date.fromisoformat(x) for x in [
'2020-08-28', # before
'2020-09-04',
'2020-09-11',
'2020-09-18',
'2020-09-25',
'2020-10-02',
'2020-10-09',
'2020-10-16',
'2021-05-28', #after
'2021-06-04',
'2021-06-11',
'2021-06-18',
'2021-06-25',
'2021-07-02',
'2021-07-09',
'2021-07-16']
]
replacement_weeks_first = datetime.date.fromisoformat('2020-10-23')
replacement_weeks_last = datetime.date.fromisoformat('2021-05-21')
def sql_iter(curs, fetchsize=1000):
""" Iterate over the results of a SELECT statement """
while True:
records = curs.fetchmany(fetchsize)
if not records:
break
else:
for r in records:
yield r
def get_first_day(db):
return db.conn.execute("SELECT day FROM stats ORDER BY day").fetchone()['day']
def get_last_day(db):
return db.conn.execute("SELECT day FROM stats ORDER BY day DESC").fetchone()['day']
def get_weekly_dates(db, day_index=4):
date = cs.fromordinal(get_first_day(db))
while date.weekday() != day_index:
date += datetime.timedelta(days=1)
dates = [date]
last_date = cs.fromordinal(get_last_day(db))
while True:
date += datetime.timedelta(weeks=1)
dates.append(date)
if date > last_date:
break
return dates
def get_weekly_stats(curs, dates, col):
i = 0
result = [0] * len(dates)
count = 0
day_i = cs.toordinal(dates[i])
for rec in sql_iter(curs):
try:
day = rec['day']
if rec[col] is None:
n = 0
else:
n = rec[col]
if day <= day_i:
count += n
else:
result[i] = count
count = n
while day > day_i:
i += 1
day_i = cs.toordinal(dates[i])
if len(dates) == i:
return result
except Exception as e:
print(dict(rec))
raise e
return result
def get_all_weekly_stats(db, dates, col, estimate_missing = True):
repo_names = [entry[0] for entry in area_plot_fmt]
df = pandas.DataFrame(index=dates, columns=db.list_repo_names())
for repo_name in db.list_repo_names():
curs = db.conn.cursor()
curs.execute("SELECT day, " + col + " FROM stats WHERE repo_id=? ORDER BY day", ( db.get_repo_id(repo_name),))
weekly_unique_views = get_weekly_stats(curs, dates, col)
curs.close()
df.loc[:, repo_name] = weekly_unique_views
if estimate_missing:
reference_weeks_mean = np.mean(df.loc[reference_weeks, repo_name])
for index, row in df.iterrows():
if index >= replacement_weeks_first and index <= replacement_weeks_last:
df.loc[index,repo_name] = reference_weeks_mean
return df
def area_plot(df, title, fontsize=None, saveas=None):
fig, ax = plt.subplots(figsize=(10,6))
plt.tick_params(axis='both', which='major', labelsize=fontsize)
fig.autofmt_xdate()
cumsum_bottom = | np.zeros(df.shape[0]) | numpy.zeros |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Feb 4 11:48:28 2019
A set of baseline correction algorithms
@author: <NAME>
"""
import numpy as np
from scipy import sparse
from scipy.spatial import ConvexHull
from scipy.interpolate import interp1d
from scipy.sparse.linalg import spsolve
from multiprocessing.pool import Pool, ThreadPool
import os
import dill
def straight(x, y):
"""
Return a straight line baseline correction.
x: wavenumbers, sorted either way
y: spectrum or spectra at those wavenumbers; shape (..., wavenumber)
progressCallback(int a, int b): callback function called to indicated that the processing
is complete to a fraction a/b.
Returns: baseline of the spectrum, measured at the same points
"""
# Create baseline using linear interpolation between vertices
if x[0] < x[-1]:
return interp1d(x[[0,-1]], y[...,[0,-1]], assume_sorted=True)(x)
return interp1d(x[[-1,0]], y[...,[-1,0]], assume_sorted=True)(x)
def apply_packed_function_for_map(dumped):
"Unpack dumped function as target function and call it with arguments."
return dill.loads(dumped[0])(dumped[1])
def pack_function_for_map(target_function, items):
dumped_function = dill.dumps(target_function)
dumped_items = [(dumped_function, item) for item in items]
return apply_packed_function_for_map, dumped_items
def mp_bgcorrection(func, y, lim_single=8, lim_tp=40, progressCallback=None):
if len(y) < 1:
return y.copy()
if y.ndim < 2:
return func(y)
if hasattr(os, 'sched_getaffinity'):
cpus = len(os.sched_getaffinity(os.getpid()))
else:
cpus = os.cpu_count()
cpus = min(cpus, len(y))
if cpus == 1 or len(y) <= lim_single:
cpus = 1
it = map(func, y)
elif len(y) <= lim_tp:
cpus = min(cpus, 3)
pool = ThreadPool(cpus)
it = pool.imap(func, y, chunksize=5)
else:
pool = Pool(cpus)
it = pool.imap(*pack_function_for_map(func, y), chunksize=10)
ret = | np.empty_like(y) | numpy.empty_like |
import _pickle, numpy as np, itertools as it
from time import perf_counter
# from cppimport import import_hook
#
# # import cppimport
#
# # cppimport.set_quiet(False)
#
import rpxdock as rp
from rpxdock.bvh import bvh_test
from rpxdock.bvh import BVH, bvh
import rpxdock.homog as hm
def test_bvh_isect_cpp():
assert bvh_test.TEST_bvh_test_isect()
def test_bvh_isect_fixed():
# print()
mindist = 0.01
totbvh, totnaive = 0, 0
for i in range(10):
xyz1 = np.random.rand(1000, 3) + [0.9, 0.9, 0]
xyz2 = np.random.rand(1000, 3)
tcre = perf_counter()
bvh1 = BVH(xyz1)
bvh2 = BVH(xyz2)
tcre = perf_counter() - tcre
assert len(bvh1) == 1000
pos1 = hm.htrans([0.9, 0.9, 0.9])
pos2 = np.eye(4)
tbvh = perf_counter()
clash1 = bvh.bvh_isect_fixed(bvh1, bvh2, mindist)
tbvh = perf_counter() - tbvh
tn = perf_counter()
clash2 = bvh.naive_isect_fixed(bvh1, bvh2, mindist)
tn = perf_counter() - tn
assert clash1 == clash2
# print(f"{i:3} clash {clash1:1} {tn / tbvh:8.2f}, {tn:1.6f}, {tbvh:1.6f}")
totbvh += tbvh
totnaive += tn
print("total times", totbvh, totnaive / totbvh, totnaive)
def test_bvh_isect():
t = rp.Timer().start()
N1, N2 = 10, 10
N = N1 * N2
mindist = 0.04
nclash = 0
for outer in range(N1):
xyz1 = np.random.rand(1250, 3) - [0.5, 0.5, 0.5]
xyz2 = np.random.rand(1250, 3) - [0.5, 0.5, 0.5]
pos1 = hm.rand_xform(N2, cart_sd=0.8)
pos2 = hm.rand_xform(N2, cart_sd=0.8)
t.checkpoint('init')
bvh1 = BVH(xyz1)
bvh2 = BVH(xyz2)
t.checkpoint('BVH')
clash = list()
for inner in range(N2):
clash1 = bvh.bvh_isect(bvh1=bvh1, bvh2=bvh2, pos1=pos1[inner], pos2=pos2[inner],
mindist=mindist)
t.checkpoint('bvh_isect')
clash2 = bvh.naive_isect(bvh1, bvh2, pos1[inner], pos2[inner], mindist)
t.checkpoint('naive_isect')
assert clash1 == clash2
clash.append(clash1)
clashvec = bvh.bvh_isect_vec(bvh1, bvh2, pos1, pos2, mindist)
t.checkpoint('bvh_isect_vec')
assert np.all(clashvec == clash)
nclash += sum(clash)
assert clashvec[1] == bvh.bvh_isect_vec(bvh1, bvh2, pos1[1], pos2[1], mindist)
bvh.bvh_isect_vec(bvh1, bvh2, pos1, pos2[1], mindist) # ?? make sure api works?
bvh.bvh_isect_vec(bvh1, bvh2, pos1[1], pos2, mindist)
print(
f"Ngeom {N1:,} Npos {N2:,} isect {nclash/N:4.2f} bvh: {int(N/t.sum.bvh_isect):,}/s",
f"bvh_vec {int(N/t.sum.bvh_isect_vec):,} fastnaive {int(N/t.sum.naive_isect):,}/s",
f"ratio {int(t.sum.naive_isect/t.sum.bvh_isect_vec):,}x",
)
def test_bvh_isect_fixed_range():
N1, N2 = 10, 10
N = N1 * N2
mindist = 0.04
nclash = 0
for outer in range(N1):
xyz1 = np.random.rand(1000, 3) - [0.5, 0.5, 0.5]
xyz2 = np.random.rand(1000, 3) - [0.5, 0.5, 0.5]
bvh1 = BVH(xyz1)
bvh2 = BVH(xyz2)
bvh1_half = BVH(xyz1[250:750])
bvh2_half = BVH(xyz2[250:750])
pos1 = hm.rand_xform(N2, cart_sd=0.5)
pos2 = hm.rand_xform(N2, cart_sd=0.5)
isect1 = bvh.bvh_isect_vec(bvh1, bvh2, pos1, pos2, mindist)
isect2, clash = bvh.bvh_isect_fixed_range_vec(bvh1, bvh2, pos1, pos2, mindist)
assert np.all(isect1 == isect2)
bounds = [250], [749], [250], [749]
isect1 = bvh.bvh_isect_vec(bvh1_half, bvh2_half, pos1, pos2, mindist)
isect2, clash = bvh.bvh_isect_fixed_range_vec(bvh1, bvh2, pos1, pos2, mindist, *bounds)
assert np.all(isect1 == isect2)
def test_bvh_min_cpp():
assert bvh_test.TEST_bvh_test_min()
def test_bvh_min_dist_fixed():
xyz1 = np.random.rand(5000, 3) + [0.9, 0.9, 0.0]
xyz2 = np.random.rand(5000, 3)
tcre = perf_counter()
bvh1 = BVH(xyz1)
bvh2 = BVH(xyz2)
tcre = perf_counter() - tcre
tbvh = perf_counter()
d, i1, i2 = bvh.bvh_min_dist_fixed(bvh1, bvh2)
tbvh = perf_counter() - tbvh
dtest = np.linalg.norm(xyz1[i1] - xyz2[i2])
assert np.allclose(d, dtest, atol=1e-6)
# tnp = perf_counter()
# dnp = np.min(np.linalg.norm(xyz1[:, None] - xyz2[None], axis=2))
# tnp = perf_counter() - tnp
tn = perf_counter()
dn = bvh.naive_min_dist_fixed(bvh1, bvh2)
tn = perf_counter() - tn
print()
print("from bvh: ", d)
print("from naive:", dn)
assert np.allclose(dn, d, atol=1e-6)
print(f"tnaivecpp {tn:5f} tbvh {tbvh:5f} tbvhcreate {tcre:5f}")
print("bvh acceleration vs naive", tn / tbvh)
# assert tn / tbvh > 100
def test_bvh_min_dist():
xyz1 = np.random.rand(1000, 3) - [0.5, 0.5, 0.5]
xyz2 = np.random.rand(1000, 3) - [0.5, 0.5, 0.5]
tcre = perf_counter()
bvh1 = BVH(xyz1)
bvh2 = BVH(xyz2)
tcre = perf_counter() - tcre
# print()
totbvh, totnaive = 0, 0
N = 10
pos1 = hm.rand_xform(N, cart_sd=1)
pos2 = hm.rand_xform(N, cart_sd=1)
dis = list()
for i in range(N):
tbvh = perf_counter()
d, i1, i2 = bvh.bvh_min_dist(bvh1, bvh2, pos1[i], pos2[i])
tbvh = perf_counter() - tbvh
dtest = np.linalg.norm(pos1[i] @ hm.hpoint(xyz1[i1]) - pos2[i] @ hm.hpoint(xyz2[i2]))
assert np.allclose(d, dtest, atol=1e-6)
tn = perf_counter()
dn = bvh.naive_min_dist(bvh1, bvh2, pos1[i], pos2[i])
tn = perf_counter() - tn
assert np.allclose(dn, d, atol=1e-6)
dis.append((d, i1, i2))
# print(
# f"tnaivecpp {tn:1.6f} tbvh {tbvh:1.6f} tcpp/tbvh {tn/tbvh:8.1f}",
# np.linalg.norm(pos1[:3, 3]),
# dtest - d,
# )
totnaive += tn
totbvh += tbvh
d, i1, i2 = bvh.bvh_min_dist_vec(bvh1, bvh2, pos1, pos2)
for a, b, c, x in zip(d, i1, i2, dis):
assert a == x[0]
assert b == x[1]
assert c == x[2]
print(
"total times",
totbvh / N * 1000,
"ms",
totnaive / totbvh,
totnaive,
f"tcre {tcre:2.4f}",
)
def test_bvh_min_dist_floormin():
xyz1 = np.random.rand(1000, 3) - [0.5, 0.5, 0.5]
xyz2 = np.random.rand(1000, 3) - [0.5, 0.5, 0.5]
tcre = perf_counter()
bvh1 = BVH(xyz1)
bvh2 = BVH(xyz2)
tcre = perf_counter() - tcre
# print()
totbvh, totnaive = 0, 0
N = 10
for i in range(N):
pos1 = hm.rand_xform(cart_sd=1)
pos2 = hm.rand_xform(cart_sd=1)
tbvh = perf_counter()
d, i1, i2 = bvh.bvh_min_dist(bvh1, bvh2, pos1, pos2)
tbvh = perf_counter() - tbvh
dtest = np.linalg.norm(pos1 @ hm.hpoint(xyz1[i1]) - pos2 @ hm.hpoint(xyz2[i2]))
assert np.allclose(d, dtest, atol=1e-6)
tn = perf_counter()
dn = bvh.naive_min_dist(bvh1, bvh2, pos1, pos2)
tn = perf_counter() - tn
assert np.allclose(dn, d, atol=1e-6)
# print(
# f"tnaivecpp {tn:1.6f} tbvh {tbvh:1.6f} tcpp/tbvh {tn/tbvh:8.1f}",
# np.linalg.norm(pos1[:3, 3]),
# dtest - d,
# )
totnaive += tn
totbvh += tbvh
print(
"total times",
totbvh / N * 1000,
"ms",
totnaive / totbvh,
totnaive,
f"tcre {tcre:2.4f}",
)
def test_bvh_slide_single_inline():
bvh1 = BVH([[-10, 0, 0]])
bvh2 = BVH([[0, 0, 0]])
d = bvh.bvh_slide(bvh1, bvh2, np.eye(4), np.eye(4), rad=1.0, dirn=[1, 0, 0])
assert d == 8
# moves xyz1 to -2,0,0
# should always come in from "infinity" from -direction
bvh1 = BVH([[10, 0, 0]])
bvh2 = BVH([[0, 0, 0]])
d = bvh.bvh_slide(bvh1, bvh2, np.eye(4), np.eye(4), rad=1.0, dirn=[1, 0, 0])
assert d == -12
# also moves xyz1 to -2,0,0
for i in range(100):
np.random.seed(i)
dirn = np.array([np.random.randn(), 0, 0])
dirn /= np.linalg.norm(dirn)
rad = np.abs(np.random.randn() / 10)
xyz1 = np.array([[np.random.randn(), 0, 0]])
xyz2 = np.array([[np.random.randn(), 0, 0]])
bvh1 = BVH(xyz1)
bvh2 = BVH(xyz2)
d = bvh.bvh_slide(bvh1, bvh2, np.eye(4), np.eye(4), rad=rad, dirn=dirn)
xyz1 += d * dirn
assert np.allclose(np.linalg.norm(xyz1 - xyz2), 2 * rad, atol=1e-4)
def test_bvh_slide_single():
nmiss = 0
for i in range(100):
# np.random.seed(i)
dirn = np.random.randn(3)
dirn /= np.linalg.norm(dirn)
rad = np.abs(np.random.randn())
xyz1 = np.random.randn(1, 3)
xyz2 = np.random.randn(1, 3)
bvh1 = BVH(xyz1)
bvh2 = BVH(xyz2)
d = bvh.bvh_slide(bvh1, bvh2, np.eye(4), np.eye(4), rad=rad, dirn=dirn)
if d < 9e8:
xyz1 += d * dirn
assert np.allclose(np.linalg.norm(xyz1 - xyz2), 2 * rad, atol=1e-4)
else:
nmiss += 1
delta = xyz2 - xyz1
d0 = delta.dot(dirn)
dperp2 = np.sum(delta * delta) - d0 * d0
target_d2 = 4 * rad**2
assert target_d2 < dperp2
print("nmiss", nmiss, nmiss / 1000)
def test_bvh_slide_single_xform():
nmiss = 0
for i in range(1000):
dirn = np.random.randn(3)
dirn /= np.linalg.norm(dirn)
rad = np.abs(np.random.randn() * 2.0)
xyz1 = np.random.randn(1, 3)
xyz2 = np.random.randn(1, 3)
bvh1 = BVH(xyz1)
bvh2 = BVH(xyz2)
pos1 = hm.rand_xform()
pos2 = hm.rand_xform()
d = bvh.bvh_slide(bvh1, bvh2, pos1, pos2, rad=rad, dirn=dirn)
if d < 9e8:
p1 = (pos1 @ hm.hpoint(xyz1[0]))[:3] + d * dirn
p2 = (pos2 @ hm.hpoint(xyz2[0]))[:3]
assert np.allclose(np.linalg.norm(p1 - p2), 2 * rad, atol=1e-4)
else:
nmiss += 1
p2 = pos2 @ hm.hpoint(xyz2[0])
p1 = pos1 @ hm.hpoint(xyz1[0])
delta = p2 - p1
d0 = delta[:3].dot(dirn)
dperp2 = np.sum(delta * delta) - d0 * d0
target_d2 = 4 * rad**2
assert target_d2 < dperp2
print("nmiss", nmiss, nmiss / 1000)
def test_bvh_slide_whole():
# timings wtih -Ofast
# slide test 10,000 iter bvhslide float: 16,934/s double: 16,491/s bvhmin 17,968/s fracmiss: 0.0834
# np.random.seed(0)
N1, N2 = 2, 10
totbvh, totbvhf, totmin = 0, 0, 0
nmiss = 0
for j in range(N1):
xyz1 = np.random.rand(5000, 3) - [0.5, 0.5, 0.5]
xyz2 = np.random.rand(5000, 3) - [0.5, 0.5, 0.5]
# tcre = perf_counter()
bvh1 = BVH(xyz1)
bvh2 = BVH(xyz2)
# bvh1f = BVH_32bit(xyz1)
# bvh2f = BVH_32bit(xyz2)
# tcre = perf_counter() - tcre
pos1 = hm.rand_xform(N2, cart_sd=0.5)
pos2 = hm.rand_xform(N2, cart_sd=0.5)
dirn = np.random.randn(3)
dirn /= np.linalg.norm(dirn)
radius = 0.001 + np.random.rand() / 10
slides = list()
for i in range(N2):
tbvh = perf_counter()
dslide = bvh.bvh_slide(bvh1, bvh2, pos1[i], pos2[i], radius, dirn)
tbvh = perf_counter() - tbvh
tbvhf = perf_counter()
# dslide = bvh.bvh_slide_32bit(bvh1f, bvh2f, pos1[i], pos2[i], radius, dirn)
tbvhf = perf_counter() - tbvhf
slides.append(dslide)
if dslide > 9e8:
tn = perf_counter()
dn, i, j = bvh.bvh_min_dist(bvh1, bvh2, pos1[i], pos2[i])
tn = perf_counter() - tn
assert dn > 2 * radius
nmiss += 1
else:
tmp = hm.htrans(dirn * dslide) @ pos1[i]
tn = perf_counter()
dn, i, j = bvh.bvh_min_dist(bvh1, bvh2, tmp, pos2[i])
tn = perf_counter() - tn
if not np.allclose(dn, 2 * radius, atol=1e-6):
print(dn, 2 * radius)
assert np.allclose(dn, 2 * radius, atol=1e-6)
# print(
# i,
# f"tnaivecpp {tn:1.6f} tbvh {tbvh:1.6f} tcpp/tbvh {tn/tbvh:8.1f}",
# np.linalg.norm(pos1[:3, 3]),
# dslide,
# )
totmin += tn
totbvh += tbvh
totbvhf += tbvhf
slides2 = bvh.bvh_slide_vec(bvh1, bvh2, pos1, pos2, radius, dirn)
assert np.allclose(slides, slides2)
N = N1 * N2
print(
f"slide test {N:,} iter bvhslide double: {int(N/totbvh):,}/s bvhmin {int(N/totmin):,}/s",
# f"slide test {N:,} iter bvhslide float: {int(N/totbvhf):,}/s double: {int(N/totbvh):,}/s bvhmin {int(N/totmin):,}/s",
f"fracmiss: {nmiss/N}",
)
def test_collect_pairs_simple():
print("test_collect_pairs_simple")
bufbvh = -np.ones((100, 2), dtype="i4")
bufnai = -np.ones((100, 2), dtype="i4")
bvh1 = BVH([[0, 0, 0], [0, 2, 0]])
bvh2 = BVH([[0.9, 0, 0], [0.9, 2, 0]])
assert len(bvh1) == 2
mindist = 1.0
pos1 = np.eye(4)
pos2 = np.eye(4)
pbvh, o = bvh.bvh_collect_pairs(bvh1, bvh2, pos1, pos2, mindist, bufbvh)
nnai = bvh.naive_collect_pairs(bvh1, bvh2, pos1, pos2, mindist, bufnai)
assert not o
print(pbvh.shape)
assert len(pbvh) == 2 and nnai == 2
assert np.all(pbvh == [[0, 0], [1, 1]])
assert np.all(bufnai[:nnai] == [[0, 0], [1, 1]])
pos1 = hm.htrans([0, 2, 0])
pbvh, o = bvh.bvh_collect_pairs(bvh1, bvh2, pos1, pos2, mindist, bufbvh)
nnai = bvh.naive_collect_pairs(bvh1, bvh2, pos1, pos2, mindist, bufnai)
assert not o
assert len(pbvh) == 1 and nnai == 1
assert np.all(pbvh == [[0, 1]])
assert np.all(bufnai[:nnai] == [[0, 1]])
pos1 = hm.htrans([0, -2, 0])
pbvh, o = bvh.bvh_collect_pairs(bvh1, bvh2, pos1, pos2, mindist, bufbvh)
nnai = bvh.naive_collect_pairs(bvh1, bvh2, pos1, pos2, mindist, bufnai)
assert not o
assert len(pbvh) == 1 and nnai == 1
assert np.all(pbvh == [[1, 0]])
assert np.all(bufnai[:nnai] == [[1, 0]])
def test_collect_pairs_simple_selection():
print("test_collect_pairs_simple_selection")
bufbvh = -np.ones((100, 2), dtype="i4")
bufnai = -np.ones((100, 2), dtype="i4")
crd1 = [[0, 0, 0], [0, 0, 0], [0, 2, 0], [0, 0, 0]]
crd2 = [[0, 0, 0], [0.9, 0, 0], [0, 0, 0], [0.9, 2, 0]]
mask1 = [1, 0, 1, 0]
mask2 = [0, 1, 0, 1]
bvh1 = BVH(crd1, mask1)
bvh2 = BVH(crd2, mask2)
assert len(bvh1) == 2
assert np.allclose(bvh1.radius(), 1.0, atol=1e-6)
assert np.allclose(bvh1.center(), [0, 1, 0], atol=1e-6)
mindist = 1.0
pos1 = np.eye(4)
pos2 = np.eye(4)
pbvh, o = bvh.bvh_collect_pairs(bvh1, bvh2, pos1, pos2, mindist, bufbvh)
assert not o
nnai = bvh.naive_collect_pairs(bvh1, bvh2, pos1, pos2, mindist, bufnai)
assert len(pbvh) == 2 and nnai == 2
assert np.all(pbvh == [[0, 1], [2, 3]])
assert np.all(bufnai[:nnai] == [[0, 1], [2, 3]])
pos1 = hm.htrans([0, 2, 0])
pbvh, o = bvh.bvh_collect_pairs(bvh1, bvh2, pos1, pos2, mindist, bufbvh)
assert not o
nnai = bvh.naive_collect_pairs(bvh1, bvh2, pos1, pos2, mindist, bufnai)
assert len(pbvh) == 1 and nnai == 1
assert np.all(pbvh == [[0, 3]])
assert np.all(bufnai[:nnai] == [[0, 3]])
pos1 = hm.htrans([0, -2, 0])
pbvh, o = bvh.bvh_collect_pairs(bvh1, bvh2, pos1, pos2, mindist, bufbvh)
assert not o
nnai = bvh.naive_collect_pairs(bvh1, bvh2, pos1, pos2, mindist, bufnai)
assert len(pbvh) == 1 and nnai == 1
assert np.all(pbvh == [[2, 1]])
assert np.all(bufnai[:nnai] == [[2, 1]])
def test_collect_pairs():
N1, N2 = 1, 50
N = N1 * N2
Npts = 500
totbvh, totbvhf, totmin = 0, 0, 0
totbvh, totnai, totct, ntot = 0, 0, 0, 0
bufbvh = -np.ones((Npts * Npts, 2), dtype="i4")
bufnai = -np.ones((Npts * Npts, 2), dtype="i4")
for j in range(N1):
xyz1 = np.random.rand(Npts, 3) - [0.5, 0.5, 0.5]
xyz2 = np.random.rand(Npts, 3) - [0.5, 0.5, 0.5]
bvh1 = BVH(xyz1)
bvh2 = BVH(xyz2)
pos1, pos2 = list(), list()
while 1:
x1 = hm.rand_xform(cart_sd=0.5)
x2 = hm.rand_xform(cart_sd=0.5)
d = np.linalg.norm(x1[:, 3] - x2[:, 3])
if 0.8 < d < 1.3:
pos1.append(x1)
pos2.append(x2)
if len(pos1) == N2:
break
pos1 = np.stack(pos1)
pos2 = np.stack(pos2)
pairs = list()
mindist = 0.002 + np.random.rand() / 10
for i in range(N2):
tbvh = perf_counter()
pbvh, o = bvh.bvh_collect_pairs(bvh1, bvh2, pos1[i], pos2[i], mindist, bufbvh)
tbvh = perf_counter() - tbvh
assert not o
tnai = perf_counter()
nnai = bvh.naive_collect_pairs(bvh1, bvh2, pos1[i], pos2[i], mindist, bufnai)
tnai = perf_counter() - tnai
tct = perf_counter()
nct = bvh.bvh_count_pairs(bvh1, bvh2, pos1[i], pos2[i], mindist)
tct = perf_counter() - tct
ntot += nct
assert nct == len(pbvh)
totnai += 1
pairs.append(pbvh.copy())
totbvh += tbvh
totnai += tnai
totct += tct
assert len(pbvh) == nnai
if len(pbvh) == 0:
continue
o = np.lexsort((pbvh[:, 1], pbvh[:, 0]))
pbvh[:] = pbvh[:][o]
o = np.lexsort((bufnai[:nnai, 1], bufnai[:nnai, 0]))
bufnai[:nnai] = bufnai[:nnai][o]
assert np.all(pbvh == bufnai[:nnai])
pair1 = pos1[i] @ hm.hpoint(xyz1[pbvh[:, 0]])[..., None]
pair2 = pos2[i] @ hm.hpoint(xyz2[pbvh[:, 1]])[..., None]
dpair = np.linalg.norm(pair2 - pair1, axis=1)
assert np.max(dpair) <= mindist
pcount = bvh.bvh_count_pairs_vec(bvh1, bvh2, pos1, pos2, mindist)
assert np.all(pcount == [len(x) for x in pairs])
pairs2, lbub = bvh.bvh_collect_pairs_vec(bvh1, bvh2, pos1, pos2, mindist)
for i, p in enumerate(pairs):
lb, ub = lbub[i]
assert np.all(pairs2[lb:ub] == pairs[i])
x, y = bvh.bvh_collect_pairs_vec(bvh1, bvh2, pos1[:3], pos2[0], mindist)
assert len(y) == 3
x, y = bvh.bvh_collect_pairs_vec(bvh1, bvh2, pos1[0], pos2[:5], mindist)
assert len(y) == 5
print(
f"collect test {N:,} iter bvh {int(N/totbvh):,}/s naive {int(N/totnai):,}/s ratio {totnai/totbvh:7.2f} count-only {int(N/totct):,}/s avg cnt {ntot/N}"
)
def test_collect_pairs_range():
N1, N2 = 1, 500
N = N1 * N2
Npts = 1000
for j in range(N1):
xyz1 = np.random.rand(Npts, 3) - [0.5, 0.5, 0.5]
xyz2 = np.random.rand(Npts, 3) - [0.5, 0.5, 0.5]
bvh1 = BVH(xyz1)
bvh2 = BVH(xyz2)
pos1, pos2 = list(), list()
while 1:
x1 = hm.rand_xform(cart_sd=0.5)
x2 = hm.rand_xform(cart_sd=0.5)
d = np.linalg.norm(x1[:, 3] - x2[:, 3])
if 0.8 < d < 1.3:
pos1.append(x1)
pos2.append(x2)
if len(pos1) == N2:
break
pos1 = np.stack(pos1)
pos2 = np.stack(pos2)
pairs = list()
mindist = 0.002 + np.random.rand() / 10
pairs, lbub = bvh.bvh_collect_pairs_vec(bvh1, bvh2, pos1, pos2, mindist)
rpairs, rlbub = bvh.bvh_collect_pairs_range_vec(bvh1, bvh2, pos1, pos2, mindist)
assert np.all(lbub == rlbub)
assert np.all(pairs == rpairs)
rpairs, rlbub = bvh.bvh_collect_pairs_range_vec(bvh1, bvh2, pos1, pos2, mindist, [250],
[750])
assert len(rlbub) == len(pos1)
assert np.all(rpairs[:, 0] >= 250)
assert np.all(rpairs[:, 0] <= 750)
filt_pairs = pairs[np.logical_and(pairs[:, 0] >= 250, pairs[:, 0] <= 750)]
# assert np.all(filt_pairs == rpairs) # sketchy???
assert np.allclose(np.unique(filt_pairs, axis=1), np.unique(rpairs, axis=1))
rpairs, rlbub = bvh.bvh_collect_pairs_range_vec(bvh1, bvh2, pos1, pos2, mindist, [600],
[1000], -1, [100], [400], -1)
assert len(rlbub) == len(pos1)
assert np.all(rpairs[:, 0] >= 600)
assert np.all(rpairs[:, 0] <= 1000)
assert np.all(rpairs[:, 1] >= 100)
assert np.all(rpairs[:, 1] <= 400)
filt_pairs = pairs[(pairs[:, 0] >= 600) * (pairs[:, 0] <= 1000) * (pairs[:, 1] >= 100) *
(pairs[:, 1] <= 400)]
assert np.all(filt_pairs == rpairs) # sketchy???
assert np.allclose(np.unique(filt_pairs, axis=1), np.unique(rpairs, axis=1))
def test_collect_pairs_range_sym():
# np.random.seed(132)
N1, N2 = 5, 100
N = N1 * N2
Npts = 1000
for j in range(N1):
xyz1 = np.random.rand(Npts, 3) - [0.5, 0.5, 0.5]
xyz2 = np.random.rand(Npts, 3) - [0.5, 0.5, 0.5]
bvh1 = BVH(xyz1)
bvh2 = BVH(xyz2)
pos1, pos2 = list(), list()
while 1:
x1 = hm.rand_xform(cart_sd=0.5)
x2 = hm.rand_xform(cart_sd=0.5)
d = np.linalg.norm(x1[:, 3] - x2[:, 3])
if 0.8 < d < 1.3:
pos1.append(x1)
pos2.append(x2)
if len(pos1) == N2:
break
pos1 = np.stack(pos1)
pos2 = np.stack(pos2)
pairs = list()
mindist = 0.002 + np.random.rand() / 10
pairs, lbub = bvh.bvh_collect_pairs_vec(bvh1, bvh2, pos1, pos2, mindist)
rpairs, rlbub = bvh.bvh_collect_pairs_range_vec(bvh1, bvh2, pos1, pos2, mindist)
assert np.all(lbub == rlbub)
assert np.all(pairs == rpairs)
bounds = [100], [400], len(xyz1) // 2
rpairs, rlbub = bvh.bvh_collect_pairs_range_vec(bvh1, bvh2, pos1, pos2, mindist, *bounds)
assert len(rlbub) == len(pos1)
assert np.all(
np.logical_or(np.logical_and(100 <= rpairs[:, 0], rpairs[:, 0] <= 400),
np.logical_and(600 <= rpairs[:, 0], rpairs[:, 0] <= 900)))
filt_pairs = pairs[np.logical_or(np.logical_and(100 <= pairs[:, 0], pairs[:, 0] <= 400),
np.logical_and(600 <= pairs[:, 0], pairs[:, 0] <= 900))]
assert np.allclose(np.unique(filt_pairs, axis=1), np.unique(rpairs, axis=1))
bounds = [100], [400], len(xyz1) // 2, [20], [180], len(xyz1) // 5
rpairs, rlbub = bvh.bvh_collect_pairs_range_vec(bvh1, bvh2, pos1, pos2, mindist, *bounds)
def awful(p):
return np.logical_and(
np.logical_or(np.logical_and(100 <= p[:, 0], p[:, 0] <= 400),
np.logical_and(600 <= p[:, 0], p[:, 0] <= 900)),
np.logical_or(
np.logical_and(+20 <= p[:, 1], p[:, 1] <= 180),
np.logical_or(
np.logical_and(220 <= p[:, 1], p[:, 1] <= 380),
np.logical_or(
np.logical_and(420 <= p[:, 1], p[:, 1] <= 580),
np.logical_or(np.logical_and(620 <= p[:, 1], p[:, 1] <= 780),
np.logical_and(820 <= p[:, 1], p[:, 1] <= 980))))))
assert len(rlbub) == len(pos1)
assert np.all(awful(rpairs))
filt_pairs = pairs[awful(pairs)]
assert np.all(filt_pairs == rpairs) # sketchy???
assert np.allclose(np.unique(filt_pairs, axis=1), np.unique(rpairs, axis=1))
def test_slide_collect_pairs():
# timings wtih -Ofast
# slide test 10,000 iter bvhslide float: 16,934/s double: 16,491/s bvhmin 17,968/s fracmiss: 0.0834
# np.random.seed(0)
N1, N2 = 2, 50
Npts = 5000
totbvh, totbvhf, totcol, totmin = 0, 0, 0, 0
nhit = 0
buf = -np.ones((Npts * Npts, 2), dtype="i4")
for j in range(N1):
xyz1 = np.random.rand(Npts, 3) - [0.5, 0.5, 0.5]
xyz2 = np.random.rand(Npts, 3) - [0.5, 0.5, 0.5]
xyzcol1 = xyz1[:int(Npts / 5)]
xyzcol2 = xyz2[:int(Npts / 5)]
# tcre = perf_counter()
bvh1 = BVH(xyz1)
bvh2 = BVH(xyz2)
bvhcol1 = BVH(xyzcol1)
bvhcol2 = BVH(xyzcol2)
# tcre = perf_counter() - tcre
for i in range(N2):
dirn = np.random.randn(3)
dirn /= np.linalg.norm(dirn)
radius = 0.001 + np.random.rand() / 10
pairdis = 3 * radius
pos1 = hm.rand_xform(cart_sd=0.5)
pos2 = hm.rand_xform(cart_sd=0.5)
tbvh = perf_counter()
dslide = bvh.bvh_slide(bvh1, bvh2, pos1, pos2, radius, dirn)
tbvh = perf_counter() - tbvh
if dslide > 9e8:
tn = perf_counter()
dn, i, j = bvh.bvh_min_dist(bvh1, bvh2, pos1, pos2)
tn = perf_counter() - tn
assert dn > 2 * radius
else:
nhit += 1
pos1 = hm.htrans(dirn * dslide) @ pos1
tn = perf_counter()
dn, i, j = bvh.bvh_min_dist(bvh1, bvh2, pos1, pos2)
tn = perf_counter() - tn
if not np.allclose(dn, 2 * radius, atol=1e-6):
print(dn, 2 * radius)
assert np.allclose(dn, 2 * radius, atol=1e-6)
tcol = perf_counter()
pair, o = bvh.bvh_collect_pairs(bvhcol1, bvhcol2, pos1, pos2, pairdis, buf)
assert not o
if len(pair) > 0:
tcol = perf_counter() - tcol
totcol += tcol
pair1 = pos1 @ hm.hpoint(xyzcol1[pair[:, 0]])[..., None]
pair2 = pos2 @ hm.hpoint(xyzcol2[pair[:, 1]])[..., None]
dpair = np.linalg.norm(pair2 - pair1, axis=1)
assert np.max(dpair) <= pairdis
totmin += tn
totbvh += tbvh
N = N1 * N2
print(
f"slide test {N:,} iter bvhslide double: {int(N/totbvh):,}/s bvhmin {int(N/totmin):,}/s",
# f"slide test {N:,} iter bvhslide float: {int(N/totbvhf):,}/s double: {int(N/totbvh):,}/s bvhmin {int(N/totmin):,}/s",
f"fracmiss: {nhit/N} collect {int(nhit/totcol):,}/s",
)
def test_bvh_accessors():
xyz = np.random.rand(10, 3) - [0.5, 0.5, 0.5]
b = BVH(xyz)
assert np.allclose(b.com()[:3], np.mean(xyz, axis=0))
p = b.centers()
dmat = np.linalg.norm(p[:, :3] - xyz[:, None], axis=2)
assert np.allclose(np.min(dmat, axis=1), 0)
def random_walk(N):
x = np.random.randn(N, 3).astype("f").cumsum(axis=0)
x -= x.mean(axis=0)
return 0.5 * x / x.std()
def test_bvh_isect_range(body=None, cart_sd=0.3, N2=10, mindist=0.02):
N1 = 1 if body else 2
N = N1 * N2
totbvh, totnaive, totbvh0, nhit = 0, 0, 0, 0
for ibvh in range(N1):
if body:
bvh1, bvh2 = body.bvh_bb, body.bvh_bb
else:
# xyz1 = np.random.rand(2000, 3) - [0.5, 0.5, 0.5]
# xyz2 = np.random.rand(2000, 3) - [0.5, 0.5, 0.5]
xyz1 = random_walk(1000)
xyz2 = random_walk(1000)
tcre = perf_counter()
bvh1 = BVH(xyz1)
bvh2 = BVH(xyz2)
tcre = perf_counter() - tcre
pos1 = hm.rand_xform(N2, cart_sd=cart_sd)
pos2 = hm.rand_xform(N2, cart_sd=cart_sd)
ranges = list()
for i in range(N2):
tbvh0 = perf_counter()
c = bvh.bvh_isect(bvh1=bvh1, bvh2=bvh2, pos1=pos1[i], pos2=pos2[i], mindist=mindist)
tbvh0 = perf_counter() - tbvh0
# if not c:
# continue
if c:
nhit += 1
tbvh = perf_counter()
range1 = bvh.isect_range_single(bvh1=bvh1, bvh2=bvh2, pos1=pos1[i], pos2=pos2[i],
mindist=mindist)
tbvh = perf_counter() - tbvh
tn = perf_counter()
range2 = bvh.naive_isect_range(bvh1, bvh2, pos1[i], pos2[i], mindist)
assert range1 == range2
tn = perf_counter() - tn
ranges.append(range1)
# print(f"{str(range1):=^80}")
# body.move_to(pos1).dump_pdb("test1.pdb")
# body.move_to(pos2).dump_pdb("test2.pdb")
# return
# print(f"{i:3} range {range1} {tn / tbvh:8.2f}, {tn:1.6f}, {tbvh:1.6f}")
totbvh += tbvh
totnaive += tn
totbvh0 += tbvh0
lb, ub = bvh.isect_range(bvh1, bvh2, pos1, pos2, mindist)
ranges = np.array(ranges)
assert np.all(lb == ranges[:, 0])
assert np.all(ub == ranges[:, 1])
ok = np.logical_and(lb >= 0, ub >= 0)
isect, clash = bvh.bvh_isect_fixed_range_vec(bvh1, bvh2, pos1, pos2, mindist, lb, ub)
assert not np.any(isect[ok])
print(
f"iscet {nhit:,} hit of {N:,} iter bvh: {int(nhit/totbvh):,}/s fastnaive {int(nhit/totnaive):,}/s",
f"ratio {int(totnaive/totbvh):,}x isect-only: {totbvh/totbvh0:3.3f}x",
)
def test_bvh_isect_range_ids():
N1 = 50
N2 = 100
N = N1 * N2
# Nids = 100
cart_sd = 0.3
mindist = 0.03
Npts = 1000
factors = [1000, 500, 250, 200, 125, 100, 50, 40, 25, 20, 10, 8, 5, 4, 2, 1]
# Npts = 6
# factors = [3]
# mindist = 0.3
# N1 = 1
assert all(Npts % f == 0 for f in factors)
for ibvh in range(N1):
# for ibvh in [5]:
# np.random.seed(ibvh)
# print(ibvh)
Nids = factors[ibvh % len(factors)]
# xyz1 = np.random.rand(2000, 3) - [0.5, 0.5, 0.5]
# xyz2 = np.random.rand(2000, 3) - [0.5, 0.5, 0.5]
xyz1 = random_walk(Npts)
xyz2 = random_walk(Npts)
tcre = perf_counter()
bvh1 = BVH(xyz1, [], np.repeat(np.arange(Nids), Npts / Nids))
bvh2 = BVH(xyz2, [], np.repeat(np.arange(Nids), Npts / Nids))
tcre = perf_counter() - tcre
pos1 = hm.rand_xform(N2, cart_sd=cart_sd)
pos2 = hm.rand_xform(N2, cart_sd=cart_sd)
# pos1 = pos1[99:]
# pos2 = pos2[99:]
# print(bvh1.vol_lb())
# print(bvh1.vol_ub())
# print(bvh1.obj_id())
# assert 0
# assert bvh1.max_id() == Nids - 1
# assert bvh1.min_lb() == 0
# assert bvh1.max_ub() == Nids - 1
lb, ub = bvh.isect_range(bvh1, bvh2, pos1, pos2, mindist)
pos1 = pos1[lb != -1]
pos2 = pos2[lb != -1]
ub = ub[lb != -1]
lb = lb[lb != -1]
# print(lb, ub)
assert np.all(0 <= lb) and np.all(lb - 1 <= ub) and np.all(ub < Nids)
isectall = bvh.bvh_isect_vec(bvh1, bvh2, pos1, pos2, mindist)
assert np.all(isectall == np.logical_or(lb > 0, ub < Nids - 1))
isect, clash = bvh.bvh_isect_fixed_range_vec(bvh1, bvh2, pos1, pos2, mindist, lb, ub)
if np.any(isect):
print(np.where(isect)[0])
print('lb', lb[isect])
print('ub', ub[isect])
print('cA', clash[isect, 0])
print('cB', clash[isect, 1])
# print('is', isect.astype('i') * 100)
# print('isectlbub', np.sum(isect), np.sum(isect) / len(isect))
assert not np.any(isect[lb <= ub])
def test_bvh_isect_range_lb_ub(body=None, cart_sd=0.3, N1=3, N2=20, mindist=0.02):
N1 = 1 if body else N1
N = N1 * N2
Npts = 1000
nhit, nrangefail = 0, 0
args = [
rp.Bunch(maxtrim=a, maxtrim_lb=b, maxtrim_ub=c) for a in (-1, 400) for b in (-1, 300)
for c in (-1, 300)
]
for ibvh, arg in it.product(range(N1), args):
if body:
bvh1, bvh2 = body.bvh_bb, body.bvh_bb
else:
# xyz1 = np.random.rand(Npts, 3) - [0.5, 0.5, 0.5]
# xyz2 = np.random.rand(Npts, 3) - [0.5, 0.5, 0.5]
xyz1 = random_walk(Npts)
xyz2 = random_walk(Npts)
bvh1 = BVH(xyz1)
bvh2 = BVH(xyz2)
pos1 = hm.rand_xform(N2, cart_sd=cart_sd)
pos2 = hm.rand_xform(N2, cart_sd=cart_sd)
ranges = list()
for i in range(N2):
c = bvh.bvh_isect(bvh1=bvh1, bvh2=bvh2, pos1=pos1[i], pos2=pos2[i], mindist=mindist)
if c: nhit += 1
range1 = bvh.isect_range_single(bvh1=bvh1, bvh2=bvh2, pos1=pos1[i], pos2=pos2[i],
mindist=mindist, **arg)
ranges.append(range1)
if range1[0] < 0:
nrangefail += 1
assert c
continue
assert (arg.maxtrim < 0) or (np.diff(range1) + 1 >= Npts - arg.maxtrim)
assert (arg.maxtrim_lb < 0) or (range1[0] <= arg.maxtrim_lb)
assert (arg.maxtrim_ub < 0) or (range1[1] + 1 >= Npts - arg.maxtrim_ub)
# mostly covered elsewhere, and quite slow
# range2 = bvh.naive_isect_range(bvh1, bvh2, pos1[i], pos2[i], mindist)
# assert range1 == range2
lb, ub = bvh.isect_range(bvh1, bvh2, pos1, pos2, mindist, **arg)
ranges = np.array(ranges)
assert np.all(lb == ranges[:, 0])
assert np.all(ub == ranges[:, 1])
print(f"iscet {nhit:,} hit of {N:,} iter, frangefail {nrangefail/nhit}", )
def test_bvh_pickle(tmpdir):
xyz1 = np.random.rand(1000, 3) - [0.5, 0.5, 0.5]
xyz2 = np.random.rand(1000, 3) - [0.5, 0.5, 0.5]
bvh1 = BVH(xyz1)
bvh2 = BVH(xyz2)
pos1 = hm.rand_xform(cart_sd=1)
pos2 = hm.rand_xform(cart_sd=1)
tbvh = perf_counter()
d, i1, i2 = bvh.bvh_min_dist(bvh1, bvh2, pos1, pos2)
rng = bvh.isect_range_single(bvh1, bvh2, pos1, pos2, mindist=d + 0.01)
with open(tmpdir + "/1", "wb") as out:
_pickle.dump(bvh1, out)
with open(tmpdir + "/2", "wb") as out:
_pickle.dump(bvh2, out)
with open(tmpdir + "/1", "rb") as out:
bvh1b = _pickle.load(out)
with open(tmpdir + "/2", "rb") as out:
bvh2b = _pickle.load(out)
assert len(bvh1) == len(bvh1b)
assert len(bvh2) == len(bvh2b)
assert np.allclose(bvh1.com(), bvh1b.com())
assert np.allclose(bvh1.centers(), bvh1b.centers())
assert np.allclose(bvh2.com(), bvh2b.com())
assert np.allclose(bvh2.centers(), bvh2b.centers())
db, i1b, i2b = bvh.bvh_min_dist(bvh1b, bvh2b, pos1, pos2)
assert np.allclose(d, db)
assert i1 == i1b
assert i2 == i2b
rngb = bvh.isect_range_single(bvh1b, bvh2b, pos1, pos2, mindist=d + 0.01)
assert rngb == rng
def test_bvh_threading_isect_may_fail():
from concurrent.futures import ThreadPoolExecutor
from itertools import repeat
reps = 1
npos = 1000
Npts = 1000
xyz1 = np.random.rand(Npts, 3) - [0.5, 0.5, 0.5]
xyz2 = np.random.rand(Npts, 3) - [0.5, 0.5, 0.5]
bvh1 = BVH(xyz1)
bvh2 = BVH(xyz2)
mindist = 0.1
tottmain, tottthread = 0, 0
nt = 2
exe = ThreadPoolExecutor(nt)
for i in range(reps):
pos1 = hm.rand_xform(npos, cart_sd=0.5)
pos2 = hm.rand_xform(npos, cart_sd=0.5)
buf = np.empty((Npts, 2), dtype="i4")
t = perf_counter()
_ = [bvh.bvh_isect(bvh1, bvh2, p1, p2, mindist) for p1, p2 in zip(pos1, pos2)]
isect = np.array(_)
tmain = perf_counter() - t
tottmain += tmain
t = perf_counter()
futures = exe.map(
bvh.bvh_isect_vec,
repeat(bvh1),
repeat(bvh2),
np.split(pos1, nt),
np.split(pos2, nt),
repeat(mindist),
)
isect2 = np.concatenate([f for f in futures])
tthread = perf_counter() - t
tottthread += tthread
print("fisect", np.sum(isect2) / len(isect2))
assert np.allclose(isect, isect2)
# print("bvh_isect", i, tmain / tthread, ">= 1.1")
# assert tmain / tthread > 1.1
print("bvh_isect", tottmain / tottthread)
def test_bvh_threading_mindist_may_fail():
from concurrent.futures import ThreadPoolExecutor
from itertools import repeat
reps = 1
npos = 100
Npts = 1000
xyz1 = np.random.rand(Npts, 3) - [0.5, 0.5, 0.5]
xyz2 = | np.random.rand(Npts, 3) | numpy.random.rand |
import math
import os
import random
import re
from collections import namedtuple
from itertools import combinations
import numpy as np
from pr2_never_collisions import NEVER_COLLISIONS
from utils import multiply, get_link_pose, joint_from_name, set_joint_position, \
set_joint_positions, get_joint_positions, get_min_limit, get_max_limit, quat_from_euler, read_pickle, set_pose, set_base_values, \
get_pose, euler_from_quat, link_from_name, has_link, point_from_pose, invert, Pose, \
unit_pose, joints_from_names, PoseSaver, get_lower_upper, get_joint_limits, get_joints, \
ConfSaver, get_bodies, create_mesh, remove_body, single_collision, unit_from_theta, angle_between, violates_limit, \
violates_limits, add_line, get_body_name, get_num_joints, approximate_as_cylinder, approximate_as_prism
# TODO: restrict number of pr2 rotations to prevent from wrapping too many times
ARM_NAMES = ('left', 'right')
def arm_from_arm(arm): # TODO: rename
assert (arm in ARM_NAMES)
return '{}_arm'.format(arm)
def gripper_from_arm(arm):
assert (arm in ARM_NAMES)
return '{}_gripper'.format(arm)
PR2_GROUPS = {
'base': ['x', 'y', 'theta'],
'torso': ['torso_lift_joint'],
'head': ['head_pan_joint', 'head_tilt_joint'],
arm_from_arm('left'): ['l_shoulder_pan_joint', 'l_shoulder_lift_joint', 'l_upper_arm_roll_joint',
'l_elbow_flex_joint', 'l_forearm_roll_joint', 'l_wrist_flex_joint', 'l_wrist_roll_joint'],
arm_from_arm('right'): ['r_shoulder_pan_joint', 'r_shoulder_lift_joint', 'r_upper_arm_roll_joint',
'r_elbow_flex_joint', 'r_forearm_roll_joint', 'r_wrist_flex_joint', 'r_wrist_roll_joint'],
gripper_from_arm('left'): ['l_gripper_l_finger_joint', 'l_gripper_r_finger_joint',
'l_gripper_l_finger_tip_joint', 'l_gripper_r_finger_tip_joint'],
gripper_from_arm('right'): ['r_gripper_l_finger_joint', 'r_gripper_r_finger_joint',
'r_gripper_l_finger_tip_joint', 'r_gripper_r_finger_tip_joint'],
# r_gripper_joint & l_gripper_joint are not mimicked
}
HEAD_LINK_NAME = 'high_def_optical_frame' # high_def_optical_frame | high_def_frame | wide_stereo_l_stereo_camera_frame | ...
# kinect - 'head_mount_kinect_rgb_optical_frame' | 'head_mount_kinect_rgb_link'
PR2_TOOL_FRAMES = {
'left': 'l_gripper_palm_link', # l_gripper_palm_link | l_gripper_tool_frame | l_gripper_tool_joint
'right': 'r_gripper_palm_link', # r_gripper_palm_link | r_gripper_tool_frame
'head': HEAD_LINK_NAME,
}
# Arm tool poses
TOOL_POSE = ([0.18, 0., 0.], [0., 0.70710678, 0., 0.70710678])
TOOL_DIRECTION = [0., 0., 1.]
#####################################
# Special configurations
TOP_HOLDING_LEFT_ARM = [0.67717021, -0.34313199, 1.2, -1.46688405, 1.24223229, -1.95442826, 2.22254125]
SIDE_HOLDING_LEFT_ARM = [0.39277395, 0.33330058, 0., -1.52238431, 2.72170996, -1.21946936, -2.98914779]
REST_LEFT_ARM = [2.13539289, 1.29629967, 3.74999698, -0.15000005, 10000., -0.10000004, 10000.]
WIDE_LEFT_ARM = [1.5806603449288885, -0.14239066980481405, 1.4484623937179126, -1.4851759349218694, 1.3911839347271555,
-1.6531320011389408, -2.978586584568441]
CENTER_LEFT_ARM = [-0.07133691252641006, -0.052973836083405494, 1.5741805775919033, -1.4481146328076862,
1.571782540186805, -1.4891468812835686, -9.413338322697955]
# WIDE_RIGHT_ARM = [-1.3175723551150083, -0.09536552225976803, -1.396727055561703, -1.4433371993320296, -1.5334243909312468, -1.7298129320065025, 6.230244924007009]
PR2_LEFT_ARM_CONFS = {
'top': TOP_HOLDING_LEFT_ARM,
}
#####################################
PR2_URDF = "models/pr2_description/pr2.urdf" # 87 joints
DRAKE_PR2_URDF = "models/drake/pr2_description/urdf/pr2_simplified.urdf" # 82 joints
def is_drake_pr2(robot): # 87
return (get_body_name(robot) == 'pr2') and (get_num_joints(robot) == 82)
#####################################
# TODO: for when the PR2 is copied and loses it's joint names
# PR2_JOINT_NAMES = []
#
# def set_pr2_joint_names(pr2):
# for joint in get_joints(pr2):
# PR2_JOINT_NAMES.append(joint)
#
# def get_pr2_joints(joint_names):
# joint_from_name = dict(zip(PR2_JOINT_NAMES, range(len(PR2_JOINT_NAMES))))
# return [joint_from_name[name] for name in joint_names]
#####################################
def rightarm_from_leftarm(config):
# right_from_left = np.array([-1, 1, -1, 1, -1, 1, 1])
right_from_left = np.array([-1, 1, -1, 1, -1, 1, -1]) # Drake
return config * right_from_left
def arm_conf(arm, left_config):
if arm == 'left':
return left_config
elif arm == 'right':
return rightarm_from_leftarm(left_config)
else:
raise ValueError(arm)
def get_carry_conf(arm, grasp_type):
if grasp_type == 'top':
return arm_conf(arm, TOP_HOLDING_LEFT_ARM)
elif grasp_type == 'side':
return arm_conf(arm, SIDE_HOLDING_LEFT_ARM)
else:
raise NotImplementedError(grasp_type)
def get_other_arm(arm):
for other_arm in ARM_NAMES:
if other_arm != arm:
return other_arm
raise ValueError(arm)
#####################################
def get_disabled_collisions(pr2):
#disabled_names = PR2_ADJACENT_LINKS
#disabled_names = PR2_DISABLED_COLLISIONS
disabled_names = NEVER_COLLISIONS
#disabled_names = PR2_DISABLED_COLLISIONS + NEVER_COLLISIONS
return {(link_from_name(pr2, name1), link_from_name(pr2, name2))
for name1, name2 in disabled_names if has_link(pr2, name1) and has_link(pr2, name2)}
def load_dae_collisions():
# pr2-beta-static.dae: link 0 = base_footprint
# pybullet: link -1 = base_footprint
dae_file = 'models/pr2_description/pr2-beta-static.dae'
dae_string = open(dae_file).read()
link_regex = r'<\s*link\s+sid="(\w+)"\s+name="(\w+)"\s*>'
link_mapping = dict(re.findall(link_regex, dae_string))
ignore_regex = r'<\s*ignore_link_pair\s+link0="kmodel1/(\w+)"\s+link1="kmodel1/(\w+)"\s*/>'
disabled_collisions = []
for link1, link2 in re.findall(ignore_regex, dae_string):
disabled_collisions.append((link_mapping[link1], link_mapping[link2]))
return disabled_collisions
def load_srdf_collisions():
srdf_file = 'models/pr2_description/pr2.srdf'
srdf_string = open(srdf_file).read()
regex = r'<\s*disable_collisions\s+link1="(\w+)"\s+link2="(\w+)"\s+reason="(\w+)"\s*/>'
disabled_collisions = []
for link1, link2, reason in re.findall(regex, srdf_string):
if reason == 'Never':
disabled_collisions.append((link1, link2))
return disabled_collisions
#####################################
def get_group_joints(robot, group):
return joints_from_names(robot, PR2_GROUPS[group])
def get_group_conf(robot, group):
return get_joint_positions(robot, get_group_joints(robot, group))
def set_group_conf(robot, group, positions):
set_joint_positions(robot, get_group_joints(robot, group), positions)
#####################################
# End-effectors
def get_arm_joints(robot, arm):
return get_group_joints(robot, arm_from_arm(arm))
#def get_arm_conf(robot, arm):
# return get_joint_positions(robot, get_arm_joints(robot, arm))
def set_arm_conf(robot, arm, conf):
set_joint_positions(robot, get_arm_joints(robot, arm), conf)
def get_gripper_link(robot, arm):
assert arm in ARM_NAMES
return link_from_name(robot, PR2_TOOL_FRAMES[arm])
# def get_gripper_pose(robot):
# # world_from_gripper * gripper_from_tool * tool_from_object = world_from_object
# pose = multiply(get_link_pose(robot, link_from_name(robot, LEFT_ARM_LINK)), TOOL_POSE)
# #pose = get_link_pose(robot, link_from_name(robot, LEFT_TOOL_NAME))
# return pose
def get_gripper_joints(robot, arm):
return get_group_joints(robot, gripper_from_arm(arm))
def open_arm(robot, arm): # These are mirrored on the pr2
for joint in get_gripper_joints(robot, arm):
set_joint_position(robot, joint, get_max_limit(robot, joint))
def close_arm(robot, arm):
for joint in get_gripper_joints(robot, arm):
set_joint_position(robot, joint, get_min_limit(robot, joint))
#####################################
# Box grasps
# TODO: test if grasp is in collision
#GRASP_LENGTH = 0.04
GRASP_LENGTH = 0.
#GRASP_LENGTH = -0.01
#MAX_GRASP_WIDTH = 0.07
MAX_GRASP_WIDTH = np.inf
SIDE_HEIGHT_OFFSET = 0.03 # z distance from top of object
# TODO: rename the box grasps
def get_top_grasps(body, under=False, tool_pose=TOOL_POSE, body_pose=unit_pose(),
max_width=MAX_GRASP_WIDTH, grasp_length=GRASP_LENGTH):
center, (w, l, h) = approximate_as_prism(body, body_pose=body_pose)
reflect_z = Pose(euler=[0, math.pi, 0])
translate_z = Pose(point=[0, 0, h / 2 - grasp_length])
translate_center = Pose(point=point_from_pose(body_pose)-center)
grasps = []
if w <= max_width:
for i in range(1 + under):
rotate_z = Pose(euler=[0, 0, math.pi / 2 + i * math.pi])
grasps += [multiply(tool_pose, translate_z, rotate_z,
reflect_z, translate_center, body_pose)]
if l <= max_width:
for i in range(1 + under):
rotate_z = Pose(euler=[0, 0, i * math.pi])
grasps += [multiply(tool_pose, translate_z, rotate_z,
reflect_z, translate_center, body_pose)]
return grasps
def get_side_grasps(body, under=False, tool_pose=TOOL_POSE, body_pose=unit_pose(),
max_width=MAX_GRASP_WIDTH, grasp_length=GRASP_LENGTH, top_offset=SIDE_HEIGHT_OFFSET):
# TODO: compute bounding box width wrt tool frame
center, (w, l, h) = approximate_as_prism(body, body_pose=body_pose)
translate_center = Pose(point=point_from_pose(body_pose)-center)
grasps = []
#x_offset = 0
x_offset = h/2 - top_offset
for j in range(1 + under):
swap_xz = Pose(euler=[0, -math.pi / 2 + j * math.pi, 0])
if w <= max_width:
translate_z = Pose(point=[x_offset, 0, l / 2 - grasp_length])
for i in range(2):
rotate_z = Pose(euler=[math.pi / 2 + i * math.pi, 0, 0])
grasps += [multiply(tool_pose, translate_z, rotate_z, swap_xz,
translate_center, body_pose)] # , np.array([w])
if l <= max_width:
translate_z = Pose(point=[x_offset, 0, w / 2 - grasp_length])
for i in range(2):
rotate_z = Pose(euler=[i * math.pi, 0, 0])
grasps += [multiply(tool_pose, translate_z, rotate_z, swap_xz,
translate_center, body_pose)] # , np.array([l])
return grasps
#####################################
# Cylinder grasps
def get_top_cylinder_grasps(body, tool_pose=TOOL_POSE, body_pose=unit_pose(),
max_width=MAX_GRASP_WIDTH, grasp_length=GRASP_LENGTH):
# Apply transformations right to left on object pose
center, (diameter, height) = approximate_as_cylinder(body, body_pose=body_pose)
reflect_z = Pose(euler=[0, math.pi, 0])
translate_z = Pose(point=[0, 0, height / 2 - grasp_length])
translate_center = Pose(point=point_from_pose(body_pose)-center)
if max_width < diameter:
return
while True:
theta = random.uniform(0, 2*np.pi)
rotate_z = Pose(euler=[0, 0, theta])
yield multiply(tool_pose, translate_z, rotate_z,
reflect_z, translate_center, body_pose)
def get_side_cylinder_grasps(body, under=False, tool_pose=TOOL_POSE, body_pose=unit_pose(),
max_width=MAX_GRASP_WIDTH, grasp_length=GRASP_LENGTH, top_offset=SIDE_HEIGHT_OFFSET):
center, (diameter, height) = approximate_as_cylinder(body, body_pose=body_pose)
translate_center = Pose(point_from_pose(body_pose)-center)
#x_offset = 0
x_offset = height/2 - top_offset
if max_width < diameter:
return
while True:
theta = random.uniform(0, 2*np.pi)
translate_rotate = ([x_offset, 0, diameter / 2 - grasp_length], quat_from_euler([theta, 0, 0]))
for j in range(1 + under):
swap_xz = Pose(euler=[0, -math.pi / 2 + j * math.pi, 0])
yield multiply(tool_pose, translate_rotate, swap_xz, translate_center, body_pose)
def get_edge_cylinder_grasps(body, under=False, tool_pose=TOOL_POSE, body_pose=unit_pose(),
grasp_length=GRASP_LENGTH):
center, (diameter, height) = approximate_as_cylinder(body, body_pose=body_pose)
translate_yz = Pose(point=[0, diameter/2, height/2 - grasp_length])
reflect_y = Pose(euler=[0, math.pi, 0])
translate_center = Pose(point=point_from_pose(body_pose)-center)
while True:
theta = random.uniform(0, 2*np.pi)
rotate_z = Pose(euler=[0, 0, theta])
for i in range(1 + under):
rotate_under = Pose(euler=[0, 0, i * math.pi])
yield multiply(tool_pose, rotate_under, translate_yz, rotate_z,
reflect_y, translate_center, body_pose)
#####################################
# Cylinder pushes
PUSH_HEIGHT = 0.02
PUSH_DISTANCE = 0.03
def get_cylinder_push(body, theta, under=False, tool_pose=TOOL_POSE, body_pose=unit_pose()):
center, (diameter, height) = approximate_as_cylinder(body, body_pose=body_pose)
reflect_z = Pose(euler=[0, math.pi, 0])
translate_z = Pose(point=[0, 0, -height / 2 + PUSH_HEIGHT])
translate_center = Pose(point=point_from_pose(body_pose)-center)
rotate_x = Pose(euler=[0, 0, theta])
translate_x = Pose(point=[-diameter / 2 - PUSH_DISTANCE, 0, 0])
grasps = []
for i in range(1 + under):
rotate_z = Pose(euler=[0, 0, i * math.pi])
grasps.append(multiply(tool_pose, translate_z, translate_x, rotate_x, rotate_z,
reflect_z, translate_center, body_pose))
return grasps
#####################################
# Button presses
PRESS_OFFSET = 0.02
def get_x_presses(body, max_orientations=1, body_pose=unit_pose(), top_offset=PRESS_OFFSET):
# gripper_from_object
# TODO: update
center, (w, _, h) = approximate_as_prism(body, body_pose=body_pose)
translate_center = Pose(-center)
press_poses = []
for j in range(max_orientations):
swap_xz = Pose(euler=[0, -math.pi / 2 + j * math.pi, 0])
translate = Pose(point=[0, 0, w / 2 + top_offset])
press_poses += [multiply(TOOL_POSE, translate, swap_xz, translate_center, body_pose)]
return press_poses
def get_top_presses(body, tool_pose=TOOL_POSE, body_pose=unit_pose(), top_offset=PRESS_OFFSET):
center, (_, height) = approximate_as_cylinder(body, body_pose=body_pose)
reflect_z = Pose(euler=[0, math.pi, 0])
translate_z = Pose(point=[0, 0, height / 2 + top_offset])
translate_center = Pose(point=point_from_pose(body_pose)-center)
while True:
theta = random.uniform(0, 2*np.pi)
rotate_z = Pose(euler=[0, 0, theta])
yield multiply(tool_pose, translate_z, rotate_z,
reflect_z, translate_center, body_pose)
GET_GRASPS = {
'top': get_top_grasps,
'side': get_side_grasps,
# 'press': get_x_presses,
}
# TODO: include approach/carry info
#####################################
# Inverse reachability
DATABASES_DIR = '../databases'
IR_FILENAME = '{}_{}_ir.pickle'
def get_database_file(filename):
directory = os.path.dirname(os.path.abspath(__file__))
return os.path.join(directory, DATABASES_DIR, filename)
def load_inverse_reachability(arm, grasp_type):
filename = IR_FILENAME.format(grasp_type, arm)
path = get_database_file(filename)
return read_pickle(path)['gripper_from_base']
def learned_forward_generator(robot, base_pose, arm, grasp_type):
gripper_from_base_list = load_inverse_reachability(arm, grasp_type)
random.shuffle(gripper_from_base_list)
for gripper_from_base in gripper_from_base_list:
yield multiply(base_pose, invert(gripper_from_base))
def learned_pose_generator(robot, gripper_pose, arm, grasp_type):
gripper_from_base_list = load_inverse_reachability(arm, grasp_type)
random.shuffle(gripper_from_base_list)
for gripper_from_base in gripper_from_base_list:
base_point, base_quat = multiply(gripper_pose, gripper_from_base)
x, y, _ = base_point
_, _, theta = euler_from_quat(base_quat)
base_values = (x, y, theta)
#set_base_values(robot, base_values)
#yield get_pose(robot)
yield base_values
#####################################
# Camera
WIDTH, HEIGHT = 640, 480
FX, FY = 772.55, 772.5
MAX_VISUAL_DISTANCE = 5.0
MAX_KINECT_DISTANCE = 2.5
def get_camera_matrix(width, height, fx, fy):
# cx, cy = 320.5, 240.5
cx, cy = width / 2., height / 2.
return np.array([
[fx, 0, cx],
[0, fy, cy],
[0, 0, 1]])
def ray_from_pixel(camera_matrix, pixel):
return np.linalg.inv(camera_matrix).dot(np.append(pixel, 1))
def pixel_from_ray(camera_matrix, ray):
return camera_matrix.dot(ray / ray[2])[:2]
def get_pr2_camera_matrix():
return get_camera_matrix(WIDTH, HEIGHT, FX, FY)
def get_pr2_view_section(z):
camera_matrix = get_pr2_camera_matrix()
pixels = [(0, 0), (WIDTH, HEIGHT)]
return [z*ray_from_pixel(camera_matrix, p) for p in pixels]
def get_pr2_field_of_view():
z = 1
view_lower, view_upper = get_pr2_view_section(z=z)
theta = angle_between([view_lower[0], 0, z], [view_upper[0], 0, z]) # 0.7853966439794928
phi = angle_between([0, view_lower[1], z], [0, view_upper[1], z]) # 0.6024511557247721
return theta, phi
def is_visible_point(camera_matrix, depth, point):
if not (0 <= point[2] < depth):
return False
px, py = pixel_from_ray(camera_matrix, point)
# TODO: bounding box methods?
return (0 <= px < WIDTH) and (0 <= py < HEIGHT)
def is_visible_aabb(body_lower, body_upper):
# TODO: do intersect as well for identifying new obstacles
z = body_lower[2]
if z < 0:
return False
view_lower, view_upper = get_pr2_view_section(z)
# TODO: bounding box methods?
return not (np.any(body_lower[:2] < view_lower[:2]) or
np.any(view_upper[:2] < body_upper[:2]))
def support_from_aabb(lower, upper):
min_x, min_y, z = lower
max_x, max_y, _ = upper
return [(min_x, min_y, z), (min_x, max_y, z),
(max_x, max_y, z), (max_x, min_y, z)]
#####################################
def cone_vertices_from_base(base):
return [np.zeros(3)] + base
def cone_wires_from_support(support):
#vertices = cone_vertices_from_base(support)
# TODO: could obtain from cone_mesh_from_support
# TODO: could also just return vertices and indices
apex = np.zeros(3)
lines = []
for vertex in support:
lines.append((apex, vertex))
#for i, v2 in enumerate(support):
# v1 = support[i-1]
# lines.append((v1, v2))
for v1, v2 in combinations(support, 2):
lines.append((v1, v2))
center = np.average(support, axis=0)
lines.append((apex, center))
return lines
def cone_mesh_from_support(support):
assert(len(support) == 4)
vertices = cone_vertices_from_base(support)
faces = [(1, 4, 3), (1, 3, 2)]
for i in range(len(support)):
index1 = 1+i
index2 = 1+(i+1)%len(support)
faces.append((0, index1, index2))
return vertices, faces
def get_viewcone_base(depth=MAX_VISUAL_DISTANCE):
# TODO: attach to the pr2?
cone = [(0, 0), (WIDTH, 0), (WIDTH, HEIGHT), (0, HEIGHT)]
camera_matrix = get_pr2_camera_matrix()
vertices = []
for pixel in cone:
ray = depth * ray_from_pixel(camera_matrix, pixel)
vertices.append(ray[:3])
return vertices
def get_viewcone(depth=MAX_VISUAL_DISTANCE, **kwargs):
# TODO: attach to the pr2?
mesh = cone_mesh_from_support(get_viewcone_base(depth=depth))
assert (mesh is not None)
return create_mesh(mesh, **kwargs)
def attach_viewcone(robot, head_name=HEAD_LINK_NAME, depth=MAX_VISUAL_DISTANCE, color=(1, 0, 0), **kwargs):
head_link = link_from_name(robot, head_name)
lines = []
for v1, v2 in cone_wires_from_support(get_viewcone_base(depth=depth)):
lines.append(add_line(v1, v2, color=color, parent=robot, parent_link=head_link, **kwargs))
return lines
#####################################
def inverse_visibility(pr2, point, head_name=HEAD_LINK_NAME):
# TODO: test visibility by getting box
# TODO: IK version
# https://github.com/PR2/pr2_controllers/blob/kinetic-devel/pr2_head_action/src/pr2_point_frame.cpp
#head_joints = [joint_from_name(pr2, name) for name in PR2_GROUPS['head']]
#head_link = head_joints[-1]
optical_frame = ('optical' in head_name)
head_link = link_from_name(pr2, head_name)
head_joints = joints_from_names(pr2, PR2_GROUPS['head'])
with ConfSaver(pr2):
set_joint_positions(pr2, head_joints, np.zeros(len(head_joints)))
head_pose = get_link_pose(pr2, head_link)
point_head = point_from_pose(multiply(invert(head_pose), Pose(point)))
if optical_frame:
dy, dz, dx = np.array([-1, -1, 1])*np.array(point_head)
else:
dx, dy, dz = np.array(point_head)
theta = np.math.atan2(dy, dx) # TODO: might need to negate the minus for the default one
phi = np.math.atan2(-dz, np.sqrt(dx ** 2 + dy ** 2))
conf = [theta, phi]
#pose = Pose(point_from_pose(head_pose), Euler(pitch=phi, yaw=theta)) # TODO: initial roll?
if violates_limits(pr2, head_joints, conf):
return None
return conf
def plan_scan_path(pr2, tilt=0):
head_joints = joints_from_names(pr2, PR2_GROUPS['head'])
start_conf = get_joint_positions(pr2, head_joints)
lower_limit, upper_limit = get_joint_limits(pr2, head_joints[0])
first_conf = np.array([lower_limit, tilt])
second_conf = np.array([upper_limit, tilt])
if start_conf[0] > 0:
first_conf, second_conf = second_conf, first_conf
return [first_conf, second_conf]
#return [start_conf, first_conf, second_conf]
#third_conf = np.array([0, tilt])
#return [start_conf, first_conf, second_conf, third_conf]
def plan_pause_scan_path(pr2, tilt=0):
head_joints = joints_from_names(pr2, PR2_GROUPS['head'])
assert(not violates_limit(pr2, head_joints[1], tilt))
theta, _ = get_pr2_field_of_view()
lower_limit, upper_limit = get_joint_limits(pr2, head_joints[0])
# Add one because half visible on limits
n = int(np.math.ceil((upper_limit - lower_limit) / theta) + 1)
epsilon = 1e-3
return [np.array([pan, tilt]) for pan in np.linspace(lower_limit + epsilon,
upper_limit - epsilon, n, endpoint=True)]
#####################################
Detection = namedtuple('Detection', ['body', 'distance'])
def get_detection_cone(pr2, body, depth=MAX_VISUAL_DISTANCE):
head_link = link_from_name(pr2, HEAD_LINK_NAME)
with PoseSaver(body):
body_head = multiply(invert(get_link_pose(pr2, head_link)), get_pose(body))
set_pose(body, body_head)
body_lower, body_upper = get_lower_upper(body)
z = body_lower[2]
if depth < z:
return None, z
if not is_visible_aabb(body_lower, body_upper):
return None, z
return cone_mesh_from_support(support_from_aabb(body_lower, body_upper)), z
def get_detections(pr2, p_false_neg=0, **kwargs):
detections = []
for body in get_bodies():
if | np.random.random() | numpy.random.random |
import cv2
import numpy as np
from collections import OrderedDict
import colour
from colour_checker_detection import detect_colour_checkers_segmentation
class CreateSpyderCheck:
name = "SpyderChecker 24"
# Color checker reference values are in xyY color space
data = OrderedDict()
data["Aqua"] = np.array([0.29131, 0.39533, 0.4102])
data["Lavender"] = np.array([0.29860, 0.28411, 0.22334])
data["Evergreen"] = np.array([0.36528, 0.46063, 0.12519])
data["Steel Blue"] = np.array([0.27138, 0.29748, 0.17448])
data["Classic Light Skin"] = np.array([0.42207, 0.37609, 0.34173])
data["Classic Dark Skin"] = np.array([0.44194, 0.38161, 0.09076])
data["Primary Orange"] = np.array([0.54238, 0.40556, 0.2918])
data["Blueprint"] = np.array([0.22769, 0.21517, 0.09976])
data["Pink"] = np.array([0.50346, 0.32519, 0.1826])
data["Violet"] = np.array([0.30813, 0.24004, 0.05791])
data["Apple Green"] = np.array([0.40262, 0.50567, 0.44332])
data["Sunflower"] = np.array([0.50890, 0.43959, 0.4314])
data["Primary Cyan"] = np.array([0.19792, 0.30072, 0.16111])
data["Primary Magenta"] = np.array([0.38429, 0.23929, 0.18286])
data["Primary Yellow"] = np.array([0.47315, 0.47936, 0.63319])
data["Primary Red"] = | np.array([0.59685, 0.31919, 0.11896]) | numpy.array |
# -*- coding: utf-8 -*-
import sys, logging
import numpy as np
from math import ceil
from gseapy.stats import multiple_testing_correction
from joblib import delayed, Parallel
def enrichment_score(gene_list, correl_vector, gene_set, weighted_score_type=1,
nperm=1000, seed=None, single=False, scale=False):
"""This is the most important function of GSEApy. It has the same algorithm with GSEA and ssGSEA.
:param gene_list: The ordered gene list gene_name_list, rank_metric.index.values
:param gene_set: gene_sets in gmt file, please use gsea_gmt_parser to get gene_set.
:param weighted_score_type: It's the same with gsea's weighted_score method. Weighting by the correlation
is a very reasonable choice that allows significant gene sets with less than perfect coherence.
options: 0(classic),1,1.5,2. default:1. if one is interested in penalizing sets for lack of
coherence or to discover sets with any type of nonrandom distribution of tags, a value p < 1
might be appropriate. On the other hand, if one uses sets with large number of genes and only
a small subset of those is expected to be coherent, then one could consider using p > 1.
Our recommendation is to use p = 1 and use other settings only if you are very experienced
with the method and its behavior.
:param correl_vector: A vector with the correlations (e.g. signal to noise scores) corresponding to the genes in
the gene list. Or rankings, rank_metric.values
:param nperm: Only use this parameter when computing esnull for statistical testing. Set the esnull value
equal to the permutation number.
:param seed: Random state for initializing gene list shuffling. Default: seed=None
:return:
ES: Enrichment score (real number between -1 and +1)
ESNULL: Enrichment score calculated from random permutations.
Hits_Indices: Index of a gene in gene_list, if gene is included in gene_set.
RES: Numerical vector containing the running enrichment score for all locations in the gene list .
"""
N = len(gene_list)
# Test whether each element of a 1-D array is also present in a second array
# It's more intuitive here than original enrichment_score source code.
# use .astype to covert bool to integer
tag_indicator = np.in1d(gene_list, gene_set, assume_unique=True).astype(int) # notice that the sign is 0 (no tag) or 1 (tag)
if weighted_score_type == 0 :
correl_vector = np.repeat(1, N)
else:
correl_vector = np.abs(correl_vector)**weighted_score_type
# get indices of tag_indicator
hit_ind = np.flatnonzero(tag_indicator).tolist()
# if used for compute esnull, set esnull equal to permutation number, e.g. 1000
# else just compute enrichment scores
# set axis to 1, because we have 2D array
axis = 1
tag_indicator = np.tile(tag_indicator, (nperm+1,1))
correl_vector = np.tile(correl_vector,(nperm+1,1))
# gene list permutation
rs = np.random.RandomState(seed)
for i in range(nperm): rs.shuffle(tag_indicator[i])
# np.apply_along_axis(rs.shuffle, 1, tag_indicator)
Nhint = tag_indicator.sum(axis=axis, keepdims=True)
sum_correl_tag = np.sum(correl_vector*tag_indicator, axis=axis, keepdims=True)
# compute ES score, the code below is identical to gsea enrichment_score method.
no_tag_indicator = 1 - tag_indicator
Nmiss = N - Nhint
norm_tag = 1.0/sum_correl_tag
norm_no_tag = 1.0/Nmiss
RES = np.cumsum(tag_indicator * correl_vector * norm_tag - no_tag_indicator * norm_no_tag, axis=axis)
if scale: RES = RES / N
if single:
es_vec = RES.sum(axis=axis)
else:
max_ES, min_ES = RES.max(axis=axis), RES.min(axis=axis)
es_vec = np.where(np.abs(max_ES) > np.abs(min_ES), max_ES, min_ES)
# extract values
es, esnull, RES = es_vec[-1], es_vec[:-1], RES[-1,:]
return es, esnull, hit_ind, RES
def enrichment_score_tensor(gene_mat, cor_mat, gene_sets, weighted_score_type, nperm=1000,
seed=None, single=False, scale=False):
"""Next generation algorithm of GSEA and ssGSEA. Works for 3d array
:param gene_mat: the ordered gene list(vector) with or without gene indices matrix.
:param cor_mat: correlation vector or matrix (e.g. signal to noise scores)
corresponding to the genes in the gene list or matrix.
:param dict gene_sets: gmt file dict.
:param float weighted_score_type: weighting by the correlation.
options: 0(classic), 1, 1.5, 2. default:1 for GSEA and 0.25 for ssGSEA.
:param int nperm: permutation times.
:param bool scale: If True, normalize the scores by number of genes_mat.
:param bool single: If True, use ssGSEA algorithm, otherwise use GSEA.
:param seed: Random state for initialize gene list shuffling.
Default: seed=None
:return: a tuple contains::
| ES: Enrichment score (real number between -1 and +1), for ssGSEA, set scale eq to True.
| ESNULL: Enrichment score calculated from random permutation.
| Hits_Indices: Indices of genes if genes are included in gene_set.
| RES: The running enrichment score for all locations in the gene list.
"""
rs = np.random.RandomState(seed)
# gene_mat -> 1d: prerank, ssSSEA or 2d: GSEA
keys = sorted(gene_sets.keys())
if weighted_score_type == 0:
# don't bother doing calcuation, just set to 1
cor_mat = np.ones(cor_mat.shape)
elif weighted_score_type > 0:
pass
else:
logging.error("Using negative values of weighted_score_type, not allowed")
raise ValueError("weighted_score_type should be postive numerics")
cor_mat = np.abs(cor_mat)
if cor_mat.ndim ==1:
# ssGSEA or Prerank
# genestes->M, genes->N, perm-> axis=2
N, M = len(gene_mat), len(keys)
# generate gene hits matrix
# for 1d ndarray of gene_mat, set assume_unique=True,
# means the input arrays are both assumed to be unique,
# which can speed up the calculation.
tag_indicator = np.vstack([np.in1d(gene_mat, gene_sets[key], assume_unique=True) for key in keys])
tag_indicator = tag_indicator.astype(int)
# index of hits
hit_ind = [ np.flatnonzero(tag).tolist() for tag in tag_indicator ]
# generate permutated hits matrix
perm_tag_tensor = np.repeat(tag_indicator, nperm+1).reshape((M,N,nperm+1))
# shuffle matrix, last matrix is not shuffled when nperm > 0
if nperm: np.apply_along_axis(lambda x: np.apply_along_axis(rs.shuffle,0,x),1, perm_tag_tensor[:,:,:-1])
# missing hits
no_tag_tensor = 1 - perm_tag_tensor
# calculate numerator, denominator of each gene hits
rank_alpha = (perm_tag_tensor*cor_mat[np.newaxis,:,np.newaxis])** weighted_score_type
elif cor_mat.ndim == 2:
# GSEA
# 2d ndarray, gene_mat and cor_mat are shuffled already
# reshape matrix
cor_mat = cor_mat.T
# gene_mat is a tuple contains (gene_name, permuate_gene_name_indices)
genes, genes_ind = gene_mat
# genestes->M, genes->N, perm-> axis=2
# don't use assume_unique=True in 2d array when use np.isin().
# elements in gene_mat are not unique, or will cause unwanted results
tag_indicator = np.vstack([np.in1d(genes, gene_sets[key], assume_unique=True) for key in keys])
tag_indicator = tag_indicator.astype(int)
perm_tag_tensor = np.stack([tag.take(genes_ind).T for tag in tag_indicator], axis=0)
#index of hits
hit_ind = [ np.flatnonzero(tag).tolist() for tag in perm_tag_tensor[:,:,-1] ]
# nohits
no_tag_tensor = 1 - perm_tag_tensor
# calculate numerator, denominator of each gene hits
rank_alpha = (perm_tag_tensor*cor_mat[np.newaxis,:,:])** weighted_score_type
else:
logging.error("Program die because of unsupported input")
raise ValueError("Correlation vector or matrix (cor_mat) is not supported")
# Nhint = tag_indicator.sum(1)
# Nmiss = N - Nhint
axis=1
P_GW_denominator = np.sum(rank_alpha, axis=axis, keepdims=True)
P_NG_denominator = np.sum(no_tag_tensor, axis=axis, keepdims=True)
REStensor = np.cumsum(rank_alpha / P_GW_denominator - no_tag_tensor / P_NG_denominator, axis=axis)
# ssGSEA: scale es by gene numbers ?
# https://gist.github.com/gaoce/39e0907146c752c127728ad74e123b33
if scale: REStensor = REStensor / len(gene_mat)
if single:
#ssGSEA
esmatrix = REStensor.sum(axis=axis)
else:
#GSEA
esmax, esmin = REStensor.max(axis=axis), REStensor.min(axis=axis)
esmatrix = np.where(np.abs(esmax)>np.abs(esmin), esmax, esmin)
es, esnull, RES = esmatrix[:,-1], esmatrix[:,:-1], REStensor[:,:,-1]
return es, esnull, hit_ind, RES
def ranking_metric_tensor(exprs, method, permutation_num, pos, neg, classes,
ascending, seed=None, skip_last=False):
"""Build shuffled ranking matrix when permutation_type eq to phenotype.
Works for 3d array.
:param exprs: gene_expression DataFrame, gene_name indexed.
:param str method: calculate correlation or ranking. methods including:
1. 'signal_to_noise' (s2n) or 'abs_signal_to_noise' (abs_s2n).
2. 't_test'.
3. 'ratio_of_classes' (also referred to as fold change).
4. 'diff_of_classes'.
5. 'log2_ratio_of_classes'.
:param int permuation_num: how many times of classes is being shuffled
:param str pos: one of labels of phenotype's names.
:param str neg: one of labels of phenotype's names.
:param list classes: a list of phenotype labels, to specify which column of
dataframe belongs to what class of phenotype.
:param bool ascending: bool. Sort ascending vs. descending.
:param seed: random_state seed
:param bool skip_last: (internal use only) whether to skip the permutation of the last rankings.
:return:
returns two 2d ndarray with shape (nperm, gene_num).
| cor_mat_indices: the indices of sorted and permutated (exclude last row) ranking matrix.
| cor_mat: sorted and permutated (exclude last row) ranking matrix.
"""
rs = np.random.RandomState(seed)
# S: samples, G: gene number
G, S = exprs.shape
# genes = exprs.index.values
expr_mat = exprs.values.T
perm_cor_tensor = np.tile(expr_mat, (permutation_num,1,1))
if skip_last:
# random shuffle on the first dim, the last matrix (expr_mat) is not shuffled
for arr in perm_cor_tensor[:-1]: rs.shuffle(arr)
else:
for arr in perm_cor_tensor: rs.shuffle(arr)
# metrics
classes = np.array(classes)
pos = classes == pos
neg = classes == neg
n_pos = np.sum(pos)
n_neg = np.sum(neg)
pos_cor_mean = perm_cor_tensor[:,pos,:].mean(axis=1)
neg_cor_mean = perm_cor_tensor[:,neg,:].mean(axis=1)
pos_cor_std = perm_cor_tensor[:,pos,:].std(axis=1, ddof=1)
neg_cor_std = perm_cor_tensor[:,neg,:].std(axis=1, ddof=1)
if method in ['signal_to_noise', 's2n']:
cor_mat = (pos_cor_mean - neg_cor_mean)/(pos_cor_std + neg_cor_std)
elif method in ['abs_signal_to_noise', 'abs_s2n']:
cor_mat = np.abs((pos_cor_mean - neg_cor_mean)/(pos_cor_std + neg_cor_std))
elif method == 't_test':
denom = np.sqrt((pos_cor_std**2)/n_pos + (neg_cor_std**2)/n_neg)
cor_mat = (pos_cor_mean - neg_cor_mean)/ denom
elif method == 'ratio_of_classes':
cor_mat = pos_cor_mean / neg_cor_mean
elif method == 'diff_of_classes':
cor_mat = pos_cor_mean - neg_cor_mean
elif method == 'log2_ratio_of_classes':
cor_mat = np.log2(pos_cor_mean / neg_cor_mean)
else:
logging.error("Please provide correct method name!!!")
raise LookupError("Input method: %s is not supported"%method)
# return matix[nperm+1, perm_cors]
cor_mat_ind = cor_mat.argsort()
# ndarray: sort in place
cor_mat.sort()
# genes_mat = genes.take(cor_mat_ind)
if ascending: return cor_mat_ind, cor_mat
# descending order of ranking and genes
# return genes_mat[:,::-1], cor_mat[:,::-1]
return cor_mat_ind[:, ::-1], cor_mat[:, ::-1]
def ranking_metric(df, method, pos, neg, classes, ascending):
"""The main function to rank an expression table. works for 2d array.
:param df: gene_expression DataFrame.
:param method: The method used to calculate a correlation or ranking. Default: 'log2_ratio_of_classes'.
Others methods are:
1. 'signal_to_noise' (s2n) or 'abs_signal_to_noise' (abs_s2n)
You must have at least three samples for each phenotype to use this metric.
The larger the signal-to-noise ratio, the larger the differences of the means (scaled by the standard deviations);
that is, the more distinct the gene expression is in each phenotype and the more the gene acts as a “class marker.”
2. 't_test'
Uses the difference of means scaled by the standard deviation and number of samples.
Note: You must have at least three samples for each phenotype to use this metric.
The larger the tTest ratio, the more distinct the gene expression is in each phenotype
and the more the gene acts as a “class marker.”
3. 'ratio_of_classes' (also referred to as fold change).
Uses the ratio of class means to calculate fold change for natural scale data.
4. 'diff_of_classes'
Uses the difference of class means to calculate fold change for natural scale data
5. 'log2_ratio_of_classes'
Uses the log2 ratio of class means to calculate fold change for natural scale data.
This is the recommended statistic for calculating fold change for log scale data.
:param str pos: one of labels of phenotype's names.
:param str neg: one of labels of phenotype's names.
:param dict classes: column id to group mapping.
:param bool ascending: bool or list of bool. Sort ascending vs. descending.
:return:
returns a pd.Series of correlation to class of each variable. Gene_name is index, and value is rankings.
visit here for more docs: http://software.broadinstitute.org/gsea/doc/GSEAUserGuideFrame.html
"""
# exclude any zero stds.
df_mean = df.groupby(by=classes, axis=1).mean()
df_std = df.groupby(by=classes, axis=1).std()
n_pos = np.sum(classes == pos)
n_neg = np.sum(classes == neg)
if method in ['signal_to_noise', 's2n']:
ser = (df_mean[pos] - df_mean[neg])/(df_std[pos] + df_std[neg])
elif method in ['abs_signal_to_noise', 'abs_s2n']:
ser = ((df_mean[pos] - df_mean[neg])/(df_std[pos] + df_std[neg])).abs()
elif method == 't_test':
ser = (df_mean[pos] - df_mean[neg])/ np.sqrt(df_std[pos]**2/n_pos+df_std[neg]**2/n_neg)
elif method == 'ratio_of_classes':
ser = df_mean[pos] / df_mean[neg]
elif method == 'diff_of_classes':
ser = df_mean[pos] - df_mean[neg]
elif method == 'log2_ratio_of_classes':
ser = np.log2(df_mean[pos] / df_mean[neg])
else:
logging.error("Please provide correct method name!!!")
raise LookupError("Input method: %s is not supported"%method)
ser = ser.sort_values(ascending=ascending)
return ser
def gsea_compute_tensor(data, gmt, n, weighted_score_type, permutation_type,
method, pheno_pos, pheno_neg, classes, ascending,
processes=1, seed=None, single=False, scale=False):
"""compute enrichment scores and enrichment nulls.
This function will split large array into smaller pieces to advoid memroy overflow.
:param data: preprocessed expression dataframe or a pre-ranked file if prerank=True.
:param dict gmt: all gene sets in .gmt file. need to call load_gmt() to get results.
:param int n: permutation number. default: 1000.
:param str method: ranking_metric method. see above.
:param str pheno_pos: one of labels of phenotype's names.
:param str pheno_neg: one of labels of phenotype's names.
:param list classes: a list of phenotype labels, to specify which column of dataframe belongs to what category of phenotype.
:param float weighted_score_type: default:1
:param bool ascending: sorting order of rankings. Default: False.
:param seed: random seed. Default: np.random.RandomState()
:param bool scale: if true, scale es by gene number.
:return: a tuple contains::
| zipped results of es, nes, pval, fdr.
| nested list of hit indices of input gene_list.
| nested list of ranked enrichment score of each input gene_sets.
| list of enriched terms
"""
w = weighted_score_type
subsets = sorted(gmt.keys())
genes_mat, cor_mat = data.index.values, data.values
base = 5 if data.shape[0] >= 5000 else 10
## phenotype permutation
np.random.seed(seed) # control the ranodm numbers
if permutation_type == "phenotype":
# shuffling classes and generate random correlation rankings
logging.debug("Start to permutate classes..............................")
if (n + 1) % base == 0: # n+1: last permute is for orignial ES calculation
num_bases = [ base ] * ((n + 1) // base)
skip_last = [0] * ( n // base) + [1] # last is not permuted
else:
num_bases = [ base ] * ((n + 1) // base) + [ (n +1) % base]
skip_last = [0] * ((n + 1) // base) + [ (n +1) % base]
random_seeds = np.random.randint(np.iinfo(np.int32).max, size=len(num_bases))
genes_ind = []
cor_mat = []
# split permutation array into smaller blocks to save memory
temp_rnk = Parallel(n_jobs=processes)(delayed(ranking_metric_tensor)(
data, method, b, pheno_pos, pheno_neg, classes, ascending, se, skip)
for b, skip, se in zip(num_bases, skip_last, random_seeds))
for k, temp in enumerate(temp_rnk):
gi, cor = temp
genes_ind.append(gi)
cor_mat.append(cor)
genes_ind, cor_mat = np.vstack(genes_ind), np.vstack(cor_mat)
# convert to tuple
genes_mat = (data.index.values, genes_ind)
logging.debug("Start to compute es and esnulls........................")
# Prerank, ssGSEA, GSEA
es = []
RES = []
hit_ind = []
esnull = []
temp_esnu = []
# split gmt dataset, too
block = ceil(len(subsets) / base)
random_seeds = np.random.randint(np.iinfo(np.int32).max, size=block)
# split large array into smaller blocks to avoid memory overflow
i, m = 1, 0
gmt_block = []
while i <= block:
# you have to reseed, or all your processes are sharing the same seed value
rs = random_seeds[i-1]
gmtrim = {k: gmt.get(k) for k in subsets[m:base * i]}
gmt_block.append(gmtrim)
m = base * i
i += 1
## if permutation_type == "phenotype": n = 0
## NOTE for GSEA: cor_mat is 2d array, it won't permute again when call enrichment_score_tensor
temp_esnu = Parallel(n_jobs=processes)(delayed(enrichment_score_tensor)(
genes_mat, cor_mat, gmtrim, w, n, rs, single, scale)
for gmtrim, rs in zip(gmt_block, random_seeds))
# esn is a list, don't need to use append method.
for si, temp in enumerate(temp_esnu):
# e, enu, hit, rune = temp.get()
e, enu, hit, rune = temp
esnull.append(enu)
es.append(e)
RES.append(rune)
hit_ind += hit
# concate results
es, esnull, RES = | np.hstack(es) | numpy.hstack |
'''
python -m visdom.server
http://localhost:8097
<env_name>.json file present in your ~/.visdom directory.
tensorboard --logdir=runs
http://localhost:6006/ 非常奇怪的出错
ONNX export failed on ATen operator ifft because torch.onnx.symbolic.ifft does not exist
'''
import seaborn as sns; sns.set()
from PIL import Image
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import DataLoader
from torch.utils.tensorboard import SummaryWriter
import visdom
import matplotlib.pyplot as plt
import numpy as np
import torchvision
import cv2
from torchvision import datasets, transforms
from .Z_utils import COMPLEX_utils as Z
def matplotlib_imshow(img, one_channel=False):
if one_channel:
img = img.mean(dim=0)
img = img / 2 + 0.5 # unnormalize
npimg = img.numpy()
if one_channel:
plt.imshow(npimg, cmap="Greys")
else:
plt.imshow(np.transpose(npimg, (1, 2, 0)))
plt.show()
class Visualize:
def __init__(self,env_title="onnet",plots=[], **kwargs):
self.log_dir = f'runs/{env_title}'
self.plots = plots
self.loss_step = 0
self.writer = SummaryWriter(self.log_dir)
self.img_dir="./dump/images/"
self.dpi = 100
#https://stackoverflow.com/questions/9662995/matplotlib-change-title-and-colorbar-text-and-tick-colors
def MatPlot(self,arr, title=""):
fig, ax = plt.subplots()
#plt.axis('off')
plt.grid(b=None)
im = ax.imshow(arr, interpolation='nearest', cmap='coolwarm')
fig.colorbar(im, orientation='horizontal')
plt.savefig(f'{self.img_dir}{title}.jpg')
#plt.show()
plt.close()
def fig2data(self,fig):
fig.canvas.draw()
if True: # https://stackoverflow.com/questions/42603161/convert-an-image-shown-in-python-into-an-opencv-image
img = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep='')
img = img.reshape(fig.canvas.get_width_height()[::-1] + (3,))
img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
return img
else:
w, h = fig.canvas.get_width_height()
buf = np.fromstring(fig.canvas.tostring_argb(), dtype=np.uint8)
buf.shape = (w, h, 4)
# canvas.tostring_argb give pixmap in ARGB mode. Roll the ALPHA channel to have it in RGBA mode
buf = np.roll(buf, 3, axis=2)
return buf
'''
sns.heatmap 很难用,需用自定义,参见https://stackoverflow.com/questions/53248186/custom-ticks-for-seaborn-heatmap
'''
def HeatMap(self, data, file_name, params={},noAxis=True, cbar=True):
title,isSave = file_name,True
if 'save' in params:
isSave = params['save']
if 'title' in params:
title = params['title']
path = '{}{}_.jpg'.format(self.img_dir, file_name)
sns.set(font_scale=3)
s = max(data.shape[1] / self.dpi, data.shape[0] / self.dpi)
# fig.set_size_inches(18.5, 10.5)
cmap = 'coolwarm' # "plasma" #https://matplotlib.org/examples/color/colormaps_reference.html
# cmap = sns.cubehelix_palette(start=1, rot=3, gamma=0.8, as_cmap=True)
if noAxis: # tight samples for training(No text!!!)
figsize = (s, s)
fig, ax = plt.subplots(figsize=figsize, dpi=self.dpi)
ax = sns.heatmap(data, ax=ax, cmap=cmap, cbar=False, xticklabels=False, yticklabels=False)
fig.savefig(path, bbox_inches='tight', pad_inches=0,figsize=(20,10))
if False:
image = cv2.imread(path)
# image = fig2data(ax.get_figure()) #会放大尺寸,难以理解
if (len(title) > 0):
assert (image.shape == self.args.spp_image_shape) # 必须固定一个尺寸
cv2.imshow("",image); cv2.waitKey(0)
plt.close("all")
return path
else: # for paper
ticks = np.linspace(0, 1, 10)
xlabels = [int(i) for i in | np.linspace(0, 56, 10) | numpy.linspace |
# This includes functions which help with the m9 motions
from __future__ import absolute_import
from __future__ import print_function
import os
import numpy as np
import GMHelper
import SimM9MotionHelper
from requests_toolbelt.adapters import appengine
appengine.monkeypatch()
CLOUD_STORAGE_BUCKET = 'm9-project-bucket-west'
os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = 'M9ProjectBroadbands-412691040693.json'
def GetSynFileFromM9Folder(Realization, Latitude, Longitude, Folder='A', M9Folder='F:/M9/DataArchive/'):
import numpy as np
path = M9Folder + '/' + Realization + '/' + Folder + '/'
SWCornerUTM = [4467300, 100080]
SWCornerLatLong = [40.26059706792827, -127.70217428430801]
import utm
utmcoord = utm.from_latlon(Latitude, Longitude, 10)[:2]
Easting, Northing = utmcoord[0] - SWCornerUTM[1], utmcoord[1] - SWCornerUTM[
0] # these are relative Easting and Northings to the SW corner
# Rounding Function
def round_to(n, precision):
correction = 0.5 if n >= 0 else -0.5
return int(n / precision + correction) * precision
stationid, northing, easting = np.genfromtxt(path + '/BroadbandLocations.utm', skip_header=1, dtype=str,
unpack=True)
northing = np.array(northing, dtype=np.float)
easting = np.array(easting, dtype=np.float)
precision = easting[1] - easting[0]
Easting = round_to(Easting, precision)
Northing = round_to(Northing, precision)
# Get File Name
for i in range(len(northing)):
y = round_to(northing[i], precision)
x = round_to(easting[i], precision)
if Easting == x and Northing == y:
Name = stationid[i]
# print i
break
if i == len(northing) - 1:
print('Syn file not found')
try:
Syn = np.loadtxt(path + '%s/%s.syn' % (Name[0:3], Name))
except:
print('error, rs or ds file not found')
return None
# Find CutOff
cutoffTime = SimM9MotionHelper.GetCutOffTime(Name, Realization, Folder)
cutoffIndex = int(cutoffTime / (Syn[1, 0] - Syn[0, 0]))
class Output():
def __init__(self):
self.FileName = Name
self.time = Syn[:, 0]
self.dt = self.time[1] - self.time[0]
self.ag_Z = Syn[:, 1] / 980. # convert to G
self.ag_X = Syn[:, 3] / 980. #convert to G
self.ag_Y = Syn[:, 2] / 980. #convert to G
self.CutOffIndex = cutoffIndex
self.CutOffTime = cutoffTime
self.LatLon = utm.to_latlon(x + SWCornerUTM[1], y + SWCornerUTM[0], 10, 'T')[:2]
return Output()
def GetSynFileFromM9FolderUsingSynFileName(Realization, SynFileName, Folder='A', M9Folder='F:/M9/DataArchive/'):
import numpy as np
path = M9Folder + '/' + Realization + '/' + Folder + '/'
Name = SynFileName
try:
Syn = np.loadtxt(path + '%s/%s.syn' % (Name[0:3], Name))
except:
print('error, rs or ds file not found')
return None
# Find CutOff
cutoffTime = SimM9MotionHelper.GetCutOffTime(Name, Realization, Folder)
cutoffIndex = int(cutoffTime / (Syn[1, 0] - Syn[0, 0]))
class Output():
def __init__(self):
self.FileName = Name
self.time = Syn[:, 0]
self.dt = self.time[1] - self.time[0]
self.ag_Z = Syn[:, 1] / 980. # convert to G
self.ag_X = Syn[:, 3] / 980. #convert to G
self.ag_Y = Syn[:, 2] / 980. #convert to G
self.CutOffIndex = cutoffIndex
self.CutOffTime = cutoffTime
return Output()
def GetSynFile(SynFileName, Folder):
import numpy as np
if not SynFileName.endswith('.syn'):
SynFileName += '.syn'
try:
Syn = np.loadtxt(Folder + SynFileName)
except:
print('error, file not found')
return None
class Output():
def __init__(self):
self.FileName = SynFileName
self.time = Syn[:, 0]
self.ag_X = Syn[:, 3] / 980. #convert to G
self.ag_Y = Syn[:, 2] / 980. #convert to G
self.ag_Z = Syn[:, 1] / 980. # convert to G
self.Dt = Syn[1,0] - Syn[0,0]
return Output()
def GetIMs(Easting, Northing, BroadbandLocation):
# Rounding Function
def round_to(n, precision):
correction = 0.5 if n >= 0 else -0.5
return int(n / precision + correction) * precision
f = open(BroadbandLocation[:-2] + 'A/BroadBandLocations.utm')
precision = 1000
Easting = round_to(Easting, precision)
Northing = round_to(Northing, precision)
# Get File Name
for line in f.readlines():
line = line.split()
y = round_to(float(line[1]), precision)
x = round_to(float(line[2]), precision)
if Easting == x and Northing == y:
Name = line[0]
import numpy as np
try:
print(Name)
RS = np.loadtxt(BroadbandLocation[:-2] + 'A/%s/RS_(%s).dat' % (Name[0:3], Name))
Ds = | np.loadtxt(BroadbandLocation[:-2] + 'A/%s/Ds_(%s).dat' % (Name[0:3], Name)) | numpy.loadtxt |
import numpy as np
'''
@alt(配列|行列|ベクトル)
@alt(作る=[作る|作成する|初期化する])
@prefix(aArray;[配列|行列|ベクトル])
@prefix(aList;リスト)
@alt(要素ごと|各要素)
ベクトル[の|][演算|計算]を[する|行う]
行列[の|][演算|計算]を[する|行う]
numpyを[使う|入れる|インポートする]
'''
iterable = np.array([0, 1, 2, 3])
aArray = np.array([1, 2, 3, 4])
aArray2 = iterable
aList = [1, 2]
n = 3
要素数 = 3
行数 = 2
列数 = 2
初期値 = 0
行番号 = 0
列番号 = 0
__X__ = np.int
dtype = __X__
'''
@X(np.int;np.int8;np.uint8;np.int16;np.int32;bool;complex)
@Y(整数;8ビット整数;符号なし8ビット整数;32ビット整数;[ブール|論理値];複素数)
<オプション>データ型を指定する
<オプション>__Y__型を使う
'''
np.array(aList)
'''
aListを配列に変換する
{aListから|配列を}作る
'''
np.array(iterable)
'''
iterableを配列に変換する
{iterableから|配列を}作る
'''
np.zeros(要素数)
'''
{全要素を|0で}初期化された配列[|を作る]
ゼロ埋めされた配列[|を作る]
'''
np.zeros(要素数, dtype=__X__)
'''
{ゼロ埋めされた|__Y__型の}配列[|を作る]
'''
np.zeros(行数, 列数)
'''
{全要素を|0で}初期化された行列[|を作る]
ゼロ埋めされた行列[|を作る]
'''
np.zeros(行数, 列数, dtype=__X__)
'''
{{全要素を|0で}初期化された|__Y__型の}行列[|を作る]
'''
np.ones(要素数, dtype=np.int)
'''
{全要素を|1で}初期化された配列[|を作る]
要素が全て1の配列[|を作る]
'''
np.ones(行数, 列数, dtype=np.int)
'''
{全要素を|1で}初期化された行列[|を作る]
全要素が1の行列[|を作る]
'''
np.full(要素数, 初期値, dtype=np.int)
'''
{全要素を|初期値で}初期化された配列[|を作る]
要素が全て初期値の配列[|を作る]
'''
np.full((行数, 列数), 初期値, dtype=np.int)
'''
{全要素を|初期値で}初期化された行列[|を作る]
全要素が初期値の行列[|を作る]
'''
np.eye(行数, 列数)
'''
単位行列[|を作る]
'''
np.identity(N)
'''
[単位正方行列|正方単位行列][|を作る]
'''
np.empty(要素数, dtype=np.int)
'''
未初期化の配列[|を作る]
'''
np.empty((行数, 列数), dtype=np.int)
'''
未初期化の行列[|を作る]
'''
np.empty_like(aArray)
'''
aArrayと同じ大きさの[空配列|空の配列]を作る
'''
N = 10
開始値 = 0
終端値 = 10
等差 = 2
np.arange(N)
'''
0からNまでの配列[|を作る]
'''
np.arange(1, N+1)
'''
1からNまでの配列[|を作る]
'''
np.arange(開始値, 終端値, 等差)
'''
等差数列を配列に変換する
'''
aArray.reshape(行数, 列数)
'''
aArray[の[次元|形状]|]を変形する
'''
aArray.reshape(-1, 1)
'''
aArrayを[2次元1列|縦ベクトル]に変形する
'''
aArray.reshape(1, -1)
'''
aArrayを[2次元1行|横ベクトル]に変形する
'''
np.zeros_like(aArray)
'''
@alt(ベースに=[元に|ベースに][|して])
[既存の|]aArrayをベースに全要素が0の配列[|を作る]
'''
np.ones_like(aArray)
'''
[既存の|]aArrayをベースに全要素が1の配列[|を作る]
'''
np.full_like(aArray, 初期値)
'''
[既存の|]aArrayをベースに全要素が初期値の配列[|を作る]
'''
指定の値 = 0
aArray[:, :] = 指定の値
'''
aArrayの全要素の値を変更する
aArrayの全要素を指定の値にする
'''
aArray[行番号, 列番号]
'''
[行列|aArray]の値[|を得る]
'''
aArray[行番号, 列番号] = 指定の値
'''
[行列|aArray]の値を変更する
'''
aArray[行番号]
'''
[行列|aArray]の行[|を選択する]
'''
aArray[:, 列番号]
'''
[行列|aArray]の列[|を選択する]
'''
# ユニーク
np.unique(aArray)
'''
[|aArrayの]ユニークな値を要素とする配列[|を得る]
'''
np.unique(aArray, return_counts=True)
'''
[|aArrayの]ユニークな要素ごとの[頻度|出現回数][|を得る]
'''
# 転置行列
[list(x) for x in list(zip(*aList))]
'''
2次元リストを転置する
2次元リストの転置行列[|を求める]
'''
aArray.T
'''
aArrayを転置する
[行列|aArray]の転置行列[|を求める]
'''
aArray + aArray2
'''
aArrayの和[|を求める]
aArrayの要素ごとに加算する
'''
aArray - aArray2
'''
aArrayの差[|を求める]
'''
aArray * n
'''
aArrayのスカラー倍[|を求める]
'''
np.multiply(aArray, aArray2)
'''
aArrayの要素ごとの[積|アダマール積][|を求める]
'''
np.dot(aArray, aArray2)
'''
aArrayの内積[|を求める]
'''
np.matmul(aArray, aArray2)
'''
[[行列|aArray]の|]行列積[|を求める]
'''
np.linalg.inv(aArray)
'''
[[行列|aArray]の|]逆行列[|を求める]
'''
np.linalg.pinv(aArray)
'''
[[行列|aArray]の|]ムーア・ペンローズの擬似逆行列[|を求める]
'''
np.linalg.det(aArray)
'''
[[行列|aArray]の|]行列式[|を求める]
'''
| np.linalg.eig(aArray) | numpy.linalg.eig |
#=======================================================================
""" A set of utilities for comparing results.
"""
#=======================================================================
from __future__ import division
import matplotlib
from matplotlib.testing.noseclasses import ImageComparisonFailure
from matplotlib.testing import image_util, util
from matplotlib import _png
from matplotlib import _get_configdir
from distutils import version
import hashlib
import math
import operator
import os
import numpy as np
import shutil
import subprocess
import sys
from functools import reduce
#=======================================================================
__all__ = [
'compare_float',
'compare_images',
'comparable_formats',
]
#-----------------------------------------------------------------------
def make_test_filename(fname, purpose):
"""
Make a new filename by inserting `purpose` before the file's
extension.
"""
base, ext = os.path.splitext(fname)
return '%s-%s%s' % (base, purpose, ext)
def compare_float( expected, actual, relTol = None, absTol = None ):
"""Fail if the floating point values are not close enough, with
the givem message.
You can specify a relative tolerance, absolute tolerance, or both.
"""
if relTol is None and absTol is None:
exMsg = "You haven't specified a 'relTol' relative tolerance "
exMsg += "or a 'absTol' absolute tolerance function argument. "
exMsg += "You must specify one."
raise ValueError(exMsg)
msg = ""
if absTol is not None:
absDiff = abs( expected - actual )
if absTol < absDiff:
expectedStr = str( expected )
actualStr = str( actual )
absDiffStr = str( absDiff )
absTolStr = str( absTol )
msg += "\n"
msg += " Expected: " + expectedStr + "\n"
msg += " Actual: " + actualStr + "\n"
msg += " Abs Diff: " + absDiffStr + "\n"
msg += " Abs Tol: " + absTolStr + "\n"
if relTol is not None:
# The relative difference of the two values. If the expected value is
# zero, then return the absolute value of the difference.
relDiff = abs( expected - actual )
if expected:
relDiff = relDiff / abs( expected )
if relTol < relDiff:
# The relative difference is a ratio, so it's always unitless.
relDiffStr = str( relDiff )
relTolStr = str( relTol )
expectedStr = str( expected )
actualStr = str( actual )
msg += "\n"
msg += " Expected: " + expectedStr + "\n"
msg += " Actual: " + actualStr + "\n"
msg += " Rel Diff: " + relDiffStr + "\n"
msg += " Rel Tol: " + relTolStr + "\n"
if msg:
return msg
else:
return None
#-----------------------------------------------------------------------
# A dictionary that maps filename extensions to functions that map
# parameters old and new to a list that can be passed to Popen to
# convert files with that extension to png format.
def get_cache_dir():
cache_dir = os.path.join(_get_configdir(), 'test_cache')
if not os.path.exists(cache_dir):
try:
os.makedirs(cache_dir)
except IOError:
return None
if not os.access(cache_dir, os.W_OK):
return None
return cache_dir
def get_file_hash(path, block_size=2**20):
md5 = hashlib.md5()
with open(path, 'rb') as fd:
while True:
data = fd.read(block_size)
if not data:
break
md5.update(data)
return md5.hexdigest()
converter = { }
def make_external_conversion_command(cmd):
def convert(old, new):
cmdline = cmd(old, new)
pipe = subprocess.Popen(cmdline, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = pipe.communicate()
errcode = pipe.wait()
if not os.path.exists(new) or errcode:
msg = "Conversion command failed:\n%s\n" % ' '.join(cmdline)
if stdout:
msg += "Standard output:\n%s\n" % stdout
if stderr:
msg += "Standard error:\n%s\n" % stderr
raise IOError(msg)
return convert
if matplotlib.checkdep_ghostscript() is not None:
def make_ghostscript_conversion_command():
# FIXME: make checkdep_ghostscript return the command
if sys.platform == 'win32':
gs = 'gswin32c'
else:
gs = 'gs'
cmd = [gs, '-q', '-sDEVICE=png16m', '-sOutputFile=-']
process = util.MiniExpect(cmd)
def do_convert(old, new):
process.expect("GS>")
process.sendline("(%s) run" % old)
with open(new, 'wb') as fd:
process.expect(">>showpage, press <return> to continue<<", fd)
process.sendline('')
return do_convert
converter['pdf'] = make_ghostscript_conversion_command()
converter['eps'] = make_ghostscript_conversion_command()
if matplotlib.checkdep_inkscape() is not None:
cmd = lambda old, new: \
['inkscape', '-z', old, '--export-png', new]
converter['svg'] = make_external_conversion_command(cmd)
def comparable_formats():
'''Returns the list of file formats that compare_images can compare
on this system.'''
return ['png'] + converter.keys()
def convert(filename, cache):
'''
Convert the named file into a png file. Returns the name of the
created file.
If *cache* is True, the result of the conversion is cached in
`~/.matplotlib/test_cache/`. The caching is based on a hash of the
exact contents of the input file. The is no limit on the size of
the cache, so it may need to be manually cleared periodically.
'''
base, extension = filename.rsplit('.', 1)
if extension not in converter:
raise ImageComparisonFailure("Don't know how to convert %s files to png" % extension)
newname = base + '_' + extension + '.png'
if not os.path.exists(filename):
raise IOError("'%s' does not exist" % filename)
# Only convert the file if the destination doesn't already exist or
# is out of date.
if (not os.path.exists(newname) or
os.stat(newname).st_mtime < os.stat(filename).st_mtime):
if cache:
cache_dir = get_cache_dir()
else:
cache_dir = None
if cache_dir is not None:
hash = get_file_hash(filename)
new_ext = os.path.splitext(newname)[1]
cached_file = os.path.join(cache_dir, hash + new_ext)
if os.path.exists(cached_file):
shutil.copyfile(cached_file, newname)
return newname
converter[extension](filename, newname)
if cache_dir is not None:
shutil.copyfile(newname, cached_file)
return newname
verifiers = { }
def verify(filename):
"""
Verify the file through some sort of verification tool.
"""
if not os.path.exists(filename):
raise IOError("'%s' does not exist" % filename)
base, extension = filename.rsplit('.', 1)
verifier = verifiers.get(extension, None)
if verifier is not None:
cmd = verifier(filename)
pipe = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = pipe.communicate()
errcode = pipe.wait()
if errcode != 0:
msg = "File verification command failed:\n%s\n" % ' '.join(cmd)
if stdout:
msg += "Standard output:\n%s\n" % stdout
if stderr:
msg += "Standard error:\n%s\n" % stderr
raise IOError(msg)
# Turning this off, because it seems to cause multiprocessing issues
if matplotlib.checkdep_xmllint() and False:
verifiers['svg'] = lambda filename: [
'xmllint', '--valid', '--nowarning', '--noout', filename]
def crop_to_same(actual_path, actual_image, expected_path, expected_image):
# clip the images to the same size -- this is useful only when
# comparing eps to pdf
if actual_path[-7:-4] == 'eps' and expected_path[-7:-4] == 'pdf':
aw, ah = actual_image.shape
ew, eh = expected_image.shape
actual_image = actual_image[int(aw/2-ew/2):int(aw/2+ew/2),int(ah/2-eh/2):int(ah/2+eh/2)]
return actual_image, expected_image
def compare_images( expected, actual, tol, in_decorator=False ):
'''Compare two image files - not the greatest, but fast and good enough.
= EXAMPLE
# img1 = "./baseline/plot.png"
# img2 = "./output/plot.png"
#
# compare_images( img1, img2, 0.001 ):
= INPUT VARIABLES
- expected The filename of the expected image.
- actual The filename of the actual image.
- tol The tolerance (a unitless float). This is used to
determine the 'fuzziness' to use when comparing images.
- in_decorator If called from image_comparison decorator, this should be
True. (default=False)
'''
verify(actual)
# Convert the image to png
extension = expected.split('.')[-1]
if extension != 'png':
actual = convert(actual, False)
expected = convert(expected, True)
# open the image files and remove the alpha channel (if it exists)
expectedImage = _png.read_png_int( expected )
actualImage = _png.read_png_int( actual )
actualImage, expectedImage = crop_to_same(actual, actualImage, expected, expectedImage)
# compare the resulting image histogram functions
expected_version = version.LooseVersion("1.6")
found_version = version.LooseVersion(np.__version__)
# On Numpy 1.6, we can use bincount with minlength, which is much faster than
# using histogram
if found_version >= expected_version:
rms = 0
for i in xrange(0, 3):
h1p = expectedImage[:,:,i]
h2p = actualImage[:,:,i]
h1h = np.bincount(h1p.ravel(), minlength=256)
h2h = np.bincount(h2p.ravel(), minlength=256)
rms += np.sum(np.power((h1h-h2h), 2))
else:
rms = 0
bins = np.arange(257)
for i in xrange(0, 3):
h1p = expectedImage[:,:,i]
h2p = actualImage[:,:,i]
h1h = np.histogram(h1p, bins=bins)[0]
h2h = np.histogram(h2p, bins=bins)[0]
rms += np.sum(np.power((h1h-h2h), 2))
rms = | np.sqrt(rms / (256 * 3)) | numpy.sqrt |
from __future__ import print_function
# Helper functions
import numpy as np
import quantities as pq
from quantities import Quantity
import yaml
import elephant
import os
from os.path import join
import MEAutility as MEA
import h5py
### LOAD FUNCTIONS ###
def load_tmp_eap(templates_folder, celltypes=None, samples_per_cat=None):
'''
Loads EAP from temporary folder
Parameters
----------
templates_folder: temporary folder
celltypes: (optional) list of celltypes to be loaded
samples_per_cat (optional) number of eap to load per category
Returns
-------
templates, locations, rotations, celltypes, info
'''
print("Loading spike data ...")
spikelist = [f for f in os.listdir(templates_folder) if f.startswith('eap')]
loclist = [f for f in os.listdir(templates_folder) if f.startswith('pos')]
rotlist = [f for f in os.listdir(templates_folder) if f.startswith('rot')]
infolist = [f for f in os.listdir(templates_folder) if f.startswith('info')]
spikes_list = []
loc_list = []
rot_list = []
cat_list = []
spikelist = sorted(spikelist)
loclist = sorted(loclist)
rotlist = sorted(rotlist)
infolist = sorted(infolist)
loaded_categories = set()
ignored_categories = set()
for idx, f in enumerate(spikelist):
celltype = f.split('-')[1][:-4]
print('loading cell type: ', f)
if celltypes is not None:
if celltype in celltypes:
spikes = np.load(join(templates_folder, f))
locs = np.load(join(templates_folder, loclist[idx]))
rots = np.load(join(templates_folder, rotlist[idx]))
if samples_per_cat is None or samples_per_cat > len(spikes):
samples_to_read = len(spikes)
else:
samples_to_read = samples_per_cat
spikes_list.extend(spikes[:samples_to_read])
rot_list.extend(rots[:samples_to_read])
loc_list.extend(locs[:samples_to_read])
cat_list.extend([celltype] * samples_to_read)
loaded_categories.add(celltype)
else:
ignored_categories.add(celltype)
else:
spikes = np.load(join(templates_folder, f))
locs = np.load(join(templates_folder, loclist[idx]))
rots = np.load(join(templates_folder, rotlist[idx]))
if samples_per_cat is None or samples_per_cat > len(spikes):
samples_to_read = len(spikes)
else:
samples_to_read = samples_per_cat
spikes_list.extend(spikes[:samples_to_read])
rot_list.extend(rots[:samples_to_read])
loc_list.extend(locs[:samples_to_read])
cat_list.extend([celltype] * samples_to_read)
loaded_categories.add(celltype)
# load info
with open(join(templates_folder, infolist[0]), 'r') as fl:
info = yaml.load(fl)
info['General'].pop('cell name', None)
print("Done loading spike data ...")
return np.array(spikes_list), np.array(loc_list), np.array(rot_list), np.array(cat_list, dtype=str), info
def load_templates(template_folder):
'''
Load generated eap templates (from template_gen.py)
Parameters
----------
template_folder: templates folder
Returns
-------
templates, locations, rotations, celltypes - np.arrays
info - dict
'''
print("Loading templates...")
templates = np.load(join(template_folder, 'templates.npy'))
locs = np.load(join(template_folder, 'locations.npy'))
rots = np.load(join(template_folder, 'rotations.npy'))
celltypes = np.load(join(template_folder, 'celltypes.npy'))
with open(join(template_folder, 'info.yaml'), 'r') as f:
info = yaml.load(f)
print("Done loading templates...")
return templates, locs, rots, celltypes, info
def load_spiketrains(spiketrain_folder):
'''
Load generated spike trains (from spiketrain_gen.py)
Parameters
----------
spiketrain_folder: spiketrain folder
Returns
-------
spiketrains - list of neo.Spiketrain
info - dict
'''
print("Loading spike trains...")
spiketrains = np.load(join(spiketrain_folder, 'gtst.npy'))
# jfm 9/25/19 -- make info.yaml in spiketrain folder optional
if os.path.exists(join(spiketrain_folder, 'info.yaml')):
with open(join(spiketrain_folder, 'info.yaml'), 'r') as f:
info = yaml.load(f)
else:
info={}
print("Done loading spike trains...")
return spiketrains, info
def load_recordings(recording_folder):
'''
Load generated recordings (from template_gen.py)
Parameters
----------
recording_folder: recordings folder
Returns
-------
recordings, times, positions, templates, spiketrains, sources, peaks - np.arrays
info - dict
'''
print("Loading recordings...")
recordings = np.load(join(recording_folder, 'recordings.npy'))
positions = np.load(join(recording_folder, 'positions.npy'))
times = np.load(join(recording_folder, 'times.npy'))
templates = np.load(join(recording_folder, 'templates.npy'))
spiketrains = np.load(join(recording_folder, 'spiketrains.npy'))
sources = np.load(join(recording_folder, 'sources.npy'))
peaks = np.load(join(recording_folder, 'peaks.npy'))
with open(join(recording_folder, 'info.yaml'), 'r') as f:
info = yaml.load(f)
if not isinstance(times, pq.Quantity):
times = times * pq.ms
print("Done loading recordings...")
return recordings, times, positions, templates, spiketrains, sources, peaks, info
### TEMPLATES INFO ###
def get_binary_cat(celltypes, excit, inhib):
'''
Parameters
----------
celltypes: np.array with celltypes
excit: list of excitatory celltypes
inhib: list of inhibitory celltypes
Returns
-------
bin_cat: binary celltype (E-I) - np.array
'''
binary_cat = []
for i, cat in enumerate(celltypes):
if np.any([ex in str(cat) for ex in excit]):
binary_cat.append('E')
elif np.any([inh in str(cat) for inh in inhib]):
binary_cat.append('I')
return np.array(binary_cat, dtype=str)
def get_EAP_features(EAP, feat_list, dt=None, EAP_times=None, threshold_detect=0, normalize=False):
'''
Parameters
----------
EAP
feat_list
dt
EAP_times
threshold_detect
normalize
Returns
-------
'''
reference_mode = 't0'
if EAP_times is not None and dt is not None:
test_dt = (EAP_times[-1] - EAP_times[0]) / (len(EAP_times) - 1)
if dt != test_dt:
raise ValueError('EAP_times and dt do not match.')
elif EAP_times is not None:
dt = (EAP_times[-1] - EAP_times[0]) / (len(EAP_times) - 1)
elif dt is not None:
EAP_times = np.arange(EAP.shape[-1]) * dt
else:
raise NotImplementedError('Please, specify either dt or EAP_times.')
if len(EAP.shape) == 1:
EAP = np.reshape(EAP, [1, 1, -1])
elif len(EAP.shape) == 2:
EAP = np.reshape(EAP, [1, EAP.shape[0], EAP.shape[1]])
if len(EAP.shape) != 3:
raise ValueError('Cannot handle EAPs with shape', EAP.shape)
if normalize:
signs = np.sign(np.min(EAP.reshape([EAP.shape[0], -1]), axis=1))
norm = np.abs(np.min(EAP.reshape([EAP.shape[0], -1]), axis=1))
EAP = np.array([EAP[i] / n if signs[i] > 0 else EAP[i] / n - 2. for i, n in enumerate(norm)])
features = {}
amps = np.zeros((EAP.shape[0], EAP.shape[1]))
na_peak = | np.zeros((EAP.shape[0], EAP.shape[1])) | numpy.zeros |
import logging
import os
import traceback
from argparse import ArgumentParser
from typing import List
import numpy as np
import pandas as pd
from scipy import stats
from record import Record, record_factory, EXPECTED_SUBGRAPH_NUMBER, convert_subgraph_index_to_label
from visualize import boxplot, lineplot, heatmap, scatterplot, MultiPageContext, errorbar
def rankdata_greater(row):
return stats.rankdata(-row, method="ordinal")
def get_consecutive_rank_tau(df):
ret = np.zeros((len(df) - 1,))
for i in range(1, len(df)):
ret[i - 1], _ = stats.kendalltau(df.iloc[i - 1], df.iloc[i])
return ret
def get_tau_curves_by_groups(df, gt, group_table, groups):
return {cur: get_tau_along_epochs(df, gt, np.where(group_table == cur)[0]) for cur in groups}
def get_tau_along_epochs(df, gt, group):
return np.array([stats.kendalltau(row[group].values, gt[group])[0] for _, row in df.iterrows()])
def get_tau_along_epochs_combining_best_groups(df, gt, group_table, groups, universe):
tau_curves_by_groups = get_tau_curves_by_groups(df, gt, group_table, groups)
ref_gt_acc = np.zeros((len(df), EXPECTED_SUBGRAPH_NUMBER))
for cur in groups:
# for each group, enumerate the epochs from the most obedient to most rebellious
for i, loc in enumerate(np.argsort(-tau_curves_by_groups[cur])):
group_mask = np.where(group_table == cur)[0]
ref_gt_acc[i][group_mask] = df[group_mask].iloc[loc]
ref_gt_acc_tau = np.array([stats.kendalltau(acc[universe], gt[universe])[0] for acc in ref_gt_acc])
return ref_gt_acc, ref_gt_acc_tau
def get_top_k_acc_rank(acc_table, acc_gt):
gt_rank = rankdata_greater(acc_gt)
idx = np.stack([np.argsort(-row) for row in acc_table])
top_acc = np.maximum.accumulate(acc_gt[idx], 1)
top_rank = np.minimum.accumulate(gt_rank[idx], 1)
return top_acc, top_rank
def report_mean_std_max_min(analysis_dir, logger, name, arr):
np.savetxt(os.path.join(analysis_dir, "METRICS-{}.txt".format(name)),
np.array([np.mean(arr), np.std(arr), np.max(arr), np.min(arr)]))
logger.info("{}: mean={:.4f}, std={:.4f}, max={:.4f}, min={:.4f}".format(name, np.mean(arr), np.std(arr),
np.max(arr), np.min(arr)))
def stack_with_index(index, row):
return np.stack([index, row]).T
def plot_top_k_variance_chart(filepath, index, top_acc, top_rank, gt_acc, topk):
gt_acc_index = np.argsort(-gt_acc)
curves = []
for k in topk:
curves.append(stack_with_index(index, np.array([gt_acc[gt_acc_index[k - 1]]] * top_acc.shape[0])))
curves.append(stack_with_index(index, top_acc[:, k - 1]))
lineplot(curves, filepath=filepath + "_acc")
curves = []
for k in topk:
curves.append(stack_with_index(index, np.array([k] * top_acc.shape[0])))
curves.append(stack_with_index(index, top_rank[:, k - 1]))
lineplot(curves, filepath=filepath + "_rank", inverse_y=True)
def pipeline_for_single_instance(logger, analysis_dir, main: Record, finetune: List[Record], by: str, gt: np.ndarray):
logger.info("Analysing results for {}".format(analysis_dir))
main_df = main.validation_acc_dataframe(by)
main_archit = main.grouping_subgraph_training_dataframe(by)
main_grouping = main.grouping_numpy
os.makedirs(analysis_dir, exist_ok=True)
# Save raw data
main_df.to_csv(os.path.join(analysis_dir, "val_acc_all_epochs.csv"), index=True)
np.savetxt(os.path.join(analysis_dir, "group_info.txt"), main_grouping, "%d")
# correlation between subgraphs
corr_matrix = main_df.corr().values
heatmap(corr_matrix, filepath=os.path.join(analysis_dir, "corr_heatmap"))
np.savetxt(os.path.join(analysis_dir, "corr_heatmap.txt"), corr_matrix)
# Consecutive tau (single)
consecutive_taus = get_consecutive_rank_tau(main_df)
lineplot([np.array(list(zip(main_df.index[1:], consecutive_taus)))],
filepath=os.path.join(analysis_dir, "consecutive_tau_single"))
# GT rank (for color reference)
gt_rank = rankdata_greater(gt)
gt_rank_color = 1 - gt_rank / EXPECTED_SUBGRAPH_NUMBER
# in some cases, it could be a subset of 64 subgraphs; process this later
# Acc variance (lineplot)
acc_curves = [np.array(list(zip(main_df.index, main_df[i]))) for i in main_df.columns]
subgraph_markers = [[] for _ in range(EXPECTED_SUBGRAPH_NUMBER)]
if len(main.groups) != len(main.columns): # hide it for ground truth
for i, (_, row) in enumerate(main_archit.iterrows()):
for k in filter(lambda k: k >= 0, row.values):
subgraph_markers[k].append(i)
else:
logger.info("Markers hidden because groups == columns")
lineplot(acc_curves, filepath=os.path.join(analysis_dir, "acc_curve_along_epochs"),
color=[gt_rank_color[i] for i in main_df.columns], alpha=0.7,
markers=[subgraph_markers[i] for i in main_df.columns],
fmt=["-D"] * len(acc_curves))
# Rank version of df
df_rank = main_df.apply(rankdata_greater, axis=1, result_type="expand")
df_rank.columns = main_df.columns
# Rank variance (lineplot)
rank_curves = [np.array(list(zip(df_rank.index, df_rank[i]))) for i in df_rank.columns]
lineplot(rank_curves, filepath=os.path.join(analysis_dir, "rank_curve_along_epochs"),
color=[gt_rank_color[i] for i in df_rank.columns], alpha=0.7, inverse_y=True, markers=subgraph_markers)
# Rank variance for top-5 subgraphs found at half and end
# recalculate for original order
for loc in [len(main_df) // 2, len(main_df) - 1]:
selected_rank_curves = [rank_curves[i] for i in np.argsort(-main_df.iloc[loc])[:5]]
lineplot(selected_rank_curves, inverse_y=True,
filepath=os.path.join(analysis_dir, "rank_curves_along_epochs_for_ep{}".format(main_df.index[loc])))
# Rank variance (boxplot), sorted by the final rank
boxplot(sorted(df_rank.values.T, key=lambda d: d[-1]),
filepath=os.path.join(analysis_dir, "rank_boxplot_along_epochs_sorted_final_rank"),
inverse_y=True)
gt_order = np.argsort(-gt)
# Group info
np.savetxt(os.path.join(analysis_dir, "group_info_sorted_gt.txt"), main_grouping[gt_order], "%d")
# Rank variance (boxplot), sorted by ground truth
boxplot([df_rank[i] for i in gt_order if i in df_rank.columns], inverse_y=True,
filepath=os.path.join(analysis_dir, "rank_boxplot_along_epochs_sorted_gt_rank"))
boxplot([df_rank[i][-10:] for i in gt_order if i in df_rank.columns], inverse_y=True,
filepath=os.path.join(analysis_dir, "rank_boxplot_along_epochs_sorted_gt_rank_last_10"))
# Tau every epoch
gt_tau_data = get_tau_along_epochs(main_df, gt, main.columns)
report_mean_std_max_min(analysis_dir, logger, "GT-Tau-In-Window", gt_tau_data)
lineplot([stack_with_index(main_df.index, gt_tau_data)],
filepath=os.path.join(analysis_dir, "tau_curve_along_epochs"))
if finetune:
# Finetune curves
for data in finetune:
try:
finetune_step = data.finetune_step
if by == "epochs":
finetune_step //= 196
half_length = len(main_df.loc[main_df.index <= finetune_step])
finetune_df = data.validation_acc_dataframe(by, cutoff=finetune_step).iloc[:half_length]
if finetune_step < min(main_df.index) - 1 or finetune_step > max(main_df.index) + 1:
continue
finetune_df.index += finetune_step
finetune_curves = [np.array([[finetune_step, main_df.loc[finetune_step, i]]] +
list(zip(finetune_df.index, finetune_df[i])))
for i in main_df.columns]
finetune_tau_curve = get_tau_along_epochs(finetune_df, gt, data.columns)
finetune_colors = [gt_rank_color[i] for i in finetune_df.columns]
logger.info("Finetune step {}, found {} finetune curves".format(finetune_step, len(finetune_curves)))
lineplot([c[:half_length] for c in acc_curves] + finetune_curves,
filepath=os.path.join(analysis_dir,
"acc_curve_along_epochs_finetune_{}".format(finetune_step)),
color=[gt_rank_color[i] for i in main_df.columns] + finetune_colors, alpha=0.7,
fmt=["-"] * len(acc_curves) + [":"] * len(finetune_curves))
lineplot([stack_with_index(main_df.index, gt_tau_data)[:half_length],
np.concatenate((np.array([[finetune_step, gt_tau_data[half_length - 1]]]),
stack_with_index(finetune_df.index, finetune_tau_curve)))],
filepath=os.path.join(analysis_dir,
"tau_curve_along_epochs_finetune_{}".format(finetune_step)),
color=["tab:blue", "tab:blue"], alpha=1, fmt=["-", ":"])
except ValueError:
pass
# Tau every epoch group by groups
grouping_info_backup = main.grouping_info.copy()
divide_group = main.group_number == 1 and len(main.columns) == 64
for partition_file in [None] + list(os.listdir("assets")):
suffix = ""
if partition_file is not None:
if not partition_file.startswith("partition"):
continue
if not divide_group:
continue
suffix = "_" + os.path.splitext(partition_file)[0]
# regrouping
main.grouping_info = {idx: g for idx, g in enumerate(np.loadtxt(os.path.join("assets", partition_file),
dtype=np.int))}
tau_curves_by_groups = get_tau_curves_by_groups(main_df, gt, main.grouping_numpy, main.groups)
tau_curves_by_groups_mean = [np.mean(tau_curves_by_groups[cur]) for cur in main.groups]
tau_curves_by_groups_std = [np.std(tau_curves_by_groups[cur]) for cur in main.groups]
report_mean_std_max_min(analysis_dir, logger, "GT-Tau-By-Groups-Mean{}".format(suffix),
np.array(tau_curves_by_groups_mean))
report_mean_std_max_min(analysis_dir, logger, "GT-Tau-By-Groups-Std{}".format(suffix),
np.array(tau_curves_by_groups_std))
tau_curves_by_groups_for_plt = [stack_with_index(main_df.index, tau_curves_by_groups[cur])
for cur in main.groups]
pd.DataFrame(tau_curves_by_groups, columns=main.groups, index=main_df.index).to_csv(
os.path.join(analysis_dir, "tau_curves_by_groups{}.csv".format(suffix))
)
lineplot(tau_curves_by_groups_for_plt,
filepath=os.path.join(analysis_dir, "tau_curves_by_groups{}".format(suffix)))
# Acc curves (by group)
with MultiPageContext(os.path.join(analysis_dir, "acc_curve_along_epochs_group_each{}".format(suffix))) as pdf:
for g in range(main.group_number):
subgraphs = np.where(main.grouping_numpy == g)[0]
gt_rank_group = [gt_rank_color[i] for i in subgraphs]
subgraph_names = list(map(convert_subgraph_index_to_label, subgraphs))
subgraph_names_ranks = ["{} (Rank {})".format(name, gt_rank[i])
for name, i in zip(subgraph_names, subgraphs)]
# cannot leverage acc_curves, because it's a list, this can be a subset, which cannot be used as index
lineplot([np.array(list(zip(main_df.index, main_df[i]))) for i in subgraphs] +
[stack_with_index(main_df.index, [gt[i]] * len(main_df.index)) for i in subgraphs],
context=pdf, color=gt_rank_group * 2, alpha=0.8, labels=subgraph_names_ranks,
fmt=["-D"] * len(subgraphs) + ["--"] * len(subgraphs),
markers=[subgraph_markers[i] for i in subgraphs] + [[]] * len(subgraphs),
title="Group {}, Subgraph {} -- {}".format(g, "/".join(map(str, subgraphs)),
"/".join(subgraph_names)))
main.grouping_info = grouping_info_backup
# Tau among steps
for k in (10, 64):
max_tau_calc = min(k, len(main_df))
tau_correlation = np.zeros((max_tau_calc, max_tau_calc))
for i in range(max_tau_calc):
for j in range(max_tau_calc):
tau_correlation[i][j] = stats.kendalltau(main_df.iloc[-i - 1], main_df.iloc[-j - 1])[0]
heatmap(tau_correlation, filepath=os.path.join(analysis_dir, "tau_correlation_last_{}".format(k)))
np.savetxt(os.path.join(analysis_dir, "tau_correlation_last_{}.txt".format(k)), tau_correlation)
tau_correlation = tau_correlation[np.triu_indices_from(tau_correlation, k=1)]
report_mean_std_max_min(analysis_dir, logger, "Tau-as-Corr-Last-{}".format(k), tau_correlation)
# Calculate best tau and log
ref_gt_acc, ref_gt_acc_tau = get_tau_along_epochs_combining_best_groups(main_df, gt, main_grouping, main.groups,
main.columns)
pd.DataFrame(ref_gt_acc).to_csv(os.path.join(analysis_dir,
"acc_epochs_combining_different_epochs_sorted_gt.csv"))
lineplot([stack_with_index(np.arange(len(ref_gt_acc_tau)), ref_gt_acc_tau)],
filepath=os.path.join(analysis_dir, "tau_curve_epochs_sorted_combining_different_epochs"))
# Show subgraph for each batch
scatterplot([stack_with_index(main_archit.index, main_archit[col]) for col in main_archit.columns],
filepath=os.path.join(analysis_dir, "subgraph_id_for_each_batch_validated"))
# Substituted with ground truth rank
scatterplot([stack_with_index(main_archit.index, gt_rank[main_archit[col]]) for col in main_archit.columns],
filepath=os.path.join(analysis_dir, "subgraph_rank_for_each_batch_validated"),
inverse_y=True)
# Top-K-Rank
top_acc, top_rank = get_top_k_acc_rank(main_df.values, gt)
plot_top_k_variance_chart(os.path.join(analysis_dir, "top_k_along_epochs"), main_df.index,
top_acc, top_rank, gt, (1, 3))
# Observe last window (for diff. epochs)
for k in (10, 64,):
report_mean_std_max_min(analysis_dir, logger, "GT-Tau-In-Window-Last-{}".format(k), gt_tau_data[-k:])
for v in (1, 3):
report_mean_std_max_min(analysis_dir, logger, "Top-{}-Rank-Last-{}".format(v, k), top_rank[-k:, v - 1])
def pipeline_for_inter_instance(logger, analysis_dir, data, by, gt):
logger.info("Analysing results for {}".format(analysis_dir))
data_as_df = [d.validation_acc_dataframe(by) for d in data]
os.makedirs(analysis_dir, exist_ok=True)
subgraphs = data[0].columns
for d in data:
assert d.columns == subgraphs
final_acc = np.zeros((len(data), len(subgraphs)))
for i, df in enumerate(data_as_df):
final_acc[i] = df.iloc[-1]
# Consecutive tau (multi)
lineplot([np.array(list(zip(df.index[1:], get_consecutive_rank_tau(df)))) for df in data_as_df],
filepath=os.path.join(analysis_dir, "taus_consecutive_epochs"))
# Final acc distribution
boxplot(final_acc, filepath=os.path.join(analysis_dir, "final_acc"))
# Final rank distribution
final_rank = np.stack([rankdata_greater(row) for row in final_acc])
boxplot(final_rank, filepath=os.path.join(analysis_dir, "final_rank_boxplot"), inverse_y=True)
# GT-Tau
gt_tau = np.array([stats.kendalltau(row, gt[subgraphs])[0] for row in final_acc])
np.savetxt(os.path.join(analysis_dir, "inst_gt_tau.txt"), gt_tau)
report_mean_std_max_min(analysis_dir, logger, "GT-Tau", gt_tau)
# Tau every epoch
tau_data = [get_tau_along_epochs(df, gt, subgraphs) for df in data_as_df]
tau_data_mean_over_instances = np.mean(np.stack(tau_data, axis=0), axis=0)
report_mean_std_max_min(analysis_dir, logger, "GT-Tau-In-Window", np.concatenate(tau_data))
tau_curves = [stack_with_index(df.index, tau_d) for df, tau_d in zip(data_as_df, tau_data)]
lineplot(tau_curves, filepath=os.path.join(analysis_dir, "tau_curve_along_epochs"))
for k in (10, 64):
tau_data_clip = [t[-k:] for t in tau_data]
report_mean_std_max_min(analysis_dir, logger, "GT-Tau-In-Window-Last-{}-Mean".format(k),
np.array([np.mean(t) for t in tau_data_clip]))
report_mean_std_max_min(analysis_dir, logger, "GT-Tau-In-Window-Last-{}-Std".format(k),
np.array([np.std(t) for t in tau_data_clip]))
report_mean_std_max_min(analysis_dir, logger, "GT-Tau-In-Window-Last-{}-Max".format(k),
np.array([ | np.max(t) | numpy.max |
import os
from torch.utils.data import Dataset, DataLoader
import torch
import numpy as np
from .base import print_loaded_dataset_shapes, log_call_parameters
class DSpritesDataset(Dataset):
def __init__(self, indices, classification=False, colored=False, data_file=None):
super(DSpritesDataset, self).__init__()
if data_file is None:
data_file = os.path.join(os.environ['DATA_DIR'], 'dsprites-dataset',
'dsprites_ndarray_co1sh3sc6or40x32y32_64x64.npz')
data = np.load(data_file, encoding='latin1', allow_pickle=True)
self.indices = indices
# color related stuff
self.colored = colored
self.colors = None
self.n_colors = 1
indices_without_color = indices
if colored:
color_file = os.path.join(os.path.dirname(os.path.abspath(__file__)),
'resources/rainbow-7.npy')
self.colors = np.load(color_file)
self.n_colors = len(self.colors)
indices_without_color = [idx // self.n_colors for idx in indices]
# factor_names and factor_sizes
meta = data['metadata'].item()
self.factor_names = list(meta['latents_names'][1:])
self.factor_sizes = list(meta['latents_sizes'][1:])
if colored:
self.factor_names.append('color')
self.factor_sizes.append(self.n_colors)
self.n_factors = len(self.factor_names)
# save relevant part of the grid
self.imgs = data['imgs'][indices_without_color]
# factor values, classes, possible_values
self.factor_values = data['latents_values'][indices_without_color]
self.factor_values = [arr[1:] for arr in self.factor_values]
self.factor_classes = data['latents_classes'][indices_without_color]
self.factor_classes = [arr[1:] for arr in self.factor_classes]
self.possible_values = []
for name in ['shape', 'scale', 'orientation', 'posX', 'posY']:
self.possible_values.append(meta['latents_possible_values'][name])
if colored:
for i, idx in enumerate(self.indices):
color_class = idx % self.n_colors
color_value = color_class / (self.n_colors - 1.0)
self.factor_classes[i] = np.append(self.factor_classes[i], color_class)
self.factor_values[i] = np.append(self.factor_values[i], color_value)
self.possible_values.append(list( | np.arange(0, self.n_colors) | numpy.arange |
import numpy as np
from cv2 import cv2
from mss import mss
from PIL import Image
import time
init_time = last_time = time.time()
count = 0
while 1:
with mss() as sct:
monitor = {'top': 40, 'left': 0, 'width': 800, 'height': 450}
img = np.array(sct.grab(monitor))
print('Loop took {} seconds ' .format(time.time()-last_time))
count += 1
last_time = time.time()
cv2.imshow('test', | np.array(img) | numpy.array |
from torch.utils.data import Dataset, DataLoader
import torchvision.transforms as transforms
import random
import numpy as np
from PIL import Image
import json
import os
from torchnet.meter import AUCMeter
def uniform_mix_C(mixing_ratio, num_classes):
'''
returns a linear interpolation of a uniform matrix and an identity matrix
'''
return mixing_ratio * np.full((num_classes, num_classes), 1 / num_classes) + \
(1 - mixing_ratio) * np.eye(num_classes)
def flip_labels_C(corruption_prob, num_classes):
'''
returns a matrix with (1 - corruption_prob) on the diagonals, and corruption_prob
concentrated in only one other entry for each row
'''
C = | np.eye(num_classes) | numpy.eye |
import networkx as nx
import numpy as np
import pandas as pd
import math
import numbers
import os
from collections import namedtuple
from graph_nets import utils_np
Point = namedtuple('Point', ['x', 'y', 'z'])
Pos = namedtuple('Pos', ['x', 'y', 'z', 'eta', 'phi', 'theta', 'r3', 'r'])
def calc_dphi(phi1, phi2):
"""Computes phi2-phi1 given in range [-pi,pi]"""
dphi = phi2 - phi1
if dphi > np.pi:
dphi -= 2*np.pi
if dphi < -np.pi:
dphi += 2*np.pi
return dphi
def pos_transform(r, phi, z):
x = r * math.cos(phi)
y = r * math.sin(phi)
r3 = math.sqrt(r**2 + z**2)
theta = math.acos(z/r3)
eta = -math.log(math.tan(theta*0.5))
return Pos(x, y, z, eta, phi, theta, r3, r)
def dist(x, y):
return math.sqrt(x**2 + y**2)
def wdist(a, d, w):
pp = a.x*a.x + a.y*a.y + a.z*a.z*w
pd = a.x*d.x + a.y*d.y + a.z*d.z*w
dd = d.x*d.x + d.y*d.y + d.z*d.z*w
return math.sqrt(abs(pp - pd*pd/dd))
def wdistr(r1, dr, az, dz, w):
pp = r1*r1+az*az*w
pd = r1*dr+az*dz*w
dd = dr*dr+dz*dz*w
return math.sqrt(abs(pp-pd*pd/dd))
def circle(a, b, c):
ax = a.x-c.x
ay = a.y-c.y
bx = b.x-c.x
by = b.y-c.y
aa = ax*ax + ay*ay
bb = bx*bx + by*by
idet = 0.5/(ax*by-ay*bx)
p0 = Point(x=(aa*by-bb*ay)*idet, y=(ax*bb-bx*aa)*idet, z=0)
r = math.sqrt(p0.x*p0.x + p0.y*p0.y)
p = Point(x=p0.x+c.x, y=p0.y+c.y, z=p0.z)
return p, r
def zdists(a, b):
origin = Point(x=0, y=0, z=0)
p, r = circle(origin, a, b)
ang_ab = 2*math.asin(dist(a.x-b.x, a.y-b.y)*0.5/r)
ang_a = 2*math.asin(dist(a.x, a.y)*0.5/r)
return abs(b.z-a.z-a.z*ang_ab/ang_a)
def get_edge_features2(in_node, out_node, add_angles=False):
# input are the features of incoming and outgoing nodes
# they are ordered as [r, phi, z]
v_in = pos_transform(*in_node)
v_out = pos_transform(*out_node)
deta = v_out.eta - v_in.eta
dphi = calc_dphi(v_out.phi, v_in.phi)
dR = np.sqrt(deta**2 + dphi**2)
#dZ = v_out.z - v_in.z
dZ = v_in.z - v_out.z #
results = {"distance": np.array([deta, dphi, dR, dZ])}
if add_angles:
pa = Point(x=v_out.x, y=v_out.y, z=v_out.z)
pb = Point(x=v_in.x, y=v_in.y, z=v_in.z)
pd = Point(x=pa.x-pb.x, y=pa.y-pb.y, z=pa.z-pb.z)
wd0 = wdist(pa, pd, 0)
wd1 = wdist(pa, pd, 1)
zd0 = zdists(pa, pb)
wdr = wdistr(v_out.r, v_in.r-v_out.r, pa.z, pd.z, 1)
results['angles'] = np.array([wd0, wd1, zd0, wdr])
return results
def get_edge_features(in_node, out_node):
# input are the features of incoming and outgoing nodes
# they are ordered as [r, phi, z]
in_r, in_phi, in_z = in_node
out_r, out_phi, out_z = out_node
in_r3 = np.sqrt(in_r**2 + in_z**2)
out_r3 = np.sqrt(out_r**2 + out_z**2)
in_theta = np.arccos(in_z/in_r3)
in_eta = -np.log(np.tan(in_theta/2.0))
out_theta = np.arccos(out_z/out_r3)
out_eta = -np.log(np.tan(out_theta/2.0))
deta = out_eta - in_eta
dphi = calc_dphi(out_phi, in_phi)
dR = | np.sqrt(deta**2 + dphi**2) | numpy.sqrt |
import numpy as np
import math
def periodize_angle(theta):
result = np.array(theta % (2.0 * np.pi))
idx = result > np.pi
result[idx] -= 2 * np.pi
return result
def dirichlet(w, K):
"""Drichlet kernel
:param w: The argument of the kernel.
:param K: order of the Dirichlet kernel.
:return: The values of the Dirichlet kernel."""
return np.sin(w * (K+0.5)) / np.sin(w/2.)
def dirichlet_inverse(y, K, threshold=0.01):
"""Numerial inverse of the Drichlet kernel
:param y: Value of the kernel.
:param K: order of the Dirichlet kernel.
:param threshold: numerical accuracy of the numerical inverse.
:return: The values of the Dirichlet kernel."""
w_solve = np.linspace(0, np.pi+np.pi/10000, 10000)
y_tmp = np.abs(dirichlet(w_solve, K) - y)
idx = np.argwhere(np.isclose(y_tmp[:-1], np.zeros(y_tmp[:-1].shape), atol=threshold)).reshape(-1)
min_inds = | np.array([], dtype=int) | numpy.array |
import numpy as nm
from sfepy.base.conf import transform_functions
from sfepy.base.testing import TestCommon
def get_vertices(coors, domain=None):
x, z = coors[:,0], coors[:,2]
return nm.where((z < 0.1) & (x < 0.1))[0]
def get_cells(coors, domain=None):
return nm.where(coors[:, 0] < 0)[0]
class Test(TestCommon):
@staticmethod
def from_conf( conf, options ):
from sfepy import data_dir
from sfepy.discrete.fem import Mesh, FEDomain
from sfepy.discrete import Functions
mesh = Mesh('test mesh',
data_dir + '/meshes/various_formats/abaqus_tet.inp')
mesh.nodal_bcs['set0'] = [0, 7]
domain = FEDomain('test domain', mesh)
conf_functions = {
'get_vertices' : (get_vertices,),
'get_cells' : (get_cells,),
}
functions = Functions.from_conf(transform_functions(conf_functions))
test = Test(conf=conf, options=options,
domain=domain, functions=functions)
return test
def test_selectors(self):
"""
Test basic region selectors.
"""
selectors = [
['all', 'cell'],
['vertices of surface', 'facet'],
['vertices of group 0', 'facet'],
['vertices of set set0', 'vertex'],
['vertices in (z < 0.1) & (x < 0.1)', 'facet'],
['vertices by get_vertices', 'cell'],
['vertex 0, 1, 2', 'vertex'],
['vertex in r.r6', 'vertex'],
['cells of group 0', 'cell'],
# ['cells of set 0', 'cell'], not implemented...
['cells by get_cells', 'cell'],
['cell 1, 4, 5', 'cell'],
['cell (0, 1), (0, 4), (0, 5)', 'cell'],
['copy r.r5', 'cell'],
['r.r5', 'cell'],
]
vertices = [
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
[0, 1, 3, 7],
[0, 7],
[1, 2, 3, 4, 5, 9, 11],
[1, 2, 3, 4, 5, 9, 11],
[0, 1, 2],
[0],
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
[0, 1, 2, 3, 4, 5, 6, 9, 10, 11],
[0, 1, 2, 3, 4, 5, 6, 8],
[0, 1, 2, 3, 4, 5, 6, 8],
[1, 2, 3, 4, 5, 9, 11],
[1, 2, 3, 4, 5, 9, 11],
]
ok = True
for ii, sel in enumerate(selectors):
self.report('select:', sel)
reg = self.domain.create_region('r%d' % ii, sel[0], kind=sel[1],
functions=self.functions)
_ok = ((len(reg.vertices) == len(vertices[ii]))
and (reg.vertices == vertices[ii]).all())
self.report(' vertices:', _ok)
ok = ok and _ok
return ok
def test_operators(self):
"""
Test operators in region selectors.
"""
ok = True
r1 = self.domain.create_region('r1', 'all')
sel = 'r.r1 -v vertices of group 0'
self.report('select:', sel)
reg = self.domain.create_region('reg', sel, kind='vertex')
av = [2, 4, 5, 6, 8, 9, 10, 11, 12]
_ok = (reg.vertices == nm.array(av)).all()
self.report(' vertices:', _ok)
ok = ok and _ok
sel = 'vertex 0, 1, 2 +v vertices of group 0'
self.report('select:', sel)
reg = self.domain.create_region('reg', sel, kind='vertex')
av = [0, 1, 2, 3, 7]
_ok = (reg.vertices == | nm.array(av) | numpy.array |
# To import required modules:
import numpy as np
import time
import os
import sys
import matplotlib
import matplotlib.cm as cm #for color maps
import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec #for specifying plot attributes
from matplotlib import ticker #for setting contour plots to log scale
import scipy.integrate #for numerical integration
import scipy.misc #for factorial function
from scipy.special import erf #error function, used in computing CDF of normal distribution
import scipy.interpolate #for interpolation functions
import corner #corner.py package for corner plots
#matplotlib.rc('text', usetex=True)
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.realpath(__file__)))))
from src.functions_general import *
from src.functions_compare_kepler import *
from src.functions_load_sims import *
from src.functions_plot_catalogs import *
from src.functions_plot_params import *
savefigures = False
savefigures_directory = '/Users/hematthi/Documents/GradSchool/Research/ExoplanetsSysSim_Clusters/Figures/Model_Optimization/AMD_system/Split_stars/Singles_ecc/Params11_KS/durations_norm_circ_singles_multis_GF2020_KS/Best_models/GP_med/'
##### To load the underlying populations:
loadfiles_directory = '/Users/hematthi/Documents/GradSchool/Research/ACI/Simulated_Data/AMD_system/Split_stars/Singles_ecc/Params11_KS/Distribute_AMD_per_mass/durations_norm_circ_singles_multis_GF2020_KS/GP_med/' #Lognormal_mass_Earthlike_rocky/
run_number = ''
N_sim, cos_factor, P_min, P_max, radii_min, radii_max = read_targets_period_radius_bounds(loadfiles_directory + 'periods%s.out' % run_number)
param_vals_all = read_sim_params(loadfiles_directory + 'periods%s.out' % run_number)
sssp_per_sys, sssp = compute_summary_stats_from_cat_phys(file_name_path=loadfiles_directory, run_number=run_number, load_full_tables=True)
##### To load some mass-radius tables:
# NWG-2018 model:
MR_table_file = '../../data/MRpredict_table_weights3025_R1001_Q1001.txt'
with open(MR_table_file, 'r') as file:
lines = (line for line in file if not line.startswith('#'))
MR_table = np.genfromtxt(lines, names=True, delimiter=', ')
# Li Zeng models:
MR_earthlike_rocky = np.genfromtxt('../../data/MR_earthlike_rocky.txt', names=['mass','radius']) # mass and radius are in Earth units
MR_pure_iron = np.genfromtxt('../../data/MR_pure_iron.txt', names=['mass','radius']) # mass and radius are in Earth units
# To construct an interpolation function for each MR relation:
MR_NWG2018_interp = scipy.interpolate.interp1d(10.**MR_table['log_R'], 10.**MR_table['05'])
MR_earthlike_rocky_interp = scipy.interpolate.interp1d(MR_earthlike_rocky['radius'], MR_earthlike_rocky['mass'])
MR_pure_iron_interp = scipy.interpolate.interp1d(MR_pure_iron['radius'], MR_pure_iron['mass'])
# To find where the Earth-like rocky relation intersects with the NWG2018 mean relation (between 1.4-1.5 R_earth):
def diff_MR(R):
M_NWG2018 = MR_NWG2018_interp(R)
M_earthlike_rocky = MR_earthlike_rocky_interp(R)
return np.abs(M_NWG2018 - M_earthlike_rocky)
# The intersection is approximately 1.472 R_earth
radii_switch = 1.472
# IDEA 1: Normal distribution for rho centered around Earth-like rocky, with a sigma_rho that grows with radius
# To define sigma_rho such that log10(sigma_rho) is a linear function of radius:
rho_earthlike_rocky = rho_from_M_R(MR_earthlike_rocky['mass'], MR_earthlike_rocky['radius']) # mean density (g/cm^3) for Earth-like rocky as a function of radius
rho_pure_iron = rho_from_M_R(MR_pure_iron['mass'], MR_pure_iron['radius']) # mean density (g/cm^3) for pure iron as a function of radius
sigma_rho_at_radii_switch = 3. # std of mean density (g/cm^3) at radii_switch
sigma_rho_at_radii_min = 1. # std of mean density (g/cm^3) at radii_min
rho_radius_slope = (np.log10(sigma_rho_at_radii_switch)-np.log10(sigma_rho_at_radii_min)) / (radii_switch - radii_min) # dlog(rho)/dR; slope between radii_min and radii_switch in log(rho)
sigma_rho = 10.**( rho_radius_slope*(MR_earthlike_rocky['radius'] - radii_min) + np.log10(sigma_rho_at_radii_min) )
# IDEA 2: Lognormal distribution for mass centered around Earth-like rocky, with a sigma_log_M that grows with radius
# To define sigma_log_M as a linear function of radius:
sigma_log_M_at_radii_switch = 0.3 # std of log_M (Earth masses) at radii_switch
sigma_log_M_at_radii_min = 0.04 # std of log_M (Earth masses) at radii_min
sigma_log_M_radius_slope = (sigma_log_M_at_radii_switch - sigma_log_M_at_radii_min) / (radii_switch - radii_min)
sigma_log_M = sigma_log_M_radius_slope*(MR_earthlike_rocky['radius'] - radii_min) + sigma_log_M_at_radii_min
##### To make mass-radius plots:
afs = 20 #axes labels font size
tfs = 20 #text labels font size
lfs = 16 #legend labels font size
bins = 100
# Density vs. radius for new model based on Li Zeng's Earth-like rocky:
fig = plt.figure(figsize=(8,8))
plot = GridSpec(4, 1, left=0.15, bottom=0.1, right=0.98, top=0.98, wspace=0, hspace=0)
ax = plt.subplot(plot[0,:]) # sigma_rho vs. radius
plt.plot(MR_earthlike_rocky['radius'], sigma_rho, color='orange', ls='-', lw=3, label=r'Linear $\log(\sigma_\rho)$ vs $R_p$')
plt.gca().set_yscale("log")
ax.tick_params(axis='both', labelsize=afs)
plt.xticks([])
plt.yticks([1., 2., 3., 4., 5.])
ax.yaxis.set_major_formatter(ticker.ScalarFormatter())
ax.yaxis.get_major_formatter().set_scientific(False)
ax.yaxis.get_major_formatter().set_useOffset(False)
plt.xlim([radii_min, radii_switch])
plt.ylim([0.9, 4.])
plt.ylabel(r'$\sigma_\rho$ ($g/cm^3$)', fontsize=tfs)
plt.legend(loc='upper left', bbox_to_anchor=(0.01,0.99), ncol=1, frameon=False, fontsize=lfs)
ax = plt.subplot(plot[1:,:]) # rho vs. radius
plt.plot(MR_pure_iron['radius'], rho_pure_iron, color='r', ls='--', lw=3, label='Pure iron')
plt.plot(MR_earthlike_rocky['radius'], rho_earthlike_rocky, color='orange', ls='--', lw=3, label='Earth-like rocky')
plt.fill_between(MR_earthlike_rocky['radius'], rho_earthlike_rocky - sigma_rho, rho_earthlike_rocky + sigma_rho, color='orange', alpha=0.5, label=r'Earth-like rocky $\pm \sigma_\rho$')
plt.fill_between(MR_earthlike_rocky['radius'], rho_earthlike_rocky - 2.*sigma_rho, rho_earthlike_rocky + 2.*sigma_rho, color='orange', alpha=0.3, label=r'Earth-like rocky $\pm 2\sigma_\rho$')
plt.fill_between(MR_earthlike_rocky['radius'], rho_earthlike_rocky - 3.*sigma_rho, rho_earthlike_rocky + 3.*sigma_rho, color='orange', alpha=0.1, label=r'Earth-like rocky $\pm 3\sigma_\rho$')
plt.axhline(y=1., color='c', lw=3, label='Water density (1 g/cm^3)')
plt.gca().set_yscale("log")
ax.tick_params(axis='both', labelsize=afs)
plt.minorticks_off()
plt.yticks([1., 2., 3., 4., 5., 7., 10., 15.])
ax.yaxis.set_minor_formatter(ticker.ScalarFormatter())
ax.yaxis.set_major_formatter(ticker.ScalarFormatter())
ax.yaxis.get_major_formatter().set_scientific(False)
ax.yaxis.get_major_formatter().set_useOffset(False)
plt.xlim([radii_min, radii_switch])
plt.ylim([0.9, 20.])
plt.xlabel(r'$R_p$ ($R_\oplus$)', fontsize=tfs)
plt.ylabel(r'$\rho$ ($g/cm^3$)', fontsize=tfs)
plt.legend(loc='lower right', bbox_to_anchor=(0.99,0.01), ncol=1, frameon=False, fontsize=lfs)
if savefigures:
plt.savefig(savefigures_directory + 'Density_radius.pdf')
plt.close()
plt.show()
# Mass vs. radius:
fig = plt.figure(figsize=(16,8))
plot = GridSpec(5, 5, left=0.1, bottom=0.1, right=0.98, top=0.98, wspace=0, hspace=0)
ax = plt.subplot(plot[1:,:4])
masses_all = sssp_per_sys['mass_all'][sssp_per_sys['mass_all'] > 0.]
radii_all = sssp_per_sys['radii_all'][sssp_per_sys['radii_all'] > 0.]
corner.hist2d(np.log10(radii_all), np.log10(masses_all), bins=50, plot_density=True, contour_kwargs={'colors': ['0.6','0.4','0.2','0']}, data_kwargs={'color': 'k'})
plt.plot(MR_table['log_R'], MR_table['05'], '-', color='g', label='Mean prediction (NWG2018)')
plt.fill_between(MR_table['log_R'], MR_table['016'], MR_table['084'], color='g', alpha=0.5, label=r'16%-84% (NWG2018)')
plt.plot(MR_table['log_R'], np.log10(M_from_R_rho(10.**MR_table['log_R'], rho=5.51)), color='b', label='Earth density (5.51 g/cm^3)')
plt.plot(MR_table['log_R'], np.log10(M_from_R_rho(10.**MR_table['log_R'], rho=3.9)), color='m', label='Mars density (3.9 g/cm^3)')
plt.plot(MR_table['log_R'], np.log10(M_from_R_rho(10.**MR_table['log_R'], rho=1.)), color='c', label='Water density (1 g/cm^3)')
plt.plot(MR_table['log_R'], np.log10(M_from_R_rho(10.**MR_table['log_R'], rho=7.9)), color='r', label='Iron density (7.9 g/cm^3)')
plt.plot(MR_table['log_R'], np.log10(M_from_R_rho(10.**MR_table['log_R'], rho=100.)), color='k', label='100 g/cm^3')
plt.plot(np.log10(MR_earthlike_rocky['radius']), np.log10(MR_earthlike_rocky['mass']), color='orange', ls='--', lw=3, label='Earth-like rocky')
#plt.fill_between(np.log10(MR_earthlike_rocky['radius']), np.log10(M_from_R_rho(MR_earthlike_rocky['radius'], rho=rho_earthlike_rocky-sigma_rho)), np.log10(M_from_R_rho(MR_earthlike_rocky['radius'], rho=rho_earthlike_rocky+sigma_rho)), color='orange', alpha=0.5, label=r'16%-84% ($\rho \sim \mathcal{N}(\rho_{\rm Earthlike\:rocky}, \sigma_\rho(R_p))$)') #label=r'$\rho \sim \mathcal{N}(\rho_{\rm Earthlike\:rocky}, 10^{[\frac{d\log\rho}{dR_p}(R_p - 0.5) + \log{\rho_0}]})$'
plt.fill_between(np.log10(MR_earthlike_rocky['radius']), np.log10(MR_earthlike_rocky['mass']) - sigma_log_M, np.log10(MR_earthlike_rocky['mass']) + sigma_log_M, color='orange', alpha=0.5, label=r'16%-84% ($\log{M_p} \sim \mathcal{N}(M_{p,\rm Earthlike\:rocky}, \sigma_{\log{M_p}})$)')
plt.plot(np.log10(MR_pure_iron['radius']), np.log10(MR_pure_iron['mass']), color='r', ls='--', lw=3, label='Pure iron')
#plt.axvline(x=np.log10(0.7), color='k', ls='--', lw=3)
plt.axvline(x=np.log10(radii_switch), color='k', ls='--', lw=3)
ax.tick_params(axis='both', labelsize=afs)
xtick_vals = np.array([0.5, 1., 2., 4., 10.])
ytick_vals = | np.array([1e-1, 1., 10., 1e2]) | numpy.array |
# encoding=utf8
"""
Functions for performing classical hypothesis testing.
Hypothesis Testing
------------------
.. autosummary::
:toctree: generated/
BinomialTest
ChiSquareTest
tTest
References
----------
<NAME>., & <NAME>. (2012). Methods of multivariate analysis (3rd Edition).
<NAME>. (1956). Nonparametric statistics: For the behavioral sciences.
McGraw-Hill. ISBN 07-057348-4
Student's t-test. (2017, June 20). In Wikipedia, The Free Encyclopedia.
From https://en.wikipedia.org/w/index.php?title=Student%27s_t-test&oldid=786562367
<NAME>. "Chi-Squared Test." From MathWorld--A Wolfram Web Resource.
http://mathworld.wolfram.com/Chi-SquaredTest.html
Wikipedia contributors. (2018, July 14). Binomial proportion confidence interval.
In Wikipedia, The Free Encyclopedia. Retrieved 15:03, August 10, 2018,
from https://en.wikipedia.org/w/index.php?title=Binomial_proportion_confidence_interval&oldid=850256725
Wikipedia contributors. (2018, July 5). Chi-squared test. In Wikipedia, The Free Encyclopedia. Retrieved 13:56,
August 19, 2018, from https://en.wikipedia.org/w/index.php?title=Chi-squared_test&oldid=848986171
Wikipedia contributors. (2018, April 12). Pearson's chi-squared test. In Wikipedia, The Free Encyclopedia.
Retrieved 12:55, August 23, 2018,
from https://en.wikipedia.org/w/index.php?title=Pearson%27s_chi-squared_test&oldid=836064929
"""
import numpy as np
import numpy_indexed as npi
from scipy.stats import beta, norm, t
from scipy.special import comb
class BinomialTest(object):
r"""
Performs a one-sample binomial test.
Parameters
----------
x : int
Number of successes out of :math:`n` trials.
n : int
Number of trials
p : float, optional
Expected probability of success
alternative: str, {'two-sided', 'greater', 'lesser'}, optional
Specifies the alternative hypothesis :math:`H_1`. Must be one of 'two-sided' (default), 'greater',
or 'less'.
alpha : float, optional
Significance level
continuity: bool, optional
If True, the continuity corrected version of the Wilson score interval is used.
Attributes
----------
x : int
Number of successes out of :math:`n` trials.
n : int
Number of trials
p : float
Expected probability of success
q : float
Defined as :math:`1 - p`
alternative : str
Specifies the alternative hypothesis :math:`H_1`. Must be one of 'two-sided' (default), 'greater',
or 'less'.
alpha : float
Significance level
continuity : bool
If True, the continuity corrected version of the Wilson score interval is used.
p_value : float
Computed p-value
z : float
z-score used in computation of intervals
clopper_pearson_interval : dict
Dictionary of the Clopper-Pearson lower and upper intervals and probability of success.
wilson_score_interval : dict
Dictionary of the Wilson Score lower and upper intervals and probability of success.
agresti_coull_interval : dict
Dictionary of the Agresti-Coull lower and upper intervals and probability of success.
arcsine_transform_interval : dict
Dictionary of the arcsine transformation lower and upper intervals and probability of success.
test_summary : dict
Dictionary containing test summary statistics.
Raises
------
ValueError
If number of successes :math:`x` is greater than the number of trials :math:`n`.
ValueError
If expected probability :math:`p` is greater than 1.
ValueError
If parameter :code:`alternative` is not one of {'two-sided', 'greater', 'lesser'}
Notes
-----
The Binomial test is a one-sample test applicable in the case of populations consisting of two classes or groups,
such as male/female, cat/dog, etc. The proportion of the first group is denoted :math:`p`, while the second group
is often denoted :math:`q`, which we know to be :math:`1 - p`. The null hypothesis of the test is that the
proportion of the population is indeed :math:`p` and gives the researcher more information to determine if the
random sample that was drawn could have come from a population having a proportion of :math:`p`.
As the name of the test implies, the binomial distribution is the sampling distribution the of the proportions
that could be observed when drawing random samples from a population. Therefore, the probability of obtaining
:math:`x` objects in one category and :math:`n - x` in the other category out of a total :math:`n` trials is
given by the binomial distribution probability mass function:
.. math::
p(x) = \binom{n}{x} P^x (1 - P)^{n - x}
:math:`(1 - P)` may be substituted for :math:`Q`. The binomial coefficient :math:`\binom{n}{x}` is defined as:
.. math::
\binom{n}{x} = \frac{n!}{k!(n - k)!}
The p-value of the test is calculated by the binomial distribution's cumulative distribution function, defined as:
.. math::
Pr(X \leq x) = \sum^{[k]}_{i=0} \binom{n}{i} P^i (1 - P)^{n - i}
There are several confidence intervals that can be computed when performing a binomial test. The most common is
known as the Clopper-Pearson interval, which is an exact interval as it is based on the binomial distribution. The
Clopper-Pearson interval can be defined several ways, one of which uses the relationship between the binomial
distribution nad the beta distribution.
.. math::
B\left(\frac{\alpha}{2};x,n-x+1\right) < \theta < B\left(1 - \frac{\alpha}{2};x + 1, n - x \right)
The Agresti-Coull interval utilizes the standard normal distribution. :math:`z` is given as
:math:`1 - \frac{\alpha}{2}`. The interval calculation proceeds as:
With :math:`x` successes out of a total :math:`n` trials, we define :math:`\tilde{n}` as:
.. math::
`\tilde{n} = n + z^2
and,
.. math::
\tilde{p} = \frac{1}{\tilde{n}} \left(x + \frac{z^2}{2} \right)
The confidence interval for the probability of success, :math:`p`, is then given as:
.. math::
\tilde{p} \pm z \sqrt{\frac{\tilde{p}}{\tilde{n}} (1 - \tilde{p})}
The arcsine transformation confidence interval is defined as:
.. math::
sin^2 \left(\arcsin{\sqrt{p}} - \frac{z}{2\sqrt{n}} \right) < \theta < sin^2 \left(arcsin{\sqrt{p}} +
\frac{z}{2\sqrt{n}} \right)
Where :math:`z` is the quantile :math:`1 - \frac{\alpha}{2}}` of the standard normal distribution, as before.
Lastly, the Wilson score interval can be computed with or without continuity correction. Without correction, the
Wilson score interval success proability :math:`p` is defined as:
.. math::
\frac{\hat{p} + \frac{z^2}{2n}}{1 + \frac{z^2}{n} \pm \frac{z}{1 + \frac{z^2}{n}}
\sqrt{\frac{\hat{p} (1 - \hat{p}}{n}}{1 + \frac{z^2}{n}}}
The Wilson score interval with continuity correction is defined as:
.. math::
w^- = max \Bigg\{0, \frac{2n\hat{P} + z^2 -
\Big[z \sqrt{z^2 - \frac{1}{n} + 4n\hat{p}(1 - \hat{p}) + (4\hat{p} - 2) + 1}\Big]}{2(n + z^2)}\Bigg\}
w^+ = min \Bigg\{1, \frac{2n\hat{P} + z^2 +
\Big[z \sqrt{z^2 - \frac{1}{n} + 4n\hat{p}(1 - \hat{p}) - (4\hat{p} - 2) + 1}\Big]}{2(n + z^2)}\Bigg\}
Where :math:`w^-` and :math:`w^+` are the lower and upper bounds of the Wilson score interval corrected for
contiunity.
Examples
--------
>>> x = 682
>>> n = 925
>>> bt = BinomialTest(n, x)
>>> bt.test_summary
{'Number of Successes': 682,
'Number of Trials': 925,
'alpha': 0.05,
'intervals': {'Agresti-Coull': {'conf level': 0.95,
'interval': (0.7079790581519885, 0.7646527304391209),
'probability of success': 0.7363158942955547},
'Arcsine Transform': {'conf level': 0.95,
'interval': (0.708462749220724, 0.7651467076803447),
'probability of success': 0.7372972972972973,
'probability variance': 0.00020939458669772768},
'Clopper-Pearson': {'conf level': 0.95,
'interval': (0.7076682640790369, 0.7654065582415227),
'probability of success': 0.7372972972972973},
'Wilson Score': {'conf level': 0.95,
'interval': (0.46782780413153596, 0.5321721958684641),
'probability of success': 0.5}},
'p-value': 2.4913404672588513e-13}
>>> bt.p_value
2.4913404672588513e-13
>>> bt.clopper_pearson_interval
{'conf level': 0.95,
'interval': (0.7076682640790369, 0.7654065582415227),
'probability of success': 0.7372972972972973}
>>> bt2 = BinomialTest(n, x, alternative='greater')
>>> bt2.p_value
1.2569330927920093e-49
>>> bt2.clopper_pearson_interval
{'conf level': 0.95,
'interval': (0.7124129244365457, 1.0),
'probability of success': 0.7372972972972973}
References
----------
<NAME>. (1956). Nonparametric statistics: For the behavioral sciences.
McGraw-Hill. ISBN 07-057348-4
Wikipedia contributors. (2018, July 14). Binomial proportion confidence interval.
In Wikipedia, The Free Encyclopedia. Retrieved 15:03, August 10, 2018,
from https://en.wikipedia.org/w/index.php?title=Binomial_proportion_confidence_interval&oldid=850256725
"""
def __init__(self, n, x, p=0.5, alternative='two-sided', alpha=0.05, continuity=True):
if x > n:
raise ValueError('number of successes cannot be greater than number of trials.')
if p > 1.0:
raise ValueError('expected probability of success cannot be greater than 1.')
if alternative not in ('two-sided', 'greater', 'less'):
raise ValueError("'alternative must be one of 'two-sided' (default), 'greater', or 'less'.")
self.n = n
self.x = x
self.p = p
self.q = 1.0 - self.p
self.alpha = alpha
self.alternative = alternative
self.continuity = continuity
self.p_value = self._p_value()
if self.alternative == 'greater':
self.z = norm.ppf(self.alpha)
elif self.alternative == 'less':
self.z = norm.ppf(1 - self.alpha)
else:
self.z = norm.ppf(1 - self.alpha / 2)
self.clopper_pearson_interval = self._clopper_pearson_interval()
self.wilson_score_interval = self._wilson_score_interval()
self.agresti_coull_interval = self._agresti_coull_interval()
self.arcsine_transform_interval = self._arcsine_transform_interval()
self.test_summary = {
'Number of Successes': self.x,
'Number of Trials': self.n,
'p-value': self.p_value,
'alpha': self.alpha,
'intervals': {
'Clopper-Pearson': self.clopper_pearson_interval,
'Wilson Score': self.wilson_score_interval,
'Agresti-Coull': self.agresti_coull_interval,
'Arcsine Transform': self.arcsine_transform_interval
}
}
def _p_value(self):
r"""
Calculates the p-value of the binomial test.
Returns
-------
pval : float
The computed p-value.
"""
successes = np.arange(self.x + 1)
pval = np.sum(comb(self.n, successes) * self.p ** successes * self.q ** (self.n - successes))
if self.alternative in ('two-sided', 'greater'):
other_tail = np.arange(self.x, self.n + 1)
y = comb(self.n, self.x) * (self.p ** self.x) * self.q ** (self.n - self.x)
p_othertail = comb(self.n, other_tail) * self.p ** other_tail * self.q ** (self.n - other_tail)
p_othertail = np.sum(p_othertail[p_othertail <= y])
if self.alternative == 'two-sided':
pval = p_othertail * 2
#pval = 1 - pval
elif self.alternative == 'greater':
pval = p_othertail
return pval
def _clopper_pearson_interval(self):
r"""
Computes the Clopper-Pearson 'exact' confidence interval.
References
----------
Wikipedia contributors. (2018, July 14). Binomial proportion confidence interval.
In Wikipedia, The Free Encyclopedia. Retrieved 00:40, August 15, 2018,
from https://en.wikipedia.org/w/index.php?title=Binomial_proportion_confidence_interval&oldid=850256725
"""
p = self.x / self.n
if self.alternative == 'less':
lower_bound = 0.0
upper_bound = beta.ppf(1 - self.alpha, self.x + 1, self.n - self.x)
elif self.alternative == 'greater':
upper_bound = 1.0
lower_bound = beta.ppf(self.alpha, self.x, self.n - self.x + 1)
else:
lower_bound = beta.ppf(self.alpha / 2, self.x, self.n - self.x + 1)
upper_bound = beta.ppf(1 - self.alpha / 2, self.x + 1, self.n - self.x)
clopper_pearson_interval = {
'probability of success': p,
'conf level': 1 - self.alpha,
'interval': (lower_bound, upper_bound)
}
return clopper_pearson_interval
def _wilson_score_interval(self):
r"""
Computes the Wilson score confidence interval.
References
----------
Wikipedia contributors. (2018, July 14). Binomial proportion confidence interval.
In Wikipedia, The Free Encyclopedia. Retrieved 00:40, August 15, 2018,
from https://en.wikipedia.org/w/index.php?title=Binomial_proportion_confidence_interval&oldid=850256725
"""
p = (self.p + (self.z ** 2 / (2. * self.n))) / (1. + (self.z ** 2. / self.n))
if self.continuity:
if self.alternative == 'less':
lower = 0.0
else:
lower = (2. * self.n * self.p + self.z ** 2. - (self.z * np.sqrt(
self.z ** 2. - (1. / self.n) + 4. * self.n * self.p * self.q + (4. * self.p - 2.) + 1.))) / \
(2. * (self.n + self.z ** 2.))
if self.alternative == 'greater':
upper = 1.0
else:
upper = (2. * self.n * self.p + self.z ** 2. + (self.z * np.sqrt(
self.z ** 2. - (1. / self.n) + 4. * self.n * self.p * self.q + (4. * self.p - 2.) + 1))) / (2. * (
self.n + self.z ** 2.))
upper_bound, lower_bound = np.minimum(1.0, upper), np.maximum(0.0, lower)
else:
bound = (self.z / (1. + self.z ** 2. / self.n)) * \
np.sqrt(((self.p * self.q) / self.n) + (self.z ** 2. / (4. * self.n ** 2.)))
if self.alternative == 'less':
lower_bound = 0.0
else:
lower_bound = p - bound
if self.alternative == 'greater':
upper_bound = 1.0
else:
upper_bound = p + bound
wilson_interval = {
'probability of success': p,
'conf level': 1 - self.alpha,
'interval': (lower_bound, upper_bound)
}
return wilson_interval
def _agresti_coull_interval(self):
r"""
Calculates the Agresti-Coull confidence interval as defined in Agresti and Coull's paper
"Approximate is Better than 'Exact' for Interval Estimation of Binomial Proportions."
References
----------
Agresti, Alan; Coull, <NAME>. (1998). "Approximate is better than 'exact' for interval estimation of binomial
proportions". The American Statistician. http://users.stat.ufl.edu/~aa/articles/agresti_coull_1998.pdf
Wikipedia contributors. (2018, July 14). Binomial proportion confidence interval.
In Wikipedia, The Free Encyclopedia. Retrieved 00:40, August 15, 2018,
from https://en.wikipedia.org/w/index.php?title=Binomial_proportion_confidence_interval&oldid=850256725
"""
nbar = self.n + self.z ** 2
p = (1 / nbar) * (self.x + self.z ** 2 / 2)
bound = self.z * np.sqrt((p / nbar) * (1 - p))
if self.alternative == 'less':
lower_bound = 0.0
else:
lower_bound = p - bound
if self.alternative == 'greater':
upper_bound = 1.0
else:
upper_bound = p + bound
agresti_coull_interval = {
'probability of success': p,
'conf level': 1 - self.alpha,
'interval': (lower_bound, upper_bound)
}
return agresti_coull_interval
def _arcsine_transform_interval(self):
r"""
Calculates the arcsine transformation interval.
References
----------
Wikipedia contributors. (2018, July 14). Binomial proportion confidence interval.
In Wikipedia, The Free Encyclopedia. Retrieved 00:40, August 15, 2018,
from https://en.wikipedia.org/w/index.php?title=Binomial_proportion_confidence_interval&oldid=850256725
"""
p = self.clopper_pearson_interval['probability of success']
p_var = (p * (1 - p)) / self.n
if self.alternative == 'less':
lower_bound = 0.0
else:
lower_bound = np.sin(np.arcsin(np.sqrt(p)) - (self.z / (2. * np.sqrt(self.n)))) ** 2
if self.alternative == 'greater':
upper_bound = 1.0
else:
upper_bound = np.sin(np.arcsin( | np.sqrt(p) | numpy.sqrt |
"""Contains the base class for the simulation."""
import numpy as np
from tqdm import auto as tqdm
import numba
import matplotlib.pyplot as plt
from matplotlib import animation
import pandas
import zarr
import datetime
import typing
class Simulation:
"""Base class for SOC simulations.
:param L: linear size of lattice, without boundary layers
:type L: int
:param save_every: number of iterations per snapshot save
:type save_every: int or None
:param wait_for_n_iters: How many iterations to skip to skip before saving data?
:type wait_for_n_iters: int
"""
values = NotImplemented
saved_snapshots = NotImplemented
BOUNDARY_SIZE = BC = 1
def __init__(self, L: int, save_every: int = 1, wait_for_n_iters: int = 10):
self.L = L
self.visited = np.zeros((self.L_with_boundary, self.L_with_boundary), dtype=bool)
self.data_acquisition = []
self.save_every = save_every
self.wait_for_n_iters = wait_for_n_iters
@property
def size(self) -> int:
"""
The total size of the simulation grid, without boundaries
"""
return self.L**2
@property
def L_with_boundary(self) -> int:
"""
The total width of the simulation grid, with boundaries.
"""
return self.L + 2 * self.BOUNDARY_SIZE
def drive(self):
"""
Drive the simulation by adding particles from the outside.
Must be overriden in subclasses.
"""
raise NotImplementedError("Your model needs to override the drive method!")
def topple_dissipate(self):
"""
Distribute material from overloaded sites to neighbors.
Must be overriden in subclasses.
"""
raise NotImplementedError("Your model needs to override the topple method!")
@classmethod
def clean_boundary_inplace(cls, array: np.ndarray) -> np.ndarray:
"""
Convenience wrapper to `common.clean_boundary_inplace` with the simulation's boundary size.
:param array: array to clean
:type array: np.ndarray
:rtype: np.ndarray
"""
return clean_boundary_inplace(array, cls.BOUNDARY_SIZE)
@classmethod
def inside(cls, array: np.ndarray) -> np.ndarray:
"""
Convenience function to get an array without simulation boundaries
:param array: array
:type array: np.ndarray
:return: array of width smaller by 2BC
:rtype: np.ndarray
"""
return array[cls.BC:-cls.BC, cls.BC:-cls.BC]
def AvalancheLoop(self) -> dict:
"""
Bring the current simulation's state to equilibrium by repeatedly
toppling and dissipating.
Returns a dictionary with the total size of the avalanche
and the number of iterations the avalanche took.
:rtype: dict
"""
self.visited[...] = False
number_of_iterations = self.topple_dissipate()
AvalancheSize = self.inside(self.visited).sum()
return dict(AvalancheSize=AvalancheSize, number_of_iterations=number_of_iterations)
def run(self, N_iterations: int,
filename: str = None,
wait_for_n_iters: int = 10,
) -> str:
"""
Simulation loop. Drives the simulation, possibly starts avalanches, gathers data.
:param N_iterations: number of iterations (per grid node if `scale` is True)
:type N_iterations: int
:rtype: dict
:param filename: filename for saving snapshots. if None, saves to memory; by default if False, makes something like array_Manna_2019-12-17T19:40:00.546426.zarr
:type filename: str
:param wait_for_n_iters: wait this many iterations before collecting data
(lets model thermalize)
:type wait_for_n_iters: int
"""
if filename is False:
filename = f"array_{self.__class__.__name__}_{datetime.datetime.now().isoformat()}.zarr"
scaled_wait_for_n_iters = wait_for_n_iters
scaled_n_iterations = N_iterations + scaled_wait_for_n_iters
if scaled_n_iterations % self.save_every != 0:
raise ValueError(f"Ensure save_every ({self.save_every}) is a divisor of the total number of iterations ({scaled_n_iterations})")
print(f"Waiting for wait_for_n_iters={wait_for_n_iters} iterations before collecting data. This should let the system thermalize.")
total_snapshots = max([scaled_n_iterations // self.save_every, 1])
self.saved_snapshots = zarr.open(filename,
shape=(
total_snapshots, # czas
self.L_with_boundary, # x
self.L_with_boundary, # y
),
chunks=(
100,
self.L_with_boundary,
self.L_with_boundary,
),
dtype=self.values.dtype,
)
self.saved_snapshots.attrs['save_every'] = self.save_every
for i in tqdm.trange(scaled_n_iterations):
self.drive()
observables = self.AvalancheLoop()
if i >= scaled_wait_for_n_iters:
self.data_acquisition.append(observables)
if self.save_every is not None and (i % self.save_every) == 0:
self._save_snapshot(i)
return filename
def _save_snapshot(self, i: int):
"""
Use Zarr to save the current values array as snapshot in the appropriate time index.
:param i: timestep index
:type i: int
"""
self.saved_snapshots[i // self.save_every] = self.values
@property
def data_df(self) -> pandas.DataFrame:
"""
Displays the gathered data as a Pandas DataFrame.
:return: dataframe with gathered data
:rtype: pandas.DataFrame
"""
return pandas.DataFrame(self.data_acquisition)
def plot_state(self, with_boundaries: bool = False) -> plt.Figure:
"""
Plots the current state of the simulation.
:param with_boundaries: should the boundaries be displayed as well?
:type with_boundaries: bool
:return: figure with plot
:rtype: plt.Figure
"""
fig, ax = plt.subplots()
if with_boundaries:
values = self.values
else:
values = self.values[self.BOUNDARY_SIZE:-self.BOUNDARY_SIZE, self.BOUNDARY_SIZE:-self.BOUNDARY_SIZE]
IM = ax.imshow(values, interpolation='nearest')
plt.colorbar(IM)
return fig
def animate_states(self,
notebook: bool = False,
with_boundaries: bool = False,
interval: int = 30,
):
"""
Animates the collected states of the simulation.
:param notebook: if True, displays via html5 video in a notebook;
otherwise returns MPL animation
:type notebook: bool
:param with_boundaries: include boundaries in the animation?
:type with_boundaries: bool
:param interval: number of miliseconds to wait between each frame.
:type interval: int
"""
fig, ax = plt.subplots()
if with_boundaries:
values = np.dstack(self.saved_snapshots)
else:
values = np.dstack(self.saved_snapshots)[self.BOUNDARY_SIZE:-self.BOUNDARY_SIZE, self.BOUNDARY_SIZE:-self.BOUNDARY_SIZE, :]
IM = ax.imshow(values[:, :, 0],
interpolation='nearest',
vmin = values.min(),
vmax = values.max()
)
plt.colorbar(IM)
iterations = values.shape[2]
title = ax.set_title("Iteration {}/{}".format(0, iterations * self.save_every))
def animate(i):
IM.set_data(values[:,:,i])
title.set_text("Iteration {}/{}".format(i * self.save_every, iterations * self.save_every))
return IM, title
anim = animation.FuncAnimation(fig,
animate,
frames=iterations,
interval=interval,
)
if notebook:
from IPython.display import HTML, display
plt.close(anim._fig)
display(HTML(anim.to_html5_video()))
else:
return anim
def save(self, file_name = 'sim'):
""" serialization of object and saving it to file"""
root = zarr.open_group('state/' + file_name + '.zarr', mode = 'w')
values = root.create_dataset('values', shape = (self.L_with_boundary, self.L_with_boundary), chunks = (10, 10), dtype = 'i4')
# TODO this probably still needs fixing
values = zarr.array(self.values)
#data_acquisition = root.create_dataset('data_acquisition', shape = (len(self.data_acquisition)), chunks = (1000), dtype = 'i4')
#data_acquisition = zarr.array(self.data_acquisition)
root.attrs['L'] = self.L
root.attrs['save_every'] = self.save_every
return root
# TODO should be a classmethod
def open(self, file_name = 'sim'):
root = zarr.open_group('state/' + file_name + '.zarr', mode = 'r')
self.values = np.array(root['values'][:])
#self.data_acquisition = root['data_acquisition'][:]
self.L = root.attrs['L']
self.save_every = root.attrs['save_every']
def get_exponent(self,
column: str = 'AvalancheSize',
low: int = 1,
high: int = 10,
plot: bool = True,
plot_filename: typing.Optional[str] = None) -> dict:
"""
Plot histogram of gathered data from data_df,
:param column: which column of data_df should be visualized?
:type column: str
:param low: lower cutoff for log-log-linear fit
:type low: int
:param high: higher cutoff for log-log-linear fit
:type high: int
:param plot: if False, skips all plotting and just returns fit parameters
:type plot: bool
:param plot_filename: optional filename for saved plot. This skips displaying the plot!
:type plot_filename: bool
:return: fit parameters
:rtype: dict
"""
df = self.data_df
filtered = df.loc[df.number_of_iterations != 0, column]
sizes, counts = np.unique(filtered, return_counts=True)
indices = (low < sizes) & (sizes < high)
coef_a, coef_b = poly = np.polyfit( | np.log10(sizes[indices]) | numpy.log10 |
#
# Copyright (c) 2021, NVIDIA CORPORATION.
#
# 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 dask.dataframe as dd
import numpy as np
import pandas as pd
import pytest
import nvtabular as nvt
from merlin.core.dispatch import make_df
from nvtabular import ColumnSelector, Schema, Workflow, ops
try:
import cudf
_CPU = [True, False]
except ImportError:
_CPU = [True]
@pytest.mark.parametrize("cpu", _CPU)
@pytest.mark.parametrize("keys", [["name"], "id", ["name", "id"]])
def test_groupby_op(keys, cpu):
# Initial timeseries dataset
size = 60
df1 = make_df(
{
"name": np.random.choice(["Dave", "Zelda"], size=size),
"id": np.random.choice([0, 1], size=size),
"ts": | np.linspace(0.0, 10.0, num=size) | numpy.linspace |
from typing import Dict, List
import numpy as np
import pandas as pd
import seaborn as sn
from matplotlib import pyplot as plt
from sklearn.base import BaseEstimator
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import confusion_matrix, roc_auc_score
from sklearn.model_selection import StratifiedKFold
from sklearn.naive_bayes import ComplementNB
from sklearn.neighbors import KNeighborsClassifier
def get_data(path: str = "") -> List[pd.DataFrame]:
"""
function to read data from csv
:param path: string path to folder containing log2.csv (default value if CWD)
:return: list of dataframes containing data and class labels respectively
"""
X = pd.read_csv("log2.csv")
y = X[["Action"]]
X = X.drop("Action", axis=1)
return [X, y]
def visualize(X: pd.DataFrame, y: pd.DataFrame) -> None:
"""
function to visualize proportion of class sizes in the dataset
:param X: dataframe containing data
:param y: dataframe containing class labels corresponding to X
:return: None
"""
y["Action"].value_counts().plot.pie(explode=(0.02, 0.04, 0.05, 0.09), title="Proportion of classes in dataset")
plt.savefig("Figures/proportions")
for i, column in enumerate(X.columns):
fig, ax = plt.subplots(1, 2)
ax[0].hist(
(
X[y["Action"] == "allow"][column],
X[y["Action"] == "deny"][column],
X[y["Action"] == "drop"][column],
X[y["Action"] == "reset-both"][column],
)
)
ax[0].set_xlabel(column)
ax[0].set_ylabel("Frequency")
ax[1].boxplot(
(
X[y["Action"] == "allow"][column],
X[y["Action"] == "deny"][column],
X[y["Action"] == "drop"][column],
X[y["Action"] == "reset-both"][column],
)
)
ax[1].set_xlabel("Action")
ax[1].set_ylabel(column)
X[column].hist(by=y["Action"])
ax[0].legend(["allow", "deny", "drop", "reset-both"])
ax[1].set_xticklabels(["allow", "deny", "drop", "reset-both"])
fig.suptitle("Distribution of classes among attributes")
plt.savefig("Figures/boxplots")
def cross_validate(estimator: BaseEstimator, X: pd.DataFrame, y: pd.DataFrame, num_splits: int, save_name: str) -> None:
"""
function to perform cross validation and call error_profile at the end to generate an error report for a sklearn
model
:param estimator: SkLearn classification model
:param X: dataframe containing data
:param y: dataframe containing class labels corresponding to X
:param num_splits: number of folds for k-fold cross validation
:param save_name: save name for error profile plots (file extension will be appended)
:return: None
"""
splitter = StratifiedKFold(n_splits=num_splits, shuffle=True, random_state=0)
predictions = {"test": [], "train": []}
y_true = {"test": [], "train": []}
for train_index, test_index in splitter.split(X, y):
estimator.fit(X.iloc[train_index, :], y.iloc[train_index, 0])
test_pred = estimator.predict(X.iloc[test_index, :])
train_pred = estimator.predict(X.iloc[train_index, :])
predictions["train"].append(train_pred)
predictions["test"].append(test_pred)
y_true["train"].append(np.array(y.iloc[train_index])[:, 0])
y_true["test"].append(np.array(y.iloc[test_index])[:, 0])
error_profile(y_true, predictions, model_type=save_name)
def fit_and_test(X, y) -> None:
"""
function to fit and test numerous models for the given data
:param X: dataframe containing data
:param y: dataframe containing class labels corresponding to X
:return: None
"""
models = {
"tree2": RandomForestClassifier(n_estimators=1, n_jobs=-1, class_weight="balanced", random_state=0),
"tree1": RandomForestClassifier(n_estimators=1, n_jobs=-1, random_state=0, criterion="entropy"),
"random_forest_10": RandomForestClassifier(
n_estimators=10, n_jobs=-1, class_weight="balanced", criterion="gini"
),
"random_forest_100": RandomForestClassifier(n_estimators=100, n_jobs=-1, criterion="entropy"),
"knn_1": KNeighborsClassifier(n_neighbors=1, n_jobs=-1, metric="hamming"),
"knn_5": KNeighborsClassifier(n_neighbors=5, n_jobs=-1, metric="hamming"),
"knn_15": KNeighborsClassifier(n_neighbors=15, n_jobs=-1, metric="hamming"),
"cnb": ComplementNB(),
}
for model_name in models.keys():
cross_validate(estimator=models[model_name], X=X, y=y, num_splits=5, save_name=model_name)
def error_profile(y_true: Dict[str, List[np.ndarray]], y_pred: Dict[str, List[np.ndarray]], model_type: str) -> None:
"""
function to generate the error profile based on true labels and predicted labels for a classification problem
:param y_true: dictionary containing true labels for training and testing of each fold
:param y_pred: dictionary containing predicted labels for training and testing of each fold
:param model_type: name of model to use to save error profile plots (file extensions will be appended)
:return: None
"""
num_folds = len(y_pred["train"])
acc = {"train": [], "test": []}
test_predictions = np.array([])
test_labels = np.array([])
for k in range(num_folds):
y_train_true = y_true["train"][k]
y_train_pred = y_pred["train"][k]
y_test_true = y_true["test"][k]
y_test_pred = y_pred["test"][k]
# Accuracies
train_acc = np.sum( | np.equal(y_train_true, y_train_pred) | numpy.equal |
import qinfer as qi
import numpy as np
import scipy as sp
import random
import math
import copy
import itertools
import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec
from inspect import currentframe, getframeinfo
try:
from lfig import LatexFigure
except:
from qmla.shared_functionality.latex_figure import LatexFigure
import qmla.logging
frameinfo = getframeinfo(currentframe())
__all__ = [
"ExperimentDesignHueristic",
"MultiParticleGuessHeuristic",
"MixedMultiParticleLinspaceHeuristic",
"VolumeAdaptiveParticleGuessHeuristic",
]
def identity(arg):
return arg
class ExperimentDesignHueristic(qi.Heuristic):
"""
Experiment Design Heuristic base class, to be inherited by specific implementations.
This object has access to the QInfer Updater and Model objects, so it can, e.g.,
sample from the particle distribution, to use these values in the design of a new experiment.
:param updater: QInfer updater for SMC
:type updater: QInfer Updater object
:param model_id: ID of model under study, defaults to 1
:type model_id: int
:param oplist: list of matrices representing the operators constituting this model, defaults to None
:type oplist: list, optional
:param norm: type of norm to use, defaults to 'Frobenius'
:type norm: str, optional
:param inv_field: inversion field to use (legacy - should not matter) defaults to 'x_'
:type inv_field: str, optional
:param t_field: name of field corresponding to $t$, defaults to 't'
:type t_field: str, optional
:param maxiters: manimum number of iterations to attempt to find distinct particles from the distribution, defaults to 10
:type maxiters: int, optional
:param other_fields: optional further fields, defaults to None
:type other_fields: list, optional
:param inv_func: inverse function, used by QInfer, (legacy - should not matter) defaults to identity
:type inv_func: function, optional
:param t_func: function for computing $t$, defaults to identity
:type t_func: function, optional
:param log_file: path to log file, defaults to 'qmla_log.log'
:type log_file: str, optional
"""
def __init__(
self,
updater,
model_id=1,
oplist=None,
norm="Frobenius",
inv_field="x_",
t_field="t",
maxiters=10,
other_fields=None,
inv_func=identity,
t_func=identity,
log_file="qmla_log.log",
**kwargs
):
super().__init__(updater)
# Most importantly - access to updater and underlying model
self._model_id = model_id
self._updater = updater
self._model = updater.model
# Other useful attributes passed
self._norm = norm
self._x_ = inv_field
self._t = t_field
self._inv_func = inv_func
self._t_func = t_func
self._other_fields = other_fields if other_fields is not None else {}
self._maxiters = maxiters
self._oplist = oplist
self._num_experiments = kwargs["num_experiments"]
self._figure_format = kwargs["figure_format"]
self._log_file = log_file
# probe ID
self.probe_id = 0
self.probe_rotation_frequency = 5
self.num_probes = kwargs["num_probes"]
# storage infrastructure
self.heuristic_data = {} # to be stored by model instance
self._resample_epochs = []
self._volumes = []
self.effective_sample_size = []
self._times_suggested = []
self._label_fontsize = 10 # consistency when plotting
def _get_exp_params_array(self, epoch_id):
r"""Return an empty array with a position for every experiment design parameter."""
experiment_params = np.empty((1,), dtype=self._model.expparams_dtype)
# fill in particle in expparams
particle = self._updater.sample()
n_params = particle.shape[1]
for i in range(n_params):
p = particle[0][i]
corresponding_expparam = self._model.modelparam_names[i]
experiment_params[corresponding_expparam] = p
# choose probe id
if epoch_id % self.probe_rotation_frequency == 0:
self.probe_id += 1
if self.probe_id >= self.num_probes:
self.probe_id = 0
experiment_params["probe_id"] = self.probe_id
return experiment_params
def log_print(self, to_print_list):
r"""Wrapper for :func:`~qmla.print_to_log`"""
qmla.logging.print_to_log(
to_print_list=to_print_list,
log_file=self._log_file,
log_identifier="Heuristic {}".format(
self._model_id
), # TODO add heuristic name
)
def __call__(self, **kwargs):
"""By calling the heuristic, it produces an experiment to be performed to learn upon.
:return: all necessary data to perform an experiment, e.g. evolution time and probe ID.
:rtype: named tuple
"""
# Process some data from the model first
try:
current_volume = kwargs["current_volume"]
except:
current_volume = None
self._volumes.append(current_volume)
if self._updater.just_resampled:
self._resample_epochs.append(kwargs["epoch_id"] - 1)
self.effective_sample_size.append(self._updater.n_ess)
# Design a new experiment
new_experiment = self.design_experiment(**kwargs)
new_time = new_experiment["t"]
if new_time > 1e6:
# TODO understand cutoff at which time
# calculation becomes unstable
new_time = np.random.uniform(1e5, 1e6)
# self.log_print([
# "Time too high -> randomising to ", new_time
# ])
if "force_time_choice" in kwargs:
new_time = kwargs["force_time_choice"]
self._times_suggested.append(new_time)
new_experiment["t"] = new_time
return new_experiment
def design_experiment(self, **kwargs):
r"""
Design an experiment.
Children classes can overwrite this function to implement custom logic
for the deisggn of experiments.
"""
raise RuntimeError("experiment design method not written for this heuristic.")
def finalise_heuristic(self, **kwargs):
r"""Any functionality the user wishes to happen at the final call to the heuristic."""
self.log_print(
[
"{} Resample epochs: {}".format(
len(self._resample_epochs),
self._resample_epochs,
)
# "\nTimes suggested:", self._times_suggested
]
)
def plot_heuristic_attributes(self, save_to_file, **kwargs):
"""
Summarise the heuristic used for the model training through several plots.
volume of distribution at each experiment
time designed by heuristic for each experiment
effecitve sample size at each experiment, used to determine when to resample
:param save_to_file: path to which the summary figure is stored
:type save_to_file: path
"""
plots_to_include = ["volume", "times_used", "effective_sample_size"]
plt.clf()
nrows = len(plots_to_include)
lf = LatexFigure(gridspec_layout=(nrows, 1))
if "volume" in plots_to_include:
ax = lf.new_axis()
self._plot_volumes(ax=ax)
ax.legend()
if "times_used" in plots_to_include:
ax = lf.new_axis()
self._plot_suggested_times(ax=ax)
ax.legend()
if "effective_sample_size" in plots_to_include:
ax = lf.new_axis()
self._plot_effective_sample_size(ax=ax)
ax.legend()
# Save figure
self.log_print(["LatexFigure has size:", lf.size])
lf.save(save_to_file, file_format=self._figure_format)
def _plot_suggested_times(self, ax, **kwargs):
full_epoch_list = range(len(self._times_suggested))
ax.scatter(
full_epoch_list,
self._times_suggested,
label=r"$t \sim k \ \frac{1}{V}$",
s=5,
)
ax.set_title("Experiment times", fontsize=self._label_fontsize)
ax.set_ylabel("Time", fontsize=self._label_fontsize)
ax.set_xlabel("Epoch", fontsize=self._label_fontsize)
self._add_resample_epochs_to_ax(ax=ax)
ax.semilogy()
def _plot_volumes(self, ax, **kwargs):
full_epoch_list = range(len(self._volumes))
ax.plot(
full_epoch_list,
self._volumes,
label="Volume",
)
ax.set_title("Volume", fontsize=self._label_fontsize)
ax.set_ylabel("Volume", fontsize=self._label_fontsize)
ax.set_xlabel("Epoch", fontsize=self._label_fontsize)
self._add_resample_epochs_to_ax(ax=ax)
ax.semilogy()
def _plot_effective_sample_size(self, ax, **kwargs):
full_epoch_list = range(len(self.effective_sample_size))
ax.plot(
full_epoch_list,
self.effective_sample_size,
label=r"$N_{ESS}$",
)
resample_thresh = self._updater.resample_thresh
ax.axhline(
resample_thresh * self.effective_sample_size[0],
label="Resample threshold ({}%)".format(resample_thresh * 100),
color="grey",
ls="-",
alpha=0.5,
)
if resample_thresh != 0.5:
ax.axhline(
self.effective_sample_size[0] / 2,
label="50%",
color="grey",
ls="--",
alpha=0.5,
)
ax.set_title("Effective Sample Size", fontsize=self._label_fontsize)
ax.set_ylabel("$N_{ESS}$", fontsize=self._label_fontsize)
ax.set_xlabel("Epoch", fontsize=self._label_fontsize)
self._add_resample_epochs_to_ax(ax=ax)
ax.legend()
ax.set_ylim(0, self.effective_sample_size[0] * 1.1)
# ax.semilogy()
def _add_resample_epochs_to_ax(self, ax, **kwargs):
c = "grey"
a = 0.5
ls = ":"
if len(self._resample_epochs) > 0:
ax.axvline(
self._resample_epochs[0], ls=ls, color=c, label="Resample", alpha=a
)
for e in self._resample_epochs[1:]:
ax.axvline(e, ls=ls, color=c, alpha=a)
class MultiParticleGuessHeuristic(ExperimentDesignHueristic):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.log_print(["Particle Guess Heuristic"])
def design_experiment(self, epoch_id=0, **kwargs):
idx_iter = 0
while idx_iter < self._maxiters:
sample = self._updater.sample(n=2)
x, xp = sample[:, np.newaxis, :]
if self._model.distance(x, xp) > 0:
break
else:
idx_iter += 1
if self._model.distance(x, xp) == 0:
self.log_print(["x,xp={},{}".format(x, xp)])
raise RuntimeError(
"PGH did not find distinct particles in \
{} iterations.".format(
self._maxiters
)
)
d = self._model.distance(x, xp)
new_time = 1 / d
eps = self._get_exp_params_array(epoch_id=epoch_id)
eps["t"] = new_time
# get sample from x
particle = self._updater.sample()
# self.log_print(["Particle for IQLE=", particle])
n_params = particle.shape[1]
for i in range(n_params):
p = particle[0][i]
corresponding_expparam = self._model.modelparam_names[i]
eps[corresponding_expparam] = p
return eps
class MixedMultiParticleLinspaceHeuristic(ExperimentDesignHueristic):
r"""
First half of experiments are standard MPGH, then force times evenly spaced
between 0 and max_time.
"""
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.log_print(["Mixed Particle Guess Heuristic"])
self.max_time_to_enforce = kwargs["max_time_to_enforce"]
self.count_number_high_times_suggested = 0
self.num_epochs_for_first_phase = self._num_experiments / 2
# generate a list of times of length Ne/2
# evenly spaced between 0, max_time (from exploration_strategy)
# then every t in that list is learned upon once.
# Higher Ne means finer granularity
# times are leared in a random order (from random.shuffle below)
num_epochs_to_space_time_list = math.ceil(
self._num_experiments - self.num_epochs_for_first_phase
)
t_list = list(
np.linspace(0, self.max_time_to_enforce, num_epochs_to_space_time_list + 1)
)
t_list.remove(0) # dont want to waste an epoch on t=0
t_list = [np.round(t, 2) for t in t_list]
# random.shuffle(t_list)
self._time_list = itertools.cycle(t_list)
def design_experiment(self, epoch_id=0, **kwargs):
idx_iter = 0
while idx_iter < self._maxiters:
x, xp = self._updater.sample(n=2)[:, np.newaxis, :]
if self._model.distance(x, xp) > 0:
break
else:
idx_iter += 1
if self._model.distance(x, xp) == 0:
raise RuntimeError(
"PGH did not find distinct particles in \
{} iterations.".format(
self._maxiters
)
)
eps = self._get_exp_params_array(epoch_id=epoch_id)
if epoch_id < self.num_epochs_for_first_phase:
d = self._model.distance(x, xp)
new_time = self._t_func(1 / d)
else:
new_time = next(self._time_list)
if new_time > self.max_time_to_enforce:
self.count_number_high_times_suggested += 1
if epoch_id == self._num_experiments - 1:
self.log_print(
[
"Number of suggested t > t_max:",
self.count_number_high_times_suggested,
]
)
eps["t"] = new_time
return eps
class SampleOrderMagnitude(ExperimentDesignHueristic):
def __init__(self, updater, **kwargs):
super().__init__(updater, **kwargs)
self.count_order_of_magnitudes = {}
self.force_order = None
def design_experiment(self, epoch_id=0, **kwargs):
experiment = self._get_exp_params_array(
epoch_id=epoch_id
) # empty experiment array
# sample from updater
idx_iter = 0
while idx_iter < self._maxiters:
x, xp = self._updater.sample(n=2)[:, np.newaxis, :]
if self._model.distance(x, xp) > 0:
break
else:
idx_iter += 1
cov_mtx = self._updater.est_covariance_mtx()
orders_of_magnitude = np.log10(
np.sqrt(np.abs(np.diag(cov_mtx)))
) # of the uncertainty on the individual parameters
orders_of_magnitude[orders_of_magnitude < 1] = 1 # lower bound
probs_of_orders = [
i / sum(orders_of_magnitude) for i in orders_of_magnitude
] # weight of each order of magnitude
# sample from the present orders of magnitude
selected_order = np.random.choice(a=orders_of_magnitude, p=probs_of_orders)
if self.force_order is not None:
selected_order = self.force_order
try:
self.count_order_of_magnitudes[np.round(selected_order)] += 1
except:
self.count_order_of_magnitudes[np.round(selected_order)] = 1
idx_params_of_similar_uncertainty = np.where(
np.isclose(orders_of_magnitude, selected_order, atol=1)
) # within 1 order of magnitude of the max
# change the scaling matrix used to calculate the distance
# to place importance only on the sampled order of magnitude
self._model._Q = np.zeros(len(orders_of_magnitude))
for idx in idx_params_of_similar_uncertainty:
self._model._Q[idx] = 1
d = self._model.distance(x, xp)
new_time = 1 / d
if self.force_order == 9:
new_time *= 100
experiment[self._t] = new_time
# print("Available orders of magnitude:", orders_of_magnitude)
# print("Selected order = ", selected_order)
# print("x= {}".format(x))
# print("x'={}".format(xp))
# print("Distance = ", d)
# print("Distance order mag=", np.log10(d))
# print("=> time=", new_time)
return experiment
def finalise_heuristic(self):
super().finalise_heuristic()
self.log_print(["count_order_of_magnitudes:", self.count_order_of_magnitudes])
class SampledUncertaintyWithConvergenceThreshold(ExperimentDesignHueristic):
def __init__(self, updater, **kwargs):
super().__init__(updater, **kwargs)
self._qinfer_model = self._model
cov_mtx = self._updater.est_covariance_mtx()
self.initial_uncertainties = np.sqrt(np.abs(np.diag(cov_mtx)))
self.track_param_uncertainties = np.zeros(self._qinfer_model.n_modelparams)
self.selection_criteria = (
"relative_volume_decrease" # 'hard_code_6' # 'hard_code_6_9_magnitudes'
)
self.count_order_of_magnitudes = {}
self.all_count_order_of_magnitudes = {}
self.counter_productive_experiments = 0
self.call_counter = 0
self._num_experiments = kwargs["num_experiments"]
self._num_exp_to_switch_magnitude = self._num_experiments / 2
print("Heuristic - num experiments = ", self._num_experiments)
print("epoch to switch target at:", self._num_exp_to_switch_magnitude)
def design_experiment(self, epoch_id=0, **kwargs):
self.call_counter += 1
experiment = self._get_exp_params_array(
epoch_id=epoch_id
) # empty experiment array
# sample from updater
idx_iter = 0
while idx_iter < self._maxiters:
x, xp = self._updater.sample(n=2)[:, np.newaxis, :]
if self._model.distance(x, xp) > 0:
break
else:
idx_iter += 1
current_param_est = self._updater.est_mean()
cov_mtx = self._updater.est_covariance_mtx()
param_uncertainties = np.sqrt(
np.abs(np.diag(cov_mtx))
) # uncertainty of params individually
orders_of_magnitude = np.log10(
param_uncertainties
) # of the uncertainty on the individual parameters
param_order_mag = np.log10(current_param_est)
relative_order_magnitude = param_order_mag / max(param_order_mag)
weighting_by_relative_order_magnitude = 10 ** relative_order_magnitude
self.track_param_uncertainties = np.vstack(
(self.track_param_uncertainties, param_uncertainties)
)
if self.selection_criteria.startswith("hard_code"):
if self.selection_criteria == "hard_code_6_9_magnitudes":
if self.call_counter > self._num_exp_to_switch_magnitude:
order_to_target = 6
else:
order_to_target = 9
elif self.selection_criteria == "hard_code_6":
order_to_target = 6
locations = np.where(
np.isclose(orders_of_magnitude, order_to_target, atol=1)
)
weights = np.zeros(len(orders_of_magnitude))
weights[locations] = 1
probability_of_param = weights / sum(weights)
elif self.selection_criteria == "relative_volume_decrease":
# probability of choosing order of magnitude
# of each parameter based on the ratio
# (change in volume)/(current estimate)
# for that parameter
print("Sampling by delta uncertainty/ estimate")
change_in_uncertainty = np.diff(
self.track_param_uncertainties[-2:], # most recent two track-params
axis=0,
)[0]
print("change in uncertainty=", change_in_uncertainty)
if np.all(change_in_uncertainty < 0):
# TODO better way to deal with all increasing uncertainties
print("All parameter uncertainties increased")
self.counter_productive_experiments += 1
weights = 1 / np.abs(change_in_uncertainty)
else:
# disregard changes which INCREASE volume:
change_in_uncertainty[change_in_uncertainty < 0] = 0
# weight = ratio of how much that change has decreased the volume
# over the current best estimate of the parameter
weights = change_in_uncertainty / current_param_est
weights *= weighting_by_relative_order_magnitude # weight the likelihood of selecting a parameter by its order of magnitude
probability_of_param = weights / sum(weights)
elif self.selection_criteria == "order_of_magniutde":
# probability directly from order of magnitude
print("Sampling by order magnitude")
probability_of_param = np.array(orders_of_magnitude) / sum(
orders_of_magnitude
)
else:
# sample evenly
print("Sampling evenly")
probability_of_param = np.ones(self._qinfer_model.n_modelparams)
# sample from the present orders of magnitude
selected_order = np.random.choice(a=orders_of_magnitude, p=probability_of_param)
try:
self.count_order_of_magnitudes[np.round(selected_order)] += 1
self.all_count_order_of_magnitudes[np.round(selected_order)] += 1
except:
self.count_order_of_magnitudes[np.round(selected_order)] = 1
self.all_count_order_of_magnitudes[np.round(selected_order)] = 1
idx_params_of_similar_uncertainty = np.where(
np.isclose(orders_of_magnitude, selected_order, atol=1)
) # within 1 order of magnitude of the max
self._model._Q = np.zeros(len(orders_of_magnitude))
for idx in idx_params_of_similar_uncertainty:
self._qinfer_model._Q[idx] = 1
d = self._qinfer_model.distance(x, xp)
new_time = 1 / d
experiment[self._t] = new_time
print("Current param estimates:", current_param_est)
try:
print("Weights:", weights)
except:
pass
print("probability_of_param: ", probability_of_param)
print("orders_of_magnitude:", orders_of_magnitude)
print("Selected order = ", selected_order)
print("x={}".format(x))
print("xp={}".format(xp))
print("Distance = ", d)
print("Distance order mag=", np.log10(d))
print("=> time=", new_time)
return experiment
class VolumeAdaptiveParticleGuessHeuristic(ExperimentDesignHueristic):
def __init__(self, updater, **kwargs):
super().__init__(updater, **kwargs)
self.time_multiplicative_factor = 1
self.derivative_frequency = self._num_experiments / 20
self.burn_in_learning_time = 6 * self.derivative_frequency
self.log_print(
[
"Derivative freq:{} \t burn in:{}".format(
self.derivative_frequency, self.burn_in_learning_time
)
]
)
self.time_factor_boost = 10 # factor to increase/decrease by
self.derivatives = {1: {}, 2: {}}
self.time_factor_changes = {"decreasing": [], "increasing": []}
self.distances = []
distance_metrics = [
"cityblock",
"euclidean",
"chebyshev",
"canberra",
"braycurtis",
"minkowski",
]
self.designed_times = {m: {} for m in distance_metrics}
self.distance_metric_to_use = "euclidean"
def design_experiment(self, epoch_id=0, **kwargs):
# Maybe increase multiplicative factor for time chosen later
if (
epoch_id % self.derivative_frequency == 0
and epoch_id > self.burn_in_learning_time
):
current_volume = self._volumes[-1]
previous_epoch_to_compare = int(-1 - self.derivative_frequency)
try:
previous_volume = self._volumes[previous_epoch_to_compare]
except:
previous_volume = self._volumes[0]
self.log_print(
[
"Couldn't find {}th element of volumes: {}".format(
previous_epoch_to_compare, self._volumes
)
]
)
relative_change = 1 - current_volume / previous_volume
self.log_print(
[
"At epoch {} V_old/V_new={}/{}. relative change={}".format(
epoch_id,
| np.round(previous_volume, 2) | numpy.round |
"""
This file contains the code required for IteratedWatersheds
"""
#----------------------------------------------------------------------------------------------#
#--------------------------------------- PRIORITY QUEUE ---------------------------------------#
#----------------------------------------------------------------------------------------------#
import itertools
import heapq
class priorityQueue:
def __init__(self):
self.pq = []
self.entry_finder = {}
self.REMOVED = "REMOVED"
self.counter = itertools.count()
def add_element(self, elt, priority=0):
""" Add an element to the queue
"""
if elt in self.entry_finder.keys():
self.remove_element(elt)
count = next(self.counter)
entry = [priority, count, elt]
self.entry_finder[elt] = entry
heapq.heappush(self.pq, entry)
def remove_element(self, elt):
"""
"""
entry = self.entry_finder[elt]
entry[-1] = self.REMOVED
def pop_element(self):
while self.pq:
priority, count, elt = heapq.heappop(self.pq)
if elt != self.REMOVED:
del self.entry_finder[elt]
return elt
raise KeyError('Cannot pop an element from empty queue')
#-----------------------------------------------------------------------------------------------#
#---------------------------------- IMAGE FORESTING TRANSFORM ----------------------------------#
#-----------------------------------------------------------------------------------------------#
import numpy as np
def _get_cost(a,b,flag='SP_SUM'):
if flag == 'SP_SUM':
return a+b
elif flag == 'SP_MAX':
return max(a,b)
else:
raise Exception('flag should be SP_SUM or SP_MAX but got {}'.format(flag))
def _ift(graph,init_labels,alg_flag='SP_SUM'):
"""Return the image foresting transform for the labels
graph : sparse matrix
The edge weighted graph on which the shortest path must be calculated
init_labels : ndarray
Initial Labelling. 0 indicates unlabelled pixels.
"""
size = graph.shape[0]
indices, indptr, data = graph.indices, graph.indptr, graph.data
# Initialization - Labels and Cost
labelling = np.array(init_labels)
cost = np.inf*np.ones(size, dtype=np.int32)
cost[init_labels > 0] = 0
pq = priorityQueue()
for i in np.where(init_labels > 0)[0]:
pq.add_element(i,0)
while pq.pq:
try:
x = pq.pop_element()
except:
break
for i in range(indptr[x],indptr[x+1]):
y = indices[i]
c_prime = _get_cost(cost[x],data[i],alg_flag) # New cost
if c_prime < cost[y]:
cost[y] = c_prime
pq.add_element(y,priority=c_prime)
labelling[y] = labelling[x]
assert np.all(labelling > 0), "Some labellings are still 0. Check if the graph is connected!!"
return labelling, np.sum(cost)
#-----------------------------------------------------------------------------------------------#
#-------------------------------------- CALCULATE CENTERS --------------------------------------#
#-----------------------------------------------------------------------------------------------#
from scipy.sparse.csgraph import floyd_warshall
def _calc_centers(graph, X, labelling, method='nearest'):
"""Return the new centers
graph : sparse matrix
Indicates the graph constructed from X
X : ndarray
Original Data
labelling: 1d array
The labelling of the vertices
method : one of 'nearest', 'floyd_warshall', 'erosion'
Method to calculate the new centers
"""
size = graph.shape[0]
centers = np.zeros(size)
max_label = int(np.max(labelling))
for label in range(1, max_label+1):
index_vert = np.where(labelling == label)[0]
if method == 'floyd_warshall':
subgraph = ((graph[index_vert]).transpose())[index_vert]
FW = floyd_warshall(subgraph, directed=False)
ind_center = np.argmin(np.max(FW, axis=-1))
centers[index_vert[ind_center]] = label
elif method == 'nearest':
mean_subgraph = np.mean(X[index_vert,:], axis=0, keepdims=True)
dist_from_mean = np.sum((X[index_vert,:] - mean_subgraph)**2, axis = -1)
ind_center = np.argmin(dist_from_mean.flatten())
centers[index_vert[ind_center]] = label
else:
raise Exception("Only use floyd_warshall or nearest methods (for now)")
return centers
#------------------------------------------------------------------------------------------------#
#-------------------------------------- ITERATED WATERSHED --------------------------------------#
#------------------------------------------------------------------------------------------------#
import numpy as np
def iterated_watershed(graph, X, number_clusters=6, max_iterations=100):
"""
"""
size = graph.shape[0]
#Initialize Random Centers
centers = np.zeros(size, dtype=np.int32)
index_centers = np.random.choice(size,number_clusters,replace=False)
centers[index_centers] = np.arange(number_clusters) + 1
#Cost
cost_history = []
opt_cost = np.inf
opt_labels = None
opt_centers = None
for i in range(max_iterations):
# Label all the vertices
labels, cost_arr = _ift(graph,centers)
# Update the optimal cost
if cost_arr < opt_cost:
opt_labels = labels
opt_cost = cost_arr
opt_centers = centers
# Compute the cost and append it to the history
cost_history.append(cost_arr)
# Compute the new centers
centersNew = _calc_centers(graph, X, labels)
# Break if the centers did not change!
if np.all(centers==centersNew):
break
else:
centers=centersNew
return opt_labels, cost_history, opt_centers
#-------------------------------------------------------------------------------------#
#------------------------------- MAKE GRAPH UNDIRECTED -------------------------------#
#-------------------------------------------------------------------------------------#
import scipy as sp
def make_undirected(G):
"""This function takes the graph and returns the undirected version.
"""
u,v,w = sp.sparse.find(G)
edges = dict()
for i in range(u.shape[0]):
edges[(u[i],v[i])] = w[i]
edges[(v[i],u[i])] = w[i]
sizeNew = len(edges)
uNew = np.zeros(sizeNew, dtype=np.int32)
vNew = np.zeros(sizeNew, dtype=np.int32)
wNew = np.zeros(sizeNew, dtype=np.float64)
i = 0
for ((u,v),w) in edges.items():
uNew[i], vNew[i], wNew[i] = u, v, w
i += 1
assert i == sizeNew, "Something went wrong"
return sp.sparse.csr_matrix((wNew,(uNew,vNew)), shape=G.shape)
#-----------------------------------------------------------------------------------------------#
#------------------------------------ CONSTRUCT 4-ADJ GRAPH ------------------------------------#
#-----------------------------------------------------------------------------------------------#
from scipy.sparse import csr_matrix
def img_to_graph(img, beta=1., eps=1e-6, which='similarity'):
"""
"""
s0, s1, s2 = img.shape
xGrid, yGrid = np.meshgrid(np.arange(s0), np.arange(s1))
indGrid = (xGrid*s1 + yGrid).transpose()
data_vert = np.sum((img[:-1,:,:] - img[1:,:,:])**2, axis = -1).flatten()
row_vert = indGrid[:-1,:].flatten()
col_vert = indGrid[1:,:].flatten()
data_horiz = np.sum((img[:,:-1,:] - img[:,1:,:])**2, axis = -1).flatten()
row_horiz = indGrid[:,:-1].flatten()
col_horiz = indGrid[:,1:].flatten()
data = np.concatenate((data_vert, data_horiz))
row = np.concatenate((row_vert, row_horiz))
col = np.concatenate((col_vert, col_horiz))
if which == 'similarity':
# Make the data into similarities
data = np.exp(-beta*data/data.std()) + eps
elif which == 'dissimilarity':
data += eps
else:
raise Exception("Should be one of similarity or dissimilarity.")
graph = csr_matrix((data,(row, col)), shape = (s0*s1, s0*s1))
graph = make_undirected(graph)
return graph
#-------------------------------------------------------------------------------------------------#
#----------------------------------------- GENERATE DATA -----------------------------------------#
#-------------------------------------------------------------------------------------------------#
from PIL import Image
import numpy as np
import os
def generate_data_1Object(number_images=10**6):
"""Generate data from weizman 1-Object dataset
"""
list_names = list(filter(lambda x:(x[0] != '.') and (x[-3:] != "mat"), os.listdir("./Workstation_files/1obj")))
np.random.shuffle(list_names)
total_count = len(list_names)
for i in range(min(total_count, number_images)):
fname = list_names[i]
img = np.array(Image.open("./Workstation_files/1obj/"+fname+"/src_color/"+fname+".png"), dtype=np.float64)
img = img/255.
list_gt_fname = list(filter(lambda x: x[0] != '.', os.listdir("./Workstation_files/1obj/"+fname+"/human_seg/")))
gt = []
for gt_name in list_gt_fname:
tmp = np.array(Image.open("./Workstation_files/1obj/"+fname+"/human_seg/"+gt_name), dtype=np.int32)
z = np.zeros(tmp.shape[:2], dtype=np.int32)
z[np.where(tmp[:,:,0]/255. == 1)] = 1
gt.append(z)
yield img, gt, fname
def generate_data_2Object(number_images=10**6):
"""Generate data from weizman 2-Object dataset
"""
list_names = list(filter(lambda x: (x[0] != '.') and (x[-3:] != "mat"), os.listdir("./Workstation_files/2obj")))
np.random.shuffle(list_names)
total_count = len(list_names)
for i in range(min(total_count, number_images)):
fname = list_names[i]
img = np.array(Image.open("./Workstation_files/2obj/"+fname+"/src_color/"+fname+".png"), dtype=np.float64)
img = img/255.
list_gt_fname = list(filter(lambda x: x[0] != '.', os.listdir("./Workstation_files/2obj/"+fname+"/human_seg/")))
gt = []
for gt_name in list_gt_fname:
tmp = np.array(Image.open("./Workstation_files/2obj/"+fname+"/human_seg/"+gt_name), dtype=np.int32)
z = np.zeros(tmp.shape[:2], dtype=np.int32)
z[np.where(tmp[:,:,0]/255. == 1)] = 1
z[np.where(tmp[:,:,2]/255. == 1)] = 2
gt.append(z)
yield img, gt, fname
#-------------------------------------------------------------------------------------------------#
#---------------------------------------- EVAULATE OUTPUT ----------------------------------------#
#-------------------------------------------------------------------------------------------------#
from sklearn.metrics import adjusted_mutual_info_score
from sklearn.metrics import adjusted_rand_score
from sklearn.metrics.cluster import contingency_matrix
from sklearn.metrics.cluster.supervised import _comb2
def evaluate_output(ypred, list_gt):
"""
"""
list_AMI, list_ARI, list_fScore, list_acc = [], [], [], []
for gt in list_gt:
ytrue = gt.flatten()
ypred = ypred.flatten()
AMI = adjusted_mutual_info_score(ytrue, ypred)
list_AMI.append(AMI)
ARI = adjusted_rand_score(ytrue, ypred)
list_ARI.append(ARI)
# Get the contigency matrix
contingency = contingency_matrix(ytrue, ypred)
# F-Score :
TP = sum(_comb2(n_ij) for n_ij in contingency.flatten())
total_positive_pred = sum(_comb2(n_c) for n_c in np.ravel(contingency.sum(axis=1)))
total_positive_true = sum(_comb2(n_c) for n_c in np.ravel(contingency.sum(axis=0)))
precision, recall = TP/total_positive_pred, TP/total_positive_true
f_score = 2*precision*recall/(precision + recall)
list_fScore.append(f_score)
# Assume that the class of a predicted label is the class with highest intersection
accuracy = np.sum(np.max(contingency, axis=0))/np.sum(contingency)
list_acc.append(accuracy)
return np.max(list_AMI), np.max(list_ARI), np.max(list_fScore), np.max(list_acc)
#-------------------------------------------------------------------------------------------------#
#-------------------------------------- SPECTRAL CLUSTERING --------------------------------------#
#-------------------------------------------------------------------------------------------------#
from scipy.sparse import csr_matrix
from sklearn.cluster import k_means
from scipy.sparse.csgraph import connected_components, laplacian
from scipy.sparse.linalg import eigsh
import scipy as sp
from scipy import sparse
from sklearn.cluster import spectral_clustering as _spectral_clustering
def spectral_clustering(graph, n_clusters, beta_weight=1., eps_weight=1e-6):
"""
"""
graphTmp = csr_matrix(graph, copy=True)
graphTmp.data = np.exp(-beta_weight*graphTmp.data/graphTmp.data.std()) + eps_weight
L = laplacian(graphTmp, normed=True)
eigval, embed = eigsh(L, 6, sigma = 1e-10)
d0, labels, d2 = k_means(embed,6, n_init=10)
return labels
#--------------------------------------------------------------------------------------------------#
#----------------------------------- ISOPERIMETRIC PARTITIONING -----------------------------------#
#--------------------------------------------------------------------------------------------------#
from IsoperimetricPartitioning import recursive_iso_parition, isoperimetric_Full
"""
isoperimetric_Full(img_graph, ground=0)
recursive_iso_parition(img_graph, algCode='full')
"""
def isoperimetric_partitioning(graph, beta_weight=1., eps_weight=1e-6, which='full'):
"""
"""
graphTmp = csr_matrix(graph, copy=True)
graphTmp.data = np.exp(-beta_weight*graphTmp.data/graphTmp.data.std()) + eps_weight
seed = 0
if which == 'full':
labels, isoSolution = isoperimetric_Full(graphTmp, ground=seed)
elif which == 'recursive':
labels = recursive_iso_parition(graphTmp, algCode='full')
return labels
#--------------------------------------------------------------------------------------------------#
#-------------------------------------- K-MEANS PARTITIONING --------------------------------------#
#--------------------------------------------------------------------------------------------------#
from sklearn.cluster import KMeans
def kmeans_adapted(img, n_clusters):
"""
"""
s0, s1, s2 = img.shape
X = img.reshape((s0*s1, s2))
xgrid, ygrid = np.meshgrid(np.arange(s0), np.arange(s1))
xgrid, ygrid = xgrid.transpose(), ygrid.transpose()
xgrid, ygrid = (xgrid.flatten()).reshape((-1,1)), (ygrid.flatten()).reshape((-1,1))
grid = np.hstack((xgrid, ygrid))
grid = grid/np.max(grid)
X = np.hstack((X, grid))
clf = KMeans(n_clusters=n_clusters)
labels = clf.fit_predict(X)
return labels
#---------------------------------------------------------------------------------------------------#
#-------------------------------------- GET ROAD NETWORK DATA --------------------------------------#
#---------------------------------------------------------------------------------------------------#
import pandas as pd
import numpy as np
import networkx as nx
import scipy as sp
def get_road_network_data(city='Mumbai'):
"""
"""
data = pd.read_csv("./RoadNetwork/"+city+"/"+city+"_Edgelist.csv")
size = data.shape[0]
X = np.array(data[['XCoord','YCoord']])
u, v = np.array(data['START_NODE'], dtype=np.int32), np.array(data['END_NODE'], dtype=np.int32)
w = np.array(data['LENGTH'], dtype=np.float64)
w = w/np.max(w) + 1e-6
G = sp.sparse.csr_matrix((w, (u,v)), shape = (size, size))
n, labels = sp.sparse.csgraph.connected_components(G)
if n == 1:
return G
# If there are more than one connected component, return the largest connected component
count_size_comp = np.bincount(labels)
z = np.argmax(count_size_comp)
indSelect = np.where(labels==z)
Gtmp = G[indSelect].transpose()[indSelect]
Gtmp = make_undirected(Gtmp)
return X[indSelect], Gtmp
#---------------------------------------------------------------------------------------------------#
#------------------------------------- K-MEANS ON ROAD NETWORK -------------------------------------#
#---------------------------------------------------------------------------------------------------#
from sklearn.cluster import KMeans
from scipy.sparse.csgraph import dijkstra
def kmeans_on_roadNetwork(G, X, nClusters):
"""
"""
clf = KMeans(n_clusters=nClusters, n_init=20)
labels = clf.fit_predict(X)
seeds = np.zeros(X.shape[0], dtype=np.int32)
for l in | np.unique(labels) | numpy.unique |
# coding=utf-8
import pandas
import numpy as np
import scipy
import statsmodels.api as sm
import traceback
import logging
import math
import random
from time import time
from msgpack import unpackb, packb
from redis import StrictRedis
from scipy import stats
from sklearn.ensemble import IsolationForest
from sklearn.cluster import KMeans
from settings import (
ALGORITHMS,
CONSENSUS,
FULL_DURATION,
MAX_TOLERABLE_BOREDOM,
MIN_TOLERABLE_LENGTH,
STALE_PERIOD,
REDIS_SOCKET_PATH,
ENABLE_SECOND_ORDER,
BOREDOM_SET_SIZE,
K_MEANS_CLUSTER,
VERTEX_WEIGHT_ETA,
VERTEX_THRESHOLD,
ANOMALY_COLUMN,
ANOMALY_PATH,
CSHL_NUM,
CSHL_PATH,
)
from algorithm_exceptions import *
logger = logging.getLogger("AnalyzerLog")
redis_conn = StrictRedis(unix_socket_path=REDIS_SOCKET_PATH)
vertex_centers = np.zeros((1, 1))
vertex_avg_score = -1
cshl_weight = [-1.35455734e-01, -5.44036064e-04, -1.35455734e-01, -5.44036064e-04,
-1.35455734e-01, -1.35455734e-01, -5.44036064e-04, -1.35455734e-01,
-5.44036064e-04, -1.35455734e-01, -5.44036064e-04, -5.44036064e-04,
-1.67484694e+00, 1.04843752e+00, 6.61651030e-01, 4.13469487e-08,
1.78945321e-01, -3.60150391e-01, 1.21850659e-01, 4.61800469e-01,
-1.00200490e-01, -1.33467708e-06, 9.32745829e-19, 4.21863030e-09,
-3.36662454e-10, -8.90717918e-06, -4.42558069e-05, -2.87667856e-09]
"""
This is no man's land. Do anything you want in here,
as long as you return a boolean that determines whether the input
timeseries is anomalous or not.
To add an algorithm, define it here, and add its name to settings.ALGORITHMS.
"""
def vertex_score(timeseries):
"""
A timeseries is anomalous if vertex score in hypergraph is greater than average score of observed anomalous vertex.
:return: True or False
"""
if vertex_centers.shape[0] <= 1:
update_vertex_param()
timeseries = np.array(timeseries)
test_data = timeseries[:, 1:]
test_data = (test_data - np.min(test_data, axis=0)) / (np.max(test_data, axis=0) - np.min(test_data, axis=0))
test_data = np.nan_to_num(test_data)
score = calculate_vertex_score(test_data, vertex_centers)
if np.sum(score[score > vertex_avg_score]) > VERTEX_THRESHOLD:
return True
return False
def cshl_detect(timeseries):
timeseries = np.delete(np.array(timeseries), [0,1,2,15], axis=1)
abnormal_num = 0
for i in range(timeseries.shape[0]):
zeta = np.dot(timeseries[i], cshl_weight)
if zeta < 0:
abnormal_num = abnormal_num + 1
if abnormal_num >= CSHL_NUM:
return True
return False
def update_vertex_param():
"""
Read observed abnormal data and update cluster centers
"""
global vertex_centers
global vertex_avg_score
origin_data = pandas.read_csv(ANOMALY_PATH).values
abnormal = origin_data[:, 3:]
abnormal = (abnormal - np.min(abnormal, axis=0)) / (np.max(abnormal, axis=0) - np.min(abnormal, axis=0))
abnormal = np.nan_to_num(abnormal)
k_means = KMeans(n_clusters=K_MEANS_CLUSTER)
k_means.fit_predict(abnormal)
vertex_centers = k_means.cluster_centers_
vertex_avg_score = np.mean(calculate_vertex_score(abnormal, vertex_centers))
def calculate_vertex_score(samples, center):
"""
we use similarity score and isolation score to initialize vertex weight
according to their correlations
:param samples: all the samples
:param center: abnormal cluster center
:return: total score of samples
"""
clf = IsolationForest()
clf.fit(samples)
num = samples.shape[0]
IS = (0.5 - clf.decision_function(samples)).reshape((num, 1))
distance = np.array(np.min(euclidean_distances(samples, center), axis=1))
dis_min = np.min(distance)
dis_max = np.max(distance)
distance = (distance - dis_min) / (dis_max - dis_min)
SS = np.exp(-distance).reshape((num, 1))
TS = VERTEX_WEIGHT_ETA * IS + (1-VERTEX_WEIGHT_ETA) * SS
return TS
def euclidean_distances(A, B):
"""
Euclidean distance between matrix A and B
:param A: np array
:param B: np array
:return: np array
"""
BT = B.transpose()
vec_prod = np.dot(A, BT)
SqA = A**2
sumSqA = np.matrix(np.sum(SqA, axis=1))
sumSqAEx = np.tile(sumSqA.transpose(), (1, vec_prod.shape[1]))
SqB = B**2
sumSqB = np.sum(SqB, axis=1)
sumSqBEx = np.tile(sumSqB, (vec_prod.shape[0], 1))
SqED = sumSqBEx + sumSqAEx - 2*vec_prod
SqED[SqED < 0] = 0.0
ED = np.sqrt(SqED)
return ED
def tail_avg(timeseries):
"""
This is a utility function used to calculate the average of the last three
datapoints in the series as a measure, instead of just the last datapoint.
It reduces noise, but it also reduces sensitivity and increases the delay
to detection.
"""
timeseries = np.array(timeseries)
timeseries = timeseries[:, 1:]
try:
t = (timeseries[-1] + timeseries[-2] + timeseries[-3]) / 3
return t
except IndexError:
return timeseries[-1]
def update_cshl():
global cshl_weight
csv_data = pandas.read_csv(CSHL_PATH, header=None)
csv_data.drop([1, 2, 15], axis=1, inplace=True)
csv_data.drop_duplicates()
normal_data = csv_data[csv_data[0] == 0]
abnormal_data = csv_data[csv_data[0] == 1]
measure_data = np.vstack((normal_data, abnormal_data))
measure_label = measure_data[:, 0]
measure_label[measure_label == 0] = -1
measure_data = measure_data[:, 1:]
measure_data = (measure_data - np.min(measure_data, axis=0)) / (
np.max(measure_data, axis=0) - np.min(measure_data, axis=0))
measure_data = np.nan_to_num(measure_data)
cshl_weight = hpconstruct(measure_data, measure_label, 5)
def hpconstruct(x, y, k):
"""
construct hypergraph and interative process
:param x: np array, train and test set
:param y: np array, cost for each sample
:param k: value, kNN
:return: evaluation criteria
"""
length = len(x)
h = np.zeros((length, length))
dvlist = []
delist = []
totaldis = 0.0
alpha = 0.05
wm = np.eye(length)
wm = (1.0 / length) * wm
# initialize W
for xi in range(length):
diffMat = np.tile(x[xi], (length, 1)) - x # 求inX与训练集各个实例的差
sqDiffMat = diffMat ** 2
sqDistances = sqDiffMat.sum(axis=1)
distances = sqDistances ** 0.5 # 求欧式距离
sortedDistIndicies = distances.argsort() # 取排序的索引,用于排label
for i in range(k):
index = sortedDistIndicies[i + 1]
h[index][xi] = distances[index]
totaldis += distances.sum()
avedis = totaldis / (length ** 2 - length)
for xi in range(length):
for yi in range(length):
if h[xi][yi]:
h[xi][yi] = math.exp(((h[xi][yi] / avedis) ** 2) / (-alpha))
h[xi][xi] = 1
# initialize H,横坐标代表点,纵坐标代表边(中心点为序号)
for xi in range(length):
vertextmp = 0
for yi in range(length):
vertextmp += wm[yi][yi] * h[xi][yi]
dvlist.append(vertextmp)
dv = np.diag(dvlist)
# initialize Dv
for xi in range(length):
edgetmp = 0
for yi in range(length):
edgetmp += h[yi][xi]
delist.append(edgetmp)
de = np.diag(delist)
# initialize De
di = []
# y = np.array([])
for i in range(length):
if y[i] == 1:
di.append(1)
elif y[i] == -1:
di.append(1)
else:
di.append(0)
v = np.diag(di)
# initialize Υ
for i in range(length):
dv[i][i] = 1 / (math.sqrt(dv[i][i]))
# de[i][i] = 1 / de[i][i]
# calculate power of Dv and De
de = | np.linalg.inv(de) | numpy.linalg.inv |
import numpy as np
from scipy.interpolate import interp1d
from pyTools import *
################################################################################
#~~~~~~~~~Log ops
################################################################################
def logPolyVal(p,x):
ord = p.order()
logs = []
for idx in xrange(ord+1):
logs.append( np.log( p[idx] ) + (ord-idx)*np.log(x) )
return logs
################################################################################
#~~~~~~~~~Symmeterize data
################################################################################
def symmeterize( x, y, interp_type='cubic' ):
if x.min() <= 0:
raise ValueError('x.min() must be greater than zero.')
xs = np.array([-x,x]).flatten()
xs.sort()
f = interp1d( x , y , kind=interp_type )
return { 'x':xs , 'y':f(np.abs(xs)) }
################################################################################
#~~~~~~~~~3D Shapes
################################################################################
def makeSphere(x0=0,y0=0,z0=0,r=1,ntheta=30,nphi=30):
u = np.linspace(0, np.pi, ntheta)
v = np.linspace(0, 2 * np.pi, nphi)
x = np.outer(np.sin(u), np.sin(v))*r
y = np.outer(np.sin(u), np.cos(v))*r
z = np.outer(np.cos(u), np.ones_like(v))*r
return x+x0, y+y0, z+z0
def makeCylinder(x0=0,y0=0,z0=0,r=1,h=10,ntheta=30,nz=30):
u = np.linspace(0, 2*np.pi, ntheta)
z = np.linspace(0, h, nz)
UU,ZZ = np.meshgrid(u,z)
XX = np.cos(UU)*r
YY = np.sin(UU)*r
# ax.plot_wireframe(x, y, z)
return XX+x0, YY+y0, ZZ+z0
def generateLine3D( x0=0, x1=1, y0=0, y1=1, z0=0, z1=0, N=2 ):
return {'line':{'xData':np.linspace(x0,x1,N),
'yData':np.linspace(y0,y1,N),
'zData':np.linspace(z0,z1,N),
'cData':np.ones((N,1))}}
################################################################################
#~~~~~~~~~2D Shapes
################################################################################
def generateCircle(R=1, X0=0, Y0=0, N = 60, thetaMin = 0, thetaMax = 2*np.pi ):
thetas = np.linspace( thetaMin , thetaMax , N)
uY = np.sin( thetas )*R
uX = np.cos( thetas )*R
return {'circle':{'xData':uX+X0, 'yData':uY+Y0}}
def generateEllipse( RX=2, RY=1, X0=0, Y0=0, N = 60, thetaMin = 0, thetaMax = 2*np.pi ):
thetas = np.linspace( thetaMin , thetaMax , N)
uY = np.sin( thetas )*RY
uX = np.cos( thetas )*RX
return {'ellipse':{'xData':uX+X0, 'yData':uY+Y0}}
def makeCylinder2D( L = 10., R = 1., N=60, view_degrees=30. ):
yFac = | np.cos(view_degrees * np.pi/180.) | numpy.cos |
import os
import numpy as np
import torch
import torch.utils.data
from PIL import Image
import torchvision
from torchvision.models.detection.faster_rcnn import FastRCNNPredictor
from torchvision.models.detection.mask_rcnn import MaskRCNNPredictor
import torch.onnx as onnx
import torchvision.models as models
from engine import train_one_epoch, evaluate
import utils
import transforms as T
from torch.profiler import profile, record_function, ProfilerActivity
class NNDataset(torch.utils.data.Dataset):
def __init__(self, root, transforms=None):
self.root = root
self.transforms = transforms
# load all image files, sorting them to
# ensure that they are aligned
self.imgs = list(sorted(os.listdir(os.path.join(root, "Images"))))
self.masks = list(sorted(os.listdir(os.path.join(root, "Masks"))))
def __getitem__(self, idx):
# load images ad masks
img_path = os.path.join(self.root, "Images", self.imgs[idx])
mask_path = os.path.join(self.root, "Masks", self.masks[idx])
img = Image.open(img_path).convert("RGB")
# convert masks to grayscale mode to distinguish background and objects
mask = Image.open(mask_path).convert("L")
mask = np.array(mask)
# instances are encoded as different colors
obj_ids = | np.unique(mask) | numpy.unique |
from math import floor, ceil
import numpy as np
import json
import os
class RPNconfig:
"""Simple config holder with ability to save and load"""
def __init__(self, image_size, fm_size, scales, sizes):
self.image_size = image_size
self.fm_size = fm_size
self.sizes = sizes
self.scales = scales
self.anchors_per_fm_point = len(sizes) * len(scales)
self.anchor_boxes, self.valid_indices = rpn_anchor_boxes(image_size,
fm_size,
sizes,
scales)
def save_json(self, path):
assert os.path.splitext(path)[-1] == '.json', 'Config can only be a json'
data = {'image_size': self.image_size,
'fm_size': self.fm_size,
'sizes': self.sizes,
'scales': self.scales}
with open(path, 'w') as file:
json.dump(data, file)
@staticmethod
def load_json(path):
assert os.path.splitext(path)[-1] == '.json', 'Config can only be a json'
with open(path, 'r') as file:
data = json.load(file)
return RPNconfig(**data)
def rpn_anchor_boxes(image_size, *args, **kwargs):
"""Generate anchor boxes and indices of valid anchor boxes beforehand"""
anchor_boxes = generate_anchor_boxes(image_size, *args, **kwargs)
valid_ab_indices = valid_anchor_boxes(anchor_boxes, image_size)
return anchor_boxes, valid_ab_indices
def generate_anchor_boxes(image_size, feature_map_size, sizes, scales):
"""Generates all anchor boxes for current RPN configuration.
Receives:
sizes: sizes of 1:1 anchor boxes
scales: sides ratios of anchor boxes
image_size: (iH, iW)
feature_map_size: (fH, fW)
Returns:
anchor_boxes: shape (N, 4) """
image_height, image_width = image_size
fm_height, fm_width = feature_map_size
height_stride = int(image_height / fm_height)
width_stride = int(image_width / fm_width)
# Compose horizontal and vertical positions into grid and reshape result into (-1, 2)
y_centers = np.arange(0, image_height, height_stride)
x_centers = np.arange(0, image_width, width_stride)
centers = np.dstack(np.meshgrid(y_centers, x_centers)).reshape((-1, 2))
# Creates anchor boxes pyramid. Somewhat vectorized version of itertools.product
r_scales = np.repeat([scales], len(sizes), axis=0).ravel()
r_sides = np.repeat([sizes], len(scales), axis=1).ravel()
ab_pyramid = np.transpose([r_sides / (r_scales ** .5),
r_sides * (r_scales ** .5)]).astype(int)
# Creates combinations of all anchor boxes centers and sides
r_centers = np.repeat(centers, len(ab_pyramid), axis=0)
r_ab_pyramid = np.repeat([ab_pyramid], len(centers), axis=0).reshape((-1, 2))
return np.hstack((r_centers, r_ab_pyramid))
def valid_anchor_boxes(anchor_boxes, image_size):
"""Return indices of valid anchor boxes,
Anchor box is considered valid if it is inside image entirely
Receives:
anchor_boxes: shape (N, 4)
image_size: (iH, iW)
Returns:
indices shape (M)
"""
img_height, img_width = image_size
y, x, height, width = np.transpose(anchor_boxes)
# TODO(Mocurin) Optimize?
# Indicator matrix
indicators = np.array([y - height // 2 >= 0,
x - width // 2 >= 0,
y + height // 2 <= img_height,
x + width // 2 <= img_width]).transpose()
# Get indices of anchor boxes inside image
return np.flatnonzero(np.all(indicators, axis=1, keepdims=False))
def compute_deltas(anchor_boxes, gt_boxes):
"""Computes deltas between anchor boxes and respective gt boxes
Receives:
anchor_boxes: shape (N, 4) 'center' format
gt_boxes: shape (N, 4) 'corners' format
Returns:
deltas: shape (n, 4)
These 4 are:
dy = gt_y_center - y) / h
dx = gt_x_center - x) / w
dh = log(gt_height / h)
dw = log(gt_width / w)"""
y, x, height, width = np.transpose(anchor_boxes)
y0, x0, y1, x1 = | np.transpose(gt_boxes) | numpy.transpose |
import os
import re
from collections import namedtuple
import numpy as np
from scipy.stats import rankdata
from sklearn.utils import check_random_state
from csrank.constants import OBJECT_RANKING
from .util import sub_sampling_rankings
from ..dataset_reader import DatasetReader
__all__ = ['DepthDatasetReader']
class DepthDatasetReader(DatasetReader):
def __init__(self, dataset_type='deep', random_state=None, **kwargs):
super(DepthDatasetReader, self).__init__(learning_problem=OBJECT_RANKING, dataset_folder='depth_data', **kwargs)
options = {'deep': ['complete_deep_train.dat', 'complete_deep_test.dat'],
'basic': ['saxena_basic61x55.dat', 'saxena_basicTest61x55.dat'],
'semantic': ['saxena_semantic61x55.dat', 'saxena_semanticTest61x55.dat']
}
if dataset_type not in options:
dataset_type = 'deep'
train_filename, test_file_name = options[dataset_type]
self.train_file = os.path.join(self.dirname, train_filename)
self.test_file = os.path.join(self.dirname, test_file_name)
self.random_state = check_random_state(random_state)
self.__load_dataset__()
def __load_dataset__(self):
self.x_train, self.depth_train = load_dataset(self.train_file)
self.x_test, self.depth_test = load_dataset(self.test_file)
def get_train_test_datasets(self, n_datasets=5):
splits = np.array(n_datasets)
return self.splitter(splits)
def get_single_train_test_split(self):
seed = self.random_state.randint(2 ** 32, dtype='uint32')
X_train, Y_train = self.get_train_dataset_sampled_partial_rankings(seed=seed)
X_train, Y_train = sub_sampling_rankings(X_train, Y_train, n_objects=5)
X_test, Y_test = self.get_test_dataset_ties()
return X_train, Y_train, X_test, Y_test
def get_dataset_dictionaries(self):
pass
def splitter(self, iter):
for i in iter:
X_train, Y_train = self.get_train_dataset_sampled_partial_rankings(seed=10 * i + 32)
X_test, Y_test = self.get_test_dataset_ties()
yield X_train, Y_train, X_test, Y_test
def get_test_dataset_sampled_partial_rankings(self, **kwargs):
self.X, self.Y = self.get_dataset_sampled_partial_rankings(datatype='test', **kwargs)
self.__check_dataset_validity__()
return self.X, self.Y
def get_train_dataset_sampled_partial_rankings(self, **kwargs):
self.X, self.Y = self.get_dataset_sampled_partial_rankings(datatype='train', **kwargs)
self.__check_dataset_validity__()
return self.X, self.Y
def get_test_dataset(self):
self.X, self.Y = self.get_dataset(datatype='test')
self.__check_dataset_validity__()
return self.X, self.Y
def get_train_dataset(self):
self.X, self.Y = self.get_dataset(datatype='train')
self.__check_dataset_validity__()
return self.X, self.Y
def get_test_dataset_ties(self):
self.X, self.Y = self.get_dataset_ties(datatype='test')
self.__check_dataset_validity__()
return self.X, self.Y
def get_train_dataset_ties(self):
self.X, self.Y = self.get_dataset_ties(datatype='train')
self.__check_dataset_validity__()
return self.X, self.Y
def get_dataset_sampled_partial_rankings(self, datatype='train', max_number_of_rankings_per_image=10, seed=42):
random_state = np.random.RandomState(seed=seed)
x_train, depth_train = self.get_deep_copy_dataset(datatype)
X = []
rankings = []
order_lengths = np.array(
[len(np.unique(depths[np.where(depths <= 0.80)[0]], return_index=True)[1]) for depths in depth_train])
order_length = np.min(order_lengths)
for features, depths in zip(x_train, depth_train):
value, obj_indices = np.unique(depths[np.where(depths <= 0.80)[0]], return_index=True)
interval = int(len(obj_indices) / order_length)
if interval < max_number_of_rankings_per_image:
num_of_orderings_per_image = interval
else:
num_of_orderings_per_image = max_number_of_rankings_per_image
objects_i = np.empty([order_length, num_of_orderings_per_image], dtype=int)
for i in range(order_length):
if i != order_length - 1:
objs = random_state.choice(obj_indices[i * interval:(i + 1) * interval], num_of_orderings_per_image,
replace=False)
else:
objs = random_state.choice(obj_indices[i * interval:len(obj_indices)], num_of_orderings_per_image,
replace=False)
objects_i[i] = objs
for i in range(num_of_orderings_per_image):
indices = objects_i[:, i]
np.random.shuffle(indices)
X.append(features[indices])
ranking = rankdata(depths[indices]) - 1
rankings.append(ranking)
X = np.array(X)
rankings = np.array(rankings)
return X, rankings
def get_dataset(self, datatype='train'):
x, y = self.get_deep_copy_dataset(datatype)
X = []
rankings = []
for features, depths in zip(x, y):
value, indices = np.unique(depths, return_index=True)
np.random.shuffle(indices)
X.append(features[indices])
ranking = rankdata(depths[indices]) - 1
rankings.append(ranking)
X = np.array(X)
rankings = np.array(rankings)
return X, rankings
def get_dataset_ties(self, datatype='train'):
X, y = self.get_deep_copy_dataset(datatype)
for depth in y:
depth[np.where(depth >= 0.80)[0]] = 0.80
rankings = np.array([rankdata(depth) - 1 for depth in y])
return X, rankings
def get_deep_copy_dataset(self, datatype):
if datatype == 'train':
x, y = np.copy(self.x_train), | np.copy(self.depth_train) | numpy.copy |
# authors: <NAME>, email:<EMAIL>
# <NAME>, email:<EMAIL>
# This is the code repo for the paper "Deep-learning based decoding of constrained sequence codes",
# in IEEE Journal on Selected Areas in Communications, https://ieeexplore.ieee.org/document/8792188.
# Credit is also given to Tobias Gruber et al and their github repo https://github.com/gruberto/DL-ChannelDecoding,
# where this code repo is initially partly written based on theirs.
#!/usr/bin/env python
import numpy as np
import random
from keras import backend as K ###
def modulateBPSK(x):
return -2 * x + 1
def addNoise_fixedlengthCode(x, sigma):
w = K.random_normal(K.shape(x), mean=0.0, stddev=sigma)
return x + w
def addNoise(x, sigma, len_test = None):
if len_test is None:
w = K.random_normal(K.shape(x), mean=0.0, stddev=sigma)
positives = K.equal(x, 3)
positives = K.cast(positives, K.floatx())
noisy = x + w
noisy = noisy - noisy*positives + 3*positives
K.print_tensor(noisy)
return noisy
else:
w = np.random.normal(0.0, sigma, x.shape)
noisy = x + w
for noisy_test_i in range(0, noisy.shape[0]):
if len_test[noisy_test_i][0] < noisy.shape[1]:
noisy[noisy_test_i][int(len_test[noisy_test_i][0]):] = [3] * (noisy.shape[1] - int(len_test[noisy_test_i][0]))
return noisy;
def ber(y_true, y_pred):
return K.mean(K.not_equal(y_true, K.round(y_pred)))
def return_output_shape(input_shape):
return input_shape
def log_likelihood_ratio(x, sigma):
return 2 * x / np.float32(sigma ** 2)
def errors(y_true, y_pred):
return K.sum(K.cast(K.not_equal(y_true, K.round(y_pred)), dtype='float'))
def half_adder(a, b):
s = a ^ b
c = a & b
return s, c
def full_adder(a, b, c):
s = (a ^ b) ^ c # for current bit position
c = (a & b) | (c & (a ^ b)) # for the next bit position
# print("s: ", s," c: ", c);
return s, c
def add_bool(a, b):
if len(a) != len(b):
raise ValueError('arrays with different length')
k = len(a)
s = np.zeros(k, dtype=bool)
c = False
for i in reversed(range(0, k)):
s[i], c = full_adder(a[i], b[i], c)
if c:
warnings.warn("Addition overflow!")
return s
def inc_bool(a):
k = len(a)
increment = np.hstack((np.zeros(k - 1, dtype=bool), np.ones(1, dtype=bool)))
# print("a: ", a," increment: ", increment);
a = add_bool(a, increment)
return a
def bitrevorder(x):
m = np.amax(x)
n = np.ceil(np.log2(m)).astype(int)
for i in range(0, len(x)):
x[i] = int('{:0{n}b}'.format(x[i], n=n)[::-1], 2)
return x
def int2bin(x, N):
if isinstance(x, list) or isinstance(x, np.ndarray):
binary = np.zeros((len(x), N), dtype='bool')
for i in range(0, len(x)):
binary[i] = np.array([int(j) for j in bin(x[i])[2:].zfill(N)])
else:
binary = np.array([int(j) for j in bin(x)[2:].zfill(N)], dtype=bool)
return binary
def bin2int(b):
if isinstance(b[0], list):
integer = np.zeros((len(b),), dtype=int)
for i in range(0, len(b)):
out = 0
for bit in b[i]:
out = (out << 1) | bit
integer[i] = out
elif isinstance(b, np.ndarray):
if len(b.shape) == 1:
out = 0
for bit in b:
out = (out << 1) | bit
integer = out
else:
integer = np.zeros((b.shape[0],), dtype=int)
for i in range(0, b.shape[0]):
out = 0
for bit in b[i]:
out = (out << 1) | bit
integer[i] = out
return integer
def polar_design_awgn(N, k, design_snr_dB):
S = 10 ** (design_snr_dB / 10)
z0 = np.zeros(N)
z0[0] = np.exp(-S)
for j in range(1, int(np.log2(N)) + 1):
u = 2 ** j
for t in range(0, int(u / 2)):
T = z0[t]
z0[t] = 2 * T - T ** 2 # upper channel
z0[int(u / 2) + t] = T ** 2 # lower channel
# sort into increasing order
idx = np.argsort(z0)
# select k best channels
idx = np.sort(bitrevorder(idx[0:k]))
A = np.zeros(N, dtype=bool)
A[idx] = True
return A
def polar_transform_iter(u):
N = len(u)
n = 1
x = np.copy(u)
stages = np.log2(N).astype(int)
for s in range(0, stages):
i = 0
while i < N:
for j in range(0, n):
idx = i + j
x[idx] = x[idx] ^ x[idx + n]
i = i + 2 * n
n = 2 * n
return x
def error_correction_hard(clen, received, codebook_decode_array_shuffle = None):
if codebook_decode_array_shuffle.size != 0:
codebook = codebook_decode_array_shuffle
else:
codebook = code_word_4b6b
min_hamming_distance = clen + 1
for key in codebook:
hamming_distance = 0
for bit in range(0, clen):
if received[bit] != key[bit]:
hamming_distance += 1
if hamming_distance < min_hamming_distance:
min_hamming_distance = hamming_distance
corrected = key
return corrected
def error_correction_soft(clen, received, codebook_decode_array_shuffle = None):
if codebook_decode_array_shuffle.size != 0:
codebook = codebook_decode_array_shuffle
else:
codebook = code_word_4b6b
min_distance = 10.0 ** 10.0
for key in codebook:
distance = 0.0
for bit in range(0, clen):
distance += abs(received[bit] - (-2.0 * key[bit] + 1.0)) * abs(received[bit] - (-2.0 * key[bit] + 1.0))
if distance < min_distance:
# print(distance,"\n")
min_distance = distance
corrected = key
return corrected
def error_correction_soft_DCfreeN5(clen, received):
if clen == 2:
codebook = code_word_DCfreeN5_len2
elif clen == 4:
codebook = code_word_DCfreeN5_len4
else:
print("received word not recoginzed (length can only be 2 or 4)")
exit(-1)
min_distance = 10.0 ** 10.0
for key in codebook:
distance = 0.0
for bit in range(0, clen):
distance += abs(received[bit] - (-2.0 * key[bit] + 1.0)) * abs(received[bit] - (-2.0 * key[bit] + 1.0))
if distance < min_distance:
# print(distance,"\n")
min_distance = distance
corrected = key
return corrected
def bit_err(ber, bits, clen):
"""
bit error rate vs S/N ratio
:param ber: ber array [sigma, error, bits]
:param bits: number of bit
:param clen: code length
:return:
"""
biterr = np.zeros((ber.shape[0], 2))
biterr[:, 0] = 10 * np.log10(1 / (2.0 * ber[:, 0] * ber[:, 0])) - 10 * np.log10(float(bits) / clen)
biterr[:, 1] = ber[:, 1] / ber[:, 2]
return biterr
def score(biterr0, biterr1):
"""
score to evaluate the decoder
:param biterr0: bit error rate (optimal) [sigma, biterr]
:param biterr1: bit error rate for evaluation [sigma. biterr]
:return:
"""
n = biterr1[0:len(biterr0) - 1, 1]/biterr0[0:len(biterr0) - 1, 1]
s = np.nansum(n)
if biterr1[len(biterr0) - 1, 1] == 0:
s += 1
else:
s += 10
s = s / 5.0
return s
def scoreBLER(BLER0, BLER1):
s= 0.0
for i in range(0, len(BLER0)):
if BLER1[i] == 0:
if BLER0[i] == 0:
s += 0
else:
s += 10
else:
s += float(BLER0[i]) / float(BLER1[i])
s = s / len(BLER0)
return s
def shuffle_code_book(encode_book):
"""
shuffle the code book
:param encode_book: code book
:return: shuffled code book
"""
codbok = np.array(list(encode_book.items()))
ids0 = np.random.permutation(codbok.shape[0])
ids1 = np.random.permutation(codbok.shape[0])
cod = codbok[ids0, 0]
word = codbok[ids1, 1]
shuff_encode_book = dict()
for i in range(len(cod)):
shuff_encode_book[cod[i]] = word[i]
return shuff_encode_book
def cartesian(arrays, out=None):
"""
Generate a cartesian product of input arrays.
Parameters
----------
arrays : list of array-like
1-D arrays to form the cartesian product of.
out : ndarray
Array to place the cartesian product in.
Returns
-------
out : ndarray
2-D array of shape (M, len(arrays)) containing cartesian products
formed of input arrays.
Examples
--------
cartesian(([1, 2, 3], [4, 5], [6, 7]))
array([[1, 4, 6],
[1, 4, 7],
[1, 5, 6],
[1, 5, 7],
[2, 4, 6],
[2, 4, 7],
[2, 5, 6],
[2, 5, 7],
[3, 4, 6],
[3, 4, 7],
[3, 5, 6],
[3, 5, 7]])
"""
arrays = [np.asarray(x) for x in arrays]
dtype = arrays[0].dtype
n = np.prod([x.size for x in arrays])
if out is None:
out = np.zeros([n, len(arrays)], dtype=dtype)
m = int(n / arrays[0].size)
out[:,0] = np.repeat(arrays[0], m)
if arrays[1:]:
cartesian(arrays[1:], out=out[0:m,1:])
for j in range(1, arrays[0].size):
out[j*m:(j+1)*m,1:] = out[0:m,1:]
return out
def create_codebook_shuffle(nframe = 5):
cbs = []
np.random.seed(0)
for i in range(nframe):
cbi = shuffle_code_book(codebook_4b6b)
cbs.append(cbi)
comb_codbok = combine_codes(cbs)
return comb_codbok
def combine_codes(codboks):
"""
combine multiple code books to a big code
:param codboks: tuple/list of code books
:return: code book for the combined code
"""
idx = ()
for cb in codboks:
key = cb.keys()
idx = idx + (list(key),)
idx = cartesian(idx)
res = dict()
cur_index = 0;
for id in idx:
cur_index += 1;
print("processing ", cur_index, " hash entry in the shuffled codebook")
cod = ''
word = ''
for i in range(len(id)):
cod += id[i]
word += " " + codboks[i][id[i]]
cod = np.array(cod.replace('[', ' ').replace(']', ' ').split()).astype(int)
word = word.lstrip(" ")
res[str(cod)] = word
return res
def get_decode_book(codbok):
"""
get decode book from code boook
:param codbok: code book
:return: decode book
"""
decodbok = dict()
decodbok_array = []
for key, val in codbok.items():
decodbok[str(np.array(val.split()).astype(int))] = key.replace('[', '').replace(']', '')
decodbok_array.append(np.array(list(val.split(' ')), dtype = 'int'))
decodbok_array = np.array(decodbok_array)
return decodbok, decodbok_array
# hash table for encoding
codebook_4b6b = {str(np.array([0, 0, 0, 0])):'0 0 1 1 1 0',
str(np.array([0, 0, 0, 1])):'0 0 1 1 0 1',
str(np.array([0, 0, 1, 0])):'0 1 0 0 1 1',
str(np.array([0, 0, 1, 1])):'0 1 0 1 1 0',
str(np.array([0, 1, 0, 0])):'0 1 0 1 0 1',
str(np.array([0, 1, 0, 1])):'1 0 0 0 1 1',
str(np.array([0, 1, 1, 0])):'1 0 0 1 1 0',
str(np.array([0, 1, 1, 1])):'1 0 0 1 0 1',
str(np.array([1, 0, 0, 0])):'0 1 1 0 0 1',
str(np.array([1, 0, 0, 1])):'0 1 1 0 1 0',
str(np.array([1, 0, 1, 0])):'0 1 1 1 0 0',
str(np.array([1, 0, 1, 1])):'1 1 0 0 0 1',
str(np.array([1, 1, 0, 0])):'1 1 0 0 1 0',
str(np.array([1, 1, 0, 1])):'1 0 1 0 0 1',
str(np.array([1, 1, 1, 0])):'1 0 1 0 1 0',
str(np.array([1, 1, 1, 1])):'1 0 1 1 0 0'}
# hash table for decoding
decode_4b6b = {str(np.array([0, 0, 1, 1, 1, 0])): '0 0 0 0',
str(np.array([0, 0, 1, 1, 0, 1])):'0 0 0 1',
str(np.array([0, 1, 0, 0, 1, 1])):'0 0 1 0',
str(np.array([0, 1, 0, 1, 1, 0])):'0 0 1 1',
str(np.array([0, 1, 0, 1, 0, 1])):'0 1 0 0',
str(np.array([1, 0, 0, 0, 1, 1])):'0 1 0 1',
str(np.array([1, 0, 0, 1, 1, 0])):'0 1 1 0',
str(np.array([1, 0, 0, 1, 0, 1])):'0 1 1 1',
str(np.array([0, 1, 1, 0, 0, 1])):'1 0 0 0',
str(np.array([0, 1, 1, 0, 1, 0])):'1 0 0 1',
str(np.array([0, 1, 1, 1, 0, 0])):'1 0 1 0',
str(np.array([1, 1, 0, 0, 0, 1])):'1 0 1 1',
str(np.array([1, 1, 0, 0, 1, 0])):'1 1 0 0',
str(np.array([1, 0, 1, 0, 0, 1])):'1 1 0 1',
str(np.array([1, 0, 1, 0, 1, 0])):'1 1 1 0',
str(np.array([1, 0, 1, 1, 0, 0])):'1 1 1 1'}
# hash table for error correction during decoding, same as codebook_decode but different type,
# to be compatible with function error_correction_hard() and error_correction_soft()
code_word_4b6b = np.array([[0, 0, 1, 1, 1, 0],
[0, 0, 1, 1, 0, 1],
[0, 1, 0, 0, 1, 1],
[0, 1, 0, 1, 1, 0],
[0, 1, 0, 1, 0, 1],
[1, 0, 0, 0, 1, 1],
[1, 0, 0, 1, 1, 0],
[1, 0, 0, 1, 0, 1],
[0, 1, 1, 0, 0, 1],
[0, 1, 1, 0, 1, 0],
[0, 1, 1, 1, 0, 0],
[1, 1, 0, 0, 0, 1],
[1, 1, 0, 0, 1, 0],
[1, 0, 1, 0, 0, 1],
[1, 0, 1, 0, 1, 0],
[1, 0, 1, 1, 0, 0]])
vary_length_1_3dk = {
str(np.array([0])): '0 1',
str(np.array([1, 0])): '0 0 1',
str(np.array([1, 1])): '0 0 0 1'
}
vary_length_DCfreeN5_state_1 = {
str(np.array([0, 1, 0])): [0, 1, 1, 1],
str( | np.array([0, 1, 1]) | numpy.array |
import json
import random
import os
import numpy as np
import torch
from torch.utils.data import Dataset
from torch.utils.data import DataLoader
import copy
import math
import h5py
import models.Constants as Constants
from bisect import bisect_left
import torch.nn.functional as F
import pickle
from pandas.io.json import json_normalize
def resampling(source_length, target_length):
return [round(i * (source_length-1) / (target_length-1)) for i in range(target_length)]
def get_frames_idx(length, n_frames, random_type, equally_sampling=False):
bound = [int(i) for i in np.linspace(0, length, n_frames+1)]
idx = []
all_idx = [i for i in range(length)]
if random_type == 'all_random' and not equally_sampling:
idx = random.sample(all_idx, n_frames)
else:
for i in range(n_frames):
if not equally_sampling:
tmp = np.random.randint(bound[i], bound[i+1])
else:
tmp = (bound[i] + bound[i+1]) // 2
idx.append(tmp)
return sorted(idx)
class VideoDataset(Dataset):
def __init__(self, opt, mode, print_info=False, shuffle_feats=0, specific=-1):
super(VideoDataset, self).__init__()
self.mode = mode
self.random_type = opt.get('random_type', 'segment_random')
assert self.mode in ['train', 'validate', 'test', 'all', 'trainval']
assert self.random_type in ['segment_random', 'all_random']
# load the json file which contains information about the dataset
data = pickle.load(open(opt['info_corpus'], 'rb'))
info = data['info']
self.itow = info['itow']
self.wtoi = {v: k for k, v in self.itow.items()}
self.itoc = info.get('itoc', None)
self.itop = info.get('itop', None)
self.itoa = info.get('itoa', None)
self.length_info = info['length_info']
self.splits = info['split']
if self.mode == 'trainval':
self.splits['trainval'] = self.splits['train'] + self.splits['validate']
self.split_category = info.get('split_category', None)
self.id_to_vid = info.get('id_to_vid', None)
self.captions = data['captions']
self.pos_tags = data['pos_tags']
self.references = pickle.load(open(opt['reference'], 'rb'))
self.specific = specific
self.num_category = opt.get('num_category', 20)
self.max_len = opt["max_len"]
self.n_frames = opt['n_frames']
self.equally_sampling = opt.get('equally_sampling', False)
self.total_frames_length = opt.get('total_frames_length', 60)
self.data_i = [self.load_database(opt["feats_i"]), opt["dim_i"], opt.get("dummy_feats_i", False)]
self.data_m = [self.load_database(opt["feats_m"]), opt["dim_m"], opt.get("dummy_feats_m", False)]
#self.data_i = [[], opt["dim_i"], opt.get("dummy_feats_i", False)]
#self.data_m = [[], opt["dim_m"], opt.get("dummy_feats_m", False)]
self.data_a = [self.load_database(opt["feats_a"]), opt["dim_a"], opt.get("dummy_feats_a", False)]
self.data_s = [self.load_database(opt.get("feats_s", [])), opt.get("dim_s", 10), False]
self.data_t = [self.load_database(opt.get("feats_t", [])), opt.get('dim_t', 10), False]
self.mask_prob = opt.get('teacher_prob', 1)
self.decoder_type = opt['decoder_type']
self.random = np.random.RandomState(opt.get('seed', 0))
self.obj = self.load_database(opt.get('object_path', ''))
self.all_caps_a_round = opt['all_caps_a_round']
self.load_feats_type = opt['load_feats_type']
self.method = opt.get('method', 'mp')
self.demand = opt['demand']
self.opt = opt
if print_info: self.print_info(opt)
self.beta_low, self.beta_high = opt.get('beta', [0, 1])
if (opt.get('triplet', False) or opt.get('knowledge_distillation_with_bert', False)) and self.mode == 'train':
self.bert_embeddings = self.load_database(opt['bert_embeddings'])
else:
self.bert_embeddings = None
if opt.get('load_generated_captions', False):
self.generated_captions = pickle.load(open(opt['generated_captions'], 'rb'))
assert self.mode in ['test']
else:
self.generated_captions = None
self.infoset = self.make_infoset()
def get_references(self):
return self.references
def get_preprocessed_references(self):
return self.captions
def make_infoset(self):
infoset = []
# decide the size of infoset
if self.specific != -1:
# we only evaluate partial examples with a specific category (MSRVTT, [0, 19])
ix_set = [int(item) for item in self.split_category[self.mode][self.specific]]
else:
# we evaluate all examples
ix_set = [int(item) for item in self.splits[self.mode]]
vatex = self.opt['dataset'] == 'VATEX' and self.mode == 'test'
for ix in ix_set:
vid = 'video%d' % ix
if vatex:
category = 0
captions = [[0]]
pos_tags = [[0]]
length_target = [0]
else:
category = self.itoc[ix] if self.itoc is not None else 0
captions = self.captions[vid]
pos_tags = self.pos_tags[vid] if self.pos_tags is not None else ([None] * len(captions))
# prepare length info for each video example, only if decoder_type == 'NARFormmer'
# e.g., 'video1': [0, 0, 3, 5, 0]
if self.length_info is None:
length_target = np.zeros(self.max_len)
else:
length_target = self.length_info[vid]
#length_target = length_target[1:self.max_len+1]
length_target = length_target[:self.max_len]
if len(length_target) < self.max_len:
length_target += [0] * (self.max_len - len(length_target))
#right_sum = sum(length_target[self.max_len+1:])
#length_target[-1] += right_sum
length_target = np.array(length_target) / sum(length_target)
if self.mode == 'train' and self.all_caps_a_round:
# infoset will contain all captions
for i, (cap, pt) in enumerate(zip(captions, pos_tags)):
item = {
'vid': vid,
'labels': cap,
'pos_tags': pt,
'category': category,
'length_target': length_target,
'cap_id': i,
}
infoset.append(item)
else:
if self.generated_captions is not None:
# edit the generated captions
cap = self.generated_captions[vid][-1]['caption']
#print(cap)
labels = [Constants.BOS]
for w in cap.split(' '):
labels.append(self.wtoi[w])
labels.append(Constants.EOS)
#print(labels)
item = {
'vid': vid,
'labels': labels,
'pos_tags': pos_tags[0],
'category': category,
'length_target': length_target
}
else:
# infoset will contain partial captions, one caption per video clip
cap_ix = random.randint(0, len(self.captions[vid]) - 1) if self.mode == 'train' else 0
#print(captions[0])
item = {
'vid': vid,
'labels': captions[cap_ix],
'pos_tags': pos_tags[cap_ix],
'category': category,
'length_target': length_target,
'cap_id': cap_ix,
}
infoset.append(item)
return infoset
def shuffle(self):
random.shuffle(self.infoset)
def __getitem__(self, ix):
vid = self.infoset[ix]['vid']
labels = self.infoset[ix]['labels']
taggings = self.infoset[ix]['pos_tags']
category = self.infoset[ix]['category']
length_target = self.infoset[ix]['length_target']
cap_id = self.infoset[ix].get('cap_id', None)
if cap_id is not None and self.bert_embeddings is not None:
bert_embs = np.asarray(self.bert_embeddings[0][vid])#[cap_id]
else:
bert_embs = None
attribute = self.itoa[vid]
frames_idx = get_frames_idx(
self.total_frames_length,
self.n_frames,
self.random_type,
equally_sampling = True if self.mode != 'train' else self.equally_sampling
) if self.load_feats_type == 0 else None
load_feats_func = self.load_feats if self.load_feats_type == 0 else self.load_feats_padding
feats_i = load_feats_func(self.data_i, vid, frames_idx)
feats_m = load_feats_func(self.data_m, vid, frames_idx, padding=False)#, scale=0.1)
feats_a = load_feats_func(self.data_a, vid, frames_idx)#, padding=False)
feats_s = load_feats_func(self.data_s, vid, frames_idx)
feats_t = load_feats_func(self.data_t, vid, frames_idx)#, padding=False)
results = self.make_source_target(labels, taggings)
tokens, labels, pure_target, taggings = map(
lambda x: results[x],
["dec_source", "dec_target", "pure_target", "tagging"]
)
tokens_1 = results.get('dec_source_1', None)
labels_1 = results.get('dec_target_1', None)
data = {}
data['feats_i'] = torch.FloatTensor(feats_i)
data['feats_m'] = torch.FloatTensor(feats_m)#.mean(0).unsqueeze(0).repeat(self.n_frames, 1)
data['feats_a'] = torch.FloatTensor(feats_a)
data['feats_s'] = F.softmax(torch.FloatTensor(feats_s), dim=1)
#print(feats_t.shape)
data['feats_t'] = torch.FloatTensor(feats_t)
data['tokens'] = torch.LongTensor(tokens)
data['labels'] = torch.LongTensor(labels)
data['pure_target'] = torch.LongTensor(pure_target)
data['length_target'] = torch.FloatTensor(length_target)
data['attribute'] = torch.FloatTensor(attribute)
if tokens_1 is not None:
data['tokens_1'] = torch.LongTensor(tokens_1)
data['labels_1'] = torch.LongTensor(labels_1)
if taggings is not None:
data['taggings'] = torch.LongTensor(taggings)
if bert_embs is not None:
data['bert_embs'] = torch.FloatTensor(bert_embs)
if self.decoder_type == 'LSTM' or self.decoder_type == 'ENSEMBLE':
tmp = | np.zeros(self.num_category) | numpy.zeros |
'''
This module makes some figures for cstwMPC. It requires that quite a few specifications
of the model have been estimated, with the results stored in ./Results.
'''
import matplotlib.pyplot as plt
import csv
import numpy as np
f = open('./Results/LCbetaPointNetWorthLorenzFig.txt','r')
my_reader = csv.reader(f,delimiter='\t')
raw_data = list(my_reader)
lorenz_percentiles = []
scf_lorenz = []
beta_point_lorenz = []
for j in range(len(raw_data)):
lorenz_percentiles.append(float(raw_data[j][0]))
scf_lorenz.append(float(raw_data[j][1]))
beta_point_lorenz.append(float(raw_data[j][2]))
f.close()
lorenz_percentiles = np.array(lorenz_percentiles)
scf_lorenz = np.array(scf_lorenz)
beta_point_lorenz = np.array(beta_point_lorenz)
f = open('./Results/LCbetaDistNetWorthLorenzFig.txt','r')
my_reader = csv.reader(f,delimiter='\t')
raw_data = list(my_reader)
beta_dist_lorenz = []
for j in range(len(raw_data)):
beta_dist_lorenz.append(float(raw_data[j][2]))
f.close()
beta_dist_lorenz = np.array(beta_dist_lorenz)
f = open('./Results/LCbetaPointNetWorthMPCfig.txt','r')
my_reader = csv.reader(f,delimiter='\t')
raw_data = list(my_reader)
mpc_percentiles = []
mpc_beta_point = []
for j in range(len(raw_data)):
mpc_percentiles.append(float(raw_data[j][0]))
mpc_beta_point.append(float(raw_data[j][1]))
f.close()
mpc_percentiles = np.asarray(mpc_percentiles)
mpc_beta_point = np.asarray(mpc_beta_point)
f = open('./Results/LCbetaDistNetWorthMPCfig.txt','r')
my_reader = csv.reader(f,delimiter='\t')
raw_data = list(my_reader)
mpc_beta_dist = []
for j in range(len(raw_data)):
mpc_beta_dist.append(float(raw_data[j][1]))
f.close()
mpc_beta_dist = np.asarray(mpc_beta_dist)
f = open('./Results/LCbetaDistLiquidMPCfig.txt','r')
my_reader = csv.reader(f,delimiter='\t')
raw_data = list(my_reader)
mpc_beta_dist_liquid = []
for j in range(len(raw_data)):
mpc_beta_dist_liquid.append(float(raw_data[j][1]))
f.close()
mpc_beta_dist_liquid = np.asarray(mpc_beta_dist_liquid)
f = open('./Results/LCbetaDistNetWorthKappaByAge.txt','r')
my_reader = csv.reader(f,delimiter='\t')
raw_data = list(my_reader)
kappa_mean_age = []
kappa_lo_beta_age = []
kappa_hi_beta_age = []
for j in range(len(raw_data)):
kappa_mean_age.append(float(raw_data[j][0]))
kappa_lo_beta_age.append(float(raw_data[j][1]))
kappa_hi_beta_age.append(float(raw_data[j][2]))
kappa_mean_age = np.array(kappa_mean_age)
kappa_lo_beta_age = np.array(kappa_lo_beta_age)
kappa_hi_beta_age = np.array(kappa_hi_beta_age)
age_list = np.array(range(len(kappa_mean_age)),dtype=float)*0.25 + 24.0
f.close()
f = open('./Results/LC_KYbyBeta.txt','r')
my_reader = csv.reader(f,delimiter='\t')
raw_data = list(my_reader)
KY_by_beta_lifecycle = []
beta_list = []
for j in range(len(raw_data)):
beta_list.append(float(raw_data[j][0]))
KY_by_beta_lifecycle.append(float(raw_data[j][1]))
beta_list = np.array(beta_list)
KY_by_beta_lifecycle = np.array(KY_by_beta_lifecycle)
f.close()
f = open('./Results/IH_KYbyBeta.txt','r')
my_reader = csv.reader(f,delimiter='\t')
raw_data = list(my_reader)
KY_by_beta_infinite = []
for j in range(len(raw_data)):
KY_by_beta_infinite.append(float(raw_data[j][1]))
KY_by_beta_infinite = np.array(KY_by_beta_infinite)
f.close()
plt.plot(100*lorenz_percentiles,beta_point_lorenz,'-.k',linewidth=1.5)
plt.plot(100*lorenz_percentiles,beta_dist_lorenz,'--k',linewidth=1.5)
plt.plot(100*lorenz_percentiles,scf_lorenz,'-k',linewidth=1.5)
plt.xlabel('Wealth percentile',fontsize=14)
plt.ylabel('Cumulative wealth ownership',fontsize=14)
plt.title('Lorenz Curve Matching, Lifecycle Model',fontsize=16)
plt.legend((r'$\beta$-point',r'$\beta$-dist','SCF data'),loc=2,fontsize=12)
plt.ylim(-0.01,1)
plt.savefig('./Figures/LorenzLifecycle.pdf')
plt.show()
plt.plot(mpc_beta_point,mpc_percentiles,'-.k',linewidth=1.5)
plt.plot(mpc_beta_dist,mpc_percentiles,'--k',linewidth=1.5)
plt.plot(mpc_beta_dist_liquid,mpc_percentiles,'-.k',linewidth=1.5)
plt.xlabel('Marginal propensity to consume',fontsize=14)
plt.ylabel('Cumulative probability',fontsize=14)
plt.title('CDF of the MPC, Lifecycle Model',fontsize=16)
plt.legend((r'$\beta$-point NW',r'$\beta$-dist NW',r'$\beta$-dist LA'),loc=0,fontsize=12)
plt.savefig('./Figures/MPCdistLifecycle.pdf')
plt.show()
plt.plot(age_list,kappa_mean_age,'-k',linewidth=1.5)
plt.plot(age_list,kappa_lo_beta_age,'--k',linewidth=1.5)
plt.plot(age_list,kappa_hi_beta_age,'-.k',linewidth=1.5)
plt.legend(('Population average','Most impatient','Most patient'),loc=2,fontsize=12)
plt.xlabel('Age',fontsize=14)
plt.ylabel('Average MPC',fontsize=14)
plt.title('Marginal Propensity to Consume by Age',fontsize=16)
plt.xlim(24,100)
plt.ylim(0,1)
plt.savefig('./Figures/MPCbyAge.pdf')
plt.show()
plt.plot(beta_list,KY_by_beta_infinite,'-k',linewidth=1.5)
plt.plot(beta_list,KY_by_beta_lifecycle,'--k',linewidth=1.5)
plt.plot([0.95,1.01],[10.26,10.26],'--k',linewidth=0.75)
plt.text(0.96,12,'U.S. K/Y ratio')
plt.legend(('Perpetual youth','Lifecycle'),loc=2,fontsize=12)
plt.xlabel(r'Discount factor $\beta$',fontsize=14)
plt.ylabel('Capital to output ratio',fontsize=14)
plt.title('K/Y Ratio by Discount Factor',fontsize=16)
plt.ylim(0,100)
plt.savefig('./Figures/KYratioByBeta.pdf')
plt.show()
f = open('./Results/IHbetaPointNetWorthLorenzFig.txt','r')
my_reader = csv.reader(f,delimiter='\t')
raw_data = list(my_reader)
lorenz_percentiles = []
scf_lorenz = []
beta_point_lorenz = []
for j in range(len(raw_data)):
lorenz_percentiles.append(float(raw_data[j][0]))
scf_lorenz.append(float(raw_data[j][1]))
beta_point_lorenz.append(float(raw_data[j][2]))
f.close()
lorenz_percentiles = np.array(lorenz_percentiles)
scf_lorenz = np.array(scf_lorenz)
beta_point_lorenz = np.array(beta_point_lorenz)
f = open('./Results/IHbetaDistNetWorthLorenzFig.txt','r')
my_reader = csv.reader(f,delimiter='\t')
raw_data = list(my_reader)
beta_dist_lorenz = []
for j in range(len(raw_data)):
beta_dist_lorenz.append(float(raw_data[j][2]))
f.close()
beta_dist_lorenz = np.array(beta_dist_lorenz)
f = open('./Results/IHbetaPointLiquidLorenzFig.txt','r')
my_reader = csv.reader(f,delimiter='\t')
raw_data = list(my_reader)
beta_point_lorenz_liquid = []
for j in range(len(raw_data)):
beta_point_lorenz_liquid.append(float(raw_data[j][2]))
f.close()
beta_point_lorenz_liquid = np.array(beta_point_lorenz_liquid)
f = open('./Results/IHbetaDistLiquidLorenzFig.txt','r')
my_reader = csv.reader(f,delimiter='\t')
raw_data = list(my_reader)
beta_dist_lorenz_liquid = []
for j in range(len(raw_data)):
beta_dist_lorenz_liquid.append(float(raw_data[j][2]))
f.close()
beta_dist_lorenz_liquid = np.array(beta_dist_lorenz_liquid)
f = open('./Results/IHbetaPointNetWorthMPCfig.txt','r')
my_reader = csv.reader(f,delimiter='\t')
raw_data = list(my_reader)
mpc_percentiles = []
mpc_beta_point = []
for j in range(len(raw_data)):
mpc_percentiles.append(float(raw_data[j][0]))
mpc_beta_point.append(float(raw_data[j][1]))
f.close()
mpc_percentiles = np.asarray(mpc_percentiles)
mpc_beta_point = np.asarray(mpc_beta_point)
f = open('./Results/IHbetaDistNetWorthMPCfig.txt','r')
my_reader = csv.reader(f,delimiter='\t')
raw_data = list(my_reader)
mpc_beta_dist = []
for j in range(len(raw_data)):
mpc_beta_dist.append(float(raw_data[j][1]))
f.close()
mpc_beta_dist = np.asarray(mpc_beta_dist)
f = open('./Results/IHbetaDistLiquidMPCfig.txt','r')
my_reader = csv.reader(f,delimiter='\t')
raw_data = list(my_reader)
mpc_beta_dist_liquid = []
for j in range(len(raw_data)):
mpc_beta_dist_liquid.append(float(raw_data[j][1]))
f.close()
mpc_beta_dist_liquid = np.asarray(mpc_beta_dist_liquid)
plt.plot(100*lorenz_percentiles,beta_point_lorenz,'-.k',linewidth=1.5)
plt.plot(100*lorenz_percentiles,scf_lorenz,'-k',linewidth=1.5)
plt.xlabel('Wealth percentile',fontsize=14)
plt.ylabel('Cumulative wealth ownership',fontsize=14)
plt.title('Lorenz Curve Matching, Perpetual Youth Model',fontsize=16)
plt.legend((r'$\beta$-point','SCF data'),loc=2,fontsize=12)
plt.ylim(-0.01,1)
plt.savefig('./Figures/LorenzInfiniteBP.pdf')
plt.show()
plt.plot(100*lorenz_percentiles,beta_point_lorenz,'-.k',linewidth=1.5)
plt.plot(100*lorenz_percentiles,beta_dist_lorenz,'--k',linewidth=1.5)
plt.plot(100*lorenz_percentiles,scf_lorenz,'-k',linewidth=1.5)
plt.xlabel('Wealth percentile',fontsize=14)
plt.ylabel('Cumulative wealth ownership',fontsize=14)
plt.title('Lorenz Curve Matching, Perpetual Youth Model',fontsize=16)
plt.legend((r'$\beta$-point',r'$\beta$-dist','SCF data'),loc=2,fontsize=12)
plt.ylim(-0.01,1)
plt.savefig('./Figures/LorenzInfinite.pdf')
plt.show()
plt.plot(100*lorenz_percentiles,beta_point_lorenz_liquid,'-.k',linewidth=1.5)
plt.plot(100*lorenz_percentiles,beta_dist_lorenz_liquid,'--k',linewidth=1.5)
plt.plot(np.array([20,40,60,80]),np.array([0.0, 0.004, 0.025,0.117]),'.r',markersize=10)
plt.xlabel('Wealth percentile',fontsize=14)
plt.ylabel('Cumulative wealth ownership',fontsize=14)
plt.title('Lorenz Curve Matching, Perpetual Youth (Liquid Assets)',fontsize=16)
plt.legend((r'$\beta$-point',r'$\beta$-dist','SCF targets'),loc=2,fontsize=12)
plt.ylim(-0.01,1)
plt.savefig('./Figures/LorenzLiquid.pdf')
plt.show()
plt.plot(mpc_beta_point,mpc_percentiles,'-.k',linewidth=1.5)
plt.plot(mpc_beta_dist,mpc_percentiles,'--k',linewidth=1.5)
plt.plot(mpc_beta_dist_liquid,mpc_percentiles,'-.k',linewidth=1.5)
plt.xlabel('Marginal propensity to consume',fontsize=14)
plt.ylabel('Cumulative probability',fontsize=14)
plt.title('CDF of the MPC, Perpetual Youth Model',fontsize=16)
plt.legend((r'$\beta$-point NW',r'$\beta$-dist NW',r'$\beta$-dist LA'),loc=0,fontsize=12)
plt.savefig('./Figures/MPCdistInfinite.pdf')
plt.show()
f = open('./Results/SensitivityRho.txt','r')
my_reader = csv.reader(f,delimiter='\t')
raw_data = list(my_reader)
rho_sensitivity = | np.array(raw_data) | numpy.array |
# -*- coding: utf-8 -*-
"""
Created on Mon May 31 15:40:31 2021
@author: jessm
this is comparing the teporal cube slices to their impainted counterparts
"""
import os
import matplotlib.pyplot as plt
import numpy as np
from astropy.table import QTable, Table, Column
from astropy import units as u
dimage=np.load('np_align30.npy')
dthresh=np.load('thresh_a30.npy')
dtable=np.load('table_a30.npy')
#reimage=np.load('np_rebinned5e7.npy')
#rethresh=np.load('thresh5e7.npy')
#retable=np.load('table5e7.npy')
reimage= | np.load('inpaint_a30.npy') | numpy.load |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
Process Hi-C output into AGP for chromosomal-scale scaffolding.
"""
from __future__ import print_function
import array
import json
import logging
import math
import os
import os.path as op
import sys
from collections import defaultdict
from functools import partial
from multiprocessing import Pool
import numpy as np
from jcvi.algorithms.ec import GA_run, GA_setup
from jcvi.algorithms.formula import outlier_cutoff
from jcvi.algorithms.matrix import get_signs
from jcvi.apps.base import ActionDispatcher, OptionParser, backup, iglob, mkdir, symlink
from jcvi.apps.console import green, red
from jcvi.apps.grid import Jobs
from jcvi.assembly.allmaps import make_movie
from jcvi.compara.synteny import check_beds, get_bed_filenames
from jcvi.formats.agp import order_to_agp
from jcvi.formats.base import LineFile, must_open
from jcvi.formats.bed import Bed
from jcvi.formats.blast import Blast
from jcvi.formats.sizes import Sizes
from jcvi.graphics.base import (
markup,
normalize_axes,
plt,
savefig,
ticker,
human_readable,
)
from jcvi.graphics.dotplot import dotplot
from jcvi.utils.cbook import gene_name, human_size
from jcvi.utils.natsort import natsorted
# Map orientations to ints
FF = {"+": 1, "-": -1, "?": 1}
RR = {"+": -1, "-": 1, "?": -1}
LB = 18 # Lower bound for golden_array()
UB = 29 # Upper bound for golden_array()
BB = UB - LB + 1 # Span for golden_array()
ACCEPT = green("ACCEPT")
REJECT = red("REJECT")
BINSIZE = 50000
class ContigOrderingLine(object):
"""Stores one line in the ContigOrdering file
"""
def __init__(self, line, sep="|"):
args = line.split()
self.contig_id = args[0]
self.contig_name = args[1].split(sep)[0]
contig_rc = args[2]
assert contig_rc in ("0", "1")
self.strand = "+" if contig_rc == "0" else "-"
self.orientation_score = args[3]
self.gap_size_after_contig = args[4]
class ContigOrdering(LineFile):
"""ContigOrdering file as created by LACHESIS, one per chromosome group.
Header contains summary information per group, followed by list of contigs
with given ordering.
"""
def __init__(self, filename):
super(ContigOrdering, self).__init__(filename)
fp = open(filename)
for row in fp:
if row[0] == "#":
continue
orderline = ContigOrderingLine(row)
self.append(orderline)
def write_agp(
self, obj, sizes, fw=sys.stdout, gapsize=100, gaptype="contig", evidence="map"
):
"""Converts the ContigOrdering file into AGP format
"""
contigorder = [(x.contig_name, x.strand) for x in self]
order_to_agp(
obj,
contigorder,
sizes,
fw,
gapsize=gapsize,
gaptype=gaptype,
evidence=evidence,
)
class CLMFile:
"""CLM file (modified) has the following format:
tig00046211+ tig00063795+ 1 53173
tig00046211+ tig00063795- 1 116050
tig00046211- tig00063795+ 1 71155
tig00046211- tig00063795- 1 134032
tig00030676+ tig00077819+ 5 136407 87625 87625 106905 102218
tig00030676+ tig00077819- 5 126178 152952 152952 35680 118923
tig00030676- tig00077819+ 5 118651 91877 91877 209149 125906
tig00030676- tig00077819- 5 108422 157204 157204 137924 142611
"""
def __init__(self, clmfile, skiprecover=False):
self.name = op.basename(clmfile).rsplit(".", 1)[0]
self.clmfile = clmfile
self.idsfile = clmfile.rsplit(".", 1)[0] + ".ids"
self.parse_ids(skiprecover)
self.parse_clm()
self.signs = None
def parse_ids(self, skiprecover):
"""IDS file has a list of contigs that need to be ordered. 'recover',
keyword, if available in the third column, is less confident.
tig00015093 46912
tig00035238 46779 recover
tig00030900 119291
"""
idsfile = self.idsfile
logging.debug("Parse idsfile `{}`".format(idsfile))
fp = open(idsfile)
tigs = []
for row in fp:
if row[0] == "#": # Header
continue
atoms = row.split()
tig, _, size = atoms
size = int(size)
if skiprecover and len(atoms) == 3 and atoms[2] == "recover":
continue
tigs.append((tig, size))
# Arrange contig names and sizes
_tigs, _sizes = zip(*tigs)
self.contigs = set(_tigs)
self.sizes = np.array(_sizes)
self.tig_to_size = dict(tigs)
# Initially all contigs are considered active
self.active = set(_tigs)
def parse_clm(self):
clmfile = self.clmfile
logging.debug("Parse clmfile `{}`".format(clmfile))
fp = open(clmfile)
contacts = {}
contacts_oriented = defaultdict(dict)
orientations = defaultdict(list)
for row in fp:
atoms = row.strip().split("\t")
assert len(atoms) == 3, "Malformed line `{}`".format(atoms)
abtig, links, dists = atoms
atig, btig = abtig.split()
at, ao = atig[:-1], atig[-1]
bt, bo = btig[:-1], btig[-1]
if at not in self.tig_to_size:
continue
if bt not in self.tig_to_size:
continue
dists = [int(x) for x in dists.split()]
contacts[(at, bt)] = len(dists)
gdists = golden_array(dists)
contacts_oriented[(at, bt)][(FF[ao], FF[bo])] = gdists
contacts_oriented[(bt, at)][(RR[bo], RR[ao])] = gdists
strandedness = 1 if ao == bo else -1
orientations[(at, bt)].append((strandedness, dists))
self.contacts = contacts
self.contacts_oriented = contacts_oriented
# Preprocess the orientations dict
for (at, bt), dists in orientations.items():
dists = [(s, d, hmean_int(d)) for (s, d) in dists]
strandedness, md, mh = min(dists, key=lambda x: x[-1])
orientations[(at, bt)] = (strandedness, len(md), mh)
self.orientations = orientations
def calculate_densities(self):
"""
Calculate the density of inter-contig links per base. Strong contigs
considered to have high level of inter-contig links in the current
partition.
"""
active = self.active
densities = defaultdict(int)
for (at, bt), links in self.contacts.items():
if not (at in active and bt in active):
continue
densities[at] += links
densities[bt] += links
logdensities = {}
for x, d in densities.items():
s = self.tig_to_size[x]
logd = np.log10(d * 1.0 / min(s, 500000))
logdensities[x] = logd
return logdensities
def report_active(self):
logging.debug(
"Active contigs: {} (length={})".format(self.N, self.active_sizes.sum())
)
def activate(self, tourfile=None, minsize=10000, backuptour=True):
"""
Select contigs in the current partition. This is the setup phase of the
algorithm, and supports two modes:
- "de novo": This is useful at the start of a new run where no tours
available. We select the strong contigs that have significant number
of links to other contigs in the partition. We build a histogram of
link density (# links per bp) and remove the contigs that appear as
outliers. The orientations are derived from the matrix decomposition
of the pairwise strandedness matrix O.
- "hotstart": This is useful when there was a past run, with a given
tourfile. In this case, the active contig list and orientations are
derived from the last tour in the file.
"""
if tourfile and (not op.exists(tourfile)):
logging.debug("Tourfile `{}` not found".format(tourfile))
tourfile = None
if tourfile:
logging.debug("Importing tourfile `{}`".format(tourfile))
tour, tour_o = iter_last_tour(tourfile, self)
self.active = set(tour)
tig_to_idx = self.tig_to_idx
tour = [tig_to_idx[x] for x in tour]
signs = sorted([(x, FF[o]) for (x, o) in zip(tour, tour_o)])
_, signs = zip(*signs)
self.signs = np.array(signs, dtype=int)
if backuptour:
backup(tourfile)
tour = array.array("i", tour)
else:
self.report_active()
while True:
logdensities = self.calculate_densities()
lb, ub = outlier_cutoff(list(logdensities.values()))
logging.debug("Log10(link_densities) ~ [{}, {}]".format(lb, ub))
remove = set(
x
for x, d in logdensities.items()
if (d < lb and self.tig_to_size[x] < minsize * 10)
)
if remove:
self.active -= remove
self.report_active()
else:
break
logging.debug("Remove contigs with size < {}".format(minsize))
self.active = set(x for x in self.active if self.tig_to_size[x] >= minsize)
tour = range(self.N) # Use starting (random) order otherwise
tour = array.array("i", tour)
# Determine orientations
self.flip_all(tour)
self.report_active()
self.tour = tour
return tour
def evaluate_tour_M(self, tour):
""" Use Cythonized version to evaluate the score of a current tour
"""
from .chic import score_evaluate_M
return score_evaluate_M(tour, self.active_sizes, self.M)
def evaluate_tour_P(self, tour):
""" Use Cythonized version to evaluate the score of a current tour,
with better precision on the distance of the contigs.
"""
from .chic import score_evaluate_P
return score_evaluate_P(tour, self.active_sizes, self.P)
def evaluate_tour_Q(self, tour):
""" Use Cythonized version to evaluate the score of a current tour,
taking orientation into consideration. This may be the most accurate
evaluation under the right condition.
"""
from .chic import score_evaluate_Q
return score_evaluate_Q(tour, self.active_sizes, self.Q)
def flip_log(self, method, score, score_flipped, tag):
logging.debug("{}: {} => {} {}".format(method, score, score_flipped, tag))
def flip_all(self, tour):
""" Initialize the orientations based on pairwise O matrix.
"""
if self.signs is None: # First run
score = 0
else:
old_signs = self.signs[: self.N]
(score,) = self.evaluate_tour_Q(tour)
# Remember we cannot have ambiguous orientation code (0 or '?') here
self.signs = get_signs(self.O, validate=False, ambiguous=False)
(score_flipped,) = self.evaluate_tour_Q(tour)
if score_flipped >= score:
tag = ACCEPT
else:
self.signs = old_signs[:]
tag = REJECT
self.flip_log("FLIPALL", score, score_flipped, tag)
return tag
def flip_whole(self, tour):
""" Test flipping all contigs at the same time to see if score improves.
"""
(score,) = self.evaluate_tour_Q(tour)
self.signs = -self.signs
(score_flipped,) = self.evaluate_tour_Q(tour)
if score_flipped > score:
tag = ACCEPT
else:
self.signs = -self.signs
tag = REJECT
self.flip_log("FLIPWHOLE", score, score_flipped, tag)
return tag
def flip_one(self, tour):
""" Test flipping every single contig sequentially to see if score
improves.
"""
n_accepts = n_rejects = 0
any_tag_ACCEPT = False
for i, t in enumerate(tour):
if i == 0:
(score,) = self.evaluate_tour_Q(tour)
self.signs[t] = -self.signs[t]
(score_flipped,) = self.evaluate_tour_Q(tour)
if score_flipped > score:
n_accepts += 1
tag = ACCEPT
else:
self.signs[t] = -self.signs[t]
n_rejects += 1
tag = REJECT
self.flip_log(
"FLIPONE ({}/{})".format(i + 1, len(self.signs)),
score,
score_flipped,
tag,
)
if tag == ACCEPT:
any_tag_ACCEPT = True
score = score_flipped
logging.debug("FLIPONE: N_accepts={} N_rejects={}".format(n_accepts, n_rejects))
return ACCEPT if any_tag_ACCEPT else REJECT
def prune_tour(self, tour, cpus):
""" Test deleting each contig and check the delta_score; tour here must
be an array of ints.
"""
while True:
(tour_score,) = self.evaluate_tour_M(tour)
logging.debug("Starting score: {}".format(tour_score))
active_sizes = self.active_sizes
M = self.M
args = []
for i, t in enumerate(tour):
stour = tour[:i] + tour[i + 1 :]
args.append((t, stour, tour_score, active_sizes, M))
# Parallel run
p = Pool(processes=cpus)
results = list(p.imap(prune_tour_worker, args))
assert len(tour) == len(
results
), "Array size mismatch, tour({}) != results({})".format(
len(tour), len(results)
)
# Identify outliers
active_contigs = self.active_contigs
idx, log10deltas = zip(*results)
lb, ub = outlier_cutoff(log10deltas)
logging.debug("Log10(delta_score) ~ [{}, {}]".format(lb, ub))
remove = set(active_contigs[x] for (x, d) in results if d < lb)
self.active -= remove
self.report_active()
tig_to_idx = self.tig_to_idx
tour = [active_contigs[x] for x in tour]
tour = array.array("i", [tig_to_idx[x] for x in tour if x not in remove])
if not remove:
break
self.tour = tour
self.flip_all(tour)
return tour
@property
def active_contigs(self):
return list(self.active)
@property
def active_sizes(self):
return np.array([self.tig_to_size[x] for x in self.active])
@property
def N(self):
return len(self.active)
@property
def oo(self):
return range(self.N)
@property
def tig_to_idx(self):
return dict((x, i) for (i, x) in enumerate(self.active))
@property
def M(self):
"""
Contact frequency matrix. Each cell contains how many inter-contig
links between i-th and j-th contigs.
"""
N = self.N
tig_to_idx = self.tig_to_idx
M = np.zeros((N, N), dtype=int)
for (at, bt), links in self.contacts.items():
if not (at in tig_to_idx and bt in tig_to_idx):
continue
ai = tig_to_idx[at]
bi = tig_to_idx[bt]
M[ai, bi] = M[bi, ai] = links
return M
@property
def O(self):
"""
Pairwise strandedness matrix. Each cell contains whether i-th and j-th
contig are the same orientation +1, or opposite orientation -1.
"""
N = self.N
tig_to_idx = self.tig_to_idx
O = np.zeros((N, N), dtype=int)
for (at, bt), (strandedness, md, mh) in self.orientations.items():
if not (at in tig_to_idx and bt in tig_to_idx):
continue
ai = tig_to_idx[at]
bi = tig_to_idx[bt]
score = strandedness * md
O[ai, bi] = O[bi, ai] = score
return O
@property
def P(self):
"""
Contact frequency matrix with better precision on distance between
contigs. In the matrix M, the distance is assumed to be the distance
between mid-points of two contigs. In matrix Q, however, we compute
harmonic mean of the links for the orientation configuration that is
shortest. This offers better precision for the distance between big
contigs.
"""
N = self.N
tig_to_idx = self.tig_to_idx
P = np.zeros((N, N, 2), dtype=int)
for (at, bt), (strandedness, md, mh) in self.orientations.items():
if not (at in tig_to_idx and bt in tig_to_idx):
continue
ai = tig_to_idx[at]
bi = tig_to_idx[bt]
P[ai, bi, 0] = P[bi, ai, 0] = md
P[ai, bi, 1] = P[bi, ai, 1] = mh
return P
@property
def Q(self):
"""
Contact frequency matrix when contigs are already oriented. This is s a
similar matrix as M, but rather than having the number of links in the
cell, it points to an array that has the actual distances.
"""
N = self.N
tig_to_idx = self.tig_to_idx
signs = self.signs
Q = np.ones((N, N, BB), dtype=int) * -1 # Use -1 as the sentinel
for (at, bt), k in self.contacts_oriented.items():
if not (at in tig_to_idx and bt in tig_to_idx):
continue
ai = tig_to_idx[at]
bi = tig_to_idx[bt]
ao = signs[ai]
bo = signs[bi]
Q[ai, bi] = k[(ao, bo)]
return Q
def hmean_int(a, a_min=5778, a_max=1149851):
""" Harmonic mean of an array, returns the closest int
"""
from scipy.stats import hmean
return int(round(hmean(np.clip(a, a_min, a_max))))
def golden_array(a, phi=1.61803398875, lb=LB, ub=UB):
""" Given list of ints, we aggregate similar values so that it becomes an
array of multiples of phi, where phi is the golden ratio.
phi ^ 14 = 843
phi ^ 33 = 7881196
So the array of counts go between 843 to 788196. One triva is that the
exponents of phi gets closer to integers as N grows. See interesting
discussion here:
<https://www.johndcook.com/blog/2017/03/22/golden-powers-are-nearly-integers/>
"""
counts = np.zeros(BB, dtype=int)
for x in a:
c = int(round(math.log(x, phi)))
if c < lb:
c = lb
if c > ub:
c = ub
counts[c - lb] += 1
return counts
def prune_tour_worker(arg):
""" Worker thread for CLMFile.prune_tour()
"""
from .chic import score_evaluate_M
t, stour, tour_score, active_sizes, M = arg
(stour_score,) = score_evaluate_M(stour, active_sizes, M)
delta_score = tour_score - stour_score
log10d = np.log10(delta_score) if delta_score > 1e-9 else -9
return t, log10d
def main():
actions = (
# LACHESIS output processing
("agp", "generate AGP file based on LACHESIS output"),
("score", "score the current LACHESIS CLM"),
# Simulation
("simulate", "simulate CLM data"),
# Scaffolding
("optimize", "optimize the contig order and orientation"),
("density", "estimate link density of contigs"),
# Plotting
("movieframe", "plot heatmap and synteny for a particular tour"),
("movie", "plot heatmap optimization history in a tourfile"),
# Reference-based analytics
("bam2mat", "convert bam file to .npy format used in plotting"),
("mergemat", "combine counts from multiple .npy data files"),
("heatmap", "plot heatmap based on .npy file"),
("dist", "plot distance distribution based on .dist.npy file"),
)
p = ActionDispatcher(actions)
p.dispatch(globals())
def fit_power_law(xs, ys):
""" Fit power law distribution.
See reference:
http://mathworld.wolfram.com/LeastSquaresFittingPowerLaw.html
Assumes the form Y = A * X^B, returns
Args:
xs ([int]): X vector
ys ([float64]): Y vector
Returns:
(A, B), the coefficients
"""
import math
sum_logXlogY, sum_logXlogX, sum_logX, sum_logY = 0, 0, 0, 0
N = len(xs)
for i in range(N):
if not xs[i] or not ys[i]:
continue
logXs, logYs = math.log(xs[i]), math.log(ys[i])
sum_logXlogY += logXs * logYs
sum_logXlogX += logXs * logXs
sum_logX += logXs
sum_logY += logYs
B = (N * sum_logXlogY - sum_logX * sum_logY) / (
N * sum_logXlogX - sum_logX * sum_logX
)
A = math.exp((sum_logY - B * sum_logX) / N)
logging.debug("Power law Y = {:.1f} * X ^ {:.4f}".format(A, B))
label = "$Y={:.1f} \\times X^{{ {:.4f} }}$".format(A, B)
return A, B, label
def dist(args):
"""
%prog dist input.dist.npy genome.json
Plot histogram based on .dist.npy data file. The .npy file stores an array
with link counts per dist bin, with the bin starts stored in the genome.json.
"""
import seaborn as sns
import pandas as pd
from jcvi.graphics.base import human_base_formatter, markup
p = OptionParser(dist.__doc__)
p.add_option("--title", help="Title of the histogram")
p.add_option("--xmin", default=300, help="Minimum distance")
p.add_option("--xmax", default=6000000, help="Maximum distance")
opts, args, iopts = p.set_image_options(args, figsize="6x6")
if len(args) != 2:
sys.exit(not p.print_help())
npyfile, jsonfile = args
pf = npyfile.rsplit(".", 1)[0]
header = json.loads(open(jsonfile).read())
distbin_starts = | np.array(header["distbinstarts"], dtype="float64") | numpy.array |
import numpy as np
import minkf as kf
def test_filter_and_smoother():
# case 1: 1d-signal, constant matrices
y = np.ones(3)
x0 = np.array([0.0])
Cest0 = 1 * np.array([[1.0]])
M = np.array([[1.0]])
K = np.array([[1.0]])
Q = np.array([[1.0]])
R = np.array([[1.0]])
res = kf.run_filter(y, x0, Cest0, M, K, Q, R, likelihood=True)
exp_x = [np.array([0.66666]), | np.array([0.875]) | numpy.array |
# 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]) | numpy.array |
# ===========================================================================
# This module is created based on the code from 2 libraries: Lasagne and keras
# Original work Copyright (c) 2014-2015 keras contributors
# Original work Copyright (c) 2014-2015 Lasagne contributors
# Modified work Copyright 2016-2017 TrungNT
# ===========================================================================
from __future__ import division, absolute_import, print_function
import numpy as np
import scipy as sp
from ..config import floatX
# ===========================================================================
# RandomStates
# ===========================================================================
_MAGIC_SEED = 12082518
_SEED_GENERATOR = np.random.RandomState(_MAGIC_SEED)
def set_magic_seed(seed):
global _MAGIC_SEED, _SEED_GENERATOR
_MAGIC_SEED = seed
_SEED_GENERATOR = np.random.RandomState(_MAGIC_SEED)
def get_magic_seed():
return _MAGIC_SEED
def get_random_magic_seed():
return _SEED_GENERATOR.randint(10e6)
def get_random_generator():
return _SEED_GENERATOR
# ===========================================================================
# Main
# ===========================================================================
def is_ndarray(x):
return isinstance(x, np.ndarray)
def np_masked_output(X, X_mask):
'''
Example
-------
X: [[1,2,3,0,0],
[4,5,0,0,0]]
X_mask: [[1,2,3,0,0],
[4,5,0,0,0]]
return: [[1,2,3],[4,5]]
'''
res = []
for x, mask in zip(X, X_mask):
x = x[np.nonzero(mask)]
res.append(x.tolist())
return res
def np_one_hot(y, n_classes=None):
'''Convert class vector (integers from 0 to nb_classes)
to binary class matrix, for use with categorical_crossentropy
'''
y = np.asarray(y, dtype='int32')
if not n_classes:
n_classes = np.max(y) + 1
Y = np.zeros((len(y), n_classes))
for i in range(len(y)):
Y[i, y[i]] = 1.
return Y
def np_split_chunks(a, maxlen, overlap):
'''
Example
-------
>>> print(split_chunks(np.array([1, 2, 3, 4, 5, 6, 7, 8]), 5, 1))
>>> [[1, 2, 3, 4, 5],
[4, 5, 6, 7, 8]]
'''
chunks = []
nchunks = int((max(a.shape) - maxlen) / (maxlen - overlap)) + 1
for i in xrange(nchunks):
start = i * (maxlen - overlap)
chunks.append(a[start: start + maxlen])
# ====== Some spare frames at the end ====== #
wasted = max(a.shape) - start - maxlen
if wasted >= (maxlen - overlap) / 2:
chunks.append(a[-maxlen:])
return chunks
def np_ordered_set(seq):
seen = {}
result = []
for marker in seq:
if marker in seen: continue
seen[marker] = 1
result.append(marker)
return np.asarray(result)
def np_shrink_labels(labels, maxdist=1):
'''
Example
-------
>>> print(shrink_labels(np.array([0, 0, 1, 0, 1, 1, 0, 0, 4, 5, 4, 6, 6, 0, 0]), 1))
>>> [0, 1, 0, 1, 0, 4, 5, 4, 6, 0]
>>> print(shrink_labels(np.array([0, 0, 1, 0, 1, 1, 0, 0, 4, 5, 4, 6, 6, 0, 0]), 2))
>>> [0, 1, 0, 4, 6, 0]
Notes
-----
Different from ordered_set, the resulted array still contain duplicate
if they a far away each other.
'''
maxdist = max(1, maxdist)
out = []
l = len(labels)
i = 0
while i < l:
out.append(labels[i])
last_val = labels[i]
dist = min(maxdist, l - i - 1)
j = 1
while (i + j < l and labels[i + j] == last_val) or (j < dist):
j += 1
i += j
return out
# ===========================================================================
# Special random algorithm for weights initialization
# ===========================================================================
def np_normal(shape, mean=0., std=1.):
return np.cast[floatX()](
get_random_generator().normal(mean, std, size=shape))
def np_uniform(shape, range=0.05):
if isinstance(range, (int, float, long)):
range = (-abs(range), abs(range))
return np.cast[floatX()](
get_random_generator().uniform(low=range[0], high=range[1], size=shape))
def np_constant(shape, val=0.):
return np.cast[floatX()](np.zeros(shape) + val)
def np_symmetric_uniform(shape, range=0.01, std=None, mean=0.0):
if std is not None:
a = mean - np.sqrt(3) * std
b = mean + | np.sqrt(3) | numpy.sqrt |
import numpy as np
from numpy import testing
import pytest
from unittest import TestCase
import pickle
from .basis import Basis
from .grid import Grid
def test_init_0():
x = np.linspace(0, 1, 10, endpoint=False)
y = np.linspace(0, 1, 20, endpoint=False)
z = np.linspace(0, 1, 30, endpoint=False)
xx, yy, zz = np.meshgrid(x, y, z, indexing='ij')
data = xx * 2 + yy * 2 + zz * 2
c = Grid(
Basis.orthorhombic((1, 1, 1)),
(x, y, z),
data,
)
assert len(c.coordinates) == 3
testing.assert_equal(c.coordinates[0], x)
| testing.assert_equal(c.coordinates[1], y) | numpy.testing.assert_equal |
# -*- coding: utf-8 -*-
########## ------------------------------- IMPORTS ------------------------ ##########
import os
import numpy as np
import pandas as pd
import seaborn as sns
from matplotlib import pyplot as plt
import PyQt5
from tidy_to_pzfx import tidy_to_grouped
# mpl.use('TkAgg')
########## ---------------------------------------------------------------- ##########
class GridGraph:
def __init__(self ,path, filename, data, x='freq',y=None):
"""
Creates an object that stores tidy data from .csv that can create a dynamic facet plot.
First column must be individual index.
Last column will be the values to graph (y-axis) unless specified with y argument.
Middle columns can contain any number of categories.
Parameters
----------
path : str, Full path of the directory containing the data to be graphed.
filename : str, name of the .csv file to export.
data: dataframe of tidy data to graph
x: col name for x axis, defaults to 'freq'
y: col name for y axis, defaults to the last column
Returns
-------
None.
"""
self.kind='box'
self.first_time=True
self.g=None
#pass inputs to object
self.path=path
self.filename=filename
self.data = data
#get the categories from the columns
self.param_list=list(self.data.columns)
# Y defaults to the last column is the value to graph
if y in self.data.columns:
self.graph_value = y
else:
self.graph_value = self.data.columns[-1]
self.param_list.remove(self.graph_value)
if x in self.param_list:
self.x=x
else:
raise Exception('"{}" not found in data!'.format(x))
PyQt5.QtCore.qInstallMessageHandler(self.handler)#supress the error message
def on_pick(self, event):
"""
Callback for clicking on graphs. Export data if title is clicked,
and changes the category if graph parameter is clicked
Parameters
----------
event : matplotlib event object.
Returns
-------
None.
"""
pivot_params=self.param_list.copy()
var1=''
var2=''
# if clicked on a graphing parameter
if ":" in event.artist.get_text():
if 'X:' in event.artist.get_text(): return
switched=event.artist.get_text().split(":")[1][1:]
self.param_list.remove(switched)# put the clicked on at the end
self.param_list.append(switched)
exec(self.type)
return
# if clicked on a graph title
elif '|' in event.artist.get_text():
# parse the string for categories and variables
str1,str2=event.artist.axes.get_title().split(r" | ")
cat1,var1=str1.split(" = ")
cat2,var2=str2.split(" = ")
# create index by filtering for both variables
index1=self.data[cat1]==var1
index2=self.data[cat2]==var2
export_index=index1&index2
# update the list of cats to pivot back to
pivot_params.remove(cat1)
pivot_params.remove(cat2)
elif " = " in event.artist.get_text():
cat1,var1=event.artist.axes.get_title().split(" = ")
export_index=self.data[cat1]==var1
pivot_params.remove(cat1)
else:
export_index= | np.ones(self.data.shape[0]) | numpy.ones |
import torch
import torch.utils.data
import torch.nn as nn
from torch import optim
from torch.nn import functional as F
import numpy as np
import pandas as pd
import os
import time
import random
import importlib
from shutil import copyfile
from functools import partial
import argparse
from se3cnn.util import *
from cnns4qspr.util.pred_blocks import VAE
from se3cnn.util.format_data import CathData
def vae_loss(vae_in, vae_out, mu, logvar):
BCE = F.binary_cross_entropy(vae_out, vae_in.view(-1, 256), reduction='mean')
KLD = -0.5 * torch.sum(1 + logvar - mu.pow(2) - logvar.exp())
return abs(BCE) + abs(KLD)
def predictor_loss(labels, predictions):
PCE = F.cross_entropy(predictions, labels, reduction='mean')
return PCE
def train_loop(model, loader, optimizer, epoch):
"""Main training loop
:param model: Model to be trained
:param train_loader: DataLoader object for training set
:param optimizer: Optimizer object
:param epoch: Current epoch index
"""
model.train()
total_losses = []
vae_losses = []
predictor_losses = []
training_accs = []
latent_space = []
training_labels = []
for batch_idx, data in enumerate(loader):
if use_gpu:
data = data.cuda()
input = data[:,:-1]
label = data[:,-1]
vae_in = torch.autograd.Variable(input)
labels = torch.autograd.Variable(label).long()
# forward and backward propagation
vae_out, mu, logvar, predictions = model(vae_in)
z = model.sample_latent_space(vae_in)
loss_vae = vae_loss(vae_in, vae_out, mu, logvar)
loss_predictor = predictor_loss(labels, predictions)
loss = loss_vae + loss_predictor
loss.backward()
optimizer.step()
optimizer.zero_grad()
_, argmax = torch.max(predictions, 1)
acc = (argmax.squeeze() == labels).float().mean()
total_losses.append(loss.item())
vae_losses.append(loss_vae.item())
predictor_losses.append(loss_predictor.item())
training_accs.append(acc.data.cpu().numpy())
latent_space.append(mu.data.cpu().numpy())
training_labels.append(labels.data.cpu().numpy())
avg_vae_loss = np.mean(vae_losses)
avg_pred_loss = np.mean(predictor_losses)
avg_acc = | np.mean(training_accs) | numpy.mean |
import pytest
import numpy as np
from scipy.linalg import toeplitz
from struntho.utils._testing import assert_allclose
from struntho.inference.maxmin_spmp_multiclass import maxmin_multiclass_cvxopt, maxmin_spmp_multiclass_p
from struntho.inference._maxmin_spmp_multiclass import multiclass_oracle_c
def create_losses(n_states):
Losses = []
# 0-1 loss
loss = np.ones((n_states, n_states))
np.fill_diagonal(loss, 0.0)
Losses.append(loss)
# ordinal loss
Losses.append(toeplitz(np.arange(n_states)))
# random loss
loss = np.random.random_sample((n_states, n_states))
np.fill_diagonal(loss, 0.0)
Losses.append(loss)
return Losses
def test_multiclass_oracle_p():
# N_states, Precisions = [2, 5, 10], [1, 2, 3]
N_states, Precisions = [5], [1, 2]
for n_states in N_states:
Losses = create_losses(n_states)
for Loss in Losses:
scores = np.random.random_sample((n_states,))
# run cvxopt
mu_cx, en_cx, _ , _ = maxmin_multiclass_cvxopt(scores, Loss)
L = np.max(Loss) * np.log(n_states)
eta = np.log(n_states) / (2 * L)
# initialize variables
nu = np.ones(n_states) / n_states
p = np.ones(n_states) / n_states
Eps = [1 / (10 ** precision) for precision in Precisions]
Logs = [int(4 * L / eps) for eps in Eps]
max_iter = Logs[-1]
mu_p, q_avg, _, _, _, En_p = maxmin_spmp_multiclass_p(nu, p, scores,
Loss, max_iter, eta, Logs=Logs)
for i, en_p in enumerate(En_p):
assert_allclose(en_p, en_cx, rtol=Precisions[i])
def test_multiclass_oracle_c():
n_states = 10
Losses = create_losses(n_states)
for Loss in Losses:
Loss = np.random.random_sample((n_states, n_states))
scores = np.random.random_sample((n_states,))
L = np.max(Loss) * | np.log(n_states) | numpy.log |
import cv2
import numpy as np
import pandas as pd
import re
def Header_Boundary(img,scaling_factor):
crop_img=img[:1200,:6800,:].copy()
blur_cr_img=cv2.blur(crop_img,(7,7))
crop_img_resize=cv2.resize(blur_cr_img, None, fx=scaling_factor, fy=scaling_factor, interpolation=cv2.INTER_AREA)
crop_img_resize_n=cv2.fastNlMeansDenoisingColored(crop_img_resize,None,10,10,7,21)
crop_img_resize_n_gray=cv2.cvtColor(crop_img_resize_n,cv2.COLOR_BGR2GRAY)
th3 = cv2.adaptiveThreshold(crop_img_resize_n_gray,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY,37,1)
max_start=int(np.argmax(np.sum(th3,axis=1))/scaling_factor)
return max_start
def rotate_check_column_border(img,th3,angle,scaling_factor,imgshape_f):
th4=rotate(th3,angle,value_replace=0)
th_sum00=np.sum(th4,axis=0)
empty_spc_clm=np.where(th_sum00<(np.min(th_sum00)+100))[0]
empty_spc_clm_dif=np.ediff1d(empty_spc_clm)
Column_boundries=(empty_spc_clm[np.where(empty_spc_clm_dif>np.mean(empty_spc_clm_dif))[0]+1]/(scaling_factor/2)).astype(int)
Column_boundries=np.delete(Column_boundries,np.where(Column_boundries<(img.shape[1]/5))[0])
Column_boundries=np.append(Column_boundries,[0,img.shape[1]])
Column_boundries=np.unique(Column_boundries)
for i in range(len(Column_boundries)):
closer=np.where(np.ediff1d(Column_boundries)<(img.shape[1])/5)[0]
if len(closer)>0:
Column_boundries=np.delete(Column_boundries,closer[-1])
else:
break
#[2968 7864 8016]
return Column_boundries[1:]
def rotate(image, angle, center = None, scale = 1.0,value_replace=0):
(h, w) = image.shape[:2]
if center is None:
center = (w / 2, h / 2)
# Perform the rotation
M = cv2.getRotationMatrix2D(center, angle, scale)
rotated = cv2.warpAffine(image, M, (w, h),borderValue=value_replace)
return rotated
def method5_column(img,th3,scaling_factor,angle_rec,morph_op=False):
for ang in angle_rec:
if morph_op:
th4=rotate(th3.copy(),ang)
else:
kernel=np.ones((100,9),np.uint8)
th4=cv2.morphologyEx(rotate(th3.copy(),ang), cv2.MORPH_CLOSE, kernel)
# cv2.imshow('morphologyEx',th4)
# cv2.waitKey(0)
th4=cv2.bitwise_not(th4)
# cv2.imshow('bitwise_not',th4)
# cv2.waitKey(0)
th4[th4==255]=1
# print([np.sum(th4,axis=0)])
# print(np.max(np.sum(th4,axis=0)),np.mean(np.sum(th4,axis=0)))
split_candidates=np.where(np.sum(th4,axis=0)>=(np.max(np.sum(th4,axis=0))-np.mean(np.sum(th4,axis=0))))[0]
split_candidates=np.unique(np.append(split_candidates,[0,th4.shape[1]]))
empty_spc_clm_dif=np.ediff1d(split_candidates)
Column_boundries=(split_candidates[np.where(empty_spc_clm_dif>np.mean(empty_spc_clm_dif))[0]+1]/(scaling_factor/2)).astype(int)
# print('Col0umn_boundries1:',Column_boundries)
Column_boundries=np.append(Column_boundries,[0,img.shape[1]])
Column_boundries=np.unique(Column_boundries)
for i in range(len(Column_boundries)):
closer=np.where(np.ediff1d(Column_boundries)<(img.shape[1])/5)[0]
if len(closer)>0:
Column_boundries=np.delete(Column_boundries,closer[-1])
else:
break
Column_boundries=Column_boundries[1:]
# print('Column_boundries2:',Column_boundries)
if len(Column_boundries)>2:
break
return Column_boundries,ang
def row_split_smaller(th3,image_row_split_ratio,angle,scaling_factor):
th4=rotate(th3.copy(),angle,value_replace=0)
image_row_th=int(th4.shape[0]/image_row_split_ratio)
row_sum_location=np.where(np.sum(th4,axis=1)<2)[0]
row_sum_location=row_sum_location[np.where(np.ediff1d(row_sum_location)==1)[0]]
row_split_pos1=[]
# print('row_sum_location:',row_sum_location)
for i in range(image_row_split_ratio):
split_s=row_sum_location[np.where((row_sum_location-(image_row_th*i))>=0)[0]]
# print('split_s:',split_s)
try:
point_place=split_s[np.where(split_s>row_split_pos1[-1]+int(image_row_th/3))[0][0]]
row_split_pos1.append(point_place)
except:
if len(split_s)>0:
row_split_pos1.append(split_s[0])
row_split_pos1=np.array(row_split_pos1)
row_split_pos1=np.append(row_split_pos1,[0,th4.shape[0]])
row_split_pos1=np.unique(row_split_pos1)
for i in range(len(row_split_pos1)):
closer=np.where(np.ediff1d(row_split_pos1)<(th4.shape[0])/5)[0]
if len(closer)>0:
row_split_pos1=np.delete(row_split_pos1,closer[-1])
else:
break
if row_split_pos1[0]<(th4.shape[0])/5:
row_split_pos1[0]=0
return (row_split_pos1/(scaling_factor)).astype(int)
def angle_out_row(column_img,scaling_factor):
blur_cr_img=cv2.blur(column_img,(13,13))
crop_img_resize=cv2.resize(blur_cr_img, None, fx=scaling_factor, fy=scaling_factor, interpolation=cv2.INTER_AREA)
crop_img_resize_n=cv2.fastNlMeansDenoisingColored(crop_img_resize,None,10,10,7,21)
crop_img_resize_n_gray=cv2.cvtColor(crop_img_resize_n,cv2.COLOR_BGR2GRAY)
th3 = cv2.adaptiveThreshold(crop_img_resize_n_gray,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY_INV,21,7)
Angles_outputs=[]
for angle in [-0.1,0.2,-0.2,0.3,-0.3,0.4,-0.4,0.5,-0.5]:
result=row_split_smaller(th3,int(1/scaling_factor),angle,scaling_factor)
Angles_outputs.append([angle,len(result),result])
Angles_outputs=np.array(Angles_outputs,dtype=object)
set_angle,_,row_split_pos1=Angles_outputs[np.argmax(Angles_outputs[:,1])]
return set_angle,row_split_pos1
def Row_splitter(column_img,scaling_factor,image_row_split_ratio=8):
blur_cr_img=cv2.blur(column_img,(13,13))
crop_img_resize=cv2.resize(blur_cr_img, None, fx=scaling_factor/2, fy=scaling_factor/2, interpolation=cv2.INTER_AREA)
crop_img_resize_n=cv2.fastNlMeansDenoisingColored(crop_img_resize,None,10,10,7,21)
crop_img_resize_n_gray=cv2.cvtColor(crop_img_resize_n,cv2.COLOR_BGR2GRAY)
th3 = cv2.adaptiveThreshold(crop_img_resize_n_gray,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY_INV,21,7)
image_row_th=int(th3.shape[0]/image_row_split_ratio)
row_sum_location=np.where(np.sum(th3,axis=1)<2)[0]
row_sum_location=row_sum_location[np.where(np.ediff1d(row_sum_location)==1)[0]]
# print(row_sum_location)
row_split_pos=[]
for i in range(image_row_split_ratio):
split_s=row_sum_location[np.where((row_sum_location-(image_row_th*i))>=0)[0]]
# print(split_s)
try:
point_place=split_s[np.where(split_s>row_split_pos[-1]+int(image_row_th/3))[0][0]]
# print(split_s,point_place)
row_split_pos.append(point_place)
except:
if len(split_s)>0:
row_split_pos.append(split_s[0])
row_split_pos=np.array(row_split_pos)
row_split_pos=np.append(row_split_pos,[0,th3.shape[0]])
row_split_pos=np.unique(row_split_pos)
for i in range(len(row_split_pos)):
closer=np.where(np.ediff1d(row_split_pos)<(th3.shape[0])/10)[0]
if len(closer)>0:
row_split_pos=np.delete(row_split_pos,closer[-1])
else:
break
row_split_pos=(row_split_pos/(scaling_factor/2)).astype(int)
return np.unique(row_split_pos)
def Column_main_Extracter_sub(img,scaling_factor):
blur_cr_img=cv2.blur(img,(13,13))
crop_img_resize=cv2.resize(blur_cr_img, None, fx=scaling_factor/2, fy=scaling_factor/2, interpolation=cv2.INTER_AREA)
crop_img_resize_n=cv2.fastNlMeansDenoisingColored(crop_img_resize,None,10,10,7,21)
crop_img_resize_n_gray=cv2.cvtColor(crop_img_resize_n,cv2.COLOR_BGR2GRAY)
th3 = cv2.adaptiveThreshold(crop_img_resize_n_gray,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY_INV,21,7)
kernel=np.ones((100,9),np.uint8)
th4=cv2.morphologyEx(th3.copy(), cv2.MORPH_CLOSE, kernel)
th_sum00=np.sum(th4,axis=0)
empty_spc_clm=np.where(th_sum00<(np.min(th_sum00)+100))[0]
empty_spc_clm_dif=np.ediff1d(empty_spc_clm)
Column_boundries=(empty_spc_clm[np.where(empty_spc_clm_dif>np.mean(empty_spc_clm_dif)+5)[0]+1]/(scaling_factor/2)).astype(int)
Column_boundries=np.delete(Column_boundries,np.where(Column_boundries<(img.shape[1]/5))[0])
if len(Column_boundries)<3:
Angles_Records=[]
for angle in [0.1,-0.1,0.2,-0.2,0.3,-0.3,0.4,-0.4,0.5,-0.5,0.6,-0.6,0.7,-0.7,0.8,-0.8]:
Column_boundries=rotate_check_column_border(img,th3.copy(),angle,scaling_factor,img.shape[1])
# print(Column_boundries)
Angles_Records.append([angle,len(Column_boundries)])
if len(Column_boundries)>2:
break
Angles_Records=np.array(Angles_Records)
if len(Column_boundries)>2:
img=rotate(img,angle,value_replace=(255,255,255))
First_Column=img[:,0:Column_boundries[0]+10]
Second_Column=img[:,Column_boundries[0]:Column_boundries[1]+10]
Third_Column=img[:,Column_boundries[1]:]
else:
angle=np.append([0],Angles_Records)
angle_rec=Angles_Records[np.where(Angles_Records[:,1]==np.max(Angles_Records[:,1]))[0]][:,0]
Column_boundries,ang=method5_column(img,th3,scaling_factor,angle_rec)
if len(Column_boundries)>2:
img=rotate(img,ang,value_replace=(255,255,255))
First_Column=img[:,0:Column_boundries[0]+10]
Second_Column=img[:,Column_boundries[0]:Column_boundries[1]+10]
Third_Column=img[:,Column_boundries[1]:]
else:
return None,None,None
else:
First_Column=img[:,0:Column_boundries[0]+10]
Second_Column=img[:,Column_boundries[0]:Column_boundries[1]+10]
Third_Column=img[:,Column_boundries[1]:]
return First_Column,Second_Column,Third_Column
def Column_main_Extracter_sub_second(img,orignal_img,scaling_factor):
blur_cr_img=cv2.blur(orignal_img,(13,13))
crop_img_resize=cv2.resize(blur_cr_img, None, fx=scaling_factor/2, fy=scaling_factor/2, interpolation=cv2.INTER_AREA)
crop_img_resize_n=cv2.fastNlMeansDenoisingColored(crop_img_resize,None,10,10,7,21)
crop_img_resize_n_gray=cv2.cvtColor(crop_img_resize_n,cv2.COLOR_BGR2GRAY)
th3 = cv2.adaptiveThreshold(crop_img_resize_n_gray,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY_INV,21,7)
top=int(th3.shape[1]/40)
bottom=int(th3.shape[1]/40)
left=int(th3.shape[1]/20)
right=int(th3.shape[1]/20)
th4 = cv2.copyMakeBorder(th3,top=top,bottom=bottom,left=left,right=right,borderType=cv2.BORDER_CONSTANT,value=0)
for angle in [0.1,-0.1,0.2,-0.2,0.3,-0.3,0.4,-0.4,0.5,-0.5,0.6,-0.6,0.7,-0.7,0.8,-0.8]:
th5=rotate(th4.copy(), angle)
kernel=np.ones((30,9),np.uint8)
th5=cv2.morphologyEx(th5.copy(), cv2.MORPH_CLOSE, kernel)
th5=cv2.bitwise_not(th5)
th5[th5<255]=0
th5[th5==255]=1
split_candidates=np.where(np.sum(th5,axis=0)>=(np.max(np.sum(th5,axis=0))-(np.mean(np.sum(th5,axis=0))/1.5)))[0]
split_candidates=np.unique(np.append(split_candidates,[0,th5.shape[1]]))
empty_spc_clm_dif=np.ediff1d(split_candidates)
Column_boundries=(split_candidates[np.where(empty_spc_clm_dif>np.mean(empty_spc_clm_dif))[0]+1]/(scaling_factor/2)).astype(int)
Column_boundries= | np.append(Column_boundries,[0,img.shape[1]]) | numpy.append |
# Copyright (c) 2012-2020 Jicamarca Radio Observatory
# All rights reserved.
#
# Distributed under the terms of the BSD 3-clause license.
"""Definition of diferent Data objects for different types of data
Here you will find the diferent data objects for the different types
of data, this data objects must be used as dataIn or dataOut objects in
processing units and operations. Currently the supported data objects are:
Voltage, Spectra, SpectraHeis, Fits, Correlation and Parameters
"""
import copy
import numpy
import datetime
import json
import schainpy.admin
from schainpy.utils import log
from .jroheaderIO import SystemHeader, RadarControllerHeader
from schainpy.model.data import _noise
def getNumpyDtype(dataTypeCode):
if dataTypeCode == 0:
numpyDtype = numpy.dtype([('real', '<i1'), ('imag', '<i1')])
elif dataTypeCode == 1:
numpyDtype = numpy.dtype([('real', '<i2'), ('imag', '<i2')])
elif dataTypeCode == 2:
numpyDtype = numpy.dtype([('real', '<i4'), ('imag', '<i4')])
elif dataTypeCode == 3:
numpyDtype = numpy.dtype([('real', '<i8'), ('imag', '<i8')])
elif dataTypeCode == 4:
numpyDtype = numpy.dtype([('real', '<f4'), ('imag', '<f4')])
elif dataTypeCode == 5:
numpyDtype = numpy.dtype([('real', '<f8'), ('imag', '<f8')])
else:
raise ValueError('dataTypeCode was not defined')
return numpyDtype
def getDataTypeCode(numpyDtype):
if numpyDtype == numpy.dtype([('real', '<i1'), ('imag', '<i1')]):
datatype = 0
elif numpyDtype == numpy.dtype([('real', '<i2'), ('imag', '<i2')]):
datatype = 1
elif numpyDtype == numpy.dtype([('real', '<i4'), ('imag', '<i4')]):
datatype = 2
elif numpyDtype == numpy.dtype([('real', '<i8'), ('imag', '<i8')]):
datatype = 3
elif numpyDtype == numpy.dtype([('real', '<f4'), ('imag', '<f4')]):
datatype = 4
elif numpyDtype == numpy.dtype([('real', '<f8'), ('imag', '<f8')]):
datatype = 5
else:
datatype = None
return datatype
def hildebrand_sekhon(data, navg):
"""
This method is for the objective determination of the noise level in Doppler spectra. This
implementation technique is based on the fact that the standard deviation of the spectral
densities is equal to the mean spectral density for white Gaussian noise
Inputs:
Data : heights
navg : numbers of averages
Return:
mean : noise's level
"""
sortdata = numpy.sort(data, axis=None)
'''
lenOfData = len(sortdata)
nums_min = lenOfData*0.2
if nums_min <= 5:
nums_min = 5
sump = 0.
sumq = 0.
j = 0
cont = 1
while((cont == 1)and(j < lenOfData)):
sump += sortdata[j]
sumq += sortdata[j]**2
if j > nums_min:
rtest = float(j)/(j-1) + 1.0/navg
if ((sumq*j) > (rtest*sump**2)):
j = j - 1
sump = sump - sortdata[j]
sumq = sumq - sortdata[j]**2
cont = 0
j += 1
lnoise = sump / j
'''
return _noise.hildebrand_sekhon(sortdata, navg)
class Beam:
def __init__(self):
self.codeList = []
self.azimuthList = []
self.zenithList = []
class GenericData(object):
flagNoData = True
def copy(self, inputObj=None):
if inputObj == None:
return copy.deepcopy(self)
for key in list(inputObj.__dict__.keys()):
attribute = inputObj.__dict__[key]
# If this attribute is a tuple or list
if type(inputObj.__dict__[key]) in (tuple, list):
self.__dict__[key] = attribute[:]
continue
# If this attribute is another object or instance
if hasattr(attribute, '__dict__'):
self.__dict__[key] = attribute.copy()
continue
self.__dict__[key] = inputObj.__dict__[key]
def deepcopy(self):
return copy.deepcopy(self)
def isEmpty(self):
return self.flagNoData
def isReady(self):
return not self.flagNoData
class JROData(GenericData):
systemHeaderObj = SystemHeader()
radarControllerHeaderObj = RadarControllerHeader()
type = None
datatype = None # dtype but in string
nProfiles = None
heightList = None
channelList = None
flagDiscontinuousBlock = False
useLocalTime = False
utctime = None
timeZone = None
dstFlag = None
errorCount = None
blocksize = None
flagDecodeData = False # asumo q la data no esta decodificada
flagDeflipData = False # asumo q la data no esta sin flip
flagShiftFFT = False
nCohInt = None
windowOfFilter = 1
C = 3e8
frequency = 49.92e6
realtime = False
beacon_heiIndexList = None
last_block = None
blocknow = None
azimuth = None
zenith = None
beam = Beam()
profileIndex = None
error = None
data = None
nmodes = None
metadata_list = ['heightList', 'timeZone', 'type']
def __str__(self):
return '{} - {}'.format(self.type, self.datatime())
def getNoise(self):
raise NotImplementedError
@property
def nChannels(self):
return len(self.channelList)
@property
def channelIndexList(self):
return list(range(self.nChannels))
@property
def nHeights(self):
return len(self.heightList)
def getDeltaH(self):
return self.heightList[1] - self.heightList[0]
@property
def ltctime(self):
if self.useLocalTime:
return self.utctime - self.timeZone * 60
return self.utctime
@property
def datatime(self):
datatimeValue = datetime.datetime.utcfromtimestamp(self.ltctime)
return datatimeValue
def getTimeRange(self):
datatime = []
datatime.append(self.ltctime)
datatime.append(self.ltctime + self.timeInterval + 1)
datatime = numpy.array(datatime)
return datatime
def getFmaxTimeResponse(self):
period = (10**-6) * self.getDeltaH() / (0.15)
PRF = 1. / (period * self.nCohInt)
fmax = PRF
return fmax
def getFmax(self):
PRF = 1. / (self.ippSeconds * self.nCohInt)
fmax = PRF
return fmax
def getVmax(self):
_lambda = self.C / self.frequency
vmax = self.getFmax() * _lambda / 2
return vmax
@property
def ippSeconds(self):
'''
'''
return self.radarControllerHeaderObj.ippSeconds
@ippSeconds.setter
def ippSeconds(self, ippSeconds):
'''
'''
self.radarControllerHeaderObj.ippSeconds = ippSeconds
@property
def code(self):
'''
'''
return self.radarControllerHeaderObj.code
@code.setter
def code(self, code):
'''
'''
self.radarControllerHeaderObj.code = code
@property
def nCode(self):
'''
'''
return self.radarControllerHeaderObj.nCode
@nCode.setter
def nCode(self, ncode):
'''
'''
self.radarControllerHeaderObj.nCode = ncode
@property
def nBaud(self):
'''
'''
return self.radarControllerHeaderObj.nBaud
@nBaud.setter
def nBaud(self, nbaud):
'''
'''
self.radarControllerHeaderObj.nBaud = nbaud
@property
def ipp(self):
'''
'''
return self.radarControllerHeaderObj.ipp
@ipp.setter
def ipp(self, ipp):
'''
'''
self.radarControllerHeaderObj.ipp = ipp
@property
def metadata(self):
'''
'''
return {attr: getattr(self, attr) for attr in self.metadata_list}
class Voltage(JROData):
dataPP_POW = None
dataPP_DOP = None
dataPP_WIDTH = None
dataPP_SNR = None
def __init__(self):
'''
Constructor
'''
self.useLocalTime = True
self.radarControllerHeaderObj = RadarControllerHeader()
self.systemHeaderObj = SystemHeader()
self.type = "Voltage"
self.data = None
self.nProfiles = None
self.heightList = None
self.channelList = None
self.flagNoData = True
self.flagDiscontinuousBlock = False
self.utctime = None
self.timeZone = 0
self.dstFlag = None
self.errorCount = None
self.nCohInt = None
self.blocksize = None
self.flagCohInt = False
self.flagDecodeData = False # asumo q la data no esta decodificada
self.flagDeflipData = False # asumo q la data no esta sin flip
self.flagShiftFFT = False
self.flagDataAsBlock = False # Asumo que la data es leida perfil a perfil
self.profileIndex = 0
self.metadata_list = ['type', 'heightList', 'timeZone', 'nProfiles', 'channelList', 'nCohInt',
'code', 'nCode', 'nBaud', 'ippSeconds', 'ipp']
def getNoisebyHildebrand(self, channel=None):
"""
Determino el nivel de ruido usando el metodo Hildebrand-Sekhon
Return:
noiselevel
"""
if channel != None:
data = self.data[channel]
nChannels = 1
else:
data = self.data
nChannels = self.nChannels
noise = numpy.zeros(nChannels)
power = data * numpy.conjugate(data)
for thisChannel in range(nChannels):
if nChannels == 1:
daux = power[:].real
else:
daux = power[thisChannel, :].real
noise[thisChannel] = hildebrand_sekhon(daux, self.nCohInt)
return noise
def getNoise(self, type=1, channel=None):
if type == 1:
noise = self.getNoisebyHildebrand(channel)
return noise
def getPower(self, channel=None):
if channel != None:
data = self.data[channel]
else:
data = self.data
power = data * numpy.conjugate(data)
powerdB = 10 * numpy.log10(power.real)
powerdB = numpy.squeeze(powerdB)
return powerdB
@property
def timeInterval(self):
return self.ippSeconds * self.nCohInt
noise = property(getNoise, "I'm the 'nHeights' property.")
class Spectra(JROData):
def __init__(self):
'''
Constructor
'''
self.useLocalTime = True
self.radarControllerHeaderObj = RadarControllerHeader()
self.systemHeaderObj = SystemHeader()
self.type = "Spectra"
self.timeZone = 0
self.nProfiles = None
self.heightList = None
self.channelList = None
self.pairsList = None
self.flagNoData = True
self.flagDiscontinuousBlock = False
self.utctime = None
self.nCohInt = None
self.nIncohInt = None
self.blocksize = None
self.nFFTPoints = None
self.wavelength = None
self.flagDecodeData = False # asumo q la data no esta decodificada
self.flagDeflipData = False # asumo q la data no esta sin flip
self.flagShiftFFT = False
self.ippFactor = 1
self.beacon_heiIndexList = []
self.noise_estimation = None
self.metadata_list = ['type', 'heightList', 'timeZone', 'pairsList', 'channelList', 'nCohInt',
'code', 'nCode', 'nBaud', 'ippSeconds', 'ipp','nIncohInt', 'nFFTPoints', 'nProfiles']
def getNoisebyHildebrand(self, xmin_index=None, xmax_index=None, ymin_index=None, ymax_index=None):
"""
Determino el nivel de ruido usando el metodo Hildebrand-Sekhon
Return:
noiselevel
"""
noise = numpy.zeros(self.nChannels)
for channel in range(self.nChannels):
daux = self.data_spc[channel,
xmin_index:xmax_index, ymin_index:ymax_index]
noise[channel] = hildebrand_sekhon(daux, self.nIncohInt)
return noise
def getNoise(self, xmin_index=None, xmax_index=None, ymin_index=None, ymax_index=None):
if self.noise_estimation is not None:
# this was estimated by getNoise Operation defined in jroproc_spectra.py
return self.noise_estimation
else:
noise = self.getNoisebyHildebrand(
xmin_index, xmax_index, ymin_index, ymax_index)
return noise
def getFreqRangeTimeResponse(self, extrapoints=0):
deltafreq = self.getFmaxTimeResponse() / (self.nFFTPoints * self.ippFactor)
freqrange = deltafreq * (numpy.arange(self.nFFTPoints + extrapoints) - self.nFFTPoints / 2.) - deltafreq / 2
return freqrange
def getAcfRange(self, extrapoints=0):
deltafreq = 10. / (self.getFmax() / (self.nFFTPoints * self.ippFactor))
freqrange = deltafreq * (numpy.arange(self.nFFTPoints + extrapoints) -self.nFFTPoints / 2.) - deltafreq / 2
return freqrange
def getFreqRange(self, extrapoints=0):
deltafreq = self.getFmax() / (self.nFFTPoints * self.ippFactor)
freqrange = deltafreq * (numpy.arange(self.nFFTPoints + extrapoints) -self.nFFTPoints / 2.) - deltafreq / 2
return freqrange
def getVelRange(self, extrapoints=0):
deltav = self.getVmax() / (self.nFFTPoints * self.ippFactor)
velrange = deltav * (numpy.arange(self.nFFTPoints + extrapoints) - self.nFFTPoints / 2.)
if self.nmodes:
return velrange/self.nmodes
else:
return velrange
@property
def nPairs(self):
return len(self.pairsList)
@property
def pairsIndexList(self):
return list(range(self.nPairs))
@property
def normFactor(self):
pwcode = 1
if self.flagDecodeData:
pwcode = numpy.sum(self.code[0]**2)
#normFactor = min(self.nFFTPoints,self.nProfiles)*self.nIncohInt*self.nCohInt*pwcode*self.windowOfFilter
normFactor = self.nProfiles * self.nIncohInt * self.nCohInt * pwcode * self.windowOfFilter
return normFactor
@property
def flag_cspc(self):
if self.data_cspc is None:
return True
return False
@property
def flag_dc(self):
if self.data_dc is None:
return True
return False
@property
def timeInterval(self):
timeInterval = self.ippSeconds * self.nCohInt * self.nIncohInt * self.nProfiles * self.ippFactor
if self.nmodes:
return self.nmodes*timeInterval
else:
return timeInterval
def getPower(self):
factor = self.normFactor
z = self.data_spc / factor
z = numpy.where(numpy.isfinite(z), z, numpy.NAN)
avg = numpy.average(z, axis=1)
return 10 * numpy.log10(avg)
def getCoherence(self, pairsList=None, phase=False):
z = []
if pairsList is None:
pairsIndexList = self.pairsIndexList
else:
pairsIndexList = []
for pair in pairsList:
if pair not in self.pairsList:
raise ValueError("Pair %s is not in dataOut.pairsList" % (
pair))
pairsIndexList.append(self.pairsList.index(pair))
for i in range(len(pairsIndexList)):
pair = self.pairsList[pairsIndexList[i]]
ccf = numpy.average(self.data_cspc[pairsIndexList[i], :, :], axis=0)
powa = numpy.average(self.data_spc[pair[0], :, :], axis=0)
powb = numpy.average(self.data_spc[pair[1], :, :], axis=0)
avgcoherenceComplex = ccf / numpy.sqrt(powa * powb)
if phase:
data = numpy.arctan2(avgcoherenceComplex.imag,
avgcoherenceComplex.real) * 180 / numpy.pi
else:
data = numpy.abs(avgcoherenceComplex)
z.append(data)
return numpy.array(z)
def setValue(self, value):
print("This property should not be initialized")
return
noise = property(getNoise, setValue, "I'm the 'nHeights' property.")
class SpectraHeis(Spectra):
def __init__(self):
self.radarControllerHeaderObj = RadarControllerHeader()
self.systemHeaderObj = SystemHeader()
self.type = "SpectraHeis"
self.nProfiles = None
self.heightList = None
self.channelList = None
self.flagNoData = True
self.flagDiscontinuousBlock = False
self.utctime = None
self.blocksize = None
self.profileIndex = 0
self.nCohInt = 1
self.nIncohInt = 1
@property
def normFactor(self):
pwcode = 1
if self.flagDecodeData:
pwcode = numpy.sum(self.code[0]**2)
normFactor = self.nIncohInt * self.nCohInt * pwcode
return normFactor
@property
def timeInterval(self):
return self.ippSeconds * self.nCohInt * self.nIncohInt
class Fits(JROData):
def __init__(self):
self.type = "Fits"
self.nProfiles = None
self.heightList = None
self.channelList = None
self.flagNoData = True
self.utctime = None
self.nCohInt = 1
self.nIncohInt = 1
self.useLocalTime = True
self.profileIndex = 0
self.timeZone = 0
def getTimeRange(self):
datatime = []
datatime.append(self.ltctime)
datatime.append(self.ltctime + self.timeInterval)
datatime = numpy.array(datatime)
return datatime
def getChannelIndexList(self):
return list(range(self.nChannels))
def getNoise(self, type=1):
if type == 1:
noise = self.getNoisebyHildebrand()
if type == 2:
noise = self.getNoisebySort()
if type == 3:
noise = self.getNoisebyWindow()
return noise
@property
def timeInterval(self):
timeInterval = self.ippSeconds * self.nCohInt * self.nIncohInt
return timeInterval
@property
def ippSeconds(self):
'''
'''
return self.ipp_sec
noise = property(getNoise, "I'm the 'nHeights' property.")
class Correlation(JROData):
def __init__(self):
'''
Constructor
'''
self.radarControllerHeaderObj = RadarControllerHeader()
self.systemHeaderObj = SystemHeader()
self.type = "Correlation"
self.data = None
self.dtype = None
self.nProfiles = None
self.heightList = None
self.channelList = None
self.flagNoData = True
self.flagDiscontinuousBlock = False
self.utctime = None
self.timeZone = 0
self.dstFlag = None
self.errorCount = None
self.blocksize = None
self.flagDecodeData = False # asumo q la data no esta decodificada
self.flagDeflipData = False # asumo q la data no esta sin flip
self.pairsList = None
self.nPoints = None
def getPairsList(self):
return self.pairsList
def getNoise(self, mode=2):
indR = numpy.where(self.lagR == 0)[0][0]
indT = numpy.where(self.lagT == 0)[0][0]
jspectra0 = self.data_corr[:, :, indR, :]
jspectra = copy.copy(jspectra0)
num_chan = jspectra.shape[0]
num_hei = jspectra.shape[2]
freq_dc = jspectra.shape[1] / 2
ind_vel = numpy.array([-2, -1, 1, 2]) + freq_dc
if ind_vel[0] < 0:
ind_vel[list(range(0, 1))] = ind_vel[list(
range(0, 1))] + self.num_prof
if mode == 1:
jspectra[:, freq_dc, :] = (
jspectra[:, ind_vel[1], :] + jspectra[:, ind_vel[2], :]) / 2 # CORRECCION
if mode == 2:
vel = numpy.array([-2, -1, 1, 2])
xx = numpy.zeros([4, 4])
for fil in range(4):
xx[fil, :] = vel[fil]**numpy.asarray(list(range(4)))
xx_inv = numpy.linalg.inv(xx)
xx_aux = xx_inv[0, :]
for ich in range(num_chan):
yy = jspectra[ich, ind_vel, :]
jspectra[ich, freq_dc, :] = numpy.dot(xx_aux, yy)
junkid = jspectra[ich, freq_dc, :] <= 0
cjunkid = sum(junkid)
if cjunkid.any():
jspectra[ich, freq_dc, junkid.nonzero()] = (
jspectra[ich, ind_vel[1], junkid] + jspectra[ich, ind_vel[2], junkid]) / 2
noise = jspectra0[:, freq_dc, :] - jspectra[:, freq_dc, :]
return noise
@property
def timeInterval(self):
return self.ippSeconds * self.nCohInt * self.nProfiles
def splitFunctions(self):
pairsList = self.pairsList
ccf_pairs = []
acf_pairs = []
ccf_ind = []
acf_ind = []
for l in range(len(pairsList)):
chan0 = pairsList[l][0]
chan1 = pairsList[l][1]
# Obteniendo pares de Autocorrelacion
if chan0 == chan1:
acf_pairs.append(chan0)
acf_ind.append(l)
else:
ccf_pairs.append(pairsList[l])
ccf_ind.append(l)
data_acf = self.data_cf[acf_ind]
data_ccf = self.data_cf[ccf_ind]
return acf_ind, ccf_ind, acf_pairs, ccf_pairs, data_acf, data_ccf
@property
def normFactor(self):
acf_ind, ccf_ind, acf_pairs, ccf_pairs, data_acf, data_ccf = self.splitFunctions()
acf_pairs = numpy.array(acf_pairs)
normFactor = numpy.zeros((self.nPairs, self.nHeights))
for p in range(self.nPairs):
pair = self.pairsList[p]
ch0 = pair[0]
ch1 = pair[1]
ch0_max = numpy.max(data_acf[acf_pairs == ch0, :, :], axis=1)
ch1_max = numpy.max(data_acf[acf_pairs == ch1, :, :], axis=1)
normFactor[p, :] = numpy.sqrt(ch0_max * ch1_max)
return normFactor
class Parameters(Spectra):
groupList = None # List of Pairs, Groups, etc
data_param = None # Parameters obtained
data_pre = None # Data Pre Parametrization
data_SNR = None # Signal to Noise Ratio
abscissaList = None # Abscissa, can be velocities, lags or time
utctimeInit = None # Initial UTC time
paramInterval = None # Time interval to calculate Parameters in seconds
useLocalTime = True
# Fitting
data_error = None # Error of the estimation
constants = None
library = None
# Output signal
outputInterval = None # Time interval to calculate output signal in seconds
data_output = None # Out signal
nAvg = None
noise_estimation = None
GauSPC = None # Fit gaussian SPC
def __init__(self):
'''
Constructor
'''
self.radarControllerHeaderObj = RadarControllerHeader()
self.systemHeaderObj = SystemHeader()
self.type = "Parameters"
self.timeZone = 0
def getTimeRange1(self, interval):
datatime = []
if self.useLocalTime:
time1 = self.utctimeInit - self.timeZone * 60
else:
time1 = self.utctimeInit
datatime.append(time1)
datatime.append(time1 + interval)
datatime = | numpy.array(datatime) | numpy.array |
# coding=utf-8
# Copyright 2021 The Google Research Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""An iterative dictionary learning procedure."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import time
from absl import logging
import numpy as np
from numpy import linalg as LA
import scipy as sp
from scipy import sparse
import sklearn.decomposition
import sklearn.linear_model
def run_lsh_omp_coder(data, dictionary, sparsity, num_buckets=1):
"""Solve the orthogonal matching pursuit problem with LSH bucketing.
Use sklearn.linear_model.orthogonal_mp to solve the following optimization
program:
argmin ||y - X*gamma||^2,
subject to ||gamma||_0 <= n_{nonzero coefs},
where
y is 'data', size = (n_samples, n_targets),
X is 'dictionary', size = (n_samples, n_features). Columns are assumed
to have unit norm,
gamma: sparse coding, size = (n_features, n_targets).
Args:
data: The matrix y in the above program,
dictionary: The matrix X in the above program,
sparsity: n_{nonzero coefs} in the above program.
num_buckets: number of LSH buckets to use, int.
Returns:
gamma.
"""
logging.info("running LSH based sklearn.linear_model.orthogonal_mp ...")
indices = lsh_knn_map(
np.transpose(np.vstack((data, dictionary))), num_buckets, 1)
logging.info("indices shape is %s", indices.shape)
data_buckets = [[] for i in range(num_buckets)]
data_index = [[] for i in range(num_buckets)]
dict_buckets = [[] for i in range(num_buckets)]
dict_index = [[] for i in range(num_buckets)]
for i in range(data.shape[0]):
data_buckets[indices[i][0]].append(data[i, :])
data_index[indices[i][0]].append(i)
for i in range(dictionary.shape[0]):
dict_buckets[indices[data.shape[0] + i][0]].append(dictionary[i, :])
dict_index[indices[data.shape[0] + i][0]].append(i)
code = sparse.lil_matrix((data.shape[0], dictionary.shape[0]))
for i in range(num_buckets):
start_time = time.time()
if len(data_buckets[i]) > 0: # pylint: disable=g-explicit-length-test
if len(dict_buckets[i]) == 0: # pylint: disable=g-explicit-length-test
logging.error(
"lsh bucketing failed...empty bucket with no dictionary elements")
else:
small_code = sklearn.linear_model.orthogonal_mp(
np.transpose(np.vstack(dict_buckets[i])),
np.transpose(np.vstack(data_buckets[i])),
n_nonzero_coefs=sparsity)
small_code = np.transpose(small_code)
row_idx = np.asarray(data_index[i])
col_idx = np.asarray(dict_index[i])
code[row_idx[:, None], col_idx] = small_code
logging.info("running time of OMP for bucket %d = %d seconds",
i, time.time() - start_time)
return code
def run_omp(data, dictionary, sparsity):
"""Solve the orthogonal matching pursuit problem.
Use sklearn.linear_model.orthogonal_mp to solve the following optimization
program:
argmin ||y - X*gamma||^2,
subject to ||gamma||_0 <= n_{nonzero coefs},
where
y is 'data', size = (n_samples, n_targets),
X is 'dictionary', size = (n_samples, n_features). Columns are assumed
to have unit norm,
gamma: sparse coding, size = (n_features, n_targets).
Args:
data: The matrix y in the above program,
dictionary: The matrix X in the above program,
sparsity: n_{nonzero coefs} in the above program.
Returns:
gamma
"""
logging.info("running sklearn.linear_model.orthogonal_mp ...")
start_time = time.time()
code = sklearn.linear_model.orthogonal_mp(
np.transpose(dictionary), np.transpose(data), n_nonzero_coefs=sparsity)
code = np.transpose(code)
logging.info("running time of omp = %s seconds", time.time() - start_time)
return code
def run_dot_product_coder(data, dictionary, sparsity, k=3, batch_size=1000):
"""Solve the orthogonal matching pursuit problem.
Use sklearn.linear_model.orthogonal_mp to solve the following optimization
program:
argmin ||y - X*gamma||^2,
subject to ||gamma||_0 <= n_{nonzero coefs},
where
y is 'data', size = (n_samples, n_targets),
X is 'dictionary', size = (n_samples, n_features). Columns are assumed
to have unit norm,
gamma: sparse coding, size = (n_features, n_targets).
Args:
data: The matrix y in the above program,
dictionary: The matrix X in the above program,
sparsity: n_{nonzero coefs} in the above program,
k: number of rows to use for generating dictionary,
batch_size: batch size, positive int.
Returns:
gamma
"""
logging.info("running sparse coder sklearn.linear_model.orthogonal_mp ...")
n, _ = data.shape
m, _ = dictionary.shape
index = 0
start_time = time.time()
code = sparse.lil_matrix((n, m))
while index + batch_size < n + 1:
logging.info("processing batch %d", index // batch_size)
small_data = np.transpose(data[index:index + batch_size, :])
prods = np.matmul(dictionary, small_data)
indices = np.argsort(-abs(prods), axis=0)
union_of_indices = indices[0:k, :]
union_of_indices = union_of_indices.flatten()
union_of_indices = np.unique(union_of_indices)
logging.info("number of indices = %d", len(union_of_indices))
small_code = sklearn.linear_model.orthogonal_mp(
np.transpose(dictionary[union_of_indices, :]),
small_data,
n_nonzero_coefs=sparsity,
precompute=False)
start_index = index
end_index = index + batch_size
code[start_index:end_index, union_of_indices] = np.transpose(small_code)
index += batch_size
if index < n:
small_data = np.transpose(data[index:n, :])
prods = np.matmul(dictionary, small_data)
indices = np.argsort(-abs(prods), axis=0)
union_of_indices = indices[0:k, :]
union_of_indices = union_of_indices.flatten()
union_of_indices = np.unique(union_of_indices)
small_code = sklearn.linear_model.orthogonal_mp(
np.transpose(dictionary[union_of_indices, :]),
small_data,
n_nonzero_coefs=sparsity,
precompute=False)
start_index = index
end_index = n
code[start_index:end_index, union_of_indices] = np.transpose(small_code)
print("running time of omp = %s seconds" % (time.time() - start_time))
return code.tocsr()
def run_batch_omp_coder(data, dictionary, sparsity, batch_size=1000):
"""Solve the orthogonal matching pursuit problem in mini-batch fashion.
Use sklearn.linear_model.orthogonal_mp to solve the following optimization
program:
argmin ||y - X*gamma||^2,
subject to ||gamma||_0 <= n_{nonzero coefs},
where
y is 'data', size = (n_samples, n_targets),
X is 'dictionary', size = (n_samples, n_features). Columns are assumed
to have unit norm,
gamma: sparse coding, size = (n_features, n_targets).
Args:
data: The matrix y in the above program,
dictionary: The matrix X in the above program,
sparsity: n_{nonzero coefs} in the above program,
batch_size: batch size, positive int.
Returns:
gamma
"""
print("running sparse coder sklearn.linear_model.orthogonal_mp ...")
[n, _] = data.shape
[m, _] = dictionary.shape
index = 0
start_time = time.time()
code = sparse.lil_matrix((n, m))
while index + batch_size < n + 1: # in range(num_iter):
logging.info("processing batch")
small_code = sklearn.linear_model.orthogonal_mp(
np.transpose(dictionary),
np.transpose(data[index:index + batch_size, :]),
n_nonzero_coefs=sparsity,
precompute=False)
start_index = index
end_index = index + batch_size
code[start_index:end_index, :] = np.transpose(small_code)
index += batch_size
if index < n:
small_code = sklearn.linear_model.orthogonal_mp(
np.transpose(dictionary),
np.transpose(data[index:n, :]),
n_nonzero_coefs=sparsity,
precompute=False)
start_index = index
end_index = n
code[start_index:end_index, :] = np.transpose(small_code)
print("running time of omp = %s seconds" % (time.time() - start_time))
return code.tocsr()
def load_indices_to_csr(indices, dict_size):
"""Load indices into a CSR (compressed sparse row) format indicator matrix.
Example:
indices = np.array([[1], [2], [0]])
dict_size = 4
sparse_matrix = load_indices_to_csr(indices, dict_size)
dense_matrix = sparse_matrix.to_dense()
# dense_matrix = [[0. 1. 0. 0.], [0. 0. 1. 0.], [1. 0. 0. 0.]]
Args:
indices: indices array, a numpy 2d array of ints;
dict_size: size of dictionary, int.
Returns:
sparse_matrix: a sparse indicator matrix in the CSR format with dense shape
(indices.shape[0], dict_size) of floats, with entries at (i, j) equal to
1.0 for i in range(indices.shape[0]), j in indices[i].
"""
rows = np.zeros(indices.shape[0] * indices.shape[1], dtype=int)
cols = np.zeros(indices.shape[0] * indices.shape[1], dtype=int)
vals = np.zeros(indices.shape[0] * indices.shape[1], dtype=float)
cnt = 0
for i in range(indices.shape[0]):
for j in indices[i]:
rows[cnt] = i
cols[cnt] = j
vals[cnt] = 1.0
cnt = cnt + 1
sparse_matrix = sp.sparse.csr_matrix((vals, (rows, cols)),
shape=(indices.shape[0], dict_size))
return sparse_matrix
def run_knn(data, sparsity, row_percentage, eps=0.9):
"""Use kNN to initialize a coding table.
First, we sample a fraction of
'row_percentage' rows of 'data'. Then for each row of 'data', we map it to
the 'sparsity' nearest rows that were sampled.
Args:
data: The original matrix
sparsity: The number rows to which each row of 'data' is mapped
row_percentage: Percent of rows in the sample
eps: approximation tolerance factor, the returned the k-th neighbor is no
further than (1 + epsilon) times the distance to the true k-th
neighbor, needs to be nonnegative, float.
Returns:
The initial sparse coding table.
"""
logging.info("Running kNN ...")
# 'sample_size' should be >= 'sparsity'
sample_size = int(data.shape[0] * row_percentage + 1)
if sample_size < sparsity:
sample_size = sparsity
logging.info("Reset sample_size to %d in run_knn().", sparsity)
logging.info("Sample size = %d", sample_size)
idx = | np.random.randint(data.shape[0], size=sample_size) | numpy.random.randint |
#!/usr/bin/python
from __future__ import division
from __future__ import print_function
import sys
import os
import re
import datetime
import zipfile
import tempfile
import argparse
import math
import warnings
import json
import csv
import numpy as np
import scipy.stats as scp
from lxml import etree as et
def get_rdml_lib_version():
"""Return the version string of the RDML library.
Returns:
The version string of the RDML library.
"""
return "1.0.0"
class NpEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, np.integer):
return int(obj)
elif isinstance(obj, np.floating):
return float(obj)
elif isinstance(obj, np.bool_):
return bool(obj)
elif isinstance(obj, np.ndarray):
return obj.tolist()
else:
return super(NpEncoder, self).default(obj)
class RdmlError(Exception):
"""Basic exception for errors raised by the RDML-Python library"""
def __init__(self, message):
Exception.__init__(self, message)
pass
class secondError(RdmlError):
"""Just to have, not used yet"""
def __init__(self, message):
RdmlError.__init__(self, message)
pass
def _get_first_child(base, tag):
"""Get a child element of the base node with a given tag.
Args:
base: The base node element. (lxml node)
tag: Child elements group tag used to select the elements. (string)
Returns:
The first child lxml node element found or None.
"""
for node in base:
if node.tag.replace("{http://www.rdml.org}", "") == tag:
return node
return None
def _get_first_child_text(base, tag):
"""Get a child element of the base node with a given tag.
Args:
base: The base node element. (lxml node)
tag: Child elements group tag used to select the elements. (string)
Returns:
The text of first child node element found or an empty string.
"""
for node in base:
if node.tag.replace("{http://www.rdml.org}", "") == tag:
return node.text
return ""
def _get_first_child_bool(base, tag, triple=True):
"""Get a child element of the base node with a given tag.
Args:
base: The base node element. (lxml node)
tag: Child elements group tag used to select the elements. (string)
triple: If True, None is returned if not found, if False, False
Returns:
The a bool value of tag or if triple is True None.
"""
for node in base:
if node.tag.replace("{http://www.rdml.org}", "") == tag:
return _string_to_bool(node.text, triple)
if triple is False:
return False
else:
return None
def _get_step_sort_nr(elem):
"""Get the number of the step eg. for sorting.
Args:
elem: The node element. (lxml node)
Returns:
The a int value of the step node nr.
"""
if elem is None:
raise RdmlError('A step element must be provided for sorting.')
ret = _get_first_child_text(elem, "nr")
if ret == "":
raise RdmlError('A step element must have a \"nr\" element for sorting.')
return int(ret)
def _sort_list_int(elem):
"""Get the first element of the array as int. for sorting.
Args:
elem: The 2d list
Returns:
The a int value of the first list element.
"""
return int(elem[0])
def _sort_list_float(elem):
"""Get the first element of the array as float. for sorting.
Args:
elem: The 2d list
Returns:
The a float value of the first list element.
"""
return float(elem[0])
def _sort_list_digital_PCR(elem):
"""Get the first column of the list as int. for sorting.
Args:
elem: The list
Returns:
The a int value of the first list element.
"""
arr = elem.split("\t")
return int(arr[0]), arr[4]
def _string_to_bool(value, triple=True):
"""Translates a string into bool value or None.
Args:
value: The string value to evaluate. (string)
triple: If True, None is returned if not found, if False, False
Returns:
The a bool value of tag or if triple is True None.
"""
if value is None or value == "":
if triple is True:
return None
else:
return False
if type(value) is bool:
return value
if type(value) is int:
if value != 0:
return True
else:
return False
if type(value) is str:
if value.lower() in ['false', '0', 'f', '-', 'n', 'no']:
return False
else:
return True
return
def _value_to_booldic(value):
"""Translates a string, list or dic to a dictionary with true/false.
Args:
value: The string value to evaluate. (string)
Returns:
The a bool value of tag or if triple is True None.
"""
ret = {}
if type(value) is str:
ret[value] = True
if type(value) is list:
for ele in value:
ret[ele] = True
if type(value) is dict:
for key, val in value.items():
ret[key] = _string_to_bool(val, triple=False)
return ret
def _get_first_child_by_pos_or_id(base, tag, by_id, by_pos):
"""Get a child element of the base node with a given tag and position or id.
Args:
base: The base node element. (lxml node)
tag: Child elements group tag used to select the elements. (string)
by_id: The unique id to search for. (string)
by_pos: The position of the element in the list (int)
Returns:
The child node element found or raise error.
"""
if by_id is None and by_pos is None:
raise RdmlError('Either an ' + tag + ' id or a position must be provided.')
if by_id is not None and by_pos is not None:
raise RdmlError('Only an ' + tag + ' id or a position can be provided.')
allChildren = _get_all_children(base, tag)
if by_id is not None:
for node in allChildren:
if node.get('id') == by_id:
return node
raise RdmlError('The ' + tag + ' id: ' + by_id + ' was not found in RDML file.')
if by_pos is not None:
if by_pos < 0 or by_pos > len(allChildren) - 1:
raise RdmlError('The ' + tag + ' position ' + by_pos + ' is out of range.')
return allChildren[by_pos]
def _add_first_child_to_dic(base, dic, opt, tag):
"""Adds the first child element with a given tag to a dictionary.
Args:
base: The base node element. (lxml node)
dic: The dictionary to add the element to (dictionary)
opt: If false and id is not found in base, the element is added with an empty string (Bool)
tag: Child elements group tag used to select the elements. (string)
Returns:
The dictionary with the added element.
"""
for node in base:
if node.tag.replace("{http://www.rdml.org}", "") == tag:
dic[tag] = node.text
return dic
if not opt:
dic[tag] = ""
return dic
def _get_all_children(base, tag):
"""Get a list of all child elements with a given tag.
Args:
base: The base node element. (lxml node)
tag: Child elements group tag used to select the elements. (string)
Returns:
A list with all child node elements found or an empty list.
"""
ret = []
for node in base:
if node.tag.replace("{http://www.rdml.org}", "") == tag:
ret.append(node)
return ret
def _get_all_children_id(base, tag):
"""Get a list of ids of all child elements with a given tag.
Args:
base: The base node element. (lxml node)
tag: Child elements group tag used to select the elements. (string)
Returns:
A list with all child id strings found or an empty list.
"""
ret = []
for node in base:
if node.tag.replace("{http://www.rdml.org}", "") == tag:
ret.append(node.get('id'))
return ret
def _get_number_of_children(base, tag):
"""Count all child elements with a given tag.
Args:
base: The base node element. (lxml node)
tag: Child elements group tag used to select the elements. (string)
Returns:
A int number of the found child elements with the id.
"""
counter = 0
for node in base:
if node.tag.replace("{http://www.rdml.org}", "") == tag:
counter += 1
return counter
def _check_unique_id(base, tag, id):
"""Find all child elements with a given group and check if the id is already used.
Args:
base: The base node element. (lxml node)
tag: Child elements group tag used to select the elements. (string)
id: The unique id to search for. (string)
Returns:
False if the id is already used, True if not.
"""
for node in base:
if node.tag.replace("{http://www.rdml.org}", "") == tag:
if node.get('id') == id:
return False
return True
def _create_new_element(base, tag, id):
"""Create a new element with a given tag and id.
Args:
base: The base node element. (lxml node)
tag: Child elements group tag. (string)
id: The unique id of the new element. (string)
Returns:
False if the id is already used, True if not.
"""
if id is None or id == "":
raise RdmlError('An ' + tag + ' id must be provided.')
if not _check_unique_id(base, tag, id):
raise RdmlError('The ' + tag + ' id "' + id + '" must be unique.')
return et.Element(tag, id=id)
def _add_new_subelement(base, basetag, tag, text, opt):
"""Create a new element with a given tag and id.
Args:
base: The base node element. (lxml node)
basetag: Child elements group tag. (string)
tag: Child elements own tag, to be created. (string)
text: The text content of the new element. (string)
opt: If true, the element is optional (Bool)
Returns:
Nothing, the base lxml element is modified.
"""
if opt is False:
if text is None or text == "":
raise RdmlError('An ' + basetag + ' ' + tag + ' must be provided.')
et.SubElement(base, tag).text = text
else:
if text is not None and text != "":
et.SubElement(base, tag).text = text
def _change_subelement(base, tag, xmlkeys, value, opt, vtype, id_as_element=False):
"""Change the value of the element with a given tag.
Args:
base: The base node element. (lxml node)
tag: Child elements own tag, to be created. (string)
xmlkeys: The list of possible keys in the right order for xml (list strings)
value: The text content of the new element.
opt: If true, the element is optional (Bool)
vtype: If true, the element is optional ("string", "int", "float")
id_as_element: If true, handle tag "id" as element, else as attribute
Returns:
Nothing, the base lxml element is modified.
"""
# Todo validate values with vtype
goodVal = value
if vtype == "bool":
ev = _string_to_bool(value, triple=True)
if ev is None or ev == "":
goodVal = ""
else:
if ev:
goodVal = "true"
else:
goodVal = "false"
if opt is False:
if goodVal is None or goodVal == "":
raise RdmlError('A value for ' + tag + ' must be provided.')
if tag == "id" and id_as_element is False:
if base.get('id') != goodVal:
par = base.getparent()
groupTag = base.tag.replace("{http://www.rdml.org}", "")
if not _check_unique_id(par, groupTag, goodVal):
raise RdmlError('The ' + groupTag + ' id "' + goodVal + '" is not unique.')
base.attrib['id'] = goodVal
return
# Check if the tag already excists
elem = _get_first_child(base, tag)
if elem is not None:
if goodVal is None or goodVal == "":
base.remove(elem)
else:
elem.text = goodVal
else:
if goodVal is not None and goodVal != "":
new_node = et.Element(tag)
new_node.text = goodVal
place = _get_tag_pos(base, tag, xmlkeys, 0)
base.insert(place, new_node)
def _get_or_create_subelement(base, tag, xmlkeys):
"""Get element with a given tag, if not present, create it.
Args:
base: The base node element. (lxml node)
tag: Child elements own tag, to be created. (string)
xmlkeys: The list of possible keys in the right order for xml (list strings)
Returns:
The node element with the tag.
"""
# Check if the tag already excists
if _get_first_child(base, tag) is None:
new_node = et.Element(tag)
place = _get_tag_pos(base, tag, xmlkeys, 0)
base.insert(place, new_node)
return _get_first_child(base, tag)
def _remove_irrelevant_subelement(base, tag):
"""If element with a given tag has no children, remove it.
Args:
base: The base node element. (lxml node)
tag: Child elements own tag, to be created. (string)
Returns:
The node element with the tag.
"""
# Check if the tag already excists
elem = _get_first_child(base, tag)
if elem is None:
return
if len(elem) == 0:
base.remove(elem)
def _move_subelement(base, tag, id, xmlkeys, position):
"""Change the value of the element with a given tag.
Args:
base: The base node element. (lxml node)
tag: The id to search for. (string)
id: The unique id of the new element. (string)
xmlkeys: The list of possible keys in the right order for xml (list strings)
position: the new position of the element (int)
Returns:
Nothing, the base lxml element is modified.
"""
pos = _get_tag_pos(base, tag, xmlkeys, position)
ele = _get_first_child_by_pos_or_id(base, tag, id, None)
base.insert(pos, ele)
def _move_subelement_pos(base, tag, oldpos, xmlkeys, position):
"""Change the value of the element with a given tag.
Args:
base: The base node element. (lxml node)
tag: The id to search for. (string)
oldpos: The unique id of the new element. (string)
xmlkeys: The list of possible keys in the right order for xml (list strings)
position: the new position of the element (int)
Returns:
Nothing, the base lxml element is modified.
"""
pos = _get_tag_pos(base, tag, xmlkeys, position)
ele = _get_first_child_by_pos_or_id(base, tag, None, oldpos)
base.insert(pos, ele)
def _get_tag_pos(base, tag, xmlkeys, pos):
"""Returns a position were to add a subelement with the given tag inc. pos offset.
Args:
base: The base node element. (lxml node)
tag: The id to search for. (string)
xmlkeys: The list of possible keys in the right order for xml (list strings)
pos: The position relative to the tag elements (int)
Returns:
The int number of were to add the element with the tag.
"""
count = _get_number_of_children(base, tag)
offset = pos
if pos is None or pos < 0:
offset = 0
pos = 0
if pos > count:
offset = count
return _get_first_tag_pos(base, tag, xmlkeys) + offset
def _get_first_tag_pos(base, tag, xmlkeys):
"""Returns a position were to add a subelement with the given tag.
Args:
base: The base node element. (lxml node)
tag: The id to search for. (string)
xmlkeys: The list of possible keys in the right order for xml (list strings)
Returns:
The int number of were to add the element with the tag.
"""
listrest = xmlkeys[xmlkeys.index(tag):]
counter = 0
for node in base:
if node.tag.replace("{http://www.rdml.org}", "") in listrest:
return counter
counter += 1
return counter
def _writeFileInRDML(rdmlName, fileName, data):
"""Writes a file in the RDML zip, even if it existed before.
Args:
rdmlName: The name of the RDML zip file
fileName: The name of the file to write into the zip
data: The data string of the file
Returns:
Nothing, modifies the RDML file.
"""
needRewrite = False
if os.path.isfile(rdmlName):
with zipfile.ZipFile(rdmlName, 'r') as RDMLin:
for item in RDMLin.infolist():
if item.filename == fileName:
needRewrite = True
if needRewrite:
tempFolder, tempName = tempfile.mkstemp(dir=os.path.dirname(rdmlName))
os.close(tempFolder)
# copy everything except the filename
with zipfile.ZipFile(rdmlName, 'r') as RDMLin:
with zipfile.ZipFile(tempName, mode='w', compression=zipfile.ZIP_DEFLATED) as RDMLout:
RDMLout.comment = RDMLin.comment
for item in RDMLin.infolist():
if item.filename != fileName:
RDMLout.writestr(item, RDMLin.read(item.filename))
if data != "":
RDMLout.writestr(fileName, data)
os.remove(rdmlName)
os.rename(tempName, rdmlName)
else:
with zipfile.ZipFile(rdmlName, mode='a', compression=zipfile.ZIP_DEFLATED) as RDMLout:
RDMLout.writestr(fileName, data)
def _lrp_linReg(xIn, yUse):
"""A function which calculates the slope or the intercept by linear regression.
Args:
xIn: The numpy array of the cycles
yUse: The numpy array that contains the fluorescence
Returns:
An array with the slope and intercept.
"""
counts = np.ones(yUse.shape)
xUse = xIn.copy()
xUse[np.isnan(yUse)] = 0
counts[np.isnan(yUse)] = 0
cycSqared = xUse * xUse
cycFluor = xUse * yUse
sumCyc = np.nansum(xUse, axis=1)
sumFluor = np.nansum(yUse, axis=1)
sumCycSquared = np.nansum(cycSqared, axis=1)
sumCycFluor = np.nansum(cycFluor, axis=1)
n = np.nansum(counts, axis=1)
ssx = sumCycSquared - (sumCyc * sumCyc) / n
sxy = sumCycFluor - (sumCyc * sumFluor) / n
slope = sxy / ssx
intercept = (sumFluor / n) - slope * (sumCyc / n)
return [slope, intercept]
def _lrp_findStopCyc(fluor, aRow):
"""Find the stop cycle of the log lin phase in fluor.
Args:
fluor: The array with the fluorescence values
aRow: The row to work on
Returns:
An int with the stop cycle.
"""
# Take care of nan values
validTwoLessCyc = 3 # Cycles so +1 to array
while (validTwoLessCyc <= fluor.shape[1] and
(np.isnan(fluor[aRow, validTwoLessCyc - 1]) or
np.isnan(fluor[aRow, validTwoLessCyc - 2]) or
np.isnan(fluor[aRow, validTwoLessCyc - 3]))):
validTwoLessCyc += 1
# First and Second Derivative values calculation
fluorShift = np.roll(fluor[aRow], 1, axis=0) # Shift to right - real position is -0.5
fluorShift[0] = np.nan
firstDerivative = fluor[aRow] - fluorShift
if np.isfinite(firstDerivative).any():
FDMaxCyc = np.nanargmax(firstDerivative, axis=0) + 1 # Cycles so +1 to array
else:
return fluor.shape[1]
firstDerivativeShift = np.roll(firstDerivative, -1, axis=0) # Shift to left
firstDerivativeShift[-1] = np.nan
secondDerivative = firstDerivativeShift - firstDerivative
if FDMaxCyc + 2 <= fluor.shape[1]:
# Only add two cycles if there is an increase without nan
if (not np.isnan(fluor[aRow, FDMaxCyc - 1]) and
not np.isnan(fluor[aRow, FDMaxCyc]) and
not np.isnan(fluor[aRow, FDMaxCyc + 1]) and
fluor[aRow, FDMaxCyc + 1] > fluor[aRow, FDMaxCyc] > fluor[aRow, FDMaxCyc - 1]):
FDMaxCyc += 2
else:
FDMaxCyc = fluor.shape[1]
maxMeanSD = 0.0
stopCyc = fluor.shape[1]
for cycInRange in range(validTwoLessCyc, FDMaxCyc):
with warnings.catch_warnings():
warnings.simplefilter("ignore", category=RuntimeWarning)
tempMeanSD = np.mean(secondDerivative[cycInRange - 2: cycInRange + 1], axis=0)
# The > 0.000000000001 is to avoid float differences to the pascal version
if not np.isnan(tempMeanSD) and (tempMeanSD - maxMeanSD) > 0.000000000001:
maxMeanSD = tempMeanSD
stopCyc = cycInRange
if stopCyc + 2 >= fluor.shape[1]:
stopCyc = fluor.shape[1]
return stopCyc
def _lrp_findStartCyc(fluor, aRow, stopCyc):
"""A function which finds the start cycle of the log lin phase in fluor.
Args:
fluor: The array with the fluorescence values
aRow: The row to work on
stopCyc: The stop cycle
Returns:
An array [int, int] with the start cycle and the fixed start cycle.
"""
startCyc = stopCyc - 1
# startCyc might be NaN, so shift it to the first value
firstNotNaN = 1 # Cycles so +1 to array
while np.isnan(fluor[aRow, firstNotNaN - 1]) and firstNotNaN < startCyc:
firstNotNaN += 1
while startCyc > firstNotNaN and np.isnan(fluor[aRow, startCyc - 1]):
startCyc -= 1
# As long as there are no NaN and new values are increasing
while (startCyc > firstNotNaN and
not np.isnan(fluor[aRow, startCyc - 2]) and
fluor[aRow, startCyc - 2] <= fluor[aRow, startCyc - 1]):
startCyc -= 1
startCycFix = startCyc
if (not np.isnan(fluor[aRow, startCyc]) and
not np.isnan(fluor[aRow, startCyc - 1]) and
not np.isnan(fluor[aRow, stopCyc - 1]) and
not np.isnan(fluor[aRow, stopCyc - 2])):
startStep = np.log10(fluor[aRow, startCyc]) - np.log10(fluor[aRow, startCyc - 1])
stopStep = np.log10(fluor[aRow, stopCyc - 1]) - np.log10(fluor[aRow, stopCyc - 2])
if startStep > 1.1 * stopStep:
startCycFix += 1
return [startCyc, startCycFix]
def _lrp_testSlopes(fluor, aRow, stopCyc, startCycFix):
"""Splits the values and calculates a slope for the upper and the lower half.
Args:
fluor: The array with the fluorescence values
aRow: The row to work on
stopCyc: The stop cycle
startCycFix: The start cycle
Returns:
An array with [slopelow, slopehigh].
"""
# Both start with full range
loopStart = [startCycFix[aRow], stopCyc[aRow]]
loopStop = [startCycFix[aRow], stopCyc[aRow]]
# Now find the center ignoring nan
while True:
loopStart[1] -= 1
loopStop[0] += 1
while (loopStart[1] - loopStop[0]) > 1 and np.isnan(fluor[aRow, loopStart[1] - 1]):
loopStart[1] -= 1
while (loopStart[1] - loopStop[0]) > 1 and np.isnan(fluor[aRow, loopStop[1] - 1]):
loopStop[0] += 1
if (loopStart[1] - loopStop[0]) <= 1:
break
# basic regression per group
ssx = [0, 0]
sxy = [0, 0]
slope = [0, 0]
for j in range(0, 2):
sumx = 0.0
sumy = 0.0
sumx2 = 0.0
sumxy = 0.0
nincl = 0.0
for i in range(loopStart[j], loopStop[j] + 1):
if not np.isnan(fluor[aRow, i - 1]):
sumx += i
sumy += np.log10(fluor[aRow, i - 1])
sumx2 += i * i
sumxy += i * np.log10(fluor[aRow, i - 1])
nincl += 1
ssx[j] = sumx2 - sumx * sumx / nincl
sxy[j] = sumxy - sumx * sumy / nincl
slope[j] = sxy[j] / ssx[j]
return [slope[0], slope[1]]
def _lrp_lastCycMeanMax(fluor, vecSkipSample, vecNoPlateau):
"""A function which calculates the mean of the max fluor in the last ten cycles.
Args:
fluor: The array with the fluorescence values
vecSkipSample: Skip the sample
vecNoPlateau: Sample has no plateau
Returns:
An float with the max mean.
"""
maxFlour = np.nanmax(fluor[:, -11:], axis=1)
maxFlour[vecSkipSample] = np.nan
maxFlour[vecNoPlateau] = np.nan
# Ignore all nan slices, to fix them below
with warnings.catch_warnings():
warnings.simplefilter("ignore", category=RuntimeWarning)
maxMean = np.nanmean(maxFlour)
if np.isnan(maxMean):
maxMean = np.nanmax(maxFlour)
return maxMean
def _lrp_meanPcrEff(tarGroup, vecTarget, pcrEff, vecSkipSample, vecNoPlateau, vecShortLogLin):
"""A function which calculates the mean efficiency of the selected target group excluding bad ones.
Args:
tarGroup: The target number
vecTarget: The vector with the targets numbers
pcrEff: The array with the PCR efficiencies
vecSkipSample: Skip the sample
vecNoPlateau: True if there is no plateau
vecShortLogLin: True indicates a short log lin phase
Returns:
An array with [meanPcrEff, pcrEffVar].
"""
cnt = 0
sumEff = 0.0
sumEff2 = 0.0
for j in range(0, len(pcrEff)):
if tarGroup is None or tarGroup == vecTarget[j]:
if (not (vecSkipSample[j] or vecNoPlateau[j] or vecShortLogLin[j])) and pcrEff[j] > 1.0:
cnt += 1
sumEff += pcrEff[j]
sumEff2 += pcrEff[j] * pcrEff[j]
if cnt > 1:
meanPcrEff = sumEff / cnt
pcrEffVar = (sumEff2 - (sumEff * sumEff) / cnt) / (cnt - 1)
else:
meanPcrEff = 1.0
pcrEffVar = 100
return [meanPcrEff, pcrEffVar]
def _lrp_startStopInWindow(fluor, aRow, upWin, lowWin):
"""Find the start and the stop of the part of the curve which is inside the window.
Args:
fluor: The array with the fluorescence values
aRow: The row to work on
upWin: The upper limit of the window
lowWin: The lower limit of the window
Returns:
The int startWinCyc, stopWinCyc and the bool notInWindow.
"""
startWinCyc = 0
stopWinCyc = 0
# Find the stopCyc and the startCyc cycle of the log lin phase
stopCyc = _lrp_findStopCyc(fluor, aRow)
[startCyc, startCycFix] = _lrp_findStartCyc(fluor, aRow, stopCyc)
if np.isfinite(fluor[aRow, startCycFix - 1:]).any():
stopMaxCyc = np.nanargmax(fluor[aRow, startCycFix - 1:]) + startCycFix
else:
return startCyc, startCyc, True
# If is true if outside the window
if fluor[aRow, startCyc - 1] > upWin or fluor[aRow, stopMaxCyc - 1] < lowWin:
notInWindow = True
if fluor[aRow, startCyc - 1] > upWin:
startWinCyc = startCyc
stopWinCyc = startCyc
if fluor[aRow, stopMaxCyc - 1] < lowWin:
startWinCyc = stopMaxCyc
stopWinCyc = stopMaxCyc
else:
notInWindow = False
# look for stopWinCyc
if fluor[aRow, stopMaxCyc - 1] < upWin:
stopWinCyc = stopMaxCyc
else:
for i in range(stopMaxCyc, startCyc, -1):
if fluor[aRow, i - 1] > upWin > fluor[aRow, i - 2]:
stopWinCyc = i - 1
# look for startWinCyc
if fluor[aRow, startCycFix - 1] > lowWin:
startWinCyc = startCycFix
else:
for i in range(stopMaxCyc, startCyc, -1):
if fluor[aRow, i - 1] > lowWin > fluor[aRow, i - 2]:
startWinCyc = i
return startWinCyc, stopWinCyc, notInWindow
def _lrp_paramInWindow(fluor, aRow, upWin, lowWin):
"""Calculates slope, nNull, PCR efficiency and mean x/y for the curve part in the window.
Args:
fluor: The array with the fluorescence values
aRow: The row to work on
upWin: The upper limit of the window
lowWin: The lower limit of the window
Returns:
The calculated values: indMeanX, indMeanY, pcrEff, nnulls, ninclu, correl.
"""
startWinCyc, stopWinCyc, notInWindow = _lrp_startStopInWindow(fluor, aRow, upWin, lowWin)
sumx = 0.0
sumy = 0.0
sumx2 = 0.0
sumy2 = 0.0
sumxy = 0.0
nincl = 0.0
ssx = 0.0
ssy = 0.0
sxy = 0.0
for i in range(startWinCyc, stopWinCyc + 1):
fluorSamp = fluor[aRow, i - 1]
if not np.isnan(fluorSamp):
logFluorSamp = np.log10(fluorSamp)
sumx += i
sumy += logFluorSamp
sumx2 += i * i
sumy2 += logFluorSamp * logFluorSamp
sumxy += i * logFluorSamp
nincl += 1
if nincl > 1:
ssx = sumx2 - sumx * sumx / nincl
ssy = sumy2 - sumy * sumy / nincl
sxy = sumxy - sumx * sumy / nincl
if ssx > 0.0 and ssy > 0.0 and nincl > 0.0:
cslope = sxy / ssx
cinterc = sumy / nincl - cslope * sumx / nincl
correl = sxy / np.sqrt(ssx * ssy)
indMeanX = sumx / nincl
indMeanY = sumy / nincl
pcrEff = np.power(10, cslope)
nnulls = np.power(10, cinterc)
else:
correl = np.nan
indMeanX = np.nan
indMeanY = np.nan
pcrEff = np.nan
nnulls = np.nan
if notInWindow:
ninclu = 0
else:
ninclu = stopWinCyc - startWinCyc + 1
return indMeanX, indMeanY, pcrEff, nnulls, ninclu, correl
def _lrp_allParamInWindow(fluor, tarGroup, vecTarget, indMeanX, indMeanY, pcrEff, nnulls, ninclu, correl, upWin, lowWin, vecNoAmplification, vecBaselineError):
"""A function which calculates the mean of the max fluor in the last ten cycles.
Args:
fluor: The array with the fluorescence values
tarGroup: The target number
vecTarget: The vector with the targets numbers
indMeanX: The vector with the x mean position
indMeanY: The vector with the y mean position
pcrEff: The array with the PCR efficiencies
nnulls: The array with the calculated nnulls
ninclu: The array with the calculated ninclu
correl: The array with the calculated correl
upWin: The upper limit of the window
lowWin: The lower limit of the window
vecNoAmplification: True if there is a amplification error
vecBaselineError: True if there is a baseline error
Returns:
An array with [indMeanX, indMeanY, pcrEff, nnulls, ninclu, correl].
"""
for row in range(0, fluor.shape[0]):
if tarGroup is None or tarGroup == vecTarget[row]:
if not (vecNoAmplification[row] or vecBaselineError[row]):
if tarGroup is None:
indMeanX[row], indMeanY[row], pcrEff[row], nnulls[row], ninclu[row], correl[row] = _lrp_paramInWindow(fluor, row, upWin[0], lowWin[0])
else:
indMeanX[row], indMeanY[row], pcrEff[row], nnulls[row], ninclu[row], correl[row] = _lrp_paramInWindow(fluor, row, upWin[tarGroup], lowWin[tarGroup])
else:
correl[row] = np.nan
indMeanX[row] = np.nan
indMeanY[row] = np.nan
pcrEff[row] = np.nan
nnulls[row] = np.nan
ninclu[row] = 0
return indMeanX, indMeanY, pcrEff, nnulls, ninclu, correl
def _lrp_meanStopFluor(fluor, tarGroup, vecTarget, stopCyc, vecSkipSample, vecNoPlateau):
"""Return the mean of the stop fluor or the max fluor if all rows have no plateau.
Args:
fluor: The array with the fluorescence values
tarGroup: The target number
vecTarget: The vector with the targets numbers
stopCyc: The vector with the stop cycle of the log lin phase
vecSkipSample: Skip the sample
vecNoPlateau: True if there is no plateau
Returns:
The meanMax fluorescence.
"""
meanMax = 0.0
maxFluor = 0.0000001
cnt = 0
if tarGroup is None:
for aRow in range(0, fluor.shape[0]):
if not vecSkipSample[aRow]:
if not vecNoPlateau[aRow]:
cnt += 1
meanMax += fluor[aRow, stopCyc[aRow] - 1]
else:
for i in range(0, fluor.shape[1]):
if fluor[aRow, i] > maxFluor:
maxFluor = fluor[aRow, i]
else:
for aRow in range(0, fluor.shape[0]):
if tarGroup == vecTarget[aRow] and not vecSkipSample[aRow]:
if not vecNoPlateau[aRow]:
cnt += 1
meanMax += fluor[aRow, stopCyc[aRow] - 1]
else:
for i in range(0, fluor.shape[1]):
if fluor[aRow, i] > maxFluor:
maxFluor = fluor[aRow, i]
if cnt > 0:
meanMax = meanMax / cnt
else:
meanMax = maxFluor
return meanMax
def _lrp_maxStartFluor(fluor, tarGroup, vecTarget, startCyc, vecSkipSample):
"""Return the maximum of the start fluorescence
Args:
fluor: The array with the fluorescence values
tarGroup: The target number
vecTarget: The vector with the targets numbers
startCyc: The vector with the start cycle of the log lin phase
vecSkipSample: Skip the sample
Returns:
The maxStart fluorescence.
"""
maxStart = -10.0
if tarGroup is None:
for aRow in range(0, fluor.shape[0]):
if not vecSkipSample[aRow]:
if fluor[aRow, startCyc[aRow] - 1] > maxStart:
maxStart = fluor[aRow, startCyc[aRow] - 1]
else:
for aRow in range(0, fluor.shape[0]):
if tarGroup == vecTarget[aRow] and not vecSkipSample[aRow]:
if fluor[aRow, startCyc[aRow] - 1] > maxStart:
maxStart = fluor[aRow, startCyc[aRow] - 1]
return 0.999 * maxStart
def _lrp_setLogWin(tarGroup, newUpWin, foldWidth, upWin, lowWin, maxFluorTotal, minFluorTotal):
"""Sets a new window and ensures its within the total fluorescence values.
Args:
tarGroup: The target number
newUpWin: The new upper window
foldWidth: The foldWith to the lower window
upWin: The upper window fluorescence
lowWin: The lower window fluorescence
maxFluorTotal: The maximum fluorescence over all rows
minFluorTotal: The minimum fluorescence over all rows
Returns:
An array with [indMeanX, indMeanY, pcrEff, nnulls, ninclu, correl].
"""
# No rounding needed, only present for exact identical output with Pascal version
tempUpWin = np.power(10, np.round(1000 * newUpWin) / 1000)
tempLowWin = np.power(10, np.round(1000 * (newUpWin - foldWidth)) / 1000)
tempUpWin = np.minimum(tempUpWin, maxFluorTotal)
tempUpWin = np.maximum(tempUpWin, minFluorTotal)
tempLowWin = np.minimum(tempLowWin, maxFluorTotal)
tempLowWin = np.maximum(tempLowWin, minFluorTotal)
if tarGroup is None:
upWin[0] = tempUpWin
lowWin[0] = tempLowWin
else:
upWin[tarGroup] = tempUpWin
lowWin[tarGroup] = tempLowWin
return upWin, lowWin
def _lrp_logStepStop(fluor, tarGroup, vecTarget, stopCyc, vecSkipSample, vecNoPlateau):
"""Calculates the log of the fluorescence increase at the stop cycle.
Args:
fluor: The array with the fluorescence values
tarGroup: The target number
vecTarget: The vector with the targets numbers
stopCyc: The vector with the stop cycle of the log lin phase
vecSkipSample: True if row should be skipped
vecNoPlateau: True if there is no plateau
Returns:
An array with [indMeanX, indMeanY, pcrEff, nnulls, ninclu, correl].
"""
cnt = 0
step = 0.0
for aRow in range(0, fluor.shape[0]):
if (tarGroup is None or tarGroup == vecTarget[aRow]) and not (vecSkipSample[aRow] or vecNoPlateau[aRow]):
cnt += 1
step += np.log10(fluor[aRow, stopCyc[aRow] - 1]) - np.log10(fluor[aRow, stopCyc[aRow] - 2])
if cnt > 0:
step = step / cnt
else:
step = np.log10(1.8)
return step
def _lrp_setWoL(fluor, tarGroup, vecTarget, pointsInWoL, indMeanX, indMeanY, pcrEff, nNulls, nInclu, correl,
upWin, lowWin, maxFluorTotal, minFluorTotal, stopCyc, startCyc, threshold,
vecNoAmplification, vecBaselineError, vecSkipSample, vecNoPlateau, vecShortLogLin, vecIsUsedInWoL):
"""Find the window with the lowest variation in PCR efficiency and calculate its values.
Args:
fluor: The array with the fluorescence values
tarGroup: The target number
vecTarget: The vector with the targets numbers
pointsInWoL: The number of points in the window
indMeanX: The vector with the x mean position
indMeanY: The vector with the y mean position
pcrEff: The array with the PCR efficiencies
nNulls: The array with the calculated nNulls
nInclu: The array with the calculated nInclu
correl: The array with the calculated correl
upWin: The upper limit of the window
lowWin: The lower limit of the window
maxFluorTotal: The maximum fluorescence over all rows
minFluorTotal: The minimum fluorescence over all rows
stopCyc: The vector with the stop cycle of the log lin phase
startCyc: The vector with the start cycle of the log lin phase
threshold: The threshold fluorescence
vecNoAmplification: True if there is a amplification error
vecBaselineError: True if there is a baseline error
vecSkipSample: Skip the sample
vecNoPlateau: True if there is no plateau
vecShortLogLin: True indicates a short log lin phase
vecIsUsedInWoL: True if used in the WoL
Returns:
The values indMeanX, indMeanY, pcrEff, nNulls, nInclu, correl, upWin, lowWin, threshold, vecIsUsedInWoL.
"""
skipGroup = False
stepSize = 0.2 # was 0.5, smaller steps help in finding WoL
# Keep 60 calculated results
memVarEff = np.zeros(60, dtype=np.float64)
memUpWin = np.zeros(60, dtype=np.float64)
memFoldWidth = np.zeros(60, dtype=np.float64)
maxFluorWin = _lrp_meanStopFluor(fluor, tarGroup, vecTarget, stopCyc, vecSkipSample, vecNoPlateau)
if maxFluorWin > 0.0:
maxFluorWin = np.log10(maxFluorWin)
else:
skipGroup = True
minFluorLim = _lrp_maxStartFluor(fluor, tarGroup, vecTarget, startCyc, vecSkipSample)
if minFluorLim > 0.0:
minFluorLim = np.log10(minFluorLim)
else:
skipGroup = True
checkMeanEff = 1.0
if not skipGroup:
foldWidth = pointsInWoL * _lrp_logStepStop(fluor, tarGroup, vecTarget, stopCyc, vecSkipSample, vecNoPlateau)
upWin, lowWin = _lrp_setLogWin(tarGroup, maxFluorWin, foldWidth, upWin, lowWin, maxFluorTotal, minFluorTotal)
_unused, _unused2, checkPcrEff, _unused3, _unused4, _unused5 = _lrp_allParamInWindow(fluor, tarGroup, vecTarget,
indMeanX, indMeanY, pcrEff,
nNulls, nInclu, correl,
upWin, lowWin,
vecNoAmplification,
vecBaselineError)
[checkMeanEff, _unused] = _lrp_meanPcrEff(tarGroup, vecTarget, checkPcrEff,
vecSkipSample, vecNoPlateau, vecShortLogLin)
if checkMeanEff < 1.001:
skipGroup = True
if skipGroup:
if tarGroup is None:
threshold[0] = (0.5 * np.round(1000 * upWin[0]) / 1000)
else:
threshold[tarGroup] = (0.5 * np.round(1000 * upWin[tarGroup]) / 1000)
if not skipGroup:
foldWidth = np.log10(np.power(checkMeanEff, pointsInWoL))
counter = -1
maxVarEff = 0.0
maxVarEffStep = -1
lastUpWin = 2 + maxFluorWin
while True:
counter += 1
step = np.log10(checkMeanEff)
newUpWin = maxFluorWin - counter * stepSize * step
if newUpWin < lastUpWin:
upWin, lowWin = _lrp_setLogWin(tarGroup, newUpWin, foldWidth, upWin, lowWin, maxFluorTotal, minFluorTotal)
_unused, _unused2, checkPcrEff, _unused3, _unused4, _unused5 = _lrp_allParamInWindow(fluor, tarGroup,
vecTarget, indMeanX,
indMeanY, pcrEff,
nNulls, nInclu,
correl,
upWin, lowWin,
vecNoAmplification,
vecBaselineError)
[checkMeanEff, _unused] = _lrp_meanPcrEff(tarGroup, vecTarget, checkPcrEff,
vecSkipSample, vecNoPlateau, vecShortLogLin)
foldWidth = np.log10(np.power(checkMeanEff, pointsInWoL))
if foldWidth < 0.5:
foldWidth = 0.5 # to avoid width = 0 above stopCyc
upWin, lowWin = _lrp_setLogWin(tarGroup, newUpWin, foldWidth, upWin, lowWin, maxFluorTotal, minFluorTotal)
_unused, _unused2, checkPcrEff, _unused3, _unused4, _unused5 = _lrp_allParamInWindow(fluor, tarGroup,
vecTarget, indMeanX,
indMeanY, pcrEff,
nNulls, nInclu,
correl,
upWin, lowWin,
vecNoAmplification,
vecBaselineError)
[checkMeanEff, checkVarEff] = _lrp_meanPcrEff(tarGroup, vecTarget, checkPcrEff,
vecSkipSample, vecNoPlateau, vecShortLogLin)
if checkVarEff > 0.0:
memVarEff[counter] = np.sqrt(checkVarEff) / checkMeanEff
else:
memVarEff[counter] = 0.0
if checkVarEff > maxVarEff:
maxVarEff = checkVarEff
maxVarEffStep = counter
memUpWin[counter] = newUpWin
memFoldWidth[counter] = foldWidth
lastUpWin = newUpWin
else:
checkVarEff = 0.0
if counter >= 60 or newUpWin - foldWidth / (pointsInWoL / 2.0) < minFluorLim or checkVarEff < 0.00000000001:
break
# corrections: start
if checkVarEff < 0.00000000001:
counter -= 1 # remove window with vareff was 0.0
validSteps = -1
while True:
validSteps += 1
if memVarEff[validSteps] < 0.000001:
break
validSteps -= 1 # i = number of valid steps
minSmooth = memVarEff[0]
minStep = 0 # default top window
# next 3 if conditions on i: added to correct smoothing
if validSteps == 0:
minStep = 0
if 0 < validSteps < 4:
n = -1
while True:
n += 1
if memVarEff[n] < minSmooth:
minSmooth = memVarEff[n]
minStep = n
if n == validSteps:
break
if validSteps >= 4:
n = 0
while True:
n += 1
smoothVar = 0.0
for m in range(n - 1, n + 2):
smoothVar = smoothVar + memVarEff[m]
smoothVar = smoothVar / 3.0
if smoothVar < minSmooth:
minSmooth = smoothVar
minStep = n
if n >= validSteps - 1 or n > maxVarEffStep:
break
# corrections: stop
# Calculate the final values again
upWin, lowWin = _lrp_setLogWin(tarGroup, memUpWin[minStep], memFoldWidth[minStep],
upWin, lowWin, maxFluorTotal, minFluorTotal)
if tarGroup is None:
threshold[0] = (0.5 * np.round(1000 * upWin[0]) / 1000)
else:
threshold[tarGroup] = (0.5 * np.round(1000 * upWin[tarGroup]) / 1000)
indMeanX, indMeanY, pcrEff, nNulls, nInclu, correl = _lrp_allParamInWindow(fluor, tarGroup, vecTarget,
indMeanX, indMeanY, pcrEff, nNulls,
nInclu, correl, upWin, lowWin,
vecNoAmplification, vecBaselineError)
for aRow in range(0, len(pcrEff)):
if tarGroup is None or tarGroup == vecTarget[aRow]:
if (not (vecSkipSample[aRow] or vecNoPlateau[aRow] or vecShortLogLin[aRow])) and pcrEff[aRow] > 1.0:
vecIsUsedInWoL[aRow] = True
else:
vecIsUsedInWoL[aRow] = False
return indMeanX, indMeanY, pcrEff, nNulls, nInclu, correl, upWin, lowWin, threshold, vecIsUsedInWoL
def _lrp_assignNoPlateau(fluor, tarGroup, vecTarget, pointsInWoL, indMeanX, indMeanY, pcrEff, nNulls, nInclu, correl,
upWin, lowWin, maxFluorTotal, minFluorTotal, stopCyc, startCyc, threshold,
vecNoAmplification, vecBaselineError, vecSkipSample, vecNoPlateau, vecShortLogLin, vecIsUsedInWoL):
"""Assign no plateau again and possibly recalculate WoL if new no plateau was found.
Args:
fluor: The array with the fluorescence values
tarGroup: The target number
vecTarget: The vector with the targets numbers
pointsInWoL: The number of points in the window
indMeanX: The vector with the x mean position
indMeanY: The vector with the y mean position
pcrEff: The array with the PCR efficiencies
nNulls: The array with the calculated nNulls
nInclu: The array with the calculated nInclu
correl: The array with the calculated correl
upWin: The upper limit of the window
lowWin: The lower limit of the window
maxFluorTotal: The maximum fluorescence over all rows
minFluorTotal: The minimum fluorescence over all rows
stopCyc: The vector with the stop cycle of the log lin phase
startCyc: The vector with the start cycle of the log lin phase
threshold: The threshold fluorescence
vecNoAmplification: True if there is a amplification error
vecBaselineError: True if there is a baseline error
vecSkipSample: Skip the sample
vecNoPlateau: True if there is no plateau
vecShortLogLin: True indicates a short log lin phase
vecIsUsedInWoL: True if used in the WoL
Returns:
The values indMeanX, indMeanY, pcrEff, nNulls, nInclu, correl, upWin, lowWin, threshold, vecIsUsedInWoL, vecNoPlateau.
"""
newNoPlateau = False
for aRow in range(0, fluor.shape[0]):
if (tarGroup is None or tarGroup == vecTarget[aRow]) and not (vecNoAmplification[aRow] or
vecBaselineError[aRow] or
vecNoPlateau[aRow]):
expectedFluor = nNulls[aRow] * np.power(pcrEff[aRow], fluor.shape[1])
if expectedFluor / fluor[aRow, fluor.shape[1] - 1] < 5:
newNoPlateau = True
vecNoPlateau[aRow] = True
if newNoPlateau:
indMeanX, indMeanY, pcrEff, nNulls, nInclu, correl, upWin, lowWin, threshold, vecIsUsedInWoL = _lrp_setWoL(fluor, tarGroup, vecTarget,
pointsInWoL, indMeanX, indMeanY, pcrEff,
nNulls, nInclu, correl, upWin,
lowWin, maxFluorTotal, minFluorTotal,
stopCyc, startCyc, threshold,
vecNoAmplification,
vecBaselineError,
vecSkipSample, vecNoPlateau,
vecShortLogLin, vecIsUsedInWoL)
return indMeanX, indMeanY, pcrEff, nNulls, nInclu, correl, upWin, lowWin, threshold, vecIsUsedInWoL, vecNoPlateau
def _lrp_removeOutlier(data, vecNoPlateau, alpha=0.05):
"""A function which calculates the skewness and Grubbs test to identify outliers ignoring nan.
Args:
data: The numpy array with the data
vecNoPlateau: The vector of samples without plateau.
alpha: The the significance level (default 0.05)
Returns:
The a bool array with the removed outliers set true.
"""
oData = np.copy(data)
oLogic = np.zeros(data.shape, dtype=np.bool_)
loopOn = True
while loopOn:
count = np.count_nonzero(~np.isnan(oData))
if count < 3:
loopOn = False
else:
mean = np.nanmean(oData)
std = np.nanstd(oData, ddof=1)
skewness = scp.skew(oData, bias=False, nan_policy='omit')
skewness_SE = np.sqrt((6 * count * (count - 1)) / ((count - 2) * (count + 1) * (count + 3)))
skewness_t = np.abs(skewness) / skewness_SE
skewness_P = scp.t.sf(skewness_t, df=np.power(10, 10)) * 2
if skewness_P < alpha / 2.0:
# It's skewed!
grubbs_t = scp.t.ppf(1 - (alpha / count) / 2, (count - 2))
grubbs_Gcrit = ((count - 1) / np.sqrt(count)) * np.sqrt(np.power(grubbs_t, 2) /
((count - 2) + np.power(grubbs_t, 2)))
if skewness > 0.0:
data_max = np.nanmax(oData)
grubbs_res = (data_max - mean) / std
max_pos = np.nanargmax(oData)
if grubbs_res > grubbs_Gcrit:
# It's a true outlier
oData[max_pos] = np.nan
oLogic[max_pos] = True
else:
if vecNoPlateau[max_pos]:
# It has no plateau
oData[max_pos] = np.nan
oLogic[max_pos] = True
else:
loopOn = False
else:
data_min = np.nanmin(oData)
grubbs_res = (mean - data_min) / std
min_pos = np.nanargmin(oData)
if grubbs_res > grubbs_Gcrit:
# It's a true outlier
oData[min_pos] = np.nan
oLogic[min_pos] = True
else:
if vecNoPlateau[min_pos]:
# It has no plateau
oData[min_pos] = np.nan
oLogic[min_pos] = True
else:
loopOn = False
else:
loopOn = False
return oLogic
def _mca_smooth(tempList, rawFluor):
"""A function to smooth the melt curve date based on Friedmans supersmoother.
# https://www.slac.stanford.edu/pubs/slacpubs/3250/slac-pub-3477.pdf
Args:
tempList:
rawFluor: The numpy array with the raw data
Returns:
The numpy array with the smoothed data.
"""
span_s = 0.05
span_m = 0.2
span_l = 0.5
smoothFluor = np.zeros(rawFluor.shape, dtype=np.float64)
padTemp = np.append(0.0, tempList)
zeroPad = np.zeros((rawFluor.shape[0], 1), dtype=np.float64)
padFluor = np.append(zeroPad, rawFluor, axis=1)
n = len(padTemp) - 1
# Find the increase in x from 0.25 to 0.75 over the total range
firstQuarter = int(0.5 + n / 4)
thirdQuarter = 3 * firstQuarter
scale = -1.0
while scale <= 0.0:
if thirdQuarter < n:
thirdQuarter += 1
if firstQuarter > 1:
firstQuarter -= 1
scale = padTemp[thirdQuarter] - padTemp[firstQuarter]
vsmlsq = 0.0001 * scale * 0.0001 * scale
countUp = 0
for fluor in padFluor:
[res_s_a, res_s_t] = _mca_sub_smooth(padTemp, fluor, span_s, vsmlsq, True)
[res_s_b, _unused] = _mca_sub_smooth(padTemp, res_s_t, span_m, vsmlsq, False)
[res_s_c, res_s_t] = _mca_sub_smooth(padTemp, fluor, span_m, vsmlsq, True)
[res_s_d, _unused] = _mca_sub_smooth(padTemp, res_s_t, span_m, vsmlsq, False)
[res_s_e, res_s_t] = _mca_sub_smooth(padTemp, fluor, span_l, vsmlsq, True)
[res_s_f, _unused] = _mca_sub_smooth(padTemp, res_s_t, span_m, vsmlsq, False)
res_s_fin = np.zeros(res_s_a.shape, dtype=np.float64)
for thirdQuarter in range(1, n + 1):
resmin = 1.0e20
if res_s_b[thirdQuarter] < resmin:
resmin = res_s_b[thirdQuarter]
res_s_fin[thirdQuarter] = span_s
if res_s_d[thirdQuarter] < resmin:
resmin = res_s_d[thirdQuarter]
res_s_fin[thirdQuarter] = span_m
if res_s_f[thirdQuarter] < resmin:
res_s_fin[thirdQuarter] = span_l
[res_s_bb, _unused] = _mca_sub_smooth(padTemp, res_s_fin, span_m, vsmlsq, False)
res_s_cc = np.zeros(res_s_a.shape, dtype=np.float64)
for thirdQuarter in range(1, n + 1):
# compare res_s_bb with spans[] and make sure the no res_s_bb[] is below span_s or above span_l
if res_s_bb[thirdQuarter] <= span_s:
res_s_bb[thirdQuarter] = span_s
if res_s_bb[thirdQuarter] >= span_l:
res_s_bb[thirdQuarter] = span_l
f = res_s_bb[thirdQuarter] - span_m
if f >= 0.0:
# in case res_s_bb[] is higher than span_m: calculate res_s_cc[] from res_s_c and res_s_e
# using linear interpolation between span_l and span_m
f = f / (span_l - span_m)
res_s_cc[thirdQuarter] = (1.0 - f) * res_s_c[thirdQuarter] + f * res_s_e[thirdQuarter]
else:
# in case res_s_bb[] is less than span_m: calculate res_s_cc[] from res_s_c and res_s_a
# using linear interpolation between span_s and span_m
f = -f / (span_m - span_s)
res_s_cc[thirdQuarter] = (1.0 - f) * res_s_c[thirdQuarter] + f * res_s_a[thirdQuarter]
# final smoothing of combined optimally smoothed values in res_s_cc[] into smo[]
[res_s_t, _unused] = _mca_sub_smooth(padTemp, res_s_cc, span_s, vsmlsq, False)
smoothFluor[countUp] = res_s_t[1:]
countUp += 1
return smoothFluor
def _mca_sub_smooth(temperature, fluor, span, vsmlsq, saveVarianceData):
"""A function to smooth the melt curve date based on Friedmans supersmoother.
# https://www.slac.stanford.edu/pubs/slacpubs/3250/slac-pub-3477.pdf
Args:
temperature:
fluor: The numpy array with the raw data
span: The selected span
vsmlsq: The width
saveVarianceData: Sava variance data
Returns:
[smoothData[], varianceData[]] where smoothData[] contains smoothed data,
varianceData[] contains residuals scaled to variance.
"""
n = len(temperature) - 1
smoothData = np.zeros(len(temperature), dtype=np.float64)
varianceData = np.zeros(len(temperature), dtype=np.float64)
windowSize = int(0.5 * span * n + 0.6)
if windowSize < 2:
windowSize = 2
windowStop = 2 * windowSize + 1 # range of smoothing window
xm = temperature[1]
ym = fluor[1]
tempVar = 0.0
fluorVar = 0.0
for i in range(2, windowStop + 1):
xm = ((i - 1) * xm + temperature[i]) / i
ym = ((i - 1) * ym + fluor[i]) / i
tmp = i * (temperature[i] - xm) / (i - 1)
tempVar += tmp * (temperature[i] - xm)
fluorVar += tmp * (fluor[i] - ym)
fbw = windowStop
for j in range(1, n + 1): # Loop through all
windowStart = j - windowSize - 1
windowEnd = j + windowSize
if not (windowStart < 1 or windowEnd > n):
tempStart = temperature[windowStart]
tempEnd = temperature[windowEnd]
fbo = fbw
fbw = fbw - 1.0
tmp = 0.0
if fbw > 0.0:
xm = (fbo * xm - tempStart) / fbw
if fbw > 0.0:
ym = (fbo * ym - fluor[windowStart]) / fbw
if fbw > 0.0:
tmp = fbo * (tempStart - xm) / fbw
tempVar = tempVar - tmp * (tempStart - xm)
fluorVar = fluorVar - tmp * (fluor[windowStart] - ym)
fbo = fbw
fbw = fbw + 1.0
tmp = 0.0
if fbw > 0.0:
xm = (fbo * xm + tempEnd) / fbw
if fbw > 0.0:
ym = (fbo * ym + fluor[windowEnd]) / fbw
if fbo > 0.0:
tmp = fbw * (tempEnd - xm) / fbo
tempVar = tempVar + tmp * (tempEnd - xm)
fluorVar = fluorVar + tmp * (fluor[windowEnd] - ym)
if tempVar > vsmlsq:
smoothData[j] = (temperature[j] - xm) * fluorVar / tempVar + ym # contains smoothed data
else:
smoothData[j] = ym # contains smoothed data
if saveVarianceData:
h = 0.0
if fbw > 0.0:
h = 1.0 / fbw
if tempVar > vsmlsq:
h = h + (temperature[j] - xm) * (temperature[j] - xm) / tempVar
if 1.0 - h > 0.0:
varianceData[j] = abs(fluor[j] - smoothData[j]) / (1.0 - h) # contains residuals scaled to variance
else:
if j > 1:
varianceData[j] = varianceData[j - 1] # contains residuals scaled to variance
else:
varianceData[j] = 0.0
return [smoothData, varianceData]
def _mca_linReg(xIn, yUse, start, stop):
"""A function which calculates the slope or the intercept by linear regression.
Args:
xIn: The numpy array of the temperatures
yUse: The numpy array that contains the fluorescence
Returns:
An array with the slope and intercept.
"""
counts = np.ones(yUse.shape)
xUse = xIn.copy()
xUse[np.isnan(yUse)] = 0
counts[np.isnan(yUse)] = 0
myStop = stop + 1
tempSqared = xUse * xUse
tempFluor = xUse * yUse
sumCyc = np.nansum(xUse[:, start:myStop], axis=1)
sumFluor = np.nansum(yUse[:, start:myStop], axis=1)
sumCycSquared = np.nansum(tempSqared[:, start:myStop], axis=1)
sumCycFluor = np.nansum(tempFluor[:, start:myStop], axis=1)
n = np.nansum(counts[:, start:myStop], axis=1)
ssx = sumCycSquared - (sumCyc * sumCyc) / n
sxy = sumCycFluor - (sumCyc * sumFluor) / n
slope = sxy / ssx
intercept = (sumFluor / n) - slope * (sumCyc / n)
return [slope, intercept]
def _cleanErrorString(inStr, cleanStyle):
outStr = ";"
inStr += ";"
if cleanStyle == "melt":
outStr = inStr.replace('several products with different melting temperatures detected', '')
outStr = outStr.replace('product with different melting temperatures detected', '')
outStr = outStr.replace('no product with expected melting temperature', '')
else:
strList = inStr.split(";")
knownWarn = ["amplification in negative control", "plateau in negative control",
"no amplification in positive control", "baseline error in positive control",
"no plateau in positive control", "noisy sample in positive control",
"Cq < 10, N0 unreliable", "Cq > 34", "no indiv PCR eff can be calculated",
"PCR efficiency outlier", "no amplification", "baseline error", "no plateau",
"noisy sample", "Cq too high"]
for ele in strList:
if ele in knownWarn:
continue
if re.search(r"^only \d+ values in log phase", ele):
continue
if re.search(r"^indiv PCR eff is .+", ele):
continue
outStr += ele + ";"
# if inStr.find('several products with different melting temperatures detected') >= 0:
# outStr += ';several products with different melting temperatures detected;'
# if inStr.find('product with different melting temperatures detected') >= 0:
# outStr += ';product with different melting temperatures detected;'
# if inStr.find('no product with expected melting temperature') >= 0:
# outStr += ';no product with expected melting temperature;'
outStr = re.sub(r';+', ';', outStr)
return outStr
def _numpyTwoAxisSave(var, fileName):
with np.printoptions(precision=3, suppress=True):
np.savetxt(fileName, var, fmt='%.6f', delimiter='\t', newline='\n')
def _getXMLDataType():
return ["tar", "cq", "N0", "ampEffMet", "ampEff", "ampEffSE", "corrF", "meltTemp",
"excl", "note", "adp", "mdp", "endPt", "bgFluor", "quantFluor"]
class Rdml:
"""RDML-Python library
The root element used to open, write, read and edit RDML files.
Attributes:
_rdmlData: The RDML XML object from lxml.
_node: The root node of the RDML XML object.
"""
def __init__(self, filename=None):
"""Inits an empty RDML instance with new() or load RDML file with load().
Args:
self: The class self parameter.
filename: The name of the RDML file to load.
Returns:
No return value. Function may raise RdmlError if required.
"""
self._rdmlData = None
self._rdmlFilename = None
self._node = None
if filename:
self.load(filename)
else:
self.new()
def __getitem__(self, key):
"""Returns data of the key.
Args:
self: The class self parameter.
key: The key of the experimenter subelement
Returns:
A string of the data or None.
"""
if key == "version":
return self.version()
if key in ["dateMade", "dateUpdated"]:
return _get_first_child_text(self._node, key)
raise KeyError
def keys(self):
"""Returns a list of the keys.
Args:
self: The class self parameter.
Returns:
A list of the key strings.
"""
return ["version", "dateMade", "dateUpdated"]
def xmlkeys(self):
"""Returns a list of the keys in the xml file.
Args:
self: The class self parameter.
Returns:
A list of the key strings.
"""
return ["dateMade", "dateUpdated", "id", "experimenter", "documentation", "dye",
"sample", "target", "thermalCyclingConditions", "experiment"]
def new(self):
"""Creates an new empty RDML object with the current date.
Args:
self: The class self parameter.
Returns:
No return value. Function may raise RdmlError if required.
"""
data = "<rdml version='1.2' xmlns:rdml='http://www.rdml.org' xmlns='http://www.rdml.org'>\n<dateMade>"
data += datetime.datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%S")
data += "</dateMade>\n<dateUpdated>"
data += datetime.datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%S")
data += "</dateUpdated>\n</rdml>"
self.loadXMLString(data)
return
def load(self, filename):
"""Load an RDML file with decompression of rdml_data.xml or an XML file. Uses loadXMLString().
Args:
self: The class self parameter.
filename: The name of the RDML file to load.
Returns:
No return value. Function may raise RdmlError if required.
"""
if zipfile.is_zipfile(filename):
self._rdmlFilename = filename
zf = zipfile.ZipFile(filename, 'r')
try:
data = zf.read('rdml_data.xml').decode('utf-8')
except KeyError:
raise RdmlError('No rdml_data.xml in compressed RDML file found.')
else:
self.loadXMLString(data)
finally:
zf.close()
else:
with open(filename, 'r') as txtfile:
data = txtfile.read()
if data:
self.loadXMLString(data)
else:
raise RdmlError('File format error, not a valid RDML or XML file.')
def save(self, filename):
"""Save an RDML file with compression of rdml_data.xml.
Args:
self: The class self parameter.
filename: The name of the RDML file to save to.
Returns:
No return value. Function may raise RdmlError if required.
"""
elem = _get_or_create_subelement(self._node, "dateUpdated", self.xmlkeys())
elem.text = datetime.datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%S")
data = et.tostring(self._rdmlData, pretty_print=True)
_writeFileInRDML(filename, 'rdml_data.xml', data)
def loadXMLString(self, data):
"""Create RDML object from xml string. !ENTITY and DOCSTRINGS will be removed.
Args:
self: The class self parameter.
data: The xml string of the RDML file to load.
Returns:
No return value. Function may raise RdmlError if required.
"""
# To avoid some xml attacs based on
# <!ENTITY entityname "replacement text">
data = re.sub(r"<\W*!ENTITY[^>]+>", "", data)
data = re.sub(r"!ENTITY", "", data)
try:
self._rdmlData = et.ElementTree(et.fromstring(data.encode('utf-8')))
# Change to bytecode and defused?
except et.XMLSyntaxError:
raise RdmlError('XML load error, not a valid RDML or XML file.')
self._node = self._rdmlData.getroot()
if self._node.tag.replace("{http://www.rdml.org}", "") != 'rdml':
raise RdmlError('Root element is not \'rdml\', not a valid RDML or XML file.')
rdml_version = self._node.get('version')
# Remainder: Update version in new() and validate()
if rdml_version not in ['1.0', '1.1', '1.2', '1.3']:
raise RdmlError('Unknown or unsupported RDML file version.')
def validate(self, filename=None):
"""Validate the RDML object against its schema or load file and validate it.
Args:
self: The class self parameter.
filename: The name of the RDML file to load.
Returns:
A string with the validation result as a two column table.
"""
notes = ""
if filename:
try:
vd = Rdml(filename)
except RdmlError as err:
notes += 'RDML file structure:\tFalse\t' + str(err) + '\n'
return notes
notes += "RDML file structure:\tTrue\tValid file structure.\n"
else:
vd = self
version = vd.version()
rdmlws = os.path.dirname(os.path.abspath(__file__))
if version == '1.0':
xmlschema_doc = et.parse(os.path.join(rdmlws, 'schema', 'RDML_v1_0_REC.xsd'))
elif version == '1.1':
xmlschema_doc = et.parse(os.path.join(rdmlws, 'schema', 'RDML_v1_1_REC.xsd'))
elif version == '1.2':
xmlschema_doc = et.parse(os.path.join(rdmlws, 'schema', 'RDML_v1_2_REC.xsd'))
elif version == '1.3':
xmlschema_doc = et.parse(os.path.join(rdmlws, 'schema', 'RDML_v1_3_CR.xsd'))
else:
notes += 'RDML version:\tFalse\tUnknown schema version' + version + '\n'
return notes
notes += "RDML version:\tTrue\t" + version + "\n"
xmlschema = et.XMLSchema(xmlschema_doc)
result = xmlschema.validate(vd._rdmlData)
if result:
notes += 'Schema validation result:\tTrue\tRDML file is valid.\n'
else:
notes += 'Schema validation result:\tFalse\tRDML file is not valid.\n'
log = xmlschema.error_log
for err in log:
notes += 'Schema validation error:\tFalse\t'
notes += "Line %s, Column %s: %s \n" % (err.line, err.column, err.message)
return notes
def isvalid(self, filename=None):
"""Validate the RDML object against its schema or load file and validate it.
Args:
self: The class self parameter.
filename: The name of the RDML file to load.
Returns:
True or false as the validation result.
"""
if filename:
try:
vd = Rdml(filename)
except RdmlError:
return False
else:
vd = self
version = vd.version()
rdmlws = os.path.dirname(os.path.abspath(__file__))
if version == '1.0':
xmlschema_doc = et.parse(os.path.join(rdmlws, 'schema', 'RDML_v1_0_REC.xsd'))
elif version == '1.1':
xmlschema_doc = et.parse(os.path.join(rdmlws, 'schema', 'RDML_v1_1_REC.xsd'))
elif version == '1.2':
xmlschema_doc = et.parse(os.path.join(rdmlws, 'schema', 'RDML_v1_2_REC.xsd'))
elif version == '1.3':
xmlschema_doc = et.parse(os.path.join(rdmlws, 'schema', 'RDML_v1_3_CR.xsd'))
else:
return False
xmlschema = et.XMLSchema(xmlschema_doc)
result = xmlschema.validate(vd._rdmlData)
if result:
return True
else:
return False
def version(self):
"""Returns the version string of the RDML object.
Args:
self: The class self parameter.
Returns:
A string of the version like '1.1'.
"""
return self._node.get('version')
def migrate_version_1_0_to_1_1(self):
"""Migrates the rdml version from v1.0 to v1.1.
Args:
self: The class self parameter.
Returns:
A list of strings with the modifications made.
"""
ret = []
rdml_version = self._node.get('version')
if rdml_version != '1.0':
raise RdmlError('RDML version for migration has to be v1.0.')
exp = _get_all_children(self._node, "thirdPartyExtensions")
if len(exp) > 0:
ret.append("Migration to v1.1 deleted \"thirdPartyExtensions\" elements.")
for node in exp:
self._node.remove(node)
hint = ""
exp1 = _get_all_children(self._node, "experiment")
for node1 in exp1:
exp2 = _get_all_children(node1, "run")
for node2 in exp2:
exp3 = _get_all_children(node2, "react")
for node3 in exp3:
exp4 = _get_all_children(node3, "data")
for node4 in exp4:
exp5 = _get_all_children(node4, "quantity")
for node5 in exp5:
hint = "Migration to v1.1 deleted react data \"quantity\" elements."
node4.remove(node5)
if hint != "":
ret.append(hint)
xml_keys = ["description", "documentation", "xRef", "type", "interRunCalibrator",
"quantity", "calibratorSample", "cdnaSynthesisMethod",
"templateRNAQuantity", "templateRNAQuality", "templateDNAQuantity", "templateDNAQuality"]
exp1 = _get_all_children(self._node, "sample")
for node1 in exp1:
hint = ""
exp2 = _get_all_children(node1, "templateRNAQuantity")
if len(exp2) > 0:
templateRNAQuantity = _get_first_child_text(node1, "templateRNAQuantity")
node1.remove(exp2[0])
if templateRNAQuantity != "":
hint = "Migration to v1.1 modified sample \"templateRNAQuantity\" element without loss."
ele = _get_or_create_subelement(node1, "templateRNAQuantity", xml_keys)
_change_subelement(ele, "value", ["value", "unit"], templateRNAQuantity, True, "float")
_change_subelement(ele, "unit", ["value", "unit"], "ng", True, "float")
if hint != "":
ret.append(hint)
hint = ""
exp2 = _get_all_children(node1, "templateRNAQuantity")
if len(exp2) > 0:
templateDNAQuantity = _get_first_child_text(node1, "templateDNAQuantity")
node1.remove(exp2[0])
if templateDNAQuantity != "":
hint = "Migration to v1.1 modified sample \"templateDNAQuantity\" element without loss."
ele = _get_or_create_subelement(node1, "templateDNAQuantity", xml_keys)
_change_subelement(ele, "value", ["value", "unit"], templateDNAQuantity, True, "float")
_change_subelement(ele, "unit", ["value", "unit"], "ng", True, "float")
if hint != "":
ret.append(hint)
xml_keys = ["description", "documentation", "xRef", "type", "amplificationEfficiencyMethod",
"amplificationEfficiency", "detectionLimit", "dyeId", "sequences", "commercialAssay"]
exp1 = _get_all_children(self._node, "target")
all_dyes = {}
hint = ""
for node1 in exp1:
hint = ""
dye_ele = _get_first_child_text(node1, "dyeId")
node1.remove(_get_first_child(node1, "dyeId"))
if dye_ele == "":
dye_ele = "conversion_dye_missing"
hint = "Migration to v1.1 created target nonsense \"dyeId\"."
forId = _get_or_create_subelement(node1, "dyeId", xml_keys)
forId.attrib['id'] = dye_ele
all_dyes[dye_ele] = True
if hint != "":
ret.append(hint)
for dkey in all_dyes.keys():
if _check_unique_id(self._node, "dye", dkey):
new_node = et.Element("dye", id=dkey)
place = _get_tag_pos(self._node, "dye", self.xmlkeys(), 999999)
self._node.insert(place, new_node)
xml_keys = ["description", "documentation", "experimenter", "instrument", "dataCollectionSoftware",
"backgroundDeterminationMethod", "cqDetectionMethod", "thermalCyclingConditions", "pcrFormat",
"runDate", "react"]
exp1 = _get_all_children(self._node, "experiment")
for node1 in exp1:
exp2 = _get_all_children(node1, "run")
for node2 in exp2:
old_format = _get_first_child_text(node2, "pcrFormat")
exp3 = _get_all_children(node2, "pcrFormat")
for node3 in exp3:
node2.remove(node3)
rows = "1"
columns = "1"
rowLabel = "ABC"
columnLabel = "123"
if old_format == "single-well":
rowLabel = "123"
if old_format == "48-well plate; A1-F8":
rows = "6"
columns = "8"
if old_format == "96-well plate; A1-H12":
rows = "8"
columns = "12"
if old_format == "384-well plate; A1-P24":
rows = "16"
columns = "24"
if old_format == "3072-well plate; A1a1-D12h8":
rows = "32"
columns = "96"
rowLabel = "A1a1"
columnLabel = "A1a1"
if old_format == "32-well rotor; 1-32":
rows = "32"
rowLabel = "123"
if old_format == "72-well rotor; 1-72":
rows = "72"
rowLabel = "123"
if old_format == "100-well rotor; 1-100":
rows = "100"
rowLabel = "123"
if old_format == "free format":
rows = "-1"
columns = "1"
rowLabel = "123"
ele3 = _get_or_create_subelement(node2, "pcrFormat", xml_keys)
_change_subelement(ele3, "rows", ["rows", "columns", "rowLabel", "columnLabel"], rows, True, "string")
_change_subelement(ele3, "columns", ["rows", "columns", "rowLabel", "columnLabel"], columns, True, "string")
_change_subelement(ele3, "rowLabel", ["rows", "columns", "rowLabel", "columnLabel"], rowLabel, True, "string")
_change_subelement(ele3, "columnLabel", ["rows", "columns", "rowLabel", "columnLabel"], columnLabel, True, "string")
if old_format == "48-well plate A1-F8" or \
old_format == "96-well plate; A1-H12" or \
old_format == "384-well plate; A1-P24":
exp3 = _get_all_children(node2, "react")
for node3 in exp3:
old_id = node3.get('id')
old_letter = ord(re.sub(r"\d", "", old_id).upper()) - ord("A")
old_nr = int(re.sub(r"\D", "", old_id))
newId = old_nr + old_letter * int(columns)
node3.attrib['id'] = str(newId)
if old_format == "3072-well plate; A1a1-D12h8":
exp3 = _get_all_children(node2, "react")
for node3 in exp3:
old_id = node3.get('id')
old_left = re.sub(r"\D\d+$", "", old_id)
old_left_letter = ord(re.sub(r"\d", "", old_left).upper()) - ord("A")
old_left_nr = int(re.sub(r"\D", "", old_left)) - 1
old_right = re.sub(r"^\D\d+", "", old_id)
old_right_letter = ord(re.sub(r"\d", "", old_right).upper()) - ord("A")
old_right_nr = int(re.sub(r"\D", "", old_right))
newId = old_left_nr * 8 + old_right_nr + old_left_letter * 768 + old_right_letter * 96
node3.attrib['id'] = str(newId)
self._node.attrib['version'] = "1.1"
return ret
def migrate_version_1_1_to_1_2(self):
"""Migrates the rdml version from v1.1 to v1.2.
Args:
self: The class self parameter.
Returns:
A list of strings with the modifications made.
"""
ret = []
rdml_version = self._node.get('version')
if rdml_version != '1.1':
raise RdmlError('RDML version for migration has to be v1.1.')
exp1 = _get_all_children(self._node, "sample")
for node1 in exp1:
hint = ""
exp2 = _get_all_children(node1, "templateRNAQuality")
for node2 in exp2:
node1.remove(node2)
hint = "Migration to v1.2 deleted sample \"templateRNAQuality\" element."
if hint != "":
ret.append(hint)
hint = ""
exp2 = _get_all_children(node1, "templateRNAQuantity")
for node2 in exp2:
node1.remove(node2)
hint = "Migration to v1.2 deleted sample \"templateRNAQuantity\" element."
if hint != "":
ret.append(hint)
hint = ""
exp2 = _get_all_children(node1, "templateDNAQuality")
for node2 in exp2:
node1.remove(node2)
hint = "Migration to v1.2 deleted sample \"templateDNAQuality\" element."
if hint != "":
ret.append(hint)
hint = ""
exp2 = _get_all_children(node1, "templateDNAQuantity")
for node2 in exp2:
node1.remove(node2)
hint = "Migration to v1.2 deleted sample \"templateDNAQuantity\" element."
if hint != "":
ret.append(hint)
self._node.attrib['version'] = "1.2"
return ret
def migrate_version_1_2_to_1_1(self):
"""Migrates the rdml version from v1.2 to v1.1.
Args:
self: The class self parameter.
Returns:
A list of strings with the modifications made.
"""
ret = []
rdml_version = self._node.get('version')
if rdml_version != '1.2':
raise RdmlError('RDML version for migration has to be v1.2.')
exp1 = _get_all_children(self._node, "sample")
for node1 in exp1:
hint = ""
exp2 = _get_all_children(node1, "annotation")
for node2 in exp2:
node1.remove(node2)
hint = "Migration to v1.1 deleted sample \"annotation\" element."
if hint != "":
ret.append(hint)
hint = ""
exp2 = _get_all_children(node1, "templateQuantity")
for node2 in exp2:
node1.remove(node2)
hint = "Migration to v1.1 deleted sample \"templateQuantity\" element."
if hint != "":
ret.append(hint)
exp1 = _get_all_children(self._node, "target")
for node1 in exp1:
hint = ""
exp2 = _get_all_children(node1, "amplificationEfficiencySE")
for node2 in exp2:
node1.remove(node2)
hint = "Migration to v1.1 deleted target \"amplificationEfficiencySE\" element."
if hint != "":
ret.append(hint)
hint = ""
exp1 = _get_all_children(self._node, "experiment")
for node1 in exp1:
exp2 = _get_all_children(node1, "run")
for node2 in exp2:
exp3 = _get_all_children(node2, "react")
for node3 in exp3:
exp4 = _get_all_children(node3, "data")
for node4 in exp4:
exp5 = _get_all_children(node4, "bgFluorSlp")
for node5 in exp5:
hint = "Migration to v1.1 deleted react data \"bgFluorSlp\" elements."
node4.remove(node5)
if hint != "":
ret.append(hint)
self._node.attrib['version'] = "1.1"
return ret
def migrate_version_1_2_to_1_3(self):
"""Migrates the rdml version from v1.2 to v1.3.
Args:
self: The class self parameter.
Returns:
A list of strings with the modifications made.
"""
ret = []
rdml_version = self._node.get('version')
if rdml_version != '1.2':
raise RdmlError('RDML version for migration has to be v1.2.')
self._node.attrib['version'] = "1.3"
return ret
def migrate_version_1_3_to_1_2(self):
"""Migrates the rdml version from v1.3 to v1.2.
Args:
self: The class self parameter.
Returns:
A list of strings with the modifications made.
"""
ret = []
rdml_version = self._node.get('version')
if rdml_version != '1.3':
raise RdmlError('RDML version for migration has to be v1.3.')
hint = ""
hint2 = ""
hint3 = ""
hint4 = ""
hint5 = ""
hint6 = ""
hint7 = ""
hint8 = ""
exp1 = _get_all_children(self._node, "experiment")
for node1 in exp1:
exp2 = _get_all_children(node1, "run")
for node2 in exp2:
exp3 = _get_all_children(node2, "react")
for node3 in exp3:
exp4 = _get_all_children(node3, "partitions")
for node4 in exp4:
hint = "Migration to v1.2 deleted react \"partitions\" elements."
node3.remove(node4)
# No data element, no react element in v 1.2
exp5 = _get_all_children(node3, "data")
if len(exp5) == 0:
hint = "Migration to v1.2 deleted run \"react\" elements."
node2.remove(node3)
exp4b = _get_all_children(node3, "data")
for node4 in exp4b:
exp5 = _get_all_children(node4, "ampEffMet")
for node5 in exp5:
hint2 = "Migration to v1.2 deleted react data \"ampEffMet\" elements."
node4.remove(node5)
exp5 = _get_all_children(node4, "N0")
for node5 in exp5:
hint3 = "Migration to v1.2 deleted react data \"N0\" elements."
node4.remove(node5)
exp5 = _get_all_children(node4, "ampEff")
for node5 in exp5:
hint4 = "Migration to v1.2 deleted react data \"ampEff\" elements."
node4.remove(node5)
exp5 = _get_all_children(node4, "ampEffSE")
for node5 in exp5:
hint5 = "Migration to v1.2 deleted react data \"ampEffSE\" elements."
node4.remove(node5)
exp5 = _get_all_children(node4, "corrF")
for node5 in exp5:
hint6 = "Migration to v1.2 deleted react data \"corrF\" elements."
node4.remove(node5)
exp5 = _get_all_children(node4, "meltTemp")
for node5 in exp5:
hint7 = "Migration to v1.2 deleted react data \"meltTemp\" elements."
node4.remove(node5)
exp5 = _get_all_children(node4, "note")
for node5 in exp5:
hint8 = "Migration to v1.2 deleted react data \"note\" elements."
node4.remove(node5)
if hint != "":
ret.append(hint)
if hint2 != "":
ret.append(hint2)
if hint3 != "":
ret.append(hint3)
if hint4 != "":
ret.append(hint4)
if hint5 != "":
ret.append(hint5)
if hint6 != "":
ret.append(hint6)
if hint7 != "":
ret.append(hint7)
if hint8 != "":
ret.append(hint8)
exp1 = _get_all_children(self._node, "sample")
hint = ""
hint2 = ""
for node1 in exp1:
exp2 = _get_all_children(node1, "type")
if "targetId" in exp2[0].attrib:
del exp2[0].attrib["targetId"]
hint = "Migration to v1.2 deleted sample type \"targetId\" attribute."
for elCount in range(1, len(exp2)):
node1.remove(exp2[elCount])
hint2 = "Migration to v1.2 deleted sample \"type\" elements."
if hint != "":
ret.append(hint)
if hint2 != "":
ret.append(hint2)
exp1 = _get_all_children(self._node, "target")
hint = ""
for node1 in exp1:
exp2 = _get_all_children(node1, "meltingTemperature")
for node2 in exp2:
node1.remove(node2)
hint = "Migration to v1.2 deleted target \"meltingTemperature\" elements."
if hint != "":
ret.append(hint)
exp1 = _get_all_children(self._node, "dye")
hint = ""
for node1 in exp1:
exp2 = _get_all_children(node1, "dyeChemistry")
for node2 in exp2:
node1.remove(node2)
hint = "Migration to v1.2 deleted dye \"dyeChemistry\" elements."
if hint != "":
ret.append(hint)
self._node.attrib['version'] = "1.2"
return ret
def recreate_lost_ids(self):
"""Searches for lost ids and repairs them.
Args:
self: The class self parameter.
Returns:
A string with the modifications.
"""
mess = ""
# Find lost dyes
foundIds = {}
allTar = _get_all_children(self._node, "target")
for node in allTar:
forId = _get_first_child(node, "dyeId")
if forId is not None:
foundIds[forId.attrib['id']] = 0
presentIds = []
exp = _get_all_children(self._node, "dye")
for node in exp:
presentIds.append(node.attrib['id'])
for used_id in foundIds:
if used_id not in presentIds:
self.new_dye(id=used_id, newposition=0)
mess += "Recreated new dye: " + used_id + "\n"
# Find lost thermalCycCon
foundIds = {}
allSam = _get_all_children(self._node, "sample")
for node in allSam:
subNode = _get_first_child(node, "cdnaSynthesisMethod")
if subNode is not None:
forId = _get_first_child(node, "thermalCyclingConditions")
if forId is not None:
foundIds[forId.attrib['id']] = 0
allExp = _get_all_children(self._node, "experiment")
for node in allExp:
subNodes = _get_all_children(node, "run")
for subNode in subNodes:
forId = _get_first_child(subNode, "thermalCyclingConditions")
if forId is not None:
foundIds[forId.attrib['id']] = 0
presentIds = []
exp = _get_all_children(self._node, "thermalCyclingConditions")
for node in exp:
presentIds.append(node.attrib['id'])
for used_id in foundIds:
if used_id not in presentIds:
self.new_therm_cyc_cons(id=used_id, newposition=0)
mess += "Recreated thermal cycling conditions: " + used_id + "\n"
# Find lost experimenter
foundIds = {}
allTh = _get_all_children(self._node, "thermalCyclingConditions")
for node in allTh:
subNodes = _get_all_children(node, "experimenter")
for subNode in subNodes:
foundIds[subNode.attrib['id']] = 0
allExp = _get_all_children(self._node, "experiment")
for node in allExp:
subNodes = _get_all_children(node, "run")
for subNode in subNodes:
lastNodes = _get_all_children(subNode, "experimenter")
for lastNode in lastNodes:
foundIds[lastNode.attrib['id']] = 0
presentIds = []
exp = _get_all_children(self._node, "experimenter")
for node in exp:
presentIds.append(node.attrib['id'])
for used_id in foundIds:
if used_id not in presentIds:
self.new_experimenter(id=used_id, firstName="unknown first name", lastName="unknown last name", newposition=0)
mess += "Recreated experimenter: " + used_id + "\n"
# Find lost documentation
foundIds = {}
allSam = _get_all_children(self._node, "sample")
for node in allSam:
subNodes = _get_all_children(node, "documentation")
for subNode in subNodes:
foundIds[subNode.attrib['id']] = 0
allTh = _get_all_children(self._node, "target")
for node in allTh:
subNodes = _get_all_children(node, "documentation")
for subNode in subNodes:
foundIds[subNode.attrib['id']] = 0
allTh = _get_all_children(self._node, "thermalCyclingConditions")
for node in allTh:
subNodes = _get_all_children(node, "documentation")
for subNode in subNodes:
foundIds[subNode.attrib['id']] = 0
allExp = _get_all_children(self._node, "experiment")
for node in allExp:
subNodes = _get_all_children(node, "documentation")
for subNode in subNodes:
foundIds[subNode.attrib['id']] = 0
subNodes = _get_all_children(node, "run")
for subNode in subNodes:
lastNodes = _get_all_children(subNode, "documentation")
for lastNode in lastNodes:
foundIds[lastNode.attrib['id']] = 0
presentIds = []
exp = _get_all_children(self._node, "documentation")
for node in exp:
presentIds.append(node.attrib['id'])
for used_id in foundIds:
if used_id not in presentIds:
self.new_documentation(id=used_id, newposition=0)
mess += "Recreated documentation: " + used_id + "\n"
# Find lost sample
foundIds = {}
allExp = _get_all_children(self._node, "experiment")
for node in allExp:
subNodes = _get_all_children(node, "run")
for subNode in subNodes:
reactNodes = _get_all_children(subNode, "react")
for reactNode in reactNodes:
lastNodes = _get_all_children(reactNode, "sample")
for lastNode in lastNodes:
foundIds[lastNode.attrib['id']] = 0
presentIds = []
exp = _get_all_children(self._node, "sample")
for node in exp:
presentIds.append(node.attrib['id'])
for used_id in foundIds:
if used_id not in presentIds:
self.new_sample(id=used_id, type="unkn", newposition=0)
mess += "Recreated sample: " + used_id + "\n"
# Find lost target
foundIds = {}
allExp = _get_all_children(self._node, "sample")
for node in allExp:
subNodes = _get_all_children(node, "type")
for subNode in subNodes:
if "targetId" in subNode.attrib:
foundIds[subNode.attrib['targetId']] = 0
allExp = _get_all_children(self._node, "experiment")
for node in allExp:
subNodes = _get_all_children(node, "run")
for subNode in subNodes:
reactNodes = _get_all_children(subNode, "react")
for reactNode in reactNodes:
dataNodes = _get_all_children(reactNode, "data")
for dataNode in dataNodes:
lastNodes = _get_all_children(dataNode, "tar")
for lastNode in lastNodes:
foundIds[lastNode.attrib['id']] = 0
partNodes = _get_all_children(reactNode, "partitions")
for partNode in partNodes:
dataNodes = _get_all_children(partNode, "data")
for dataNode in dataNodes:
lastNodes = _get_all_children(dataNode, "tar")
for lastNode in lastNodes:
foundIds[lastNode.attrib['id']] = 0
# Search in Table files
if self._rdmlFilename is not None and self._rdmlFilename != "":
if zipfile.is_zipfile(self._rdmlFilename):
zf = zipfile.ZipFile(self._rdmlFilename, 'r')
for item in zf.infolist():
if re.search("^partitions/", item.filename):
fileContent = zf.read(item.filename).decode('utf-8')
newlineFix = fileContent.replace("\r\n", "\n")
tabLines = newlineFix.split("\n")
header = tabLines[0].split("\t")
for cell in header:
if cell != "":
foundIds[cell] = 0
zf.close()
presentIds = []
exp = _get_all_children(self._node, "target")
for node in exp:
presentIds.append(node.attrib['id'])
for used_id in foundIds:
if used_id not in presentIds:
self.new_target(id=used_id, type="toi", newposition=0)
mess += "Recreated target: " + used_id + "\n"
return mess
def repair_rdml_file(self):
"""Searches for known errors and repairs them.
Args:
self: The class self parameter.
Returns:
A string with the modifications.
"""
mess = ""
mess += self.fixExclFalse()
mess += self.fixDuplicateReact()
return mess
def fixExclFalse(self):
"""Searches in experiment-run-react-data for excl=false and deletes the elements.
Args:
self: The class self parameter.
Returns:
A string with the modifications.
"""
mess = ""
count = 0
allExp = _get_all_children(self._node, "experiment")
for node in allExp:
subNodes = _get_all_children(node, "run")
for subNode in subNodes:
reactNodes = _get_all_children(subNode, "react")
for reactNode in reactNodes:
dataNodes = _get_all_children(reactNode, "data")
for dataNode in dataNodes:
lastNodes = _get_all_children(dataNode, "excl")
for lastNode in lastNodes:
if lastNode.text.lower() == "false":
count += 1
dataNode.remove(lastNode)
if count > 0:
mess = "The element excl=false was removed " + str(count) + " times!\n"
return mess
def fixDuplicateReact(self):
"""Searches in experiment-run-react for duplicates and keeps only the first.
Args:
self: The class self parameter.
Returns:
A string with the modifications.
"""
mess = ""
foundIds = {}
count = 0
allExp = _get_all_children(self._node, "experiment")
for node in allExp:
subNodes = _get_all_children(node, "run")
for subNode in subNodes:
reactNodes = _get_all_children(subNode, "react")
for reactNode in reactNodes:
tId = reactNode.attrib['id']
if tId not in foundIds:
foundIds[tId] = 0
else:
count += 1
subNode.remove(reactNode)
if count > 0:
mess = str(count) + " duplicate react elements were removed!\n"
return mess
def rdmlids(self):
"""Returns a list of all rdml id elements.
Args:
self: The class self parameter.
Returns:
A list of all rdml id elements.
"""
exp = _get_all_children(self._node, "id")
ret = []
for node in exp:
ret.append(Rdmlid(node))
return ret
def new_rdmlid(self, publisher, serialNumber, MD5Hash=None, newposition=None):
"""Creates a new rdml id element.
Args:
self: The class self parameter.
publisher: Publisher who created the serialNumber (required)
serialNumber: Serial Number for this file provided by publisher (required)
MD5Hash: A MD5 hash for this file (optional)
newposition: The new position of the element in the list (optional)
Returns:
Nothing, changes self.
"""
new_node = et.Element("id")
_add_new_subelement(new_node, "id", "publisher", publisher, False)
_add_new_subelement(new_node, "id", "serialNumber", serialNumber, False)
_add_new_subelement(new_node, "id", "MD5Hash", MD5Hash, True)
place = _get_tag_pos(self._node, "id", self.xmlkeys(), newposition)
self._node.insert(place, new_node)
def move_rdmlid(self, oldposition, newposition):
"""Moves the element to the new position in the list.
Args:
self: The class self parameter.
oldposition: The old position of the element
newposition: The new position of the element
Returns:
No return value, changes self. Function may raise RdmlError if required.
"""
pos = _get_tag_pos(self._node, "id", self.xmlkeys(), newposition)
ele = _get_first_child_by_pos_or_id(self._node, "id", None, oldposition)
self._node.insert(pos, ele)
def get_rdmlid(self, byposition=None):
"""Returns an experimenter element by position or id.
Args:
self: The class self parameter.
byposition: Select the element by position in the list.
Returns:
The found element or None.
"""
return Rdmlid(_get_first_child_by_pos_or_id(self._node, "id", None, byposition))
def delete_rdmlid(self, byposition=None):
"""Deletes an experimenter element.
Args:
self: The class self parameter.
byposition: Select the element by position in the list.
Returns:
Nothing, changes self.
"""
elem = _get_first_child_by_pos_or_id(self._node, "id", None, byposition)
self._node.remove(elem)
def experimenters(self):
"""Returns a list of all experimenter elements.
Args:
self: The class self parameter.
Returns:
A list of all experimenter elements.
"""
exp = _get_all_children(self._node, "experimenter")
ret = []
for node in exp:
ret.append(Experimenter(node))
return ret
def new_experimenter(self, id, firstName, lastName, email=None, labName=None, labAddress=None, newposition=None):
"""Creates a new experimenter element.
Args:
self: The class self parameter.
id: Experimenter unique id
firstName: Experimenters first name (required)
lastName: Experimenters last name (required)
email: Experimenters email (optional)
labName: Experimenters lab name (optional)
labAddress: Experimenters lab address (optional)
newposition: Experimenters position in the list of experimenters (optional)
Returns:
Nothing, changes self.
"""
new_node = _create_new_element(self._node, "experimenter", id)
_add_new_subelement(new_node, "experimenter", "firstName", firstName, False)
_add_new_subelement(new_node, "experimenter", "lastName", lastName, False)
_add_new_subelement(new_node, "experimenter", "email", email, True)
_add_new_subelement(new_node, "experimenter", "labName", labName, True)
_add_new_subelement(new_node, "experimenter", "labAddress", labAddress, True)
place = _get_tag_pos(self._node, "experimenter", self.xmlkeys(), newposition)
self._node.insert(place, new_node)
def move_experimenter(self, id, newposition):
"""Moves the element to the new position in the list.
Args:
self: The class self parameter.
id: Experimenter unique id
newposition: The new position of the element
Returns:
No return value, changes self. Function may raise RdmlError if required.
"""
_move_subelement(self._node, "experimenter", id, self.xmlkeys(), newposition)
def get_experimenter(self, byid=None, byposition=None):
"""Returns an experimenter element by position or id.
Args:
self: The class self parameter.
byid: Select the element by the element id.
byposition: Select the element by position in the list.
Returns:
The found element or None.
"""
return Experimenter(_get_first_child_by_pos_or_id(self._node, "experimenter", byid, byposition))
def delete_experimenter(self, byid=None, byposition=None):
"""Deletes an experimenter element.
Args:
self: The class self parameter.
byid: Select the element by the element id.
byposition: Select the element by position in the list.
Returns:
Nothing, changes self.
"""
elem = _get_first_child_by_pos_or_id(self._node, "experimenter", byid, byposition)
self._node.remove(elem)
def documentations(self):
"""Returns a list of all documentation elements.
Args:
self: The class self parameter.
Returns:
A list of all documentation elements.
"""
exp = _get_all_children(self._node, "documentation")
ret = []
for node in exp:
ret.append(Documentation(node))
return ret
def new_documentation(self, id, text=None, newposition=None):
"""Creates a new documentation element.
Args:
self: The class self parameter.
id: Documentation unique id
text: Documentation descriptive test (optional)
newposition: Experimenters position in the list of experimenters (optional)
Returns:
Nothing, changes self.
"""
new_node = _create_new_element(self._node, "documentation", id)
_add_new_subelement(new_node, "documentation", "text", text, True)
place = _get_tag_pos(self._node, "documentation", self.xmlkeys(), newposition)
self._node.insert(place, new_node)
def move_documentation(self, id, newposition):
"""Moves the element to the new position in the list.
Args:
self: The class self parameter.
id: Documentation unique id
newposition: The new position of the element
Returns:
No return value, changes self. Function may raise RdmlError if required.
"""
_move_subelement(self._node, "documentation", id, self.xmlkeys(), newposition)
def get_documentation(self, byid=None, byposition=None):
"""Returns an documentation element by position or id.
Args:
self: The class self parameter.
byid: Select the element by the element id.
byposition: Select the element by position in the list.
Returns:
The found element or None.
"""
return Documentation(_get_first_child_by_pos_or_id(self._node, "documentation", byid, byposition))
def delete_documentation(self, byid=None, byposition=None):
"""Deletes an documentation element.
Args:
self: The class self parameter.
byid: Select the element by the element id.
byposition: Select the element by position in the list.
Returns:
Nothing, changes self.
"""
elem = _get_first_child_by_pos_or_id(self._node, "documentation", byid, byposition)
self._node.remove(elem)
def dyes(self):
"""Returns a list of all dye elements.
Args:
self: The class self parameter.
Returns:
A list of all dye elements.
"""
exp = _get_all_children(self._node, "dye")
ret = []
for node in exp:
ret.append(Dye(node))
return ret
def new_dye(self, id, description=None, newposition=None):
"""Creates a new dye element.
Args:
self: The class self parameter.
id: Dye unique id
description: Dye descriptive test (optional)
newposition: Dye position in the list of dyes (optional)
Returns:
Nothing, changes self.
"""
new_node = _create_new_element(self._node, "dye", id)
_add_new_subelement(new_node, "dye", "description", description, True)
place = _get_tag_pos(self._node, "dye", self.xmlkeys(), newposition)
self._node.insert(place, new_node)
def move_dye(self, id, newposition):
"""Moves the element to the new position in the list.
Args:
self: The class self parameter.
id: Dye unique id
newposition: The new position of the element
Returns:
No return value, changes self. Function may raise RdmlError if required.
"""
_move_subelement(self._node, "dye", id, self.xmlkeys(), newposition)
def get_dye(self, byid=None, byposition=None):
"""Returns an dye element by position or id.
Args:
self: The class self parameter.
byid: Select the element by the element id.
byposition: Select the element by position in the list.
Returns:
The found element or None.
"""
return Dye(_get_first_child_by_pos_or_id(self._node, "dye", byid, byposition))
def delete_dye(self, byid=None, byposition=None):
"""Deletes an dye element.
Args:
self: The class self parameter.
byid: Select the element by the element id.
byposition: Select the element by position in the list.
Returns:
Nothing, changes self.
"""
elem = _get_first_child_by_pos_or_id(self._node, "dye", byid, byposition)
self._node.remove(elem)
def samples(self):
"""Returns a list of all sample elements.
Args:
self: The class self parameter.
Returns:
A list of all sample elements.
"""
exp = _get_all_children(self._node, "sample")
ret = []
for node in exp:
ret.append(Sample(node))
return ret
def new_sample(self, id, type, targetId=None, newposition=None):
"""Creates a new sample element.
Args:
self: The class self parameter.
id: Sample unique id (required)
type: Sample type (required)
targetId: The target linked to the type (makes sense in "pos" or "ntp" context) (optional)
newposition: Experimenters position in the list of experimenters (optional)
Returns:
Nothing, changes self.
"""
if type not in ["unkn", "ntc", "nac", "std", "ntp", "nrt", "pos", "opt"]:
raise RdmlError('Unknown or unsupported sample type value "' + type + '".')
new_node = _create_new_element(self._node, "sample", id)
typeEL = et.SubElement(new_node, "type")
typeEL.text = type
ver = self._node.get('version')
if ver == "1.3":
if targetId is not None:
if not targetId == "":
typeEL.attrib["targetId"] = targetId
place = _get_tag_pos(self._node, "sample", self.xmlkeys(), newposition)
self._node.insert(place, new_node)
def move_sample(self, id, newposition):
"""Moves the element to the new position in the list.
Args:
self: The class self parameter.
id: Sample unique id
newposition: The new position of the element
Returns:
No return value, changes self. Function may raise RdmlError if required.
"""
_move_subelement(self._node, "sample", id, self.xmlkeys(), newposition)
def get_sample(self, byid=None, byposition=None):
"""Returns an sample element by position or id.
Args:
self: The class self parameter.
byid: Select the element by the element id.
byposition: Select the element by position in the list.
Returns:
The found element or None.
"""
return Sample(_get_first_child_by_pos_or_id(self._node, "sample", byid, byposition))
def delete_sample(self, byid=None, byposition=None):
"""Deletes an sample element.
Args:
self: The class self parameter.
byid: Select the element by the element id.
byposition: Select the element by position in the list.
Returns:
Nothing, changes self.
"""
elem = _get_first_child_by_pos_or_id(self._node, "sample", byid, byposition)
self._node.remove(elem)
def targets(self):
"""Returns a list of all target elements.
Args:
self: The class self parameter.
Returns:
A list of all target elements.
"""
exp = _get_all_children(self._node, "target")
ret = []
for node in exp:
ret.append(Target(node, self._rdmlFilename))
return ret
def new_target(self, id, type, newposition=None):
"""Creates a new target element.
Args:
self: The class self parameter.
id: Target unique id (required)
type: Target type (required)
newposition: Targets position in the list of targets (optional)
Returns:
Nothing, changes self.
"""
if type not in ["ref", "toi"]:
raise RdmlError('Unknown or unsupported target type value "' + type + '".')
new_node = _create_new_element(self._node, "target", id)
_add_new_subelement(new_node, "target", "type", type, False)
place = _get_tag_pos(self._node, "target", self.xmlkeys(), newposition)
self._node.insert(place, new_node)
def move_target(self, id, newposition):
"""Moves the element to the new position in the list.
Args:
self: The class self parameter.
id: Target unique id
newposition: The new position of the element
Returns:
No return value, changes self. Function may raise RdmlError if required.
"""
_move_subelement(self._node, "target", id, self.xmlkeys(), newposition)
def get_target(self, byid=None, byposition=None):
"""Returns an target element by position or id.
Args:
self: The class self parameter.
byid: Select the element by the element id.
byposition: Select the element by position in the list.
Returns:
The found element or None.
"""
return Target(_get_first_child_by_pos_or_id(self._node, "target", byid, byposition), self._rdmlFilename)
def delete_target(self, byid=None, byposition=None):
"""Deletes an target element.
Args:
self: The class self parameter.
byid: Select the element by the element id.
byposition: Select the element by position in the list.
Returns:
Nothing, changes self.
"""
elem = _get_first_child_by_pos_or_id(self._node, "target", byid, byposition)
self._node.remove(elem)
def therm_cyc_cons(self):
"""Returns a list of all thermalCyclingConditions elements.
Args:
self: The class self parameter.
Returns:
A list of all target elements.
"""
exp = _get_all_children(self._node, "thermalCyclingConditions")
ret = []
for node in exp:
ret.append(Therm_cyc_cons(node))
return ret
def new_therm_cyc_cons(self, id, newposition=None):
"""Creates a new thermalCyclingConditions element.
Args:
self: The class self parameter.
id: ThermalCyclingConditions unique id (required)
newposition: ThermalCyclingConditions position in the list of ThermalCyclingConditions (optional)
Returns:
Nothing, changes self.
"""
new_node = _create_new_element(self._node, "thermalCyclingConditions", id)
step = et.SubElement(new_node, "step")
et.SubElement(step, "nr").text = "1"
et.SubElement(step, "lidOpen")
place = _get_tag_pos(self._node, "thermalCyclingConditions", self.xmlkeys(), newposition)
self._node.insert(place, new_node)
def move_therm_cyc_cons(self, id, newposition):
"""Moves the element to the new position in the list.
Args:
self: The class self parameter.
id: ThermalCyclingConditions unique id
newposition: The new position of the element
Returns:
No return value, changes self. Function may raise RdmlError if required.
"""
_move_subelement(self._node, "thermalCyclingConditions", id, self.xmlkeys(), newposition)
def get_therm_cyc_cons(self, byid=None, byposition=None):
"""Returns an thermalCyclingConditions element by position or id.
Args:
self: The class self parameter.
byid: Select the element by the element id.
byposition: Select the element by position in the list.
Returns:
The found element or None.
"""
return Therm_cyc_cons(_get_first_child_by_pos_or_id(self._node, "thermalCyclingConditions", byid, byposition))
def delete_therm_cyc_cons(self, byid=None, byposition=None):
"""Deletes an thermalCyclingConditions element.
Args:
self: The class self parameter.
byid: Select the element by the element id.
byposition: Select the element by position in the list.
Returns:
Nothing, changes self.
"""
elem = _get_first_child_by_pos_or_id(self._node, "thermalCyclingConditions", byid, byposition)
self._node.remove(elem)
def experiments(self):
"""Returns a list of all experiment elements.
Args:
self: The class self parameter.
Returns:
A list of all experiment elements.
"""
exp = _get_all_children(self._node, "experiment")
ret = []
for node in exp:
ret.append(Experiment(node, self._rdmlFilename))
return ret
def new_experiment(self, id, newposition=None):
"""Creates a new experiment element.
Args:
self: The class self parameter.
id: Experiment unique id (required)
newposition: Experiment position in the list of experiments (optional)
Returns:
Nothing, changes self.
"""
new_node = _create_new_element(self._node, "experiment", id)
place = _get_tag_pos(self._node, "experiment", self.xmlkeys(), newposition)
self._node.insert(place, new_node)
def move_experiment(self, id, newposition):
"""Moves the element to the new position in the list.
Args:
self: The class self parameter.
id: Experiments unique id
newposition: The new position of the element
Returns:
No return value, changes self. Function may raise RdmlError if required.
"""
_move_subelement(self._node, "experiment", id, self.xmlkeys(), newposition)
def get_experiment(self, byid=None, byposition=None):
"""Returns an experiment element by position or id.
Args:
self: The class self parameter.
byid: Select the element by the element id.
byposition: Select the element by position in the list.
Returns:
The found element or None.
"""
return Experiment(_get_first_child_by_pos_or_id(self._node, "experiment", byid, byposition), self._rdmlFilename)
def delete_experiment(self, byid=None, byposition=None):
"""Deletes an experiment element.
Args:
self: The class self parameter.
byid: Select the element by the element id.
byposition: Select the element by position in the list.
Returns:
Nothing, changes self.
"""
elem = _get_first_child_by_pos_or_id(self._node, "experiment", byid, byposition)
experiment = Experiment(elem, self._rdmlFilename)
# Required to delete digital files
runs = _get_all_children(elem, "run")
for node in runs:
run = Run(node, self._rdmlFilename)
experiment.delete_run(byid=run["id"])
# Now delete the experiment element
self._node.remove(elem)
def tojson(self):
"""Returns a json of the RDML object without fluorescence data.
Args:
self: The class self parameter.
Returns:
A json of the data.
"""
allRdmlids = self.rdmlids()
rdmlids = []
for elem in allRdmlids:
rdmlids.append(elem.tojson())
allExperimenters = self.experimenters()
experimenters = []
for exp in allExperimenters:
experimenters.append(exp.tojson())
allDocumentations = self.documentations()
documentations = []
for exp in allDocumentations:
documentations.append(exp.tojson())
allDyes = self.dyes()
dyes = []
for exp in allDyes:
dyes.append(exp.tojson())
allSamples = self.samples()
samples = []
for exp in allSamples:
samples.append(exp.tojson())
allTargets = self.targets()
targets = []
for exp in allTargets:
targets.append(exp.tojson())
allTherm_cyc_cons = self.therm_cyc_cons()
therm_cyc_cons = []
for exp in allTherm_cyc_cons:
therm_cyc_cons.append(exp.tojson())
allExperiments = self.experiments()
experiments = []
for exp in allExperiments:
experiments.append(exp.tojson())
data = {
"rdml": {
"version": self["version"],
"dateMade": self["dateMade"],
"dateUpdated": self["dateUpdated"],
"ids": rdmlids,
"experimenters": experimenters,
"documentations": documentations,
"dyes": dyes,
"samples": samples,
"targets": targets,
"therm_cyc_cons": therm_cyc_cons,
"experiments": experiments
}
}
return data
class Rdmlid:
"""RDML-Python library
The rdml id element used to read and edit one experimenter.
Attributes:
_node: The rdml id node of the RDML XML object.
"""
def __init__(self, node):
"""Inits an rdml id instance.
Args:
self: The class self parameter.
node: The experimenter node.
Returns:
No return value. Function may raise RdmlError if required.
"""
self._node = node
def __getitem__(self, key):
"""Returns the value for the key.
Args:
self: The class self parameter.
key: The key of the experimenter subelement
Returns:
A string of the data or None.
"""
if key in ["publisher", "serialNumber"]:
return _get_first_child_text(self._node, key)
if key in ["MD5Hash"]:
var = _get_first_child_text(self._node, key)
if var == "":
return None
else:
return var
raise KeyError
def __setitem__(self, key, value):
"""Changes the value for the key.
Args:
self: The class self parameter.
key: The key of the experimenter subelement
value: The new value for the key
Returns:
No return value, changes self. Function may raise RdmlError if required.
"""
if key in ["publisher", "serialNumber"]:
return _change_subelement(self._node, key, self.xmlkeys(), value, False, "string")
if key in ["MD5Hash"]:
return _change_subelement(self._node, key, self.xmlkeys(), value, True, "string")
raise KeyError
def keys(self):
"""Returns a list of the keys.
Args:
self: The class self parameter.
Returns:
A list of the key strings.
"""
return ["publisher", "serialNumber", "MD5Hash"]
def xmlkeys(self):
"""Returns a list of the keys in the xml file.
Args:
self: The class self parameter.
Returns:
A list of the key strings.
"""
return self.keys()
def tojson(self):
"""Returns a json of the RDML object without fluorescence data.
Args:
self: The class self parameter.
Returns:
A json of the data.
"""
data = {
"publisher": _get_first_child_text(self._node, "publisher"),
"serialNumber": _get_first_child_text(self._node, "serialNumber")
}
_add_first_child_to_dic(self._node, data, True, "MD5Hash")
return data
class Experimenter:
"""RDML-Python library
The experimenter element used to read and edit one experimenter.
Attributes:
_node: The experimenter node of the RDML XML object.
"""
def __init__(self, node):
"""Inits an experimenter instance.
Args:
self: The class self parameter.
node: The experimenter node.
Returns:
No return value. Function may raise RdmlError if required.
"""
self._node = node
def __getitem__(self, key):
"""Returns the value for the key.
Args:
self: The class self parameter.
key: The key of the experimenter subelement
Returns:
A string of the data or None.
"""
if key == "id":
return self._node.get('id')
if key in ["firstName", "lastName"]:
return _get_first_child_text(self._node, key)
if key in ["email", "labName", "labAddress"]:
var = _get_first_child_text(self._node, key)
if var == "":
return None
else:
return var
raise KeyError
def __setitem__(self, key, value):
"""Changes the value for the key.
Args:
self: The class self parameter.
key: The key of the experimenter subelement
value: The new value for the key
Returns:
No return value, changes self. Function may raise RdmlError if required.
"""
if key == "id":
self.change_id(value, merge_with_id=False)
return
if key in ["firstName", "lastName"]:
return _change_subelement(self._node, key, self.xmlkeys(), value, False, "string")
if key in ["email", "labName", "labAddress"]:
return _change_subelement(self._node, key, self.xmlkeys(), value, True, "string")
raise KeyError
def change_id(self, value, merge_with_id=False):
"""Changes the value for the id.
Args:
self: The class self parameter.
value: The new value for the id.
merge_with_id: If True only allow a unique id, if False only rename its uses with existing id.
Returns:
No return value, changes self. Function may raise RdmlError if required.
"""
oldValue = self._node.get('id')
if oldValue != value:
par = self._node.getparent()
if not _string_to_bool(merge_with_id, triple=False):
_change_subelement(self._node, "id", self.xmlkeys(), value, False, "string")
else:
groupTag = self._node.tag.replace("{http://www.rdml.org}", "")
if _check_unique_id(par, groupTag, value):
raise RdmlError('The ' + groupTag + ' id "' + value + '" does not exist.')
allTh = _get_all_children(par, "thermalCyclingConditions")
for node in allTh:
subNodes = _get_all_children(node, "experimenter")
for subNode in subNodes:
if subNode.attrib['id'] == oldValue:
subNode.attrib['id'] = value
allExp = _get_all_children(par, "experiment")
for node in allExp:
subNodes = _get_all_children(node, "run")
for subNode in subNodes:
lastNodes = _get_all_children(subNode, "experimenter")
for lastNode in lastNodes:
if lastNode.attrib['id'] == oldValue:
lastNode.attrib['id'] = value
return
def keys(self):
"""Returns a list of the keys.
Args:
self: The class self parameter.
Returns:
A list of the key strings.
"""
return ["id", "firstName", "lastName", "email", "labName", "labAddress"]
def xmlkeys(self):
"""Returns a list of the keys in the xml file.
Args:
self: The class self parameter.
Returns:
A list of the key strings.
"""
return self.keys()
def tojson(self):
"""Returns a json of the RDML object without fluorescence data.
Args:
self: The class self parameter.
Returns:
A json of the data.
"""
data = {
"id": self._node.get('id'),
"firstName": _get_first_child_text(self._node, "firstName"),
"lastName": _get_first_child_text(self._node, "lastName")
}
_add_first_child_to_dic(self._node, data, True, "email")
_add_first_child_to_dic(self._node, data, True, "labName")
_add_first_child_to_dic(self._node, data, True, "labAddress")
return data
class Documentation:
"""RDML-Python library
The documentation element used to read and edit one documentation tag.
Attributes:
_node: The documentation node of the RDML XML object.
"""
def __init__(self, node):
"""Inits an documentation instance.
Args:
self: The class self parameter.
node: The documentation node.
Returns:
No return value. Function may raise RdmlError if required.
"""
self._node = node
def __getitem__(self, key):
"""Returns the value for the key.
Args:
self: The class self parameter.
key: The key of the documentation subelement
Returns:
A string of the data or None.
"""
if key == "id":
return self._node.get('id')
if key == "text":
var = _get_first_child_text(self._node, key)
if var == "":
return None
else:
return var
raise KeyError
def __setitem__(self, key, value):
"""Changes the value for the key.
Args:
self: The class self parameter.
key: The key of the documentation subelement
value: The new value for the key
Returns:
No return value, changes self. Function may raise RdmlError if required.
"""
if key == "id":
self.change_id(value, merge_with_id=False)
return
if key == "text":
return _change_subelement(self._node, key, self.xmlkeys(), value, True, "string")
raise KeyError
def change_id(self, value, merge_with_id=False):
"""Changes the value for the id.
Args:
self: The class self parameter.
value: The new value for the id.
merge_with_id: If True only allow a unique id, if False only rename its uses with existing id.
Returns:
No return value, changes self. Function may raise RdmlError if required.
"""
oldValue = self._node.get('id')
if oldValue != value:
par = self._node.getparent()
if not _string_to_bool(merge_with_id, triple=False):
_change_subelement(self._node, "id", self.xmlkeys(), value, False, "string")
else:
groupTag = self._node.tag.replace("{http://www.rdml.org}", "")
if _check_unique_id(par, groupTag, value):
raise RdmlError('The ' + groupTag + ' id "' + value + '" does not exist.')
allSam = _get_all_children(par, "sample")
for node in allSam:
subNodes = _get_all_children(node, "documentation")
for subNode in subNodes:
if subNode.attrib['id'] == oldValue:
subNode.attrib['id'] = value
allTh = _get_all_children(par, "target")
for node in allTh:
subNodes = _get_all_children(node, "documentation")
for subNode in subNodes:
if subNode.attrib['id'] == oldValue:
subNode.attrib['id'] = value
allTh = _get_all_children(par, "thermalCyclingConditions")
for node in allTh:
subNodes = _get_all_children(node, "documentation")
for subNode in subNodes:
if subNode.attrib['id'] == oldValue:
subNode.attrib['id'] = value
allExp = _get_all_children(par, "experiment")
for node in allExp:
subNodes = _get_all_children(node, "documentation")
for subNode in subNodes:
if subNode.attrib['id'] == oldValue:
subNode.attrib['id'] = value
subNodes = _get_all_children(node, "run")
for subNode in subNodes:
lastNodes = _get_all_children(subNode, "documentation")
for lastNode in lastNodes:
if lastNode.attrib['id'] == oldValue:
lastNode.attrib['id'] = value
return
def keys(self):
"""Returns a list of the keys.
Args:
self: The class self parameter.
Returns:
A list of the key strings.
"""
return ["id", "text"]
def xmlkeys(self):
"""Returns a list of the keys in the xml file.
Args:
self: The class self parameter.
Returns:
A list of the key strings.
"""
return self.keys()
def tojson(self):
"""Returns a json of the RDML object without fluorescence data.
Args:
self: The class self parameter.
Returns:
A json of the data.
"""
data = {
"id": self._node.get('id'),
}
_add_first_child_to_dic(self._node, data, True, "text")
return data
class Dye:
"""RDML-Python library
The dye element used to read and edit one dye.
Attributes:
_node: The dye node of the RDML XML object.
"""
def __init__(self, node):
"""Inits an dye instance.
Args:
self: The class self parameter.
node: The dye node.
Returns:
No return value. Function may raise RdmlError if required.
"""
self._node = node
def __getitem__(self, key):
"""Returns the value for the key.
Args:
self: The class self parameter.
key: The key of the dye subelement
Returns:
A string of the data or None.
"""
if key == "id":
return self._node.get('id')
if key in ["description", "dyeChemistry"]:
var = _get_first_child_text(self._node, key)
if var == "":
return None
else:
return var
raise KeyError
def __setitem__(self, key, value):
"""Changes the value for the key.
Args:
self: The class self parameter.
key: The key of the dye subelement
value: The new value for the key
Returns:
No return value, changes self. Function may raise RdmlError if required.
"""
if key == "dyeChemistry":
if value not in ["non-saturating DNA binding dye", "saturating DNA binding dye", "hybridization probe",
"hydrolysis probe", "labelled forward primer", "labelled reverse primer",
"DNA-zyme probe"]:
raise RdmlError('Unknown or unsupported sample type value "' + value + '".')
if key == "id":
self.change_id(value, merge_with_id=False)
return
if key == "description":
return _change_subelement(self._node, key, self.xmlkeys(), value, True, "string")
par = self._node.getparent()
ver = par.get('version')
if ver == "1.3":
if key == "dyeChemistry":
return _change_subelement(self._node, key, self.xmlkeys(), value, True, "string")
raise KeyError
def change_id(self, value, merge_with_id=False):
"""Changes the value for the id.
Args:
self: The class self parameter.
value: The new value for the id.
merge_with_id: If True only allow a unique id, if False only rename its uses with existing id.
Returns:
No return value, changes self. Function may raise RdmlError if required.
"""
oldValue = self._node.get('id')
if oldValue != value:
par = self._node.getparent()
if not _string_to_bool(merge_with_id, triple=False):
_change_subelement(self._node, "id", self.xmlkeys(), value, False, "string")
else:
groupTag = self._node.tag.replace("{http://www.rdml.org}", "")
if _check_unique_id(par, groupTag, value):
raise RdmlError('The ' + groupTag + ' id "' + value + '" does not exist.')
allTar = _get_all_children(par, "target")
for node in allTar:
forId = _get_first_child(node, "dyeId")
if forId is not None:
if forId.attrib['id'] == oldValue:
forId.attrib['id'] = value
return
def keys(self):
"""Returns a list of the keys.
Args:
self: The class self parameter.
Returns:
A list of the key strings.
"""
return ["id", "description", "dyeChemistry"]
def xmlkeys(self):
"""Returns a list of the keys in the xml file.
Args:
self: The class self parameter.
Returns:
A list of the key strings.
"""
return self.keys()
def tojson(self):
"""Returns a json of the RDML object.
Args:
self: The class self parameter.
Returns:
A json of the data.
"""
data = {
"id": self._node.get('id'),
}
_add_first_child_to_dic(self._node, data, True, "description")
_add_first_child_to_dic(self._node, data, True, "dyeChemistry")
return data
class Sample:
"""RDML-Python library
The samples element used to read and edit one sample.
Attributes:
_node: The sample node of the RDML XML object.
"""
def __init__(self, node):
"""Inits an sample instance.
Args:
self: The class self parameter.
node: The sample node.
Returns:
No return value. Function may raise RdmlError if required.
"""
self._node = node
def __getitem__(self, key):
"""Returns the value for the key.
Args:
self: The class self parameter.
key: The key of the sample subelement
Returns:
A string of the data or None.
"""
if key == "id":
return self._node.get('id')
if key == "description":
var = _get_first_child_text(self._node, key)
if var == "":
return None
else:
return var
if key in ["interRunCalibrator", "calibratorSample"]:
return _get_first_child_bool(self._node, key, triple=True)
if key in ["cdnaSynthesisMethod_enzyme", "cdnaSynthesisMethod_primingMethod",
"cdnaSynthesisMethod_dnaseTreatment", "cdnaSynthesisMethod_thermalCyclingConditions"]:
ele = _get_first_child(self._node, "cdnaSynthesisMethod")
if ele is None:
return None
if key == "cdnaSynthesisMethod_enzyme":
return _get_first_child_text(ele, "enzyme")
if key == "cdnaSynthesisMethod_primingMethod":
return _get_first_child_text(ele, "primingMethod")
if key == "cdnaSynthesisMethod_dnaseTreatment":
return _get_first_child_text(ele, "dnaseTreatment")
if key == "cdnaSynthesisMethod_thermalCyclingConditions":
forId = _get_first_child(ele, "thermalCyclingConditions")
if forId is not None:
return forId.attrib['id']
else:
return None
raise RdmlError('Sample cdnaSynthesisMethod programming read error.')
if key == "quantity":
ele = _get_first_child(self._node, key)
vdic = {}
vdic["value"] = _get_first_child_text(ele, "value")
vdic["unit"] = _get_first_child_text(ele, "unit")
if len(vdic.keys()) != 0:
return vdic
else:
return None
par = self._node.getparent()
ver = par.get('version')
if ver == "1.1":
if key in ["templateRNAQuality", "templateDNAQuality"]:
ele = _get_first_child(self._node, key)
vdic = {}
vdic["method"] = _get_first_child_text(ele, "method")
vdic["result"] = _get_first_child_text(ele, "result")
if len(vdic.keys()) != 0:
return vdic
else:
return None
if key in ["templateRNAQuantity", "templateDNAQuantity"]:
ele = _get_first_child(self._node, key)
vdic = {}
vdic["value"] = _get_first_child_text(ele, "value")
vdic["unit"] = _get_first_child_text(ele, "unit")
if len(vdic.keys()) != 0:
return vdic
else:
return None
if ver == "1.2" or ver == "1.3":
if key == "templateQuantity":
ele = _get_first_child(self._node, key)
vdic = {}
vdic["nucleotide"] = _get_first_child_text(ele, "nucleotide")
vdic["conc"] = _get_first_child_text(ele, "conc")
if len(vdic.keys()) != 0:
return vdic
else:
return None
raise KeyError
def __setitem__(self, key, value):
"""Changes the value for the key.
Args:
self: The class self parameter.
key: The key of the sample subelement
value: The new value for the key
Returns:
No return value, changes self. Function may raise RdmlError if required.
"""
if key == "id":
self.change_id(value, merge_with_id=False)
return
if key == "description":
return _change_subelement(self._node, key, self.xmlkeys(), value, True, "string")
if key in ["interRunCalibrator", "calibratorSample"]:
return _change_subelement(self._node, key, self.xmlkeys(), value, True, "bool")
if key in ["cdnaSynthesisMethod_enzyme", "cdnaSynthesisMethod_primingMethod",
"cdnaSynthesisMethod_dnaseTreatment", "cdnaSynthesisMethod_thermalCyclingConditions"]:
ele = _get_or_create_subelement(self._node, "cdnaSynthesisMethod", self.xmlkeys())
if key == "cdnaSynthesisMethod_enzyme":
_change_subelement(ele, "enzyme",
["enzyme", "primingMethod", "dnaseTreatment", "thermalCyclingConditions"],
value, True, "string")
if key == "cdnaSynthesisMethod_primingMethod":
if value not in ["", "oligo-dt", "random", "target-specific", "oligo-dt and random", "other"]:
raise RdmlError('Unknown or unsupported sample ' + key + ' value "' + value + '".')
_change_subelement(ele, "primingMethod",
["enzyme", "primingMethod", "dnaseTreatment", "thermalCyclingConditions"],
value, True, "string")
if key == "cdnaSynthesisMethod_dnaseTreatment":
_change_subelement(ele, "dnaseTreatment",
["enzyme", "primingMethod", "dnaseTreatment", "thermalCyclingConditions"],
value, True, "bool")
if key == "cdnaSynthesisMethod_thermalCyclingConditions":
forId = _get_or_create_subelement(ele, "thermalCyclingConditions",
["enzyme", "primingMethod", "dnaseTreatment",
"thermalCyclingConditions"])
if value is not None and value != "":
# We do not check that ID is valid to allow recreate_lost_ids()
forId.attrib['id'] = value
else:
ele.remove(forId)
_remove_irrelevant_subelement(self._node, "cdnaSynthesisMethod")
return
if key == "quantity":
if value is None:
return
if "value" not in value or "unit" not in value:
raise RdmlError('Sample ' + key + ' must have a dictionary with "value" and "unit" as value.')
if value["unit"] not in ["", "cop", "fold", "dil", "ng", "nMol", "other"]:
raise RdmlError('Unknown or unsupported sample ' + key + ' value "' + value + '".')
ele = _get_or_create_subelement(self._node, key, self.xmlkeys())
_change_subelement(ele, "value", ["value", "unit"], value["value"], True, "float")
if value["value"] != "":
_change_subelement(ele, "unit", ["value", "unit"], value["unit"], True, "string")
else:
_change_subelement(ele, "unit", ["value", "unit"], "", True, "string")
_remove_irrelevant_subelement(self._node, key)
return
par = self._node.getparent()
ver = par.get('version')
if ver == "1.1":
if key in ["templateRNAQuality", "templateDNAQuality"]:
if value is None:
return
if "method" not in value or "result" not in value:
raise RdmlError('"' + key + '" must have a dictionary with "method" and "result" as value.')
ele = _get_or_create_subelement(self._node, key, self.xmlkeys())
_change_subelement(ele, "method", ["method", "result"], value["method"], True, "string")
_change_subelement(ele, "result", ["method", "result"], value["result"], True, "float")
_remove_irrelevant_subelement(self._node, key)
return
if key in ["templateRNAQuantity", "templateDNAQuantity"]:
if value is None:
return
if "value" not in value or "unit" not in value:
raise RdmlError('Sample ' + key + ' must have a dictionary with "value" and "unit" as value.')
if value["unit"] not in ["", "cop", "fold", "dil", "ng", "nMol", "other"]:
raise RdmlError('Unknown or unsupported sample ' + key + ' value "' + value + '".')
ele = _get_or_create_subelement(self._node, key, self.xmlkeys())
_change_subelement(ele, "value", ["value", "unit"], value["value"], True, "float")
if value["value"] != "":
_change_subelement(ele, "unit", ["value", "unit"], value["unit"], True, "string")
else:
_change_subelement(ele, "unit", ["value", "unit"], "", True, "string")
_remove_irrelevant_subelement(self._node, key)
return
if ver == "1.2" or ver == "1.3":
if key == "templateQuantity":
if value is None:
return
if "nucleotide" not in value or "conc" not in value:
raise RdmlError('Sample ' + key + ' must have a dictionary with "nucleotide" and "conc" as value.')
if value["nucleotide"] not in ["", "DNA", "genomic DNA", "cDNA", "RNA"]:
raise RdmlError('Unknown or unsupported sample ' + key + ' value "' + value + '".')
ele = _get_or_create_subelement(self._node, key, self.xmlkeys())
_change_subelement(ele, "conc", ["conc", "nucleotide"], value["conc"], True, "float")
if value["conc"] != "":
_change_subelement(ele, "nucleotide", ["conc", "nucleotide"], value["nucleotide"], True, "string")
else:
_change_subelement(ele, "nucleotide", ["conc", "nucleotide"], "", True, "string")
_remove_irrelevant_subelement(self._node, key)
return
raise KeyError
def change_id(self, value, merge_with_id=False):
"""Changes the value for the id.
Args:
self: The class self parameter.
value: The new value for the id.
merge_with_id: If True only allow a unique id, if False only rename its uses with existing id.
Returns:
No return value, changes self. Function may raise RdmlError if required.
"""
oldValue = self._node.get('id')
if oldValue != value:
par = self._node.getparent()
if not _string_to_bool(merge_with_id, triple=False):
_change_subelement(self._node, "id", self.xmlkeys(), value, False, "string")
else:
groupTag = self._node.tag.replace("{http://www.rdml.org}", "")
if _check_unique_id(par, groupTag, value):
raise RdmlError('The ' + groupTag + ' id "' + value + '" does not exist.')
allExp = _get_all_children(par, "experiment")
for node in allExp:
subNodes = _get_all_children(node, "run")
for subNode in subNodes:
reactNodes = _get_all_children(subNode, "react")
for reactNode in reactNodes:
lastNodes = _get_all_children(reactNode, "sample")
for lastNode in lastNodes:
if lastNode.attrib['id'] == oldValue:
lastNode.attrib['id'] = value
return
def keys(self):
"""Returns a list of the keys.
Args:
self: The class self parameter.
Returns:
A list of the key strings.
"""
par = self._node.getparent()
ver = par.get('version')
if ver == "1.1":
return ["id", "description", "interRunCalibrator", "quantity", "calibratorSample",
"cdnaSynthesisMethod_enzyme", "cdnaSynthesisMethod_primingMethod",
"cdnaSynthesisMethod_dnaseTreatment", "cdnaSynthesisMethod_thermalCyclingConditions",
"templateRNAQuantity", "templateRNAQuality", "templateDNAQuantity", "templateDNAQuality"]
return ["id", "description", "annotation", "interRunCalibrator", "quantity", "calibratorSample",
"cdnaSynthesisMethod_enzyme", "cdnaSynthesisMethod_primingMethod",
"cdnaSynthesisMethod_dnaseTreatment", "cdnaSynthesisMethod_thermalCyclingConditions",
"templateQuantity"]
def xmlkeys(self):
"""Returns a list of the keys in the xml file.
Args:
self: The class self parameter.
Returns:
A list of the key strings.
"""
par = self._node.getparent()
ver = par.get('version')
if ver == "1.1":
return ["description", "documentation", "xRef", "type", "interRunCalibrator",
"quantity", "calibratorSample", "cdnaSynthesisMethod",
"templateRNAQuantity", "templateRNAQuality", "templateDNAQuantity", "templateDNAQuality"]
return ["description", "documentation", "xRef", "annotation", "type", "interRunCalibrator",
"quantity", "calibratorSample", "cdnaSynthesisMethod", "templateQuantity"]
def types(self):
"""Returns a list of the types in the xml file.
Args:
self: The class self parameter.
Returns:
A list of dics with type and id strings.
"""
typesList = _get_all_children(self._node, "type")
ret = []
for node in typesList:
data = {}
data["type"] = node.text
if "targetId" in node.attrib:
data["targetId"] = node.attrib["targetId"]
else:
data["targetId"] = ""
ret.append(data)
return ret
def new_type(self, type, targetId=None, newposition=None):
"""Creates a new type element.
Args:
self: The class self parameter.
type: The "unkn", "ntc", "nac", "std", "ntp", "nrt", "pos" or "opt" type of sample
targetId: The target linked to the type (makes sense in "pos" or "ntp" context)
newposition: The new position of the element
Returns:
Nothing, changes self.
"""
if type not in ["unkn", "ntc", "nac", "std", "ntp", "nrt", "pos", "opt"]:
raise RdmlError('Unknown or unsupported sample type value "' + type + '".')
new_node = et.Element("type")
new_node.text = type
par = self._node.getparent()
ver = par.get('version')
if ver == "1.3":
if targetId is not None:
if not targetId == "":
new_node.attrib["targetId"] = targetId
place = _get_tag_pos(self._node, "type", self.xmlkeys(), newposition)
self._node.insert(place, new_node)
def edit_type(self, type, oldposition, newposition=None, targetId=None):
"""Edits a type element.
Args:
self: The class self parameter.
oldposition: The old position of the element
newposition: The new position of the element
type: The "unkn", "ntc", "nac", "std", "ntp", "nrt", "pos" or "opt" type of sample
targetId: The target linked to the type (makes sense in "pos" or "ntp" context)
Returns:
Nothing, changes self.
"""
if type not in ["unkn", "ntc", "nac", "std", "ntp", "nrt", "pos", "opt"]:
raise RdmlError('Unknown or unsupported sample type value "' + type + '".')
if oldposition is None:
raise RdmlError('A oldposition is required to edit a type.')
pos = _get_tag_pos(self._node, "type", self.xmlkeys(), newposition)
ele = _get_first_child_by_pos_or_id(self._node, "type", None, oldposition)
ele.text = type
par = self._node.getparent()
ver = par.get('version')
if "targetId" in ele.attrib:
del ele.attrib["targetId"]
if ver == "1.3":
if targetId is not None:
if not targetId == "":
ele.attrib["targetId"] = targetId
self._node.insert(pos, ele)
def move_type(self, oldposition, newposition):
"""Moves the element to the new position in the list.
Args:
self: The class self parameter.
oldposition: The old position of the element
newposition: The new position of the element
Returns:
No return value, changes self. Function may raise RdmlError if required.
"""
pos = _get_tag_pos(self._node, "type", self.xmlkeys(), newposition)
ele = _get_first_child_by_pos_or_id(self._node, "type", None, oldposition)
self._node.insert(pos, ele)
def delete_type(self, byposition):
"""Deletes an type element.
Args:
self: The class self parameter.
byposition: Select the element by position in the list.
Returns:
Nothing, changes self.
"""
ls = self.types()
if len(ls) < 2:
return
elem = _get_first_child_by_pos_or_id(self._node, "type", None, byposition)
self._node.remove(elem)
def xrefs(self):
"""Returns a list of the xrefs in the xml file.
Args:
self: The class self parameter.
Returns:
A list of dics with name and id strings.
"""
xref = _get_all_children(self._node, "xRef")
ret = []
for node in xref:
data = {}
_add_first_child_to_dic(node, data, True, "name")
_add_first_child_to_dic(node, data, True, "id")
ret.append(data)
return ret
def new_xref(self, name=None, id=None, newposition=None):
"""Creates a new xrefs element.
Args:
self: The class self parameter.
name: Publisher who created the xRef
id: Serial Number for this sample provided by publisher
newposition: The new position of the element
Returns:
Nothing, changes self.
"""
if name is None and id is None:
raise RdmlError('Either name or id is required to create a xRef.')
new_node = et.Element("xRef")
_add_new_subelement(new_node, "xRef", "name", name, True)
_add_new_subelement(new_node, "xRef", "id", id, True)
place = _get_tag_pos(self._node, "xRef", self.xmlkeys(), newposition)
self._node.insert(place, new_node)
def edit_xref(self, oldposition, newposition=None, name=None, id=None):
"""Creates a new xrefs element.
Args:
self: The class self parameter.
oldposition: The old position of the element
newposition: The new position of the element
name: Publisher who created the xRef
id: Serial Number for this sample provided by publisher
Returns:
Nothing, changes self.
"""
if oldposition is None:
raise RdmlError('A oldposition is required to edit a xRef.')
if (name is None or name == "") and (id is None or id == ""):
self.delete_xref(oldposition)
return
pos = _get_tag_pos(self._node, "xRef", self.xmlkeys(), newposition)
ele = _get_first_child_by_pos_or_id(self._node, "xRef", None, oldposition)
_change_subelement(ele, "name", ["name", "id"], name, True, "string")
_change_subelement(ele, "id", ["name", "id"], id, True, "string", id_as_element=True)
self._node.insert(pos, ele)
def move_xref(self, oldposition, newposition):
"""Moves the element to the new position in the list.
Args:
self: The class self parameter.
oldposition: The old position of the element
newposition: The new position of the element
Returns:
No return value, changes self. Function may raise RdmlError if required.
"""
pos = _get_tag_pos(self._node, "xRef", self.xmlkeys(), newposition)
ele = _get_first_child_by_pos_or_id(self._node, "xRef", None, oldposition)
self._node.insert(pos, ele)
def delete_xref(self, byposition):
"""Deletes an experimenter element.
Args:
self: The class self parameter.
byposition: Select the element by position in the list.
Returns:
Nothing, changes self.
"""
elem = _get_first_child_by_pos_or_id(self._node, "xRef", None, byposition)
self._node.remove(elem)
def annotations(self):
"""Returns a list of the annotations in the xml file.
Args:
self: The class self parameter.
Returns:
A list of dics with property and value strings.
"""
par = self._node.getparent()
ver = par.get('version')
if ver == "1.1":
return []
xref = _get_all_children(self._node, "annotation")
ret = []
for node in xref:
data = {}
_add_first_child_to_dic(node, data, True, "property")
_add_first_child_to_dic(node, data, True, "value")
ret.append(data)
return ret
def new_annotation(self, property=None, value=None, newposition=None):
"""Creates a new annotation element.
Args:
self: The class self parameter.
property: The property
value: Its value
newposition: The new position of the element
Returns:
Nothing, changes self.
"""
par = self._node.getparent()
ver = par.get('version')
if ver == "1.1":
return
if property is None or value is None:
raise RdmlError('Property and value are required to create a annotation.')
new_node = et.Element("annotation")
_add_new_subelement(new_node, "annotation", "property", property, True)
_add_new_subelement(new_node, "annotation", "value", value, True)
place = _get_tag_pos(self._node, "annotation", self.xmlkeys(), newposition)
self._node.insert(place, new_node)
def edit_annotation(self, oldposition, newposition=None, property=None, value=None):
"""Edits an annotation element.
Args:
self: The class self parameter.
oldposition: The old position of the element
newposition: The new position of the element
property: The property
value: Its value
Returns:
Nothing, changes self.
"""
par = self._node.getparent()
ver = par.get('version')
if ver == "1.1":
return
if oldposition is None:
raise RdmlError('A oldposition is required to edit a annotation.')
if (property is None or property == "") or (value is None or value == ""):
self.delete_annotation(oldposition)
return
pos = _get_tag_pos(self._node, "annotation", self.xmlkeys(), newposition)
ele = _get_first_child_by_pos_or_id(self._node, "annotation", None, oldposition)
_change_subelement(ele, "property", ["property", "value"], property, True, "string")
_change_subelement(ele, "value", ["property", "value"], value, True, "string")
self._node.insert(pos, ele)
def move_annotation(self, oldposition, newposition):
"""Moves the element to the new position in the list.
Args:
self: The class self parameter.
oldposition: The old position of the element
newposition: The new position of the element
Returns:
No return value, changes self. Function may raise RdmlError if required.
"""
par = self._node.getparent()
ver = par.get('version')
if ver == "1.1":
return
pos = _get_tag_pos(self._node, "annotation", self.xmlkeys(), newposition)
ele = _get_first_child_by_pos_or_id(self._node, "annotation", None, oldposition)
self._node.insert(pos, ele)
def delete_annotation(self, byposition):
"""Deletes an annotation element.
Args:
self: The class self parameter.
byposition: Select the element by position in the list.
Returns:
Nothing, changes self.
"""
par = self._node.getparent()
ver = par.get('version')
if ver == "1.1":
return
elem = _get_first_child_by_pos_or_id(self._node, "annotation", None, byposition)
self._node.remove(elem)
def documentation_ids(self):
"""Returns a list of the keys in the xml file.
Args:
self: The class self parameter.
Returns:
A list of the key strings.
"""
return _get_all_children_id(self._node, "documentation")
def update_documentation_ids(self, ids):
"""Returns a json of the RDML object without fluorescence data.
Args:
self: The class self parameter.
ids: A dictionary with id and true/false pairs
Returns:
True if a change was made, else false. Function may raise RdmlError if required.
"""
old = self.documentation_ids()
good_ids = _value_to_booldic(ids)
mod = False
for id, inc in good_ids.items():
if inc is True:
if id not in old:
new_node = _create_new_element(self._node, "documentation", id)
place = _get_tag_pos(self._node, "documentation", self.xmlkeys(), 999999999)
self._node.insert(place, new_node)
mod = True
else:
if id in old:
elem = _get_first_child_by_pos_or_id(self._node, "documentation", id, None)
self._node.remove(elem)
mod = True
return mod
def move_documentation(self, oldposition, newposition):
"""Moves the element to the new position in the list.
Args:
self: The class self parameter.
oldposition: The old position of the element
newposition: The new position of the element
Returns:
No return value, changes self. Function may raise RdmlError if required.
"""
pos = _get_tag_pos(self._node, "documentation", self.xmlkeys(), newposition)
ele = _get_first_child_by_pos_or_id(self._node, "documentation", None, oldposition)
self._node.insert(pos, ele)
def tojson(self):
"""Returns a json of the RDML object without fluorescence data.
Args:
self: The class self parameter.
Returns:
A json of the data.
"""
par = self._node.getparent()
ver = par.get('version')
data = {
"id": self._node.get('id'),
}
_add_first_child_to_dic(self._node, data, True, "description")
data["documentations"] = self.documentation_ids()
data["xRefs"] = self.xrefs()
if ver == "1.2" or ver == "1.3":
data["annotations"] = self.annotations()
data["types"] = self.types()
_add_first_child_to_dic(self._node, data, True, "interRunCalibrator")
elem = _get_first_child(self._node, "quantity")
if elem is not None:
qdic = {}
_add_first_child_to_dic(elem, qdic, False, "value")
_add_first_child_to_dic(elem, qdic, False, "unit")
data["quantity"] = qdic
_add_first_child_to_dic(self._node, data, True, "calibratorSample")
elem = _get_first_child(self._node, "cdnaSynthesisMethod")
if elem is not None:
qdic = {}
_add_first_child_to_dic(elem, qdic, True, "enzyme")
_add_first_child_to_dic(elem, qdic, True, "primingMethod")
_add_first_child_to_dic(elem, qdic, True, "dnaseTreatment")
forId = _get_first_child(elem, "thermalCyclingConditions")
if forId is not None:
if forId.attrib['id'] != "":
qdic["thermalCyclingConditions"] = forId.attrib['id']
if len(qdic.keys()) != 0:
data["cdnaSynthesisMethod"] = qdic
if ver == "1.1":
elem = _get_first_child(self._node, "templateRNAQuantity")
if elem is not None:
qdic = {}
_add_first_child_to_dic(elem, qdic, False, "value")
_add_first_child_to_dic(elem, qdic, False, "unit")
data["templateRNAQuantity"] = qdic
elem = _get_first_child(self._node, "templateRNAQuality")
if elem is not None:
qdic = {}
_add_first_child_to_dic(elem, qdic, False, "method")
_add_first_child_to_dic(elem, qdic, False, "result")
data["templateRNAQuality"] = qdic
elem = _get_first_child(self._node, "templateDNAQuantity")
if elem is not None:
qdic = {}
_add_first_child_to_dic(elem, qdic, False, "value")
_add_first_child_to_dic(elem, qdic, False, "unit")
data["templateDNAQuantity"] = qdic
elem = _get_first_child(self._node, "templateDNAQuality")
if elem is not None:
qdic = {}
_add_first_child_to_dic(elem, qdic, False, "method")
_add_first_child_to_dic(elem, qdic, False, "result")
data["templateDNAQuality"] = qdic
if ver == "1.2" or ver == "1.3":
elem = _get_first_child(self._node, "templateQuantity")
if elem is not None:
qdic = {}
_add_first_child_to_dic(elem, qdic, False, "nucleotide")
_add_first_child_to_dic(elem, qdic, False, "conc")
data["templateQuantity"] = qdic
return data
class Target:
"""RDML-Python library
The target element used to read and edit one target.
Attributes:
_node: The target node of the RDML XML object.
_rdmlFilename: The RDML filename
"""
def __init__(self, node, rdmlFilename):
"""Inits an target instance.
Args:
self: The class self parameter.
node: The target node.
rdmlFilename: The RDML filename.
Returns:
No return value. Function may raise RdmlError if required.
"""
self._node = node
self._rdmlFilename = rdmlFilename
def __getitem__(self, key):
"""Returns the value for the key.
Args:
self: The class self parameter.
key: The key of the target subelement
Returns:
A string of the data or None.
"""
if key == "id":
return self._node.get('id')
if key == "type":
return _get_first_child_text(self._node, key)
if key in ["description", "amplificationEfficiencyMethod", "amplificationEfficiency",
"amplificationEfficiencySE", "meltingTemperature", "detectionLimit"]:
var = _get_first_child_text(self._node, key)
if var == "":
return None
else:
return var
if key == "dyeId":
forId = _get_first_child(self._node, key)
if forId is not None:
return forId.attrib['id']
else:
return None
if key in ["sequences_forwardPrimer_threePrimeTag", "sequences_forwardPrimer_fivePrimeTag",
"sequences_forwardPrimer_sequence", "sequences_reversePrimer_threePrimeTag",
"sequences_reversePrimer_fivePrimeTag", "sequences_reversePrimer_sequence",
"sequences_probe1_threePrimeTag", "sequences_probe1_fivePrimeTag",
"sequences_probe1_sequence", "sequences_probe2_threePrimeTag",
"sequences_probe2_fivePrimeTag", "sequences_probe2_sequence",
"sequences_amplicon_threePrimeTag", "sequences_amplicon_fivePrimeTag",
"sequences_amplicon_sequence"]:
prim = _get_first_child(self._node, "sequences")
if prim is None:
return None
sec = None
if key in ["sequences_forwardPrimer_threePrimeTag", "sequences_forwardPrimer_fivePrimeTag",
"sequences_forwardPrimer_sequence"]:
sec = _get_first_child(prim, "forwardPrimer")
if key in ["sequences_reversePrimer_threePrimeTag", "sequences_reversePrimer_fivePrimeTag",
"sequences_reversePrimer_sequence"]:
sec = _get_first_child(prim, "reversePrimer")
if key in ["sequences_probe1_threePrimeTag", "sequences_probe1_fivePrimeTag", "sequences_probe1_sequence"]:
sec = _get_first_child(prim, "probe1")
if key in ["sequences_probe2_threePrimeTag", "sequences_probe2_fivePrimeTag", "sequences_probe2_sequence"]:
sec = _get_first_child(prim, "probe2")
if key in ["sequences_amplicon_threePrimeTag", "sequences_amplicon_fivePrimeTag",
"sequences_amplicon_sequence"]:
sec = _get_first_child(prim, "amplicon")
if sec is None:
return None
if key in ["sequences_forwardPrimer_threePrimeTag", "sequences_reversePrimer_threePrimeTag",
"sequences_probe1_threePrimeTag", "sequences_probe2_threePrimeTag",
"sequences_amplicon_threePrimeTag"]:
return _get_first_child_text(sec, "threePrimeTag")
if key in ["sequences_forwardPrimer_fivePrimeTag", "sequences_reversePrimer_fivePrimeTag",
"sequences_probe1_fivePrimeTag", "sequences_probe2_fivePrimeTag",
"sequences_amplicon_fivePrimeTag"]:
return _get_first_child_text(sec, "fivePrimeTag")
if key in ["sequences_forwardPrimer_sequence", "sequences_reversePrimer_sequence",
"sequences_probe1_sequence", "sequences_probe2_sequence",
"sequences_amplicon_sequence"]:
return _get_first_child_text(sec, "sequence")
raise RdmlError('Target sequences programming read error.')
if key in ["commercialAssay_company", "commercialAssay_orderNumber"]:
prim = _get_first_child(self._node, "commercialAssay")
if prim is None:
return None
if key == "commercialAssay_company":
return _get_first_child_text(prim, "company")
if key == "commercialAssay_orderNumber":
return _get_first_child_text(prim, "orderNumber")
par = self._node.getparent()
ver = par.get('version')
if ver == "1.2" or ver == "1.3":
if key == "amplificationEfficiencySE":
var = _get_first_child_text(self._node, key)
if var == "":
return None
else:
return var
raise KeyError
def __setitem__(self, key, value):
"""Changes the value for the key.
Args:
self: The class self parameter.
key: The key of the target subelement
value: The new value for the key
Returns:
No return value, changes self. Function may raise RdmlError if required.
"""
par = self._node.getparent()
ver = par.get('version')
if key == "type":
if value not in ["ref", "toi"]:
raise RdmlError('Unknown or unsupported target type value "' + value + '".')
if key == "id":
self.change_id(value, merge_with_id=False)
return
if key == "type":
return _change_subelement(self._node, key, self.xmlkeys(), value, False, "string")
if key in ["description", "amplificationEfficiencyMethod"]:
return _change_subelement(self._node, key, self.xmlkeys(), value, True, "string")
if key in ["amplificationEfficiency", "detectionLimit"]:
return _change_subelement(self._node, key, self.xmlkeys(), value, True, "float")
if ver == "1.2" or ver == "1.3":
if key == "amplificationEfficiencySE":
return _change_subelement(self._node, key, self.xmlkeys(), value, True, "float")
if ver == "1.3":
if key == "meltingTemperature":
return _change_subelement(self._node, key, self.xmlkeys(), value, True, "float")
if key == "dyeId":
forId = _get_or_create_subelement(self._node, "dyeId", self.xmlkeys())
if value is not None and value != "":
# We do not check that ID is valid to allow recreate_lost_ids()
forId.attrib['id'] = value
else:
self._node.remove(forId)
return
if key in ["sequences_forwardPrimer_threePrimeTag", "sequences_forwardPrimer_fivePrimeTag",
"sequences_forwardPrimer_sequence", "sequences_reversePrimer_threePrimeTag",
"sequences_reversePrimer_fivePrimeTag", "sequences_reversePrimer_sequence",
"sequences_probe1_threePrimeTag", "sequences_probe1_fivePrimeTag",
"sequences_probe1_sequence", "sequences_probe2_threePrimeTag",
"sequences_probe2_fivePrimeTag", "sequences_probe2_sequence",
"sequences_amplicon_threePrimeTag", "sequences_amplicon_fivePrimeTag",
"sequences_amplicon_sequence"]:
prim = _get_or_create_subelement(self._node, "sequences", self.xmlkeys())
sec = None
if key in ["sequences_forwardPrimer_threePrimeTag", "sequences_forwardPrimer_fivePrimeTag",
"sequences_forwardPrimer_sequence"]:
sec = _get_or_create_subelement(prim, "forwardPrimer",
["forwardPrimer", "reversePrimer", "probe1", "probe2", "amplicon"])
if key in ["sequences_reversePrimer_threePrimeTag", "sequences_reversePrimer_fivePrimeTag",
"sequences_reversePrimer_sequence"]:
sec = _get_or_create_subelement(prim, "reversePrimer",
["forwardPrimer", "reversePrimer", "probe1", "probe2", "amplicon"])
if key in ["sequences_probe1_threePrimeTag", "sequences_probe1_fivePrimeTag", "sequences_probe1_sequence"]:
sec = _get_or_create_subelement(prim, "probe1",
["forwardPrimer", "reversePrimer", "probe1", "probe2", "amplicon"])
if key in ["sequences_probe2_threePrimeTag", "sequences_probe2_fivePrimeTag", "sequences_probe2_sequence"]:
sec = _get_or_create_subelement(prim, "probe2",
["forwardPrimer", "reversePrimer", "probe1", "probe2", "amplicon"])
if key in ["sequences_amplicon_threePrimeTag", "sequences_amplicon_fivePrimeTag",
"sequences_amplicon_sequence"]:
sec = _get_or_create_subelement(prim, "amplicon",
["forwardPrimer", "reversePrimer", "probe1", "probe2", "amplicon"])
if sec is None:
return None
if key in ["sequences_forwardPrimer_threePrimeTag", "sequences_reversePrimer_threePrimeTag",
"sequences_probe1_threePrimeTag", "sequences_probe2_threePrimeTag",
"sequences_amplicon_threePrimeTag"]:
_change_subelement(sec, "threePrimeTag",
["threePrimeTag", "fivePrimeTag", "sequence"], value, True, "string")
if key in ["sequences_forwardPrimer_fivePrimeTag", "sequences_reversePrimer_fivePrimeTag",
"sequences_probe1_fivePrimeTag", "sequences_probe2_fivePrimeTag",
"sequences_amplicon_fivePrimeTag"]:
_change_subelement(sec, "fivePrimeTag",
["threePrimeTag", "fivePrimeTag", "sequence"], value, True, "string")
if key in ["sequences_forwardPrimer_sequence", "sequences_reversePrimer_sequence",
"sequences_probe1_sequence", "sequences_probe2_sequence",
"sequences_amplicon_sequence"]:
_change_subelement(sec, "sequence",
["threePrimeTag", "fivePrimeTag", "sequence"], value, True, "string")
if key in ["sequences_forwardPrimer_threePrimeTag", "sequences_forwardPrimer_fivePrimeTag",
"sequences_forwardPrimer_sequence"]:
_remove_irrelevant_subelement(prim, "forwardPrimer")
if key in ["sequences_reversePrimer_threePrimeTag", "sequences_reversePrimer_fivePrimeTag",
"sequences_reversePrimer_sequence"]:
_remove_irrelevant_subelement(prim, "reversePrimer")
if key in ["sequences_probe1_threePrimeTag", "sequences_probe1_fivePrimeTag", "sequences_probe1_sequence"]:
_remove_irrelevant_subelement(prim, "probe1")
if key in ["sequences_probe2_threePrimeTag", "sequences_probe2_fivePrimeTag", "sequences_probe2_sequence"]:
_remove_irrelevant_subelement(prim, "probe2")
if key in ["sequences_amplicon_threePrimeTag", "sequences_amplicon_fivePrimeTag",
"sequences_amplicon_sequence"]:
_remove_irrelevant_subelement(prim, "amplicon")
_remove_irrelevant_subelement(self._node, "sequences")
return
if key in ["commercialAssay_company", "commercialAssay_orderNumber"]:
ele = _get_or_create_subelement(self._node, "commercialAssay", self.xmlkeys())
if key == "commercialAssay_company":
_change_subelement(ele, "company", ["company", "orderNumber"], value, True, "string")
if key == "commercialAssay_orderNumber":
_change_subelement(ele, "orderNumber", ["company", "orderNumber"], value, True, "string")
_remove_irrelevant_subelement(self._node, "commercialAssay")
return
par = self._node.getparent()
ver = par.get('version')
if ver == "1.2" or ver == "1.3":
if key == "amplificationEfficiencySE":
return _change_subelement(self._node, key, self.xmlkeys(), value, True, "float")
raise KeyError
def change_id(self, value, merge_with_id=False):
"""Changes the value for the id.
Args:
self: The class self parameter.
value: The new value for the id.
merge_with_id: If True only allow a unique id, if False only rename its uses with existing id.
Returns:
No return value, changes self. Function may raise RdmlError if required.
"""
oldValue = self._node.get('id')
if oldValue != value:
par = self._node.getparent()
if not _string_to_bool(merge_with_id, triple=False):
_change_subelement(self._node, "id", self.xmlkeys(), value, False, "string")
else:
groupTag = self._node.tag.replace("{http://www.rdml.org}", "")
if _check_unique_id(par, groupTag, value):
raise RdmlError('The ' + groupTag + ' id "' + value + '" does not exist.')
allExp = _get_all_children(par, "sample")
for node in allExp:
subNodes = _get_all_children(node, "type")
for subNode in subNodes:
if "targetId" in subNode.attrib:
if subNode.attrib['targetId'] == oldValue:
subNode.attrib['targetId'] = value
allExp = _get_all_children(par, "experiment")
for node in allExp:
subNodes = _get_all_children(node, "run")
for subNode in subNodes:
reactNodes = _get_all_children(subNode, "react")
for reactNode in reactNodes:
dataNodes = _get_all_children(reactNode, "data")
for dataNode in dataNodes:
lastNodes = _get_all_children(dataNode, "tar")
for lastNode in lastNodes:
if lastNode.attrib['id'] == oldValue:
lastNode.attrib['id'] = value
partit = _get_first_child(reactNode, "partitions")
if partit is not None:
digDataNodes = _get_all_children(partit, "data")
for digDataNode in digDataNodes:
lastNodes = _get_all_children(digDataNode, "tar")
for lastNode in lastNodes:
if lastNode.attrib['id'] == oldValue:
lastNode.attrib['id'] = value
# Search in Table files
if self._rdmlFilename is not None and self._rdmlFilename != "":
if zipfile.is_zipfile(self._rdmlFilename):
fileList = []
tempName = ""
flipFiles = False
with zipfile.ZipFile(self._rdmlFilename, 'r') as RDMLin:
for item in RDMLin.infolist():
if re.search("^partitions/", item.filename):
fileContent = RDMLin.read(item.filename).decode('utf-8')
newlineFix = fileContent.replace("\r\n", "\n")
tabLines = newlineFix.split("\n")
header = tabLines[0].split("\t")
needRewrite = False
for cell in header:
if cell == oldValue:
needRewrite = True
if needRewrite:
fileList.append(item.filename)
if len(fileList) > 0:
tempFolder, tempName = tempfile.mkstemp(dir=os.path.dirname(self._rdmlFilename))
os.close(tempFolder)
flipFiles = True
with zipfile.ZipFile(tempName, mode='w', compression=zipfile.ZIP_DEFLATED) as RDMLout:
RDMLout.comment = RDMLin.comment
for item in RDMLin.infolist():
if item.filename not in fileList:
RDMLout.writestr(item, RDMLin.read(item.filename))
else:
fileContent = RDMLin.read(item.filename).decode('utf-8')
newlineFix = fileContent.replace("\r\n", "\n")
tabLines = newlineFix.split("\n")
header = tabLines[0].split("\t")
headerText = ""
for cell in header:
if cell == oldValue:
headerText += value + "\t"
else:
headerText += cell + "\t"
outFileStr = re.sub(r'\t$', '\n', headerText)
for tabLine in tabLines[1:]:
if tabLine != "":
outFileStr += tabLine + "\n"
RDMLout.writestr(item.filename, outFileStr)
if flipFiles:
os.remove(self._rdmlFilename)
os.rename(tempName, self._rdmlFilename)
return
def keys(self):
"""Returns a list of the keys.
Args:
self: The class self parameter.
Returns:
A list of the key strings.
"""
return ["id", "description", "type", "amplificationEfficiencyMethod", "amplificationEfficiency",
"amplificationEfficiencySE", "meltingTemperature", "detectionLimit", "dyeId",
"sequences_forwardPrimer_threePrimeTag",
"sequences_forwardPrimer_fivePrimeTag", "sequences_forwardPrimer_sequence",
"sequences_reversePrimer_threePrimeTag", "sequences_reversePrimer_fivePrimeTag",
"sequences_reversePrimer_sequence", "sequences_probe1_threePrimeTag",
"sequences_probe1_fivePrimeTag", "sequences_probe1_sequence", "sequences_probe2_threePrimeTag",
"sequences_probe2_fivePrimeTag", "sequences_probe2_sequence", "sequences_amplicon_threePrimeTag",
"sequences_amplicon_fivePrimeTag", "sequences_amplicon_sequence", "commercialAssay_company",
"commercialAssay_orderNumber"] # Also change in LinRegPCR save RDML
def xmlkeys(self):
"""Returns a list of the keys in the xml file.
Args:
self: The class self parameter.
Returns:
A list of the key strings.
"""
return ["description", "documentation", "xRef", "type", "amplificationEfficiencyMethod",
"amplificationEfficiency", "amplificationEfficiencySE", "meltingTemperature",
"detectionLimit", "dyeId", "sequences", "commercialAssay"]
def xrefs(self):
"""Returns a list of the xrefs in the xml file.
Args:
self: The class self parameter.
Returns:
A list of dics with name and id strings.
"""
xref = _get_all_children(self._node, "xRef")
ret = []
for node in xref:
data = {}
_add_first_child_to_dic(node, data, True, "name")
_add_first_child_to_dic(node, data, True, "id")
ret.append(data)
return ret
def new_xref(self, name=None, id=None, newposition=None):
"""Creates a new xrefs element.
Args:
self: The class self parameter.
name: Publisher who created the xRef
id: Serial Number for this target provided by publisher
newposition: The new position of the element
Returns:
Nothing, changes self.
"""
if name is None and id is None:
raise RdmlError('Either name or id is required to create a xRef.')
new_node = et.Element("xRef")
_add_new_subelement(new_node, "xRef", "name", name, True)
_add_new_subelement(new_node, "xRef", "id", id, True)
place = _get_tag_pos(self._node, "xRef", self.xmlkeys(), newposition)
self._node.insert(place, new_node)
def edit_xref(self, oldposition, newposition=None, name=None, id=None):
"""Creates a new xrefs element.
Args:
self: The class self parameter.
oldposition: The old position of the element
newposition: The new position of the element
name: Publisher who created the xRef
id: Serial Number for this target provided by publisher
Returns:
Nothing, changes self.
"""
if oldposition is None:
raise RdmlError('A oldposition is required to edit a xRef.')
if (name is None or name == "") and (id is None or id == ""):
self.delete_xref(oldposition)
return
pos = _get_tag_pos(self._node, "xRef", self.xmlkeys(), newposition)
ele = _get_first_child_by_pos_or_id(self._node, "xRef", None, oldposition)
_change_subelement(ele, "name", ["name", "id"], name, True, "string")
_change_subelement(ele, "id", ["name", "id"], id, True, "string", id_as_element=True)
self._node.insert(pos, ele)
def move_xref(self, oldposition, newposition):
"""Moves the element to the new position in the list.
Args:
self: The class self parameter.
oldposition: The old position of the element
newposition: The new position of the element
Returns:
No return value, changes self. Function may raise RdmlError if required.
"""
pos = _get_tag_pos(self._node, "xRef", self.xmlkeys(), newposition)
ele = _get_first_child_by_pos_or_id(self._node, "xRef", None, oldposition)
self._node.insert(pos, ele)
def delete_xref(self, byposition):
"""Deletes an experimenter element.
Args:
self: The class self parameter.
byposition: Select the element by position in the list.
Returns:
Nothing, changes self.
"""
elem = _get_first_child_by_pos_or_id(self._node, "xRef", None, byposition)
self._node.remove(elem)
def documentation_ids(self):
"""Returns a list of the keys in the xml file.
Args:
self: The class self parameter.
Returns:
A list of the key strings.
"""
return _get_all_children_id(self._node, "documentation")
def update_documentation_ids(self, ids):
"""Returns a json of the RDML object without fluorescence data.
Args:
self: The class self parameter.
ids: A dictionary with id and true/false pairs
Returns:
True if a change was made, else false. Function may raise RdmlError if required.
"""
old = self.documentation_ids()
good_ids = _value_to_booldic(ids)
mod = False
for id, inc in good_ids.items():
if inc is True:
if id not in old:
new_node = _create_new_element(self._node, "documentation", id)
place = _get_tag_pos(self._node, "documentation", self.xmlkeys(), 999999999)
self._node.insert(place, new_node)
mod = True
else:
if id in old:
elem = _get_first_child_by_pos_or_id(self._node, "documentation", id, None)
self._node.remove(elem)
mod = True
return mod
def move_documentation(self, oldposition, newposition):
"""Moves the element to the new position in the list.
Args:
self: The class self parameter.
oldposition: The old position of the element
newposition: The new position of the element
Returns:
No return value, changes self. Function may raise RdmlError if required.
"""
pos = _get_tag_pos(self._node, "documentation", self.xmlkeys(), newposition)
ele = _get_first_child_by_pos_or_id(self._node, "documentation", None, oldposition)
self._node.insert(pos, ele)
def tojson(self):
"""Returns a json of the RDML object without fluorescence data.
Args:
self: The class self parameter.
Returns:
A json of the data.
"""
data = {
"id": self._node.get('id'),
}
_add_first_child_to_dic(self._node, data, True, "description")
data["documentations"] = self.documentation_ids()
data["xRefs"] = self.xrefs()
_add_first_child_to_dic(self._node, data, False, "type")
_add_first_child_to_dic(self._node, data, True, "amplificationEfficiencyMethod")
_add_first_child_to_dic(self._node, data, True, "amplificationEfficiency")
_add_first_child_to_dic(self._node, data, True, "amplificationEfficiencySE")
_add_first_child_to_dic(self._node, data, True, "meltingTemperature")
_add_first_child_to_dic(self._node, data, True, "detectionLimit")
forId = _get_first_child(self._node, "dyeId")
if forId is not None:
if forId.attrib['id'] != "":
data["dyeId"] = forId.attrib['id']
elem = _get_first_child(self._node, "sequences")
if elem is not None:
qdic = {}
sec = _get_first_child(elem, "forwardPrimer")
if sec is not None:
sdic = {}
_add_first_child_to_dic(sec, sdic, True, "threePrimeTag")
_add_first_child_to_dic(sec, sdic, True, "fivePrimeTag")
_add_first_child_to_dic(sec, sdic, True, "sequence")
if len(sdic.keys()) != 0:
qdic["forwardPrimer"] = sdic
sec = _get_first_child(elem, "reversePrimer")
if sec is not None:
sdic = {}
_add_first_child_to_dic(sec, sdic, True, "threePrimeTag")
_add_first_child_to_dic(sec, sdic, True, "fivePrimeTag")
_add_first_child_to_dic(sec, sdic, True, "sequence")
if len(sdic.keys()) != 0:
qdic["reversePrimer"] = sdic
sec = _get_first_child(elem, "probe1")
if sec is not None:
sdic = {}
_add_first_child_to_dic(sec, sdic, True, "threePrimeTag")
_add_first_child_to_dic(sec, sdic, True, "fivePrimeTag")
_add_first_child_to_dic(sec, sdic, True, "sequence")
if len(sdic.keys()) != 0:
qdic["probe1"] = sdic
sec = _get_first_child(elem, "probe2")
if sec is not None:
sdic = {}
_add_first_child_to_dic(sec, sdic, True, "threePrimeTag")
_add_first_child_to_dic(sec, sdic, True, "fivePrimeTag")
_add_first_child_to_dic(sec, sdic, True, "sequence")
if len(sdic.keys()) != 0:
qdic["probe2"] = sdic
sec = _get_first_child(elem, "amplicon")
if sec is not None:
sdic = {}
_add_first_child_to_dic(sec, sdic, True, "threePrimeTag")
_add_first_child_to_dic(sec, sdic, True, "fivePrimeTag")
_add_first_child_to_dic(sec, sdic, True, "sequence")
if len(sdic.keys()) != 0:
qdic["amplicon"] = sdic
if len(qdic.keys()) != 0:
data["sequences"] = qdic
elem = _get_first_child(self._node, "commercialAssay")
if elem is not None:
qdic = {}
_add_first_child_to_dic(elem, qdic, True, "company")
_add_first_child_to_dic(elem, qdic, True, "orderNumber")
if len(qdic.keys()) != 0:
data["commercialAssay"] = qdic
return data
class Therm_cyc_cons:
"""RDML-Python library
The thermalCyclingConditions element used to read and edit one thermal Cycling Conditions.
Attributes:
_node: The thermalCyclingConditions node of the RDML XML object.
"""
def __init__(self, node):
"""Inits an thermalCyclingConditions instance.
Args:
self: The class self parameter.
node: The thermalCyclingConditions node.
Returns:
No return value. Function may raise RdmlError if required.
"""
self._node = node
def __getitem__(self, key):
"""Returns the value for the key.
Args:
self: The class self parameter.
key: The key of the thermalCyclingConditions subelement
Returns:
A string of the data or None.
"""
if key == "id":
return self._node.get('id')
if key in ["description", "lidTemperature"]:
var = _get_first_child_text(self._node, key)
if var == "":
return None
else:
return var
raise KeyError
def __setitem__(self, key, value):
"""Changes the value for the key.
Args:
self: The class self parameter.
key: The key of the thermalCyclingConditions subelement
value: The new value for the key
Returns:
No return value, changes self. Function may raise RdmlError if required.
"""
if key == "id":
self.change_id(value, merge_with_id=False)
return
if key == "description":
return _change_subelement(self._node, key, self.xmlkeys(), value, True, "string")
if key == "lidTemperature":
return _change_subelement(self._node, key, self.xmlkeys(), value, True, "float")
raise KeyError
def change_id(self, value, merge_with_id=False):
"""Changes the value for the id.
Args:
self: The class self parameter.
value: The new value for the id.
merge_with_id: If True only allow a unique id, if False only rename its uses with existing id.
Returns:
No return value, changes self. Function may raise RdmlError if required.
"""
oldValue = self._node.get('id')
if oldValue != value:
par = self._node.getparent()
if not _string_to_bool(merge_with_id, triple=False):
_change_subelement(self._node, "id", self.xmlkeys(), value, False, "string")
else:
groupTag = self._node.tag.replace("{http://www.rdml.org}", "")
if _check_unique_id(par, groupTag, value):
raise RdmlError('The ' + groupTag + ' id "' + value + '" does not exist.')
allSam = _get_all_children(par, "sample")
for node in allSam:
subNode = _get_first_child(node, "cdnaSynthesisMethod")
if subNode is not None:
forId = _get_first_child(subNode, "thermalCyclingConditions")
if forId is not None:
if forId.attrib['id'] == oldValue:
forId.attrib['id'] = value
allExp = _get_all_children(par, "experiment")
for node in allExp:
subNodes = _get_all_children(node, "run")
for subNode in subNodes:
forId = _get_first_child(subNode, "thermalCyclingConditions")
if forId is not None:
if forId.attrib['id'] == oldValue:
forId.attrib['id'] = value
return
def keys(self):
"""Returns a list of the keys.
Args:
self: The class self parameter.
Returns:
A list of the key strings.
"""
return ["id", "description", "lidTemperature"]
def xmlkeys(self):
"""Returns a list of the keys in the xml file.
Args:
self: The class self parameter.
Returns:
A list of the key strings.
"""
return ["description", "documentation", "lidTemperature", "experimenter", "step"]
def documentation_ids(self):
"""Returns a list of the keys in the xml file.
Args:
self: The class self parameter.
Returns:
A list of the key strings.
"""
return _get_all_children_id(self._node, "documentation")
def update_documentation_ids(self, ids):
"""Returns a json of the RDML object without fluorescence data.
Args:
self: The class self parameter.
ids: A dictionary with id and true/false pairs
Returns:
True if a change was made, else false. Function may raise RdmlError if required.
"""
old = self.documentation_ids()
good_ids = _value_to_booldic(ids)
mod = False
for id, inc in good_ids.items():
if inc is True:
if id not in old:
new_node = _create_new_element(self._node, "documentation", id)
place = _get_tag_pos(self._node, "documentation", self.xmlkeys(), 999999999)
self._node.insert(place, new_node)
mod = True
else:
if id in old:
elem = _get_first_child_by_pos_or_id(self._node, "documentation", id, None)
self._node.remove(elem)
mod = True
return mod
def move_documentation(self, oldposition, newposition):
"""Moves the element to the new position in the list.
Args:
self: The class self parameter.
oldposition: The old position of the element
newposition: The new position of the element
Returns:
No return value, changes self. Function may raise RdmlError if required.
"""
pos = _get_tag_pos(self._node, "documentation", self.xmlkeys(), newposition)
ele = _get_first_child_by_pos_or_id(self._node, "documentation", None, oldposition)
self._node.insert(pos, ele)
def experimenter_ids(self):
"""Returns a list of the keys in the xml file.
Args:
self: The class self parameter.
Returns:
A list of the key strings.
"""
return _get_all_children_id(self._node, "experimenter")
def update_experimenter_ids(self, ids):
"""Returns a json of the RDML object without fluorescence data.
Args:
self: The class self parameter.
ids: A dictionary with id and true/false pairs
Returns:
True if a change was made, else false. Function may raise RdmlError if required.
"""
old = self.experimenter_ids()
good_ids = _value_to_booldic(ids)
mod = False
for id, inc in good_ids.items():
if inc is True:
if id not in old:
new_node = _create_new_element(self._node, "experimenter", id)
place = _get_tag_pos(self._node, "experimenter", self.xmlkeys(), 999999999)
self._node.insert(place, new_node)
mod = True
else:
if id in old:
elem = _get_first_child_by_pos_or_id(self._node, "experimenter", id, None)
self._node.remove(elem)
mod = True
return mod
def move_experimenter(self, oldposition, newposition):
"""Moves the element to the new position in the list.
Args:
self: The class self parameter.
oldposition: The old position of the element
newposition: The new position of the element
Returns:
No return value, changes self. Function may raise RdmlError if required.
"""
pos = _get_tag_pos(self._node, "experimenter", self.xmlkeys(), newposition)
ele = _get_first_child_by_pos_or_id(self._node, "experimenter", None, oldposition)
self._node.insert(pos, ele)
def steps(self):
"""Returns a list of all step elements.
Args:
self: The class self parameter.
Returns:
A list of all step elements.
"""
# The steps are sorted transiently to not modify the file in a read situation
exp = _get_all_children(self._node, "step")
srt_exp = sorted(exp, key=_get_step_sort_nr)
ret = []
for node in srt_exp:
ret.append(Step(node))
return ret
def new_step_temperature(self, temperature, duration,
temperatureChange=None, durationChange=None,
measure=None, ramp=None, nr=None):
"""Creates a new step element.
Args:
self: The class self parameter.
temperature: The temperature of the step in degrees Celsius (required)
duration: The duration of this step in seconds (required)
temperatureChange: The change of the temperature from one cycle to the next (optional)
durationChange: The change of the duration from one cycle to the next (optional)
measure: Indicates to make a measurement and store it as meltcurve or real-time data (optional)
ramp: Limit temperature change from one step to the next in degrees Celsius per second (optional)
nr: Step unique nr (optional)
Returns:
Nothing, changes self.
"""
if measure is not None and measure not in ["", "real time", "meltcurve"]:
raise RdmlError('Unknown or unsupported step measure value: "' + measure + '".')
nr = int(nr)
count = _get_number_of_children(self._node, "step")
new_node = et.Element("step")
xml_temp_step = ["temperature", "duration", "temperatureChange", "durationChange", "measure", "ramp"]
_add_new_subelement(new_node, "step", "nr", str(count + 1), False)
subel = et.SubElement(new_node, "temperature")
_change_subelement(subel, "temperature", xml_temp_step, temperature, False, "float")
_change_subelement(subel, "duration", xml_temp_step, duration, False, "posint")
_change_subelement(subel, "temperatureChange", xml_temp_step, temperatureChange, True, "float")
_change_subelement(subel, "durationChange", xml_temp_step, durationChange, True, "int")
_change_subelement(subel, "measure", xml_temp_step, measure, True, "string")
_change_subelement(subel, "ramp", xml_temp_step, ramp, True, "float")
place = _get_first_tag_pos(self._node, "step", self.xmlkeys()) + count
self._node.insert(place, new_node)
# Now move step at final position
self.move_step(count + 1, nr)
def new_step_gradient(self, highTemperature, lowTemperature, duration,
temperatureChange=None, durationChange=None,
measure=None, ramp=None, nr=None):
"""Creates a new step element.
Args:
self: The class self parameter.
highTemperature: The high gradient temperature of the step in degrees Celsius (required)
lowTemperature: The low gradient temperature of the step in degrees Celsius (required)
duration: The duration of this step in seconds (required)
temperatureChange: The change of the temperature from one cycle to the next (optional)
durationChange: The change of the duration from one cycle to the next (optional)
measure: Indicates to make a measurement and store it as meltcurve or real-time data (optional)
ramp: Limit temperature change from one step to the next in degrees Celsius per second (optional)
nr: Step unique nr (optional)
Returns:
Nothing, changes self.
"""
if measure is not None and measure not in ["", "real time", "meltcurve"]:
raise RdmlError('Unknown or unsupported step measure value: "' + measure + '".')
nr = int(nr)
count = _get_number_of_children(self._node, "step")
new_node = et.Element("step")
xml_temp_step = ["highTemperature", "lowTemperature", "duration", "temperatureChange",
"durationChange", "measure", "ramp"]
_add_new_subelement(new_node, "step", "nr", str(count + 1), False)
subel = et.SubElement(new_node, "gradient")
_change_subelement(subel, "highTemperature", xml_temp_step, highTemperature, False, "float")
_change_subelement(subel, "lowTemperature", xml_temp_step, lowTemperature, False, "float")
_change_subelement(subel, "duration", xml_temp_step, duration, False, "posint")
_change_subelement(subel, "temperatureChange", xml_temp_step, temperatureChange, True, "float")
_change_subelement(subel, "durationChange", xml_temp_step, durationChange, True, "int")
_change_subelement(subel, "measure", xml_temp_step, measure, True, "string")
_change_subelement(subel, "ramp", xml_temp_step, ramp, True, "float")
place = _get_first_tag_pos(self._node, "step", self.xmlkeys()) + count
self._node.insert(place, new_node)
# Now move step at final position
self.move_step(count + 1, nr)
def new_step_loop(self, goto, repeat, nr=None):
"""Creates a new step element.
Args:
self: The class self parameter.
goto: The step nr to go back to (required)
repeat: The number of times to go back to goto step, one less than cycles (optional)
nr: Step unique nr (optional)
Returns:
Nothing, changes self.
"""
nr = int(nr)
count = _get_number_of_children(self._node, "step")
new_node = et.Element("step")
xml_temp_step = ["goto", "repeat"]
_add_new_subelement(new_node, "step", "nr", str(count + 1), False)
subel = et.SubElement(new_node, "loop")
_change_subelement(subel, "goto", xml_temp_step, goto, False, "posint")
_change_subelement(subel, "repeat", xml_temp_step, repeat, False, "posint")
place = _get_first_tag_pos(self._node, "step", self.xmlkeys()) + count
self._node.insert(place, new_node)
# Now move step at final position
self.move_step(count + 1, nr)
def new_step_pause(self, temperature, nr=None):
"""Creates a new step element.
Args:
self: The class self parameter.
temperature: The temperature of the step in degrees Celsius (required)
nr: Step unique nr (optional)
Returns:
Nothing, changes self.
"""
nr = int(nr)
count = _get_number_of_children(self._node, "step")
new_node = et.Element("step")
xml_temp_step = ["temperature"]
_add_new_subelement(new_node, "step", "nr", str(count + 1), False)
subel = et.SubElement(new_node, "pause")
_change_subelement(subel, "temperature", xml_temp_step, temperature, False, "float")
place = _get_first_tag_pos(self._node, "step", self.xmlkeys()) + count
self._node.insert(place, new_node)
# Now move step at final position
self.move_step(count + 1, nr)
def new_step_lidOpen(self, nr=None):
"""Creates a new step element.
Args:
self: The class self parameter.
nr: Step unique nr (optional)
Returns:
Nothing, changes self.
"""
nr = int(nr)
count = _get_number_of_children(self._node, "step")
new_node = et.Element("step")
_add_new_subelement(new_node, "step", "nr", str(count + 1), False)
et.SubElement(new_node, "lidOpen")
place = _get_first_tag_pos(self._node, "step", self.xmlkeys()) + count
self._node.insert(place, new_node)
# Now move step at final position
self.move_step(count + 1, nr)
def cleanup_steps(self):
"""The steps may not be in a order that makes sense. This function fixes it.
Args:
self: The class self parameter.
Returns:
No return value, changes self. Function may raise RdmlError if required.
"""
# The steps in the xml may be not sorted by "nr", so sort first
exp = _get_all_children(self._node, "step")
srt_exp = sorted(exp, key=_get_step_sort_nr)
i = 0
for node in srt_exp:
if _get_step_sort_nr(node) != _get_step_sort_nr(exp[i]):
pos = _get_first_tag_pos(self._node, "step", self.xmlkeys()) + i
self._node.insert(pos, node)
i += 1
# The steps in the xml may not have the correct numbering, so fix it
exp = _get_all_children(self._node, "step")
i = 1
for node in exp:
if _get_step_sort_nr(node) != i:
elem = _get_first_child(node, "nr")
elem.text = str(i)
i += 1
def move_step(self, oldnr, newnr):
"""Moves the element to the new position in the list.
Args:
self: The class self parameter.
oldnr: The old position of the element
newnr: The new position of the element
Returns:
No return value, changes self. Function may raise RdmlError if required.
"""
# The steps in the xml may be not sorted well, so fix it
self.cleanup_steps()
# Change the nr
_move_subelement_pos(self._node, "step", oldnr - 1, self.xmlkeys(), newnr - 1)
# Fix the nr
exp = _get_all_children(self._node, "step")
i = 1
goto_mod = 0
goto_start = newnr
goto_end = oldnr
if oldnr > newnr:
goto_mod = 1
if oldnr < newnr:
goto_mod = -1
goto_start = oldnr
goto_end = newnr
for node in exp:
if _get_step_sort_nr(node) != i:
elem = _get_first_child(node, "nr")
elem.text = str(i)
# Fix the goto steps
ele_type = _get_first_child(node, "loop")
if ele_type is not None:
ele_goto = _get_first_child(ele_type, "goto")
if ele_goto is not None:
jump_to = int(ele_goto.text)
if goto_start <= jump_to < goto_end:
ele_goto.text = str(jump_to + goto_mod)
i += 1
def get_step(self, bystep):
"""Returns an sample element by position or id.
Args:
self: The class self parameter.
bystep: Select the element by step nr in the list.
Returns:
The found element or None.
"""
return Step(_get_first_child_by_pos_or_id(self._node, "step", None, bystep - 1))
def delete_step(self, bystep=None):
"""Deletes an step element.
Args:
self: The class self parameter.
bystep: Select the element by step nr in the list.
Returns:
Nothing, changes self.
"""
elem = _get_first_child_by_pos_or_id(self._node, "step", None, bystep - 1)
self._node.remove(elem)
self.cleanup_steps()
# Fix the goto steps
exp = _get_all_children(self._node, "step")
for node in exp:
ele_type = _get_first_child(node, "loop")
if ele_type is not None:
ele_goto = _get_first_child(ele_type, "goto")
if ele_goto is not None:
jump_to = int(ele_goto.text)
if bystep < jump_to:
ele_goto.text = str(jump_to - 1)
def tojson(self):
"""Returns a json of the RDML object without fluorescence data.
Args:
self: The class self parameter.
Returns:
A json of the data.
"""
allSteps = self.steps()
steps = []
for exp in allSteps:
steps.append(exp.tojson())
data = {
"id": self._node.get('id'),
}
_add_first_child_to_dic(self._node, data, True, "description")
data["documentations"] = self.documentation_ids()
_add_first_child_to_dic(self._node, data, True, "lidTemperature")
data["experimenters"] = self.experimenter_ids()
data["steps"] = steps
return data
class Step:
"""RDML-Python library
The samples element used to read and edit one sample.
Attributes:
_node: The sample node of the RDML XML object.
"""
def __init__(self, node):
"""Inits an sample instance.
Args:
self: The class self parameter.
node: The sample node.
Returns:
No return value. Function may raise RdmlError if required.
"""
self._node = node
def __getitem__(self, key):
"""Returns the value for the key.
Args:
self: The class self parameter.
key: The key of the sample subelement. Be aware that change of type deletes all entries
except nr and description
Returns:
A string of the data or None.
"""
if key == "nr":
return _get_first_child_text(self._node, key)
if key == "description":
var = _get_first_child_text(self._node, key)
if var == "":
return None
else:
return var
ele_type = _get_first_child(self._node, "temperature")
if ele_type is not None:
if key == "type":
return "temperature"
if key in ["temperature", "duration"]:
return _get_first_child_text(ele_type, key)
if key in ["temperatureChange", "durationChange", "measure", "ramp"]:
var = _get_first_child_text(ele_type, key)
if var == "":
return None
else:
return var
ele_type = _get_first_child(self._node, "gradient")
if ele_type is not None:
if key == "type":
return "gradient"
if key in ["highTemperature", "lowTemperature", "duration"]:
return _get_first_child_text(ele_type, key)
if key in ["temperatureChange", "durationChange", "measure", "ramp"]:
var = _get_first_child_text(ele_type, key)
if var == "":
return None
else:
return var
ele_type = _get_first_child(self._node, "loop")
if ele_type is not None:
if key == "type":
return "loop"
if key in ["goto", "repeat"]:
return _get_first_child_text(ele_type, key)
ele_type = _get_first_child(self._node, "pause")
if ele_type is not None:
if key == "type":
return "pause"
if key == "temperature":
return _get_first_child_text(ele_type, key)
ele_type = _get_first_child(self._node, "lidOpen")
if ele_type is not None:
if key == "type":
return "lidOpen"
raise KeyError
def __setitem__(self, key, value):
"""Changes the value for the key.
Args:
self: The class self parameter.
key: The key of the sample subelement
value: The new value for the key
Returns:
No return value, changes self. Function may raise RdmlError if required.
"""
if key in ["nr", "type"]:
raise RdmlError('"' + key + '" can not be set. Use thermal cycling conditions methods instead')
if key == "description":
return _change_subelement(self._node, key, self.xmlkeys(), value, True, "string")
ele_type = _get_first_child(self._node, "temperature")
if ele_type is not None:
xml_temp_step = ["temperature", "duration", "temperatureChange", "durationChange", "measure", "ramp"]
if key == "temperature":
return _change_subelement(ele_type, key, xml_temp_step, value, False, "float")
if key == "duration":
return _change_subelement(ele_type, key, xml_temp_step, value, False, "posint")
if key in ["temperatureChange", "ramp"]:
return _change_subelement(ele_type, key, xml_temp_step, value, True, "float")
if key == "durationChange":
return _change_subelement(ele_type, key, xml_temp_step, value, True, "int")
if key == "measure":
if value not in ["", "real time", "meltcurve"]:
raise RdmlError('Unknown or unsupported step measure value: "' + value + '".')
return _change_subelement(ele_type, key, xml_temp_step, value, True, "string")
ele_type = _get_first_child(self._node, "gradient")
if ele_type is not None:
xml_temp_step = ["highTemperature", "lowTemperature", "duration", "temperatureChange",
"durationChange", "measure", "ramp"]
if key in ["highTemperature", "lowTemperature"]:
return _change_subelement(ele_type, key, xml_temp_step, value, False, "float")
if key == "duration":
return _change_subelement(ele_type, key, xml_temp_step, value, False, "posint")
if key in ["temperatureChange", "ramp"]:
return _change_subelement(ele_type, key, xml_temp_step, value, True, "float")
if key == "durationChange":
return _change_subelement(ele_type, key, xml_temp_step, value, True, "int")
if key == "measure":
if value not in ["", "real time", "meltcurve"]:
raise RdmlError('Unknown or unsupported step measure value: "' + value + '".')
return _change_subelement(ele_type, key, xml_temp_step, value, True, "string")
ele_type = _get_first_child(self._node, "loop")
if ele_type is not None:
xml_temp_step = ["goto", "repeat"]
if key in xml_temp_step:
return _change_subelement(ele_type, key, xml_temp_step, value, False, "posint")
ele_type = _get_first_child(self._node, "pause")
if ele_type is not None:
xml_temp_step = ["temperature"]
if key == "temperature":
return _change_subelement(ele_type, key, xml_temp_step, value, False, "float")
raise KeyError
def keys(self):
"""Returns a list of the keys.
Args:
self: The class self parameter.
Returns:
A list of the key strings.
"""
ele_type = _get_first_child(self._node, "temperature")
if ele_type is not None:
return ["nr", "type", "description", "temperature", "duration", "temperatureChange",
"durationChange", "measure", "ramp"]
ele_type = _get_first_child(self._node, "gradient")
if ele_type is not None:
return ["nr", "type", "description", "highTemperature", "lowTemperature", "duration",
"temperatureChange", "durationChange", "measure", "ramp"]
ele_type = _get_first_child(self._node, "loop")
if ele_type is not None:
return ["nr", "type", "description", "goto", "repeat"]
ele_type = _get_first_child(self._node, "pause")
if ele_type is not None:
return ["nr", "type", "description", "temperature"]
ele_type = _get_first_child(self._node, "lidOpen")
if ele_type is not None:
return ["nr", "type", "description"]
return []
def xmlkeys(self):
"""Returns a list of the keys in the xml file.
Args:
self: The class self parameter.
Returns:
A list of the key strings.
"""
ele_type = _get_first_child(self._node, "temperature")
if ele_type is not None:
return ["temperature", "duration", "temperatureChange", "durationChange", "measure", "ramp"]
ele_type = _get_first_child(self._node, "gradient")
if ele_type is not None:
return ["highTemperature", "lowTemperature", "duration", "temperatureChange",
"durationChange", "measure", "ramp"]
ele_type = _get_first_child(self._node, "loop")
if ele_type is not None:
return ["goto", "repeat"]
ele_type = _get_first_child(self._node, "pause")
if ele_type is not None:
return ["temperature"]
ele_type = _get_first_child(self._node, "lidOpen")
if ele_type is not None:
return []
return []
def tojson(self):
"""Returns a json of the RDML object without fluorescence data.
Args:
self: The class self parameter.
Returns:
A json of the data.
"""
data = {}
_add_first_child_to_dic(self._node, data, False, "nr")
_add_first_child_to_dic(self._node, data, True, "description")
elem = _get_first_child(self._node, "temperature")
if elem is not None:
qdic = {}
_add_first_child_to_dic(elem, qdic, False, "temperature")
_add_first_child_to_dic(elem, qdic, False, "duration")
_add_first_child_to_dic(elem, qdic, True, "temperatureChange")
_add_first_child_to_dic(elem, qdic, True, "durationChange")
_add_first_child_to_dic(elem, qdic, True, "measure")
_add_first_child_to_dic(elem, qdic, True, "ramp")
data["temperature"] = qdic
elem = _get_first_child(self._node, "gradient")
if elem is not None:
qdic = {}
_add_first_child_to_dic(elem, qdic, False, "highTemperature")
_add_first_child_to_dic(elem, qdic, False, "lowTemperature")
_add_first_child_to_dic(elem, qdic, False, "duration")
_add_first_child_to_dic(elem, qdic, True, "temperatureChange")
_add_first_child_to_dic(elem, qdic, True, "durationChange")
_add_first_child_to_dic(elem, qdic, True, "measure")
_add_first_child_to_dic(elem, qdic, True, "ramp")
data["gradient"] = qdic
elem = _get_first_child(self._node, "loop")
if elem is not None:
qdic = {}
_add_first_child_to_dic(elem, qdic, False, "goto")
_add_first_child_to_dic(elem, qdic, False, "repeat")
data["loop"] = qdic
elem = _get_first_child(self._node, "pause")
if elem is not None:
qdic = {}
_add_first_child_to_dic(elem, qdic, False, "temperature")
data["pause"] = qdic
elem = _get_first_child(self._node, "lidOpen")
if elem is not None:
data["lidOpen"] = "lidOpen"
return data
class Experiment:
"""RDML-Python library
The target element used to read and edit one experiment.
Attributes:
_node: The target node of the RDML XML object.
_rdmlFilename: The RDML filename
"""
def __init__(self, node, rdmlFilename):
"""Inits an experiment instance.
Args:
self: The class self parameter.
node: The experiment node.
rdmlFilename: The RDML filename.
Returns:
No return value. Function may raise RdmlError if required.
"""
self._node = node
self._rdmlFilename = rdmlFilename
def __getitem__(self, key):
"""Returns the value for the key.
Args:
self: The class self parameter.
key: The key of the experiment subelement
Returns:
A string of the data or None.
"""
if key == "id":
return self._node.get('id')
if key == "description":
var = _get_first_child_text(self._node, key)
if var == "":
return None
else:
return var
raise KeyError
def __setitem__(self, key, value):
"""Changes the value for the key.
Args:
self: The class self parameter.
key: The key of the target subelement
value: The new value for the key
Returns:
No return value, changes self. Function may raise RdmlError if required.
"""
if key == "id":
return _change_subelement(self._node, key, self.xmlkeys(), value, False, "string")
if key == "description":
return _change_subelement(self._node, key, self.xmlkeys(), value, True, "string")
raise KeyError
def keys(self):
"""Returns a list of the keys.
Args:
self: The class self parameter.
Returns:
A list of the key strings.
"""
return ["id", "description"]
def xmlkeys(self):
"""Returns a list of the keys in the xml file.
Args:
self: The class self parameter.
Returns:
A list of the key strings.
"""
return ["description", "documentation", "run"]
def documentation_ids(self):
"""Returns a list of the keys in the xml file.
Args:
self: The class self parameter.
Returns:
A list of the key strings.
"""
return _get_all_children_id(self._node, "documentation")
def update_documentation_ids(self, ids):
"""Returns a json of the RDML object without fluorescence data.
Args:
self: The class self parameter.
ids: A dictionary with id and true/false pairs
Returns:
True if a change was made, else false. Function may raise RdmlError if required.
"""
old = self.documentation_ids()
good_ids = _value_to_booldic(ids)
mod = False
for id, inc in good_ids.items():
if inc is True:
if id not in old:
new_node = _create_new_element(self._node, "documentation", id)
place = _get_tag_pos(self._node, "documentation", self.xmlkeys(), 999999999)
self._node.insert(place, new_node)
mod = True
else:
if id in old:
elem = _get_first_child_by_pos_or_id(self._node, "documentation", id, None)
self._node.remove(elem)
mod = True
return mod
def move_documentation(self, oldposition, newposition):
"""Moves the element to the new position in the list.
Args:
self: The class self parameter.
oldposition: The old position of the element
newposition: The new position of the element
Returns:
No return value, changes self. Function may raise RdmlError if required.
"""
pos = _get_tag_pos(self._node, "documentation", self.xmlkeys(), newposition)
ele = _get_first_child_by_pos_or_id(self._node, "documentation", None, oldposition)
self._node.insert(pos, ele)
def runs(self):
"""Returns a list of all run elements.
Args:
self: The class self parameter.
Returns:
A list of all run elements.
"""
exp = _get_all_children(self._node, "run")
ret = []
for node in exp:
ret.append(Run(node, self._rdmlFilename))
return ret
def new_run(self, id, newposition=None):
"""Creates a new run element.
Args:
self: The class self parameter.
id: Run unique id (required)
newposition: Run position in the list of experiments (optional)
Returns:
Nothing, changes self.
"""
new_node = _create_new_element(self._node, "run", id)
place = _get_tag_pos(self._node, "run", self.xmlkeys(), newposition)
self._node.insert(place, new_node)
def move_run(self, id, newposition):
"""Moves the element to the new position in the list.
Args:
self: The class self parameter.
id: Run unique id
newposition: The new position of the element
Returns:
No return value, changes self. Function may raise RdmlError if required.
"""
_move_subelement(self._node, "run", id, self.xmlkeys(), newposition)
def get_run(self, byid=None, byposition=None):
"""Returns an run element by position or id.
Args:
self: The class self parameter.
byid: Select the element by the element id.
byposition: Select the element by position in the list.
Returns:
The found element or None.
"""
return Run(_get_first_child_by_pos_or_id(self._node, "run", byid, byposition), self._rdmlFilename)
def delete_run(self, byid=None, byposition=None):
"""Deletes an run element.
Args:
self: The class self parameter.
byid: Select the element by the element id.
byposition: Select the element by position in the list.
Returns:
Nothing, changes self.
"""
elem = _get_first_child_by_pos_or_id(self._node, "run", byid, byposition)
# Delete in Table files
fileList = []
exp = _get_all_children(elem, "react")
for node in exp:
partit = _get_first_child(node, "partitions")
if partit is not None:
finalFileName = "partitions/" + _get_first_child_text(partit, "endPtTable")
if finalFileName != "partitions/":
fileList.append(finalFileName)
if len(fileList) > 0:
if self._rdmlFilename is not None and self._rdmlFilename != "":
if zipfile.is_zipfile(self._rdmlFilename):
with zipfile.ZipFile(self._rdmlFilename, 'r') as RDMLin:
tempFolder, tempName = tempfile.mkstemp(dir=os.path.dirname(self._rdmlFilename))
os.close(tempFolder)
with zipfile.ZipFile(tempName, mode='w', compression=zipfile.ZIP_DEFLATED) as RDMLout:
RDMLout.comment = RDMLin.comment
for item in RDMLin.infolist():
if item.filename not in fileList:
RDMLout.writestr(item, RDMLin.read(item.filename))
os.remove(self._rdmlFilename)
os.rename(tempName, self._rdmlFilename)
# Delete the node
self._node.remove(elem)
def tojson(self):
"""Returns a json of the RDML object without fluorescence data.
Args:
self: The class self parameter.
Returns:
A json of the data.
"""
allRuns = self.runs()
runs = []
for exp in allRuns:
runs.append(exp.tojson())
data = {
"id": self._node.get('id'),
}
_add_first_child_to_dic(self._node, data, True, "description")
data["documentations"] = self.documentation_ids()
data["runs"] = runs
return data
class Run:
"""RDML-Python library
The run element used to read and edit one run.
Attributes:
_node: The run node of the RDML XML object.
_rdmlFilename: The RDML filename.
"""
def __init__(self, node, rdmlFilename):
"""Inits an run instance.
Args:
self: The class self parameter.
node: The sample node.
rdmlFilename: The RDML filename.
Returns:
No return value. Function may raise RdmlError if required.
"""
self._node = node
self._rdmlFilename = rdmlFilename
def __getitem__(self, key):
"""Returns the value for the key.
Args:
self: The class self parameter.
key: The key of the run subelement
Returns:
A string of the data or None.
"""
if key == "id":
return self._node.get('id')
if key in ["description", "instrument", "backgroundDeterminationMethod", "cqDetectionMethod", "runDate"]:
var = _get_first_child_text(self._node, key)
if var == "":
return None
else:
return var
if key == "thermalCyclingConditions":
forId = _get_first_child(self._node, "thermalCyclingConditions")
if forId is not None:
return forId.attrib['id']
else:
return None
if key in ["dataCollectionSoftware_name", "dataCollectionSoftware_version"]:
ele = _get_first_child(self._node, "dataCollectionSoftware")
if ele is None:
return None
if key == "dataCollectionSoftware_name":
return _get_first_child_text(ele, "name")
if key == "dataCollectionSoftware_version":
return _get_first_child_text(ele, "version")
raise RdmlError('Run dataCollectionSoftware programming read error.')
if key in ["pcrFormat_rows", "pcrFormat_columns", "pcrFormat_rowLabel", "pcrFormat_columnLabel"]:
ele = _get_first_child(self._node, "pcrFormat")
if ele is None:
return None
if key == "pcrFormat_rows":
return _get_first_child_text(ele, "rows")
if key == "pcrFormat_columns":
return _get_first_child_text(ele, "columns")
if key == "pcrFormat_rowLabel":
return _get_first_child_text(ele, "rowLabel")
if key == "pcrFormat_columnLabel":
return _get_first_child_text(ele, "columnLabel")
raise RdmlError('Run pcrFormat programming read error.')
raise KeyError
def __setitem__(self, key, value):
"""Changes the value for the key.
Args:
self: The class self parameter.
key: The key of the run subelement
value: The new value for the key
Returns:
No return value, changes self. Function may raise RdmlError if required.
"""
if key == "cqDetectionMethod":
if value not in ["", "automated threshold and baseline settings", "manual threshold and baseline settings",
"second derivative maximum", "other"]:
raise RdmlError('Unknown or unsupported run cqDetectionMethod value "' + value + '".')
if key in ["pcrFormat_rowLabel", "pcrFormat_columnLabel"]:
if value not in ["ABC", "123", "A1a1"]:
raise RdmlError('Unknown or unsupported run ' + key + ' value "' + value + '".')
if key == "id":
return _change_subelement(self._node, key, self.xmlkeys(), value, False, "string")
if key in ["description", "instrument", "backgroundDeterminationMethod", "cqDetectionMethod", "runDate"]:
return _change_subelement(self._node, key, self.xmlkeys(), value, True, "string")
if key == "thermalCyclingConditions":
forId = _get_or_create_subelement(self._node, "thermalCyclingConditions", self.xmlkeys())
if value is not None and value != "":
# We do not check that ID is valid to allow recreate_lost_ids()
forId.attrib['id'] = value
else:
self._node.remove(forId)
return
if key in ["dataCollectionSoftware_name", "dataCollectionSoftware_version"]:
ele = _get_or_create_subelement(self._node, "dataCollectionSoftware", self.xmlkeys())
if key == "dataCollectionSoftware_name":
_change_subelement(ele, "name", ["name", "version"], value, True, "string")
if key == "dataCollectionSoftware_version":
_change_subelement(ele, "version", ["name", "version"], value, True, "string")
_remove_irrelevant_subelement(self._node, "dataCollectionSoftware")
return
if key in ["pcrFormat_rows", "pcrFormat_columns", "pcrFormat_rowLabel", "pcrFormat_columnLabel"]:
ele = _get_or_create_subelement(self._node, "pcrFormat", self.xmlkeys())
if key == "pcrFormat_rows":
_change_subelement(ele, "rows", ["rows", "columns", "rowLabel", "columnLabel"], value, True, "string")
if key == "pcrFormat_columns":
_change_subelement(ele, "columns", ["rows", "columns", "rowLabel", "columnLabel"], value, True, "string")
if key == "pcrFormat_rowLabel":
_change_subelement(ele, "rowLabel", ["rows", "columns", "rowLabel", "columnLabel"], value, True, "string")
if key == "pcrFormat_columnLabel":
_change_subelement(ele, "columnLabel", ["rows", "columns", "rowLabel", "columnLabel"], value, True, "string")
_remove_irrelevant_subelement(self._node, "pcrFormat")
return
raise KeyError
def keys(self):
"""Returns a list of the keys.
Args:
self: The class self parameter.
Returns:
A list of the key strings.
"""
return ["id", "description", "instrument", "dataCollectionSoftware_name", "dataCollectionSoftware_version",
"backgroundDeterminationMethod", "cqDetectionMethod", "thermalCyclingConditions", "pcrFormat_rows",
"pcrFormat_columns", "pcrFormat_rowLabel", "pcrFormat_columnLabel", "runDate", "react"]
def xmlkeys(self):
"""Returns a list of the keys in the xml file.
Args:
self: The class self parameter.
Returns:
A list of the key strings.
"""
return ["description", "documentation", "experimenter", "instrument", "dataCollectionSoftware",
"backgroundDeterminationMethod", "cqDetectionMethod", "thermalCyclingConditions", "pcrFormat",
"runDate", "react"]
def documentation_ids(self):
"""Returns a list of the keys in the xml file.
Args:
self: The class self parameter.
Returns:
A list of the key strings.
"""
return _get_all_children_id(self._node, "documentation")
def update_documentation_ids(self, ids):
"""Returns a json of the RDML object without fluorescence data.
Args:
self: The class self parameter.
ids: A dictionary with id and true/false pairs
Returns:
True if a change was made, else false. Function may raise RdmlError if required.
"""
old = self.documentation_ids()
good_ids = _value_to_booldic(ids)
mod = False
for id, inc in good_ids.items():
if inc is True:
if id not in old:
new_node = _create_new_element(self._node, "documentation", id)
place = _get_tag_pos(self._node, "documentation", self.xmlkeys(), 999999999)
self._node.insert(place, new_node)
mod = True
else:
if id in old:
elem = _get_first_child_by_pos_or_id(self._node, "documentation", id, None)
self._node.remove(elem)
mod = True
return mod
def move_documentation(self, oldposition, newposition):
"""Moves the element to the new position in the list.
Args:
self: The class self parameter.
oldposition: The old position of the element
newposition: The new position of the element
Returns:
No return value, changes self. Function may raise RdmlError if required.
"""
pos = _get_tag_pos(self._node, "documentation", self.xmlkeys(), newposition)
ele = _get_first_child_by_pos_or_id(self._node, "documentation", None, oldposition)
self._node.insert(pos, ele)
def experimenter_ids(self):
"""Returns a list of the keys in the xml file.
Args:
self: The class self parameter.
Returns:
A list of the key strings.
"""
return _get_all_children_id(self._node, "experimenter")
def update_experimenter_ids(self, ids):
"""Returns a json of the RDML object without fluorescence data.
Args:
self: The class self parameter.
ids: A dictionary with id and true/false pairs
Returns:
True if a change was made, else false. Function may raise RdmlError if required.
"""
old = self.experimenter_ids()
good_ids = _value_to_booldic(ids)
mod = False
for id, inc in good_ids.items():
if inc is True:
if id not in old:
new_node = _create_new_element(self._node, "experimenter", id)
place = _get_tag_pos(self._node, "experimenter", self.xmlkeys(), 999999999)
self._node.insert(place, new_node)
mod = True
else:
if id in old:
elem = _get_first_child_by_pos_or_id(self._node, "experimenter", id, None)
self._node.remove(elem)
mod = True
return mod
def move_experimenter(self, oldposition, newposition):
"""Moves the element to the new position in the list.
Args:
self: The class self parameter.
oldposition: The old position of the element
newposition: The new position of the element
Returns:
No return value, changes self. Function may raise RdmlError if required.
"""
pos = _get_tag_pos(self._node, "experimenter", self.xmlkeys(), newposition)
ele = _get_first_child_by_pos_or_id(self._node, "experimenter", None, oldposition)
self._node.insert(pos, ele)
def tojson(self):
"""Returns a json of the RDML object without fluorescence data.
Args:
self: The class self parameter.
Returns:
A json of the data.
"""
data = {
"id": self._node.get('id'),
}
_add_first_child_to_dic(self._node, data, True, "description")
data["documentations"] = self.documentation_ids()
data["experimenters"] = self.experimenter_ids()
_add_first_child_to_dic(self._node, data, True, "instrument")
elem = _get_first_child(self._node, "dataCollectionSoftware")
if elem is not None:
qdic = {}
_add_first_child_to_dic(elem, qdic, True, "name")
_add_first_child_to_dic(elem, qdic, True, "version")
if len(qdic.keys()) != 0:
data["dataCollectionSoftware"] = qdic
_add_first_child_to_dic(self._node, data, True, "backgroundDeterminationMethod")
_add_first_child_to_dic(self._node, data, True, "cqDetectionMethod")
forId = _get_first_child(self._node, "thermalCyclingConditions")
if forId is not None:
if forId.attrib['id'] != "":
data["thermalCyclingConditions"] = forId.attrib['id']
elem = _get_first_child(self._node, "pcrFormat")
if elem is not None:
qdic = {}
_add_first_child_to_dic(elem, qdic, False, "rows")
_add_first_child_to_dic(elem, qdic, False, "columns")
_add_first_child_to_dic(elem, qdic, False, "rowLabel")
_add_first_child_to_dic(elem, qdic, False, "columnLabel")
data["pcrFormat"] = qdic
_add_first_child_to_dic(self._node, data, True, "runDate")
data["react"] = _get_number_of_children(self._node, "react")
return data
def export_table(self, dMode):
"""Returns a tab seperated table file with the react fluorescence data.
Args:
self: The class self parameter.
dMode: amp for amplification data, melt for meltcurve data
Returns:
A string with the data.
"""
samTypeLookup = {}
tarTypeLookup = {}
tarDyeLookup = {}
data = ""
# Get the information for the lookup dictionaries
pExp = self._node.getparent()
pRoot = pExp.getparent()
samples = _get_all_children(pRoot, "sample")
for sample in samples:
if sample.attrib['id'] != "":
samId = sample.attrib['id']
forType = _get_first_child_text(sample, "type")
if forType != "":
samTypeLookup[samId] = forType
targets = _get_all_children(pRoot, "target")
for target in targets:
if target.attrib['id'] != "":
tarId = target.attrib['id']
forType = _get_first_child_text(target, "type")
if forType != "":
tarTypeLookup[tarId] = forType
forId = _get_first_child(target, "dyeId")
if forId is not None:
if forId.attrib['id'] != "":
tarDyeLookup[tarId] = forId.attrib['id']
# Now create the header line
data += "Well\tSample\tSample Type\tTarget\tTarget Type\tDye\t"
reacts = _get_all_children(self._node, "react")
if len(reacts) < 1:
return ""
react_datas = _get_all_children(reacts[0], "data")
if len(react_datas) < 1:
return ""
headArr = []
if dMode == "amp":
adps = _get_all_children(react_datas[0], "adp")
for adp in adps:
headArr.append(_get_first_child_text(adp, "cyc"))
headArr = sorted(headArr, key=int)
else:
mdps = _get_all_children(react_datas[0], "mdp")
for mdp in mdps:
headArr.append(_get_first_child_text(mdp, "tmp"))
headArr = sorted(headArr, key=float, reverse=True)
for hElem in headArr:
data += hElem + "\t"
data += '\n'
# Now create the data lines
reacts = _get_all_children(self._node, "react")
wellData = []
for react in reacts:
reactId = react.get('id')
dataSample = reactId + '\t'
react_sample = "No Sample"
react_sample_type = "No Sample Type"
forId = _get_first_child(react, "sample")
if forId is not None:
if forId.attrib['id'] != "":
react_sample = forId.attrib['id']
react_sample_type = samTypeLookup[react_sample]
dataSample += react_sample + '\t' + react_sample_type
react_datas = _get_all_children(react, "data")
for react_data in react_datas:
dataLine = dataSample
react_target = "No Target"
react_target_type = "No Target Type"
react_target_dye = "No Dye"
forId = _get_first_child(react_data, "tar")
if forId is not None:
if forId.attrib['id'] != "":
react_target = forId.attrib['id']
react_target_type = tarTypeLookup[react_target]
react_target_dye = tarDyeLookup[react_target]
dataLine += "\t" + react_target + '\t' + react_target_type + '\t' + react_target_dye
fluorList = []
if dMode == "amp":
adps = _get_all_children(react_data, "adp")
for adp in adps:
cyc = _get_first_child_text(adp, "cyc")
fluor = _get_first_child_text(adp, "fluor")
fluorList.append([cyc, fluor])
fluorList = sorted(fluorList, key=_sort_list_int)
else:
mdps = _get_all_children(react_data, "mdp")
for mdp in mdps:
tmp = _get_first_child_text(mdp, "tmp")
fluor = _get_first_child_text(mdp, "fluor")
fluorList.append([tmp, fluor])
fluorList = sorted(fluorList, key=_sort_list_float)
for hElem in fluorList:
dataLine += "\t" + hElem[1]
dataLine += '\n'
wellData.append([reactId, dataLine])
wellData = sorted(wellData, key=_sort_list_int)
for hElem in wellData:
data += hElem[1]
return data
def import_table(self, rootEl, filename, dMode):
"""Imports data from a tab seperated table file with react fluorescence data.
Args:
self: The class self parameter.
rootEl: The rdml root element.
filename: The tab file to open.
dMode: amp for amplification data, melt for meltcurve data.
Returns:
A string with the modifications made.
"""
ret = ""
with open(filename, "r") as tfile:
fileContent = tfile.read()
newlineFix = fileContent.replace("\r\n", "\n")
tabLines = newlineFix.split("\n")
head = tabLines[0].split("\t")
if (head[0] != "Well" or head[1] != "Sample" or head[2] != "Sample Type" or
head[3] != "Target" or head[4] != "Target Type" or head[5] != "Dye"):
raise RdmlError('The tab-format is not valid, essential columns are missing.')
# Get the information for the lookup dictionaries
samTypeLookup = {}
tarTypeLookup = {}
dyeLookup = {}
samples = _get_all_children(rootEl._node, "sample")
for sample in samples:
if sample.attrib['id'] != "":
samId = sample.attrib['id']
forType = _get_first_child_text(sample, "type")
if forType != "":
samTypeLookup[samId] = forType
targets = _get_all_children(rootEl._node, "target")
for target in targets:
if target.attrib['id'] != "":
tarId = target.attrib['id']
forType = _get_first_child_text(target, "type")
if forType != "":
tarTypeLookup[tarId] = forType
forId = _get_first_child(target, "dyeId")
if forId is not None and forId.attrib['id'] != "":
dyeLookup[forId.attrib['id']] = 1
# Process the lines
for tabLine in tabLines[1:]:
sLin = tabLine.split("\t")
if len(sLin) < 7 or sLin[1] == "" or sLin[2] == "" or sLin[3] == "" or sLin[4] == "" or sLin[5] == "":
continue
if sLin[1] not in samTypeLookup:
rootEl.new_sample(sLin[1], sLin[2])
samTypeLookup[sLin[1]] = sLin[2]
ret += "Created sample \"" + sLin[1] + "\" with type \"" + sLin[2] + "\"\n"
if sLin[3] not in tarTypeLookup:
if sLin[5] not in dyeLookup:
rootEl.new_dye(sLin[5])
dyeLookup[sLin[5]] = 1
ret += "Created dye \"" + sLin[5] + "\"\n"
rootEl.new_target(sLin[3], sLin[4])
elem = rootEl.get_target(byid=sLin[3])
elem["dyeId"] = sLin[5]
tarTypeLookup[sLin[3]] = sLin[4]
ret += "Created " + sLin[3] + " with type \"" + sLin[4] + "\" and dye \"" + sLin[5] + "\"\n"
react = None
data = None
# Get the position number if required
wellPos = sLin[0]
if re.search(r"\D\d+", sLin[0]):
old_letter = ord(re.sub(r"\d", "", sLin[0]).upper()) - ord("A")
old_nr = int(re.sub(r"\D", "", sLin[0]))
newId = old_nr + old_letter * int(self["pcrFormat_columns"])
wellPos = str(newId)
if re.search(r"\D\d+\D\d+", sLin[0]):
old_left = re.sub(r"\D\d+$", "", sLin[0])
old_left_letter = ord(re.sub(r"\d", "", old_left).upper()) - ord("A")
old_left_nr = int(re.sub(r"\D", "", old_left)) - 1
old_right = re.sub(r"^\D\d+", "", sLin[0])
old_right_letter = ord(re.sub(r"\d", "", old_right).upper()) - ord("A")
old_right_nr = int(re.sub(r"\D", "", old_right))
newId = old_left_nr * 8 + old_right_nr + old_left_letter * 768 + old_right_letter * 96
wellPos = str(newId)
exp = _get_all_children(self._node, "react")
for node in exp:
if wellPos == node.attrib['id']:
react = node
forId = _get_first_child_text(react, "sample")
if forId and forId != "" and forId.attrib['id'] != sLin[1]:
ret += "Missmatch: Well " + wellPos + " (" + sLin[0] + ") has sample \"" + forId.attrib['id'] + \
"\" in RDML file and sample \"" + sLin[1] + "\" in tab file.\n"
break
if react is None:
new_node = et.Element("react", id=wellPos)
place = _get_tag_pos(self._node, "react", self.xmlkeys(), 9999999)
self._node.insert(place, new_node)
react = new_node
new_node = et.Element("sample", id=sLin[1])
react.insert(0, new_node)
exp = _get_all_children(react, "data")
for node in exp:
forId = _get_first_child(node, "tar")
if forId is not None and forId.attrib['id'] == sLin[3]:
data = node
break
if data is None:
new_node = et.Element("data")
place = _get_tag_pos(react, "data", ["sample", "data", "partitions"], 9999999)
react.insert(place, new_node)
data = new_node
new_node = et.Element("tar", id=sLin[3])
place = _get_tag_pos(data, "tar",
_getXMLDataType(),
9999999)
data.insert(place, new_node)
if dMode == "amp":
presentAmp = _get_first_child(data, "adp")
if presentAmp is not None:
ret += "Well " + wellPos + " (" + sLin[0] + ") with sample \"" + sLin[1] + " and target \"" + \
sLin[3] + "\" has already amplification data, no data were added.\n"
else:
colCount = 6
for col in sLin[6:]:
new_node = et.Element("adp")
place = _get_tag_pos(data, "adp",
_getXMLDataType(),
9999999)
data.insert(place, new_node)
new_sub = et.Element("cyc")
new_sub.text = head[colCount]
place = _get_tag_pos(new_node, "cyc", ["cyc", "tmp", "fluor"], 9999999)
new_node.insert(place, new_sub)
new_sub = et.Element("fluor")
new_sub.text = col
place = _get_tag_pos(new_node, "fluor", ["cyc", "tmp", "fluor"], 9999999)
new_node.insert(place, new_sub)
colCount += 1
if dMode == "melt":
presentAmp = _get_first_child(data, "mdp")
if presentAmp is not None:
ret += "Well " + wellPos + " (" + sLin[0] + ") with sample \"" + sLin[1] + " and target \"" + \
sLin[3] + "\" has already melting data, no data were added.\n"
else:
colCount = 6
for col in sLin[6:]:
new_node = et.Element("mdp")
place = _get_tag_pos(data, "mdp",
_getXMLDataType(),
9999999)
data.insert(place, new_node)
new_sub = et.Element("tmp")
new_sub.text = head[colCount]
place = _get_tag_pos(new_node, "tmp", ["tmp", "fluor"], 9999999)
new_node.insert(place, new_sub)
new_sub = et.Element("fluor")
new_sub.text = col
place = _get_tag_pos(new_node, "fluor", ["tmp", "fluor"], 9999999)
new_node.insert(place, new_sub)
colCount += 1
return ret
def import_digital_data(self, rootEl, fileformat, filename, filelist, ignoreCh=""):
"""Imports data from a tab seperated table file with digital PCR overview data.
Args:
self: The class self parameter.
rootEl: The rdml root element.
fileformat: The format of the files (RDML, BioRad).
filename: The tab overvie file to open (recommended but optional).
filelist: A list of tab files with fluorescence data (optional, works without filename).
Returns:
A string with the modifications made.
"""
tempList = re.split(r"\D+", ignoreCh)
ignoreList = []
for posNum in tempList:
if re.search(r"\d", posNum):
ignoreList.append(int(posNum))
ret = ""
wellNames = []
uniqueFileNames = []
if filelist is None:
filelist = []
# Get the information for the lookup dictionaries
samTypeLookup = {}
tarTypeLookup = {}
dyeLookup = {}
headerLookup = {}
fileLookup = {}
fileNameSuggLookup = {}
samples = _get_all_children(rootEl._node, "sample")
for sample in samples:
if sample.attrib['id'] != "":
samId = sample.attrib['id']
forType = _get_first_child_text(sample, "type")
if forType != "":
samTypeLookup[samId] = forType
targets = _get_all_children(rootEl._node, "target")
for target in targets:
if target.attrib['id'] != "":
tarId = target.attrib['id']
forType = _get_first_child_text(target, "type")
if forType != "":
tarTypeLookup[tarId] = forType
dyes = _get_all_children(rootEl._node, "dye")
for dye in dyes:
if dye.attrib['id'] != "":
dyeLookup[dye.attrib['id']] = 1
# Work the overview file
if filename is not None:
with open(filename, newline='') as tfile: # add encoding='utf-8' ?
posCount = 0
posWell = 0
posSample = -1
posSampleType = -1
posDye = -1
posDyeCh2 = -1
posDyeCh3 = -1
posTarget = -1
posTargetCh2 = -1
posTargetCh3 = -1
posTargetType = -1
posCopConc = -1
posPositives = -1
posNegatives = -1
posCopConcCh2 = -1
posPositivesCh2 = -1
posNegativesCh2 = -1
posCopConcCh3 = -1
posPositivesCh3 = -1
posNegativesCh3 = -1
posUndefined = -1
posExcluded = -1
posVolume = -1
posFilename = -1
countUpTarget = 1
if fileformat == "RDML":
tabLines = list(csv.reader(tfile, delimiter='\t'))
for hInfo in tabLines[0]:
if hInfo == "Sample":
posSample = posCount
if hInfo == "SampleType":
posSampleType = posCount
if hInfo == "Target":
posTarget = posCount
if hInfo == "TargetType":
posTargetType = posCount
if hInfo == "Dye":
posDye = posCount
if hInfo == "Copies":
posCopConc = posCount
if hInfo == "Positives":
posPositives = posCount
if hInfo == "Negatives":
posNegatives = posCount
if hInfo == "Undefined":
posUndefined = posCount
if hInfo == "Excluded":
posExcluded = posCount
if hInfo == "Volume":
posVolume = posCount
if hInfo == "FileName":
posFilename = posCount
posCount += 1
elif fileformat == "Bio-Rad":
tabLines = list(csv.reader(tfile, delimiter=','))
for hInfo in tabLines[0]:
if hInfo == "Sample":
posSample = posCount
if hInfo in ["TargetType", "TypeAssay"]:
posDye = posCount
if hInfo in ["Target", "Assay"]:
posTarget = posCount
if hInfo == "CopiesPer20uLWell":
posCopConc = posCount
if hInfo == "Positives":
posPositives = posCount
if hInfo == "Negatives":
posNegatives = posCount
posCount += 1
elif fileformat == "Stilla":
posWell = 1
tabLines = list(csv.reader(tfile, delimiter=','))
for hInfo in tabLines[0]:
hInfo = re.sub(r"^ +", '', hInfo)
if hInfo == "SampleName":
posSample = posCount
# This is a hack of the format to allow specification of targets
if hInfo == "Blue_Channel_Target":
posTarget = posCount
if hInfo == "Green_Channel_Target":
posTargetCh2 = posCount
if hInfo == "Red_Channel_Target":
posTargetCh3 = posCount
# End of hack
if hInfo == "Blue_Channel_Concentration":
posCopConc = posCount
if hInfo == "Blue_Channel_NumberOfPositiveDroplets":
posPositives = posCount
if hInfo == "Blue_Channel_NumberOfNegativeDroplets":
posNegatives = posCount
if hInfo == "Green_Channel_Concentration":
posCopConcCh2 = posCount
if hInfo == "Green_Channel_NumberOfPositiveDroplets":
posPositivesCh2 = posCount
if hInfo == "Green_Channel_NumberOfNegativeDroplets":
posNegativesCh2 = posCount
if hInfo == "Red_Channel_Concentration":
posCopConcCh3 = posCount
if hInfo == "Red_Channel_NumberOfPositiveDroplets":
posPositivesCh3 = posCount
if hInfo == "Red_Channel_NumberOfNegativeDroplets":
posNegativesCh3 = posCount
posCount += 1
else:
raise RdmlError('Unknown digital file format.')
if posSample == -1:
raise RdmlError('The overview tab-format is not valid, sample columns are missing.')
if posDye == -1 and fileformat != "Stilla":
raise RdmlError('The overview tab-format is not valid, dye / channel columns are missing.')
if posTarget == -1 and fileformat != "Stilla":
raise RdmlError('The overview tab-format is not valid, target columns are missing.')
if posPositives == -1:
raise RdmlError('The overview tab-format is not valid, positives columns are missing.')
if posNegatives == -1:
raise RdmlError('The overview tab-format is not valid, negatives columns are missing.')
# Process the lines
for rowNr in range(1, len(tabLines)):
emptyLine = True
if len(tabLines[rowNr]) < 7:
continue
for colNr in range(0, len(tabLines[rowNr])):
if tabLines[rowNr][colNr] != "":
emptyLine = False
tabLines[rowNr][colNr] = re.sub(r'^ +', '', tabLines[rowNr][colNr])
tabLines[rowNr][colNr] = re.sub(r' +$', '', tabLines[rowNr][colNr])
if emptyLine is True:
continue
sLin = tabLines[rowNr]
if sLin[posSample] not in samTypeLookup:
posSampleTypeName = "unkn"
if posSampleType != -1:
posSampleTypeName = sLin[posSampleType]
rootEl.new_sample(sLin[posSample], posSampleTypeName)
samTypeLookup[sLin[posSample]] = posSampleTypeName
ret += "Created sample \"" + sLin[posSample] + "\" with type \"" + posSampleTypeName + "\"\n"
# Fix well position
wellPos = re.sub(r"\"", "", sLin[posWell])
if fileformat == "Stilla":
wellPos = re.sub(r'^\d+-', '', wellPos)
# Create nonexisting targets and dyes
if fileformat == "Stilla":
if 1 not in ignoreList:
if posTarget > -1:
crTarName = sLin[posTarget]
else:
crTarName = " Target " + str(countUpTarget) + " Ch1"
countUpTarget += 1
chan = "Ch1"
if crTarName not in tarTypeLookup:
if chan not in dyeLookup:
rootEl.new_dye(chan)
dyeLookup[chan] = 1
ret += "Created dye \"" + chan + "\"\n"
rootEl.new_target(crTarName, "toi")
elem = rootEl.get_target(byid=crTarName)
elem["dyeId"] = chan
tarTypeLookup[crTarName] = "toi"
ret += "Created " + crTarName + " with type \"toi\" and dye \"" + chan + "\"\n"
if wellPos.upper() not in headerLookup:
headerLookup[wellPos.upper()] = {}
headerLookup[wellPos.upper()][chan] = crTarName
if 2 not in ignoreList:
if posTargetCh2 > -1:
crTarName = sLin[posTargetCh2]
else:
crTarName = " Target " + str(countUpTarget) + " Ch2"
countUpTarget += 1
chan = "Ch2"
if crTarName not in tarTypeLookup:
if chan not in dyeLookup:
rootEl.new_dye(chan)
dyeLookup[chan] = 1
ret += "Created dye \"" + chan + "\"\n"
rootEl.new_target(crTarName, "toi")
elem = rootEl.get_target(byid=crTarName)
elem["dyeId"] = chan
tarTypeLookup[crTarName] = "toi"
ret += "Created " + crTarName + " with type \"toi\" and dye \"" + chan + "\"\n"
if wellPos.upper() not in headerLookup:
headerLookup[wellPos.upper()] = {}
headerLookup[wellPos.upper()][chan] = crTarName
if 3 not in ignoreList:
if posTargetCh3 > -1:
crTarName = sLin[posTargetCh3]
else:
crTarName = " Target " + str(countUpTarget) + " Ch3"
countUpTarget += 1
chan = "Ch3"
if crTarName not in tarTypeLookup:
if chan not in dyeLookup:
rootEl.new_dye(chan)
dyeLookup[chan] = 1
ret += "Created dye \"" + chan + "\"\n"
rootEl.new_target(crTarName, "toi")
elem = rootEl.get_target(byid=crTarName)
elem["dyeId"] = chan
tarTypeLookup[crTarName] = "toi"
ret += "Created " + crTarName + " with type \"toi\" and dye \"" + chan + "\"\n"
if wellPos.upper() not in headerLookup:
headerLookup[wellPos.upper()] = {}
headerLookup[wellPos.upper()][chan] = crTarName
else:
if fileformat == "Bio-Rad":
posDyeName = sLin[posDye][:3]
else:
posDyeName = sLin[posDye]
if posTarget > -1 and int(re.sub(r"\D", "", posDyeName)) not in ignoreList:
if sLin[posTarget] not in tarTypeLookup:
if posDyeName not in dyeLookup:
rootEl.new_dye(posDyeName)
dyeLookup[posDyeName] = 1
ret += "Created dye \"" + posDyeName + "\"\n"
posTargetTypeName = "toi"
if posTargetType != -1:
posTargetTypeName = sLin[posTargetType]
rootEl.new_target(sLin[posTarget], posTargetTypeName)
elem = rootEl.get_target(byid=sLin[posTarget])
elem["dyeId"] = posDyeName
tarTypeLookup[sLin[posTarget]] = posTargetTypeName
ret += "Created " + sLin[posTarget] + " with type \"" + posTargetTypeName + "\" and dye \"" + posDyeName + "\"\n"
if wellPos.upper() not in headerLookup:
headerLookup[wellPos.upper()] = {}
headerLookup[wellPos.upper()][posDyeName] = sLin[posTarget]
if posFilename != -1 and sLin[posFilename] != "":
fileNameSuggLookup[wellPos.upper()] = sLin[posFilename]
react = None
partit = None
data = None
# Get the position number if required
wellPosStore = wellPos
if re.search(r"\D\d+", wellPos):
old_letter = ord(re.sub(r"\d", "", wellPos.upper())) - ord("A")
old_nr = int(re.sub(r"\D", "", wellPos))
newId = old_nr + old_letter * int(self["pcrFormat_columns"])
wellPos = str(newId)
exp = _get_all_children(self._node, "react")
for node in exp:
if wellPos == node.attrib['id']:
react = node
forId = _get_first_child_text(react, "sample")
if forId and forId != "" and forId.attrib['id'] != sLin[posSample]:
ret += "Missmatch: Well " + wellPos + " (" + sLin[posWell] + ") has sample \"" + forId.attrib['id'] + \
"\" in RDML file and sample \"" + sLin[posSample] + "\" in tab file.\n"
break
if react is None:
new_node = et.Element("react", id=wellPos)
place = _get_tag_pos(self._node, "react", self.xmlkeys(), 9999999)
self._node.insert(place, new_node)
react = new_node
new_node = et.Element("sample", id=sLin[posSample])
react.insert(0, new_node)
partit = _get_first_child(react, "partitions")
if partit is None:
new_node = et.Element("partitions")
place = _get_tag_pos(react, "partitions", ["sample", "data", "partitions"], 9999999)
react.insert(place, new_node)
partit = new_node
new_node = et.Element("volume")
if fileformat == "RDML":
new_node.text = sLin[posVolume]
elif fileformat == "Bio-Rad":
new_node.text = "0.85"
elif fileformat == "Stilla":
new_node.text = "0.59"
else:
new_node.text = "0.70"
place = _get_tag_pos(partit, "volume", ["volume", "endPtTable", "data"], 9999999)
partit.insert(place, new_node)
if fileformat == "Stilla":
exp = _get_all_children(partit, "data")
for i in range(1, 4):
if i in ignoreList:
continue
data = None
posDyeName = "Ch" + str(i)
stillaTarget = headerLookup[wellPosStore.upper()][posDyeName]
stillaConc = "0"
stillaPos = "0"
stillaNeg = "0"
if i == 1:
stillaConc = sLin[posCopConc]
stillaPos = sLin[posPositives]
stillaNeg = sLin[posNegatives]
if i == 2:
stillaConc = sLin[posCopConcCh2]
stillaPos = sLin[posPositivesCh2]
stillaNeg = sLin[posNegativesCh2]
if i == 3:
stillaConc = sLin[posCopConcCh3]
stillaPos = sLin[posPositivesCh3]
stillaNeg = sLin[posNegativesCh3]
if re.search(r"\.", stillaConc):
stillaConc = re.sub(r"0+$", "", stillaConc)
stillaConc = re.sub(r"\.$", ".0", stillaConc)
for node in exp:
forId = _get_first_child(node, "tar")
if forId is not None and forId.attrib['id'] == stillaTarget:
data = node
break
if data is None:
new_node = et.Element("data")
place = _get_tag_pos(partit, "data", ["volume", "endPtTable", "data"], 9999999)
partit.insert(place, new_node)
data = new_node
new_node = et.Element("tar", id=stillaTarget)
place = _get_tag_pos(data, "tar", ["tar", "pos", "neg", "undef", "excl", "conc"], 9999999)
data.insert(place, new_node)
new_node = et.Element("pos")
new_node.text = stillaPos
place = _get_tag_pos(data, "pos", ["tar", "pos", "neg", "undef", "excl", "conc"], 9999999)
data.insert(place, new_node)
new_node = et.Element("neg")
new_node.text = stillaNeg
place = _get_tag_pos(data, "neg", ["tar", "pos", "neg", "undef", "excl", "conc"], 9999999)
data.insert(place, new_node)
new_node = et.Element("conc")
new_node.text = stillaConc
place = _get_tag_pos(data, "conc", ["tar", "pos", "neg", "undef", "excl", "conc"], 9999999)
data.insert(place, new_node)
else:
exp = _get_all_children(partit, "data")
for node in exp:
forId = _get_first_child(node, "tar")
if forId is not None and forId.attrib['id'] == sLin[posTarget]:
data = node
break
if data is None:
new_node = et.Element("data")
place = _get_tag_pos(partit, "data", ["volume", "endPtTable", "data"], 9999999)
partit.insert(place, new_node)
data = new_node
new_node = et.Element("tar", id=sLin[posTarget])
place = _get_tag_pos(data, "tar", ["tar", "pos", "neg", "undef", "excl", "conc"], 9999999)
data.insert(place, new_node)
new_node = et.Element("pos")
new_node.text = sLin[posPositives]
place = _get_tag_pos(data, "pos", ["tar", "pos", "neg", "undef", "excl", "conc"], 9999999)
data.insert(place, new_node)
new_node = et.Element("neg")
new_node.text = sLin[posNegatives]
place = _get_tag_pos(data, "neg", ["tar", "pos", "neg", "undef", "excl", "conc"], 9999999)
data.insert(place, new_node)
if posUndefined != -1 and sLin[posUndefined] != "":
new_node = et.Element("undef")
new_node.text = sLin[posUndefined]
place = _get_tag_pos(data, "neg", ["tar", "pos", "neg", "undef", "excl", "conc"], 9999999)
data.insert(place, new_node)
if posExcluded != -1 and sLin[posExcluded] != "":
new_node = et.Element("excl")
new_node.text = sLin[posExcluded]
place = _get_tag_pos(data, "neg", ["tar", "pos", "neg", "undef", "excl", "conc"], 9999999)
data.insert(place, new_node)
if posCopConc != -1:
new_node = et.Element("conc")
if int(sLin[posPositives]) == 0:
new_node.text = "0"
else:
if fileformat == "RDML":
new_node.text = sLin[posCopConc]
elif fileformat == "Bio-Rad":
new_node.text = str(float(sLin[posCopConc])/20)
else:
new_node.text = sLin[posCopConc]
place = _get_tag_pos(data, "conc", ["tar", "pos", "neg", "undef", "excl", "conc"], 9999999)
data.insert(place, new_node)
# Read the raw data files
# Extract the well position from file names
constNameChars = 0
if len(filelist) > 0:
charStopCount = False
for i in range(len(filelist[0])):
currChar = None
if charStopCount is False:
for wellFileName in filelist:
if currChar is None:
currChar = wellFileName[i]
else:
if currChar != wellFileName[i]:
charStopCount = True
if charStopCount is False:
constNameChars = i + 1
for wellFileName in filelist:
currName = wellFileName[constNameChars:].upper()
currName = currName.replace(".CSV", "")
currName = currName.replace(".TSV", "")
currName = currName.replace("_AMPLITUDE", "")
currName = currName.replace("_COMPENSATEDDATA", "")
currName = currName.replace("_RAWDATA", "")
currName = re.sub(r"^\d+_", "", currName)
wellNames.append(currName)
fileLookup[currName] = wellFileName
# Propose a filename for raw data
runId = self._node.get('id')
runFix = re.sub(r"[^A-Za-z0-9]", "", runId)
experimentId = self._node.getparent().get('id')
experimentFix = re.sub(r"[^A-Za-z0-9]", "", experimentId)
propFileName = "partitions/" + experimentFix + "_" + runFix
# Get the used unique file names
if zipfile.is_zipfile(self._rdmlFilename):
with zipfile.ZipFile(self._rdmlFilename, 'r') as rdmlObj:
# Get list of files names in rdml zip
allRDMLfiles = rdmlObj.namelist()
for ele in allRDMLfiles:
if re.search("^partitions/", ele):
uniqueFileNames.append(ele.lower())
# Now process the files
warnVolume = ""
for well in wellNames:
outTabFile = ""
keepCh1 = False
keepCh2 = False
keepCh3 = False
header = ""
react = None
partit = None
dataCh1 = None
dataCh2 = None
dataCh3 = None
wellPos = well
if re.search(r"\D\d+", well):
old_letter = ord(re.sub(r"\d", "", well).upper()) - ord("A")
old_nr = int(re.sub(r"\D", "", well))
newId = old_nr + old_letter * int(self["pcrFormat_columns"])
wellPos = str(newId)
exp = _get_all_children(self._node, "react")
for node in exp:
if wellPos == node.attrib['id']:
react = node
break
if react is None:
sampleName = "Sample in " + well
if sampleName not in samTypeLookup:
rootEl.new_sample(sampleName, "unkn")
samTypeLookup[sampleName] = "unkn"
ret += "Created sample \"" + sampleName + "\" with type \"" + "unkn" + "\"\n"
new_node = et.Element("react", id=wellPos)
place = _get_tag_pos(self._node, "react", self.xmlkeys(), 9999999)
self._node.insert(place, new_node)
react = new_node
new_node = et.Element("sample", id=sampleName)
react.insert(0, new_node)
partit = _get_first_child(react, "partitions")
if partit is None:
new_node = et.Element("partitions")
place = _get_tag_pos(react, "partitions", ["sample", "data", "partitions"], 9999999)
react.insert(place, new_node)
partit = new_node
new_node = et.Element("volume")
if fileformat == "RDML":
new_node.text = "0.7"
warnVolume = "No information on partition volume given, used 0.7."
elif fileformat == "Bio-Rad":
new_node.text = "0.85"
elif fileformat == "Stilla":
new_node.text = "0.59"
else:
new_node.text = "0.85"
place = _get_tag_pos(partit, "volume", ["volume", "endPtTable", "data"], 9999999)
partit.insert(place, new_node)
if wellPos in fileNameSuggLookup:
finalFileName = "partitions/" + fileNameSuggLookup[wellPos]
else:
finalFileName = "partitions/" + _get_first_child_text(partit, "endPtTable")
if finalFileName == "partitions/":
finalFileName = propFileName + "_" + wellPos + "_" + well + ".tsv"
triesCount = 0
if finalFileName.lower() in uniqueFileNames:
while triesCount < 100:
finalFileName = propFileName + "_" + wellPos + "_" + well + "_" + str(triesCount) + ".tsv"
if finalFileName.lower() not in uniqueFileNames:
uniqueFileNames.append(finalFileName.lower())
break
# print(finalFileName, flush=True)
with open(fileLookup[well], newline='') as wellfile: # add encoding='utf-8' ?
if fileformat == "RDML":
wellLines = list(csv.reader(wellfile, delimiter='\t'))
wellFileContent = wellfile.read()
_writeFileInRDML(self._rdmlFilename, finalFileName, wellFileContent)
delElem = _get_first_child(partit, "endPtTable")
if delElem is not None:
partit.remove(delElem)
new_node = et.Element("endPtTable")
new_node.text = re.sub(r'^partitions/', '', finalFileName)
place = _get_tag_pos(partit, "endPtTable", ["volume", "endPtTable", "data"], 9999999)
partit.insert(place, new_node)
header = wellLines[0]
for col in range(0, len(header), 2):
cPos = 0
cNeg = 0
cUndef = 0
cExcl = 0
if header[col] != "":
targetName = header[col]
if targetName not in tarTypeLookup:
dye = "Ch" + str(int((col + 1) / 2))
if dye not in dyeLookup:
rootEl.new_dye(dye)
dyeLookup[dye] = 1
ret += "Created dye \"" + dye + "\"\n"
rootEl.new_target(targetName, "toi")
elem = rootEl.get_target(byid=targetName)
elem["dyeId"] = dye
tarTypeLookup[targetName] = "toi"
ret += "Created target " + targetName + " with type \"" + "toi" + "\" and dye \"" + dye + "\"\n"
for line in wellLines[1:]:
splitLine = line.split("\t")
if len(splitLine) - 1 < col + 1:
continue
if splitLine[col + 1] == "p":
cPos += 1
if splitLine[col + 1] == "n":
cNeg += 1
if splitLine[col + 1] == "u":
cUndef += 1
if splitLine[col + 1] == "e":
cExcl += 1
data = None
exp = _get_all_children(partit, "data")
for node in exp:
forId = _get_first_child(node, "tar")
if forId is not None and forId.attrib['id'] == targetName:
data = node
if data is None:
new_node = et.Element("data")
place = _get_tag_pos(partit, "data", ["volume", "endPtTable", "data"], 9999999)
partit.insert(place, new_node)
data = new_node
new_node = et.Element("tar", id=targetName)
place = _get_tag_pos(data, "tar", ["tar", "pos", "neg", "undef", "excl", "conc"], 9999999)
data.insert(place, new_node)
delElem = _get_first_child(partit, "pos")
if delElem is not None:
data.remove(delElem)
new_node = et.Element("pos")
new_node.text = str(cPos)
place = _get_tag_pos(data, "pos", ["tar", "pos", "neg", "undef", "excl", "conc"], 9999999)
data.insert(place, new_node)
delElem = _get_first_child(partit, "neg")
if delElem is not None:
data.remove(delElem)
new_node = et.Element("neg")
new_node.text = str(cNeg)
place = _get_tag_pos(data, "pos", ["tar", "pos", "neg", "undef", "excl", "conc"], 9999999)
data.insert(place, new_node)
delElem = _get_first_child(partit, "undef")
if delElem is not None:
data.remove(delElem)
if cExcl > 0:
new_node = et.Element("undef")
new_node.text = str(cUndef)
place = _get_tag_pos(data, "pos", ["tar", "pos", "neg", "undef", "excl", "conc"], 9999999)
data.insert(place, new_node)
delElem = _get_first_child(partit, "excl")
if delElem is not None:
data.remove(delElem)
if cExcl > 0:
new_node = et.Element("excl")
new_node.text = str(cExcl)
place = _get_tag_pos(data, "pos", ["tar", "pos", "neg", "undef", "excl", "conc"], 9999999)
data.insert(place, new_node)
elif fileformat == "Bio-Rad":
wellLines = list(csv.reader(wellfile, delimiter=','))
ch1Pos = "0"
ch1Neg = "0"
ch1sum = 0
ch2Pos = "0"
ch2Neg = "0"
ch2sum = 0
if well in headerLookup:
if "Ch1" in headerLookup[well] and 1 not in ignoreList:
keepCh1 = True
header += headerLookup[well]["Ch1"] + "\t" + headerLookup[well]["Ch1"] + "\t"
if "Ch2" in headerLookup[well] and 2 not in ignoreList:
keepCh2 = True
header += headerLookup[well]["Ch2"] + "\t" + headerLookup[well]["Ch2"] + "\t"
outTabFile += re.sub(r'\t$', '\n', header)
else:
headerLookup[well] = {}
dyes = ["Ch1", "Ch2"]
if len(wellLines) > 1:
ch1Pos = ""
ch1Neg = ""
ch2Pos = ""
ch2Neg = ""
if re.search(r"\d", wellLines[1][0]) and 1 not in ignoreList:
keepCh1 = True
if len(wellLines[1]) > 1 and re.search(r"\d", wellLines[1][1]) and 2 not in ignoreList:
keepCh2 = True
for dye in dyes:
if dye not in dyeLookup:
rootEl.new_dye(dye)
dyeLookup[dye] = 1
ret += "Created dye \"" + dye + "\"\n"
dyeCount = 0
for dye in dyes:
dyeCount += 1
targetName = "Target in " + well + " " + dye
if targetName not in tarTypeLookup:
rootEl.new_target(targetName, "toi")
elem = rootEl.get_target(byid=targetName)
elem["dyeId"] = dye
tarTypeLookup[targetName] = "toi"
ret += "Created target " + targetName + " with type \"" + "toi" + "\" and dye \"" + dye + "\"\n"
headerLookup[well][dye] = targetName
if (dyeCount == 1 and keepCh1) or (dyeCount == 2 and keepCh2):
header += targetName + "\t" + targetName + "\t"
outTabFile += re.sub(r'\t$', '\n', header)
if keepCh1 or keepCh2:
exp = _get_all_children(partit, "data")
for node in exp:
forId = _get_first_child(node, "tar")
if keepCh1 and forId is not None and forId.attrib['id'] == headerLookup[well]["Ch1"]:
dataCh1 = node
ch1Pos = _get_first_child_text(dataCh1, "pos")
ch1Neg = _get_first_child_text(dataCh1, "neg")
ch1sum += int(ch1Pos) + int(ch1Neg)
if keepCh2 and forId is not None and forId.attrib['id'] == headerLookup[well]["Ch2"]:
dataCh2 = node
ch2Pos = _get_first_child_text(dataCh2, "pos")
ch2Neg = _get_first_child_text(dataCh2, "neg")
ch2sum += int(ch2Pos) + int(ch2Neg)
if dataCh1 is None and keepCh1:
new_node = et.Element("data")
place = _get_tag_pos(partit, "data", ["volume", "endPtTable", "data"], 9999999)
partit.insert(place, new_node)
dataCh1 = new_node
new_node = et.Element("tar", id=headerLookup[well]["Ch1"])
place = _get_tag_pos(dataCh1, "tar", ["tar", "pos", "neg", "undef", "excl", "conc"], 9999999)
dataCh1.insert(place, new_node)
ch1Pos = ""
ch1Neg = ""
ch1sum = 2
if dataCh2 is None and keepCh2:
new_node = et.Element("data")
place = _get_tag_pos(partit, "data", ["volume", "endPtTable", "data"], 9999999)
partit.insert(place, new_node)
dataCh2 = new_node
new_node = et.Element("tar", id=headerLookup[well]["Ch2"])
place = _get_tag_pos(dataCh2, "tar", ["tar", "pos", "neg", "undef", "excl", "conc"], 9999999)
dataCh2.insert(place, new_node)
ch2Pos = ""
ch2Neg = ""
ch2sum = 2
if dataCh1 is None and dataCh2 is None:
continue
if ch1sum < 1 and ch2sum < 1:
continue
if ch1Pos == "" and ch1Neg == "" and ch2Pos == "" and ch2Neg == "":
countPart = 0
for splitLine in wellLines[1:]:
if len(splitLine[0]) < 2:
continue
if keepCh1:
outTabFile += splitLine[0] + "\t" + "u"
if keepCh2:
if keepCh1:
outTabFile += "\t"
outTabFile += splitLine[1] + "\t" + "u\n"
else:
outTabFile += "\n"
countPart += 1
if keepCh1:
new_node = et.Element("pos")
new_node.text = "0"
place = _get_tag_pos(dataCh1, "pos", ["tar", "pos", "neg", "undef", "excl", "conc"], 9999999)
dataCh1.insert(place, new_node)
new_node = et.Element("neg")
new_node.text = "0"
place = _get_tag_pos(dataCh1, "neg", ["tar", "pos", "neg", "undef", "excl", "conc"], 9999999)
dataCh1.insert(place, new_node)
new_node = et.Element("undef")
new_node.text = str(countPart)
place = _get_tag_pos(dataCh1, "neg", ["tar", "pos", "neg", "undef", "excl", "conc"], 9999999)
dataCh1.insert(place, new_node)
if keepCh2:
new_node = et.Element("pos")
new_node.text = "0"
place = _get_tag_pos(dataCh2, "pos", ["tar", "pos", "neg", "undef", "excl", "conc"],
9999999)
dataCh2.insert(place, new_node)
new_node = et.Element("neg")
new_node.text = "0"
place = _get_tag_pos(dataCh2, "neg", ["tar", "pos", "neg", "undef", "excl", "conc"],
9999999)
dataCh2.insert(place, new_node)
new_node = et.Element("undef")
new_node.text = str(countPart)
place = _get_tag_pos(dataCh2, "neg", ["tar", "pos", "neg", "undef", "excl", "conc"],
9999999)
dataCh2.insert(place, new_node)
else:
ch1Arr = []
ch2Arr = []
ch1Cut = 0
ch2Cut = 0
for splitLine in wellLines[1:]:
if len(splitLine) < 2:
continue
if keepCh1:
ch1Arr.append(float(splitLine[0]))
if keepCh2:
ch2Arr.append(float(splitLine[1]))
if keepCh1:
ch1Arr.sort()
if 0 < int(ch1Neg) <= len(ch1Arr):
ch1Cut = ch1Arr[int(ch1Neg) - 1]
if keepCh2:
ch2Arr.sort()
if 0 < int(ch2Neg) <= len(ch2Arr):
ch2Cut = ch2Arr[int(ch2Neg) - 1]
for splitLine in wellLines[1:]:
if len(splitLine) < 2:
continue
if keepCh1:
outTabFile += splitLine[0] + "\t"
if float(splitLine[0]) > ch1Cut:
outTabFile += "p"
else:
outTabFile += "n"
if keepCh2:
if keepCh1:
outTabFile += "\t"
outTabFile += splitLine[1] + "\t"
if float(splitLine[1]) > ch2Cut:
outTabFile += "p\n"
else:
outTabFile += "n\n"
else:
outTabFile += "\n"
_writeFileInRDML(self._rdmlFilename, finalFileName, outTabFile)
new_node = et.Element("endPtTable")
new_node.text = re.sub(r'^partitions/', '', finalFileName)
place = _get_tag_pos(partit, "endPtTable", ["volume", "endPtTable", "data"], 9999999)
partit.insert(place, new_node)
else:
react.remove(partit)
elif fileformat == "Stilla":
wellLines = list(csv.reader(wellfile, delimiter=','))
ch1Pos = "0"
ch1Neg = "0"
ch1sum = 0
ch2Pos = "0"
ch2Neg = "0"
ch2sum = 0
ch3Pos = "0"
ch3Neg = "0"
ch3sum = 0
if well in headerLookup:
if "Ch1" in headerLookup[well] and 1 not in ignoreList:
keepCh1 = True
header += headerLookup[well]["Ch1"] + "\t" + headerLookup[well]["Ch1"] + "\t"
if "Ch2" in headerLookup[well] and 2 not in ignoreList:
keepCh2 = True
header += headerLookup[well]["Ch2"] + "\t" + headerLookup[well]["Ch2"] + "\t"
if "Ch3" in headerLookup[well] and 3 not in ignoreList:
keepCh3 = True
header += headerLookup[well]["Ch3"] + "\t" + headerLookup[well]["Ch3"] + "\t"
outTabFile += re.sub(r'\t$', '\n', header)
else:
headerLookup[well] = {}
dyes = ["Ch1", "Ch2", "Ch3"]
if len(wellLines) > 1:
ch1Pos = ""
ch1Neg = ""
ch2Pos = ""
ch2Neg = ""
ch3Pos = ""
ch3Neg = ""
if re.search(r"\d", wellLines[1][0]) and 1 not in ignoreList:
keepCh1 = True
if len(wellLines[1]) > 1 and re.search(r"\d", wellLines[1][1]) and 2 not in ignoreList:
keepCh2 = True
if len(wellLines[1]) > 2 and re.search(r"\d", wellLines[1][2]) and 3 not in ignoreList:
keepCh3 = True
for dye in dyes:
if dye not in dyeLookup:
rootEl.new_dye(dye)
dyeLookup[dye] = 1
ret += "Created dye \"" + dye + "\"\n"
dyeCount = 0
for dye in dyes:
dyeCount += 1
targetName = "Target in " + well + " " + dye
if targetName not in tarTypeLookup:
rootEl.new_target(targetName, "toi")
elem = rootEl.get_target(byid=targetName)
elem["dyeId"] = dye
tarTypeLookup[targetName] = "toi"
ret += "Created target " + targetName + " with type \"" + "toi" + "\" and dye \"" + dye + "\"\n"
if (dyeCount == 1 and keepCh1) or (dyeCount == 2 and keepCh2) or (dyeCount == 3 and keepCh3):
headerLookup[well][dye] = targetName
header += targetName + "\t" + targetName + "\t"
outTabFile += re.sub(r'\t$', '\n', header)
if keepCh1 or keepCh2 or keepCh3:
exp = _get_all_children(partit, "data")
for node in exp:
forId = _get_first_child(node, "tar")
if keepCh1 and forId is not None and forId.attrib['id'] == headerLookup[well]["Ch1"]:
dataCh1 = node
ch1Pos = _get_first_child_text(dataCh1, "pos")
ch1Neg = _get_first_child_text(dataCh1, "neg")
ch1sum += int(ch1Pos) + int(ch1Neg)
if keepCh2 and forId is not None and forId.attrib['id'] == headerLookup[well]["Ch2"]:
dataCh2 = node
ch2Pos = _get_first_child_text(dataCh2, "pos")
ch2Neg = _get_first_child_text(dataCh2, "neg")
ch2sum += int(ch2Pos) + int(ch2Neg)
if keepCh3 and forId is not None and forId.attrib['id'] == headerLookup[well]["Ch3"]:
dataCh3 = node
ch3Pos = _get_first_child_text(dataCh3, "pos")
ch3Neg = _get_first_child_text(dataCh3, "neg")
ch3sum += int(ch3Pos) + int(ch3Neg)
if dataCh1 is None and keepCh1:
new_node = et.Element("data")
place = _get_tag_pos(partit, "data", ["volume", "endPtTable", "data"], 9999999)
partit.insert(place, new_node)
dataCh1 = new_node
new_node = et.Element("tar", id=headerLookup[well]["Ch1"])
place = _get_tag_pos(dataCh1, "tar", ["tar", "pos", "neg", "undef", "excl", "conc"],
9999999)
dataCh1.insert(place, new_node)
ch1Pos = ""
ch1Neg = ""
ch1sum = 2
if dataCh2 is None and keepCh2:
new_node = et.Element("data")
place = _get_tag_pos(partit, "data", ["volume", "endPtTable", "data"], 9999999)
partit.insert(place, new_node)
dataCh2 = new_node
new_node = et.Element("tar", id=headerLookup[well]["Ch2"])
place = _get_tag_pos(dataCh2, "tar", ["tar", "pos", "neg", "undef", "excl", "conc"],
9999999)
dataCh2.insert(place, new_node)
ch2Pos = ""
ch2Neg = ""
ch2sum = 2
if dataCh3 is None and keepCh3:
new_node = et.Element("data")
place = _get_tag_pos(partit, "data", ["volume", "endPtTable", "data"], 9999999)
partit.insert(place, new_node)
dataCh3 = new_node
new_node = et.Element("tar", id=headerLookup[well]["Ch3"])
place = _get_tag_pos(dataCh3, "tar", ["tar", "pos", "neg", "undef", "excl", "conc"],
9999999)
dataCh3.insert(place, new_node)
ch3Pos = ""
ch3Neg = ""
ch3sum = 2
if dataCh1 is None and dataCh2 is None and dataCh3 is None:
continue
if ch1sum < 1 and ch2sum < 1 and ch3sum < 1:
continue
if ch1Pos == "" and ch1Neg == "" and ch2Pos == "" and ch2Neg == "" and ch3Pos == "" and ch3Neg == "":
countPart = 0
for splitLine in wellLines[1:]:
if len(splitLine[0]) < 2:
continue
if keepCh1:
outTabFile += splitLine[0] + "\t" + "u"
if keepCh2:
if keepCh1:
outTabFile += "\t"
outTabFile += splitLine[1] + "\t" + "u"
if keepCh3:
if keepCh1 or keepCh2:
outTabFile += "\t"
outTabFile += splitLine[2] + "\t" + "u\n"
else:
outTabFile += "\n"
countPart += 1
if keepCh1:
new_node = et.Element("pos")
new_node.text = "0"
place = _get_tag_pos(dataCh1, "pos", ["tar", "pos", "neg", "undef", "excl", "conc"],
9999999)
dataCh1.insert(place, new_node)
new_node = et.Element("neg")
new_node.text = "0"
place = _get_tag_pos(dataCh1, "neg", ["tar", "pos", "neg", "undef", "excl", "conc"],
9999999)
dataCh1.insert(place, new_node)
new_node = et.Element("undef")
new_node.text = str(countPart)
place = _get_tag_pos(dataCh1, "neg", ["tar", "pos", "neg", "undef", "excl", "conc"],
9999999)
dataCh1.insert(place, new_node)
if keepCh2:
new_node = et.Element("pos")
new_node.text = "0"
place = _get_tag_pos(dataCh2, "pos", ["tar", "pos", "neg", "undef", "excl", "conc"],
9999999)
dataCh2.insert(place, new_node)
new_node = et.Element("neg")
new_node.text = "0"
place = _get_tag_pos(dataCh2, "neg", ["tar", "pos", "neg", "undef", "excl", "conc"],
9999999)
dataCh2.insert(place, new_node)
new_node = et.Element("undef")
new_node.text = str(countPart)
place = _get_tag_pos(dataCh2, "neg", ["tar", "pos", "neg", "undef", "excl", "conc"],
9999999)
dataCh2.insert(place, new_node)
if keepCh3:
new_node = et.Element("pos")
new_node.text = "0"
place = _get_tag_pos(dataCh3, "pos", ["tar", "pos", "neg", "undef", "excl", "conc"],
9999999)
dataCh3.insert(place, new_node)
new_node = et.Element("neg")
new_node.text = "0"
place = _get_tag_pos(dataCh3, "neg", ["tar", "pos", "neg", "undef", "excl", "conc"],
9999999)
dataCh3.insert(place, new_node)
new_node = et.Element("undef")
new_node.text = str(countPart)
place = _get_tag_pos(dataCh3, "neg", ["tar", "pos", "neg", "undef", "excl", "conc"],
9999999)
dataCh3.insert(place, new_node)
else:
ch1Arr = []
ch2Arr = []
ch3Arr = []
ch1Cut = 0
ch2Cut = 0
ch3Cut = 0
for splitLine in wellLines[1:]:
if len(splitLine) < 3:
continue
if keepCh1:
ch1Arr.append(float(splitLine[0]))
if keepCh2:
ch2Arr.append(float(splitLine[1]))
if keepCh3:
ch3Arr.append(float(splitLine[2]))
if keepCh1:
ch1Arr.sort()
if 0 < int(ch1Neg) <= len(ch1Arr):
ch1Cut = ch1Arr[int(ch1Neg) - 1]
if keepCh2:
ch2Arr.sort()
if 0 < int(ch2Neg) <= len(ch2Arr):
ch2Cut = ch2Arr[int(ch2Neg) - 1]
if keepCh3:
ch3Arr.sort()
if 0 < int(ch3Neg) <= len(ch3Arr):
ch3Cut = ch3Arr[int(ch3Neg) - 1]
for splitLine in wellLines[1:]:
if len(splitLine) < 2:
continue
if keepCh1:
outTabFile += splitLine[0] + "\t"
if float(splitLine[0]) > ch1Cut:
outTabFile += "p"
else:
outTabFile += "n"
if keepCh2:
if keepCh1:
outTabFile += "\t"
outTabFile += splitLine[1] + "\t"
if float(splitLine[1]) > ch2Cut:
outTabFile += "p"
else:
outTabFile += "n"
if keepCh3:
if keepCh1 or keepCh2:
outTabFile += "\t"
outTabFile += splitLine[2] + "\t"
if float(splitLine[2]) > ch3Cut:
outTabFile += "p\n"
else:
outTabFile += "n\n"
else:
outTabFile += "\n"
_writeFileInRDML(self._rdmlFilename, finalFileName, outTabFile)
new_node = et.Element("endPtTable")
new_node.text = re.sub(r'^partitions/', '', finalFileName)
place = _get_tag_pos(partit, "endPtTable", ["volume", "endPtTable", "data"], 9999999)
partit.insert(place, new_node)
else:
react.remove(partit)
ret += warnVolume
return ret
def get_digital_overview_data(self, rootEl):
"""Provides the digital overview data in tab seperated format.
Args:
self: The class self parameter.
rootEl: The rdml root element.
Returns:
A string with the overview data table.
"""
# 0 1 2 3 4 5 6 7 8 9 10 11 12 13
ret = "Pos\tWell\tSample\tSampleType\tTarget\tTargetType\tDye\tCopies\tPositives\tNegatives\tUndefined\tExcluded\tVolume\tFileName\n"
tabLines = []
# Fill the lookup dics
samTypeLookup = {}
tarTypeLookup = {}
tarDyeLookup = {}
samples = _get_all_children(rootEl._node, "sample")
for sample in samples:
if sample.attrib['id'] != "":
samId = sample.attrib['id']
forType = _get_first_child_text(sample, "type")
if forType != "":
samTypeLookup[samId] = forType
targets = _get_all_children(rootEl._node, "target")
for target in targets:
if target.attrib['id'] != "":
tarId = target.attrib['id']
forType = _get_first_child_text(target, "type")
if forType != "":
tarTypeLookup[tarId] = forType
forId = _get_first_child(target, "dyeId")
if forId is not None and forId.attrib['id'] != "":
tarDyeLookup[tarId] = forId.attrib['id']
reacts = _get_all_children(self._node, "react")
for react in reacts:
pPos = react.attrib['id']
posId = int(react.attrib['id'])
pIdNumber = posId % int(self["pcrFormat_columns"])
pIdLetter = chr(ord("A") + int(posId / int(self["pcrFormat_columns"])))
pWell = pIdLetter + str(pIdNumber)
pSample = ""
pSampleType = ""
pFileName = ""
forId = _get_first_child(react, "sample")
if forId is not None:
if forId.attrib['id'] != "":
pSample = forId.attrib['id']
pSampleType = samTypeLookup[forId.attrib['id']]
partit = _get_first_child(react, "partitions")
if partit is not None:
endPtTable = _get_first_child_text(partit, "endPtTable")
if endPtTable != "":
pFileName = endPtTable
pVolume = _get_first_child_text(partit, "volume")
partit_datas = _get_all_children(partit, "data")
for partit_data in partit_datas:
pTarget = ""
pTargetType = ""
pDye = ""
forId = _get_first_child(partit_data, "tar")
if forId is not None:
if forId.attrib['id'] != "":
pTarget = forId.attrib['id']
pTargetType = tarTypeLookup[pTarget]
pDye = tarDyeLookup[pTarget]
pCopies = _get_first_child_text(partit_data, "conc")
pPositives = _get_first_child_text(partit_data, "pos")
pNegatives = _get_first_child_text(partit_data, "neg")
pUnknown = _get_first_child_text(partit_data, "undef")
pExcluded = _get_first_child_text(partit_data, "excl")
retLine = pPos + "\t"
retLine += pWell + "\t"
retLine += pSample + "\t"
retLine += pSampleType + "\t"
retLine += pTarget + "\t"
retLine += pTargetType + "\t"
retLine += pDye + "\t"
retLine += pCopies + "\t"
retLine += pPositives + "\t"
retLine += pNegatives + "\t"
retLine += pUnknown + "\t"
retLine += pExcluded + "\t"
retLine += pVolume + "\t"
retLine += pFileName + "\n"
tabLines.append(retLine)
tabLines.sort(key=_sort_list_digital_PCR)
for tLine in tabLines:
ret += tLine
return ret
def get_digital_raw_data(self, reactPos):
"""Provides the digital of a react in tab seperated format.
Args:
self: The class self parameter.
reactPos: The react id to get the digital raw data from
Returns:
A string with the raw data table.
"""
react = None
retVal = ""
# Get the position number if required
wellPos = str(reactPos)
if re.search(r"\D\d+", wellPos):
old_letter = ord(re.sub(r"\d", "", wellPos.upper())) - ord("A")
old_nr = int(re.sub(r"\D", "", wellPos))
newId = old_nr + old_letter * int(self["pcrFormat_columns"])
wellPos = str(newId)
exp = _get_all_children(self._node, "react")
for node in exp:
if wellPos == node.attrib['id']:
react = node
break
if react is None:
return ""
partit = _get_first_child(react, "partitions")
if partit is None:
return ""
finalFileName = "partitions/" + _get_first_child_text(partit, "endPtTable")
if finalFileName == "partitions/":
return ""
if zipfile.is_zipfile(self._rdmlFilename):
zf = zipfile.ZipFile(self._rdmlFilename, 'r')
try:
retVal = zf.read(finalFileName).decode('utf-8')
except KeyError:
raise RdmlError('No ' + finalFileName + ' in compressed RDML file found.')
finally:
zf.close()
return retVal
def getreactjson(self):
"""Returns a json of the react data including fluorescence data.
Args:
self: The class self parameter.
Returns:
A json of the data.
"""
all_data = {}
data = []
reacts = _get_all_children(self._node, "react")
adp_cyc_max = 0.0
adp_fluor_min = 99999999
adp_fluor_max = 0.0
mdp_tmp_min = 120.0
mdp_tmp_max = 0.0
mdp_fluor_min = 99999999
mdp_fluor_max = 0.0
max_data = 0
max_partition_data = 0
anyCorrections = 0
for react in reacts:
react_json = {
"id": react.get('id'),
}
forId = _get_first_child(react, "sample")
if forId is not None:
if forId.attrib['id'] != "":
react_json["sample"] = forId.attrib['id']
react_datas = _get_all_children(react, "data")
max_data = max(max_data, len(react_datas))
react_datas_json = []
for react_data in react_datas:
in_react = {}
forId = _get_first_child(react_data, "tar")
if forId is not None:
if forId.attrib['id'] != "":
in_react["tar"] = forId.attrib['id']
_add_first_child_to_dic(react_data, in_react, True, "cq")
_add_first_child_to_dic(react_data, in_react, True, "N0")
_add_first_child_to_dic(react_data, in_react, True, "ampEffMet")
_add_first_child_to_dic(react_data, in_react, True, "ampEff")
_add_first_child_to_dic(react_data, in_react, True, "ampEffSE")
_add_first_child_to_dic(react_data, in_react, True, "corrF")
# Calculate the correction factors
calcCorr = _get_first_child_text(react_data, "corrF")
calcCq = _get_first_child_text(react_data, "cq")
calcN0 = _get_first_child_text(react_data, "N0")
calcEff = _get_first_child_text(react_data, "ampEff")
in_react["corrCq"] = ""
in_react["corrN0"] = ""
if not calcCorr == "":
calcCorr = float(calcCorr)
if not np.isnan(calcCorr):
if 0.0 < calcCorr < 1.0:
if calcEff == "":
calcEff = 2.0
else:
calcEff = float(calcEff)
if not np.isnan(calcEff):
if 0.0 < calcEff < 3.0:
if not calcCq == "":
calcCq = float(calcCq)
if not np.isnan(calcCq):
if calcCq > 0.0:
finalCq = calcCq - np.log10(calcCorr) / np.log10(calcEff)
in_react["corrCq"] = "{:.3f}".format(finalCq)
anyCorrections = 1
else:
in_react["corrCq"] = "-1.0"
if not calcN0 == "":
calcN0 = float(calcN0)
if not np.isnan(calcN0):
if calcCq > 0.0:
finalN0 = calcCorr * calcN0
in_react["corrN0"] = "{:.2e}".format(finalN0)
anyCorrections = 1
else:
in_react["corrN0"] = "-1.0"
if calcCorr == 0.0:
if not calcCq == "":
in_react["corrCq"] = ""
if not calcN0 == "":
in_react["corrN0"] = 0.0
if calcCorr == 1.0:
if not calcCq == "":
in_react["corrCq"] = calcCq
if not calcN0 == "":
in_react["corrN0"] = calcN0
_add_first_child_to_dic(react_data, in_react, True, "meltTemp")
_add_first_child_to_dic(react_data, in_react, True, "excl")
_add_first_child_to_dic(react_data, in_react, True, "note")
_add_first_child_to_dic(react_data, in_react, True, "endPt")
_add_first_child_to_dic(react_data, in_react, True, "bgFluor")
_add_first_child_to_dic(react_data, in_react, True, "bgFluorSlp")
_add_first_child_to_dic(react_data, in_react, True, "quantFluor")
adps = _get_all_children(react_data, "adp")
adps_json = []
for adp in adps:
cyc = _get_first_child_text(adp, "cyc")
fluor = _get_first_child_text(adp, "fluor")
adp_cyc_max = max(adp_cyc_max, float(cyc))
adp_fluor_min = min(adp_fluor_min, float(fluor))
adp_fluor_max = max(adp_fluor_max, float(fluor))
in_adp = [cyc, fluor, _get_first_child_text(adp, "tmp")]
adps_json.append(in_adp)
in_react["adps"] = adps_json
mdps = _get_all_children(react_data, "mdp")
mdps_json = []
for mdp in mdps:
tmp = _get_first_child_text(mdp, "tmp")
fluor = _get_first_child_text(mdp, "fluor")
mdp_tmp_min = min(mdp_tmp_min, float(tmp))
mdp_tmp_max = max(mdp_tmp_max, float(tmp))
mdp_fluor_min = min(mdp_fluor_min, float(fluor))
mdp_fluor_max = max(mdp_fluor_max, float(fluor))
in_mdp = [tmp, fluor]
mdps_json.append(in_mdp)
in_react["mdps"] = mdps_json
react_datas_json.append(in_react)
react_json["datas"] = react_datas_json
partit = _get_first_child(react, "partitions")
if partit is not None:
in_partitions = {}
endPtTable = _get_first_child_text(partit, "endPtTable")
if endPtTable != "":
in_partitions["endPtTable"] = endPtTable
partit_datas = _get_all_children(partit, "data")
max_partition_data = max(max_partition_data, len(partit_datas))
partit_datas_json = []
for partit_data in partit_datas:
in_partit = {}
forId = _get_first_child(partit_data, "tar")
if forId is not None:
if forId.attrib['id'] != "":
in_partit["tar"] = forId.attrib['id']
_add_first_child_to_dic(partit_data, in_partit, False, "pos")
_add_first_child_to_dic(partit_data, in_partit, False, "neg")
_add_first_child_to_dic(partit_data, in_partit, True, "undef")
_add_first_child_to_dic(partit_data, in_partit, True, "excl")
_add_first_child_to_dic(partit_data, in_partit, True, "conc")
partit_datas_json.append(in_partit)
in_partitions["datas"] = partit_datas_json
react_json["partitions"] = in_partitions
data.append(react_json)
all_data["reacts"] = data
all_data["adp_cyc_max"] = adp_cyc_max
all_data["anyCalcCorrections"] = anyCorrections
all_data["adp_fluor_min"] = adp_fluor_min
all_data["adp_fluor_max"] = adp_fluor_max
all_data["mdp_tmp_min"] = mdp_tmp_min
all_data["mdp_tmp_max"] = mdp_tmp_max
all_data["mdp_fluor_min"] = mdp_fluor_min
all_data["mdp_fluor_max"] = mdp_fluor_max
all_data["max_data_len"] = max_data
all_data["max_partition_data_len"] = max_partition_data
return all_data
def setExclNote(self, vReact, vTar, vExcl, vNote):
"""Saves the note and excl string for one react/data combination.
Args:
self: The class self parameter.
vReact: The reaction id.
vTar: The target id.
vExcl: The exclusion string to save.
vNote: The note string to save.
Returns:
Nothing, updates RDML data.
"""
expParent = self._node.getparent()
rootPar = expParent.getparent()
ver = rootPar.get('version')
dataXMLelements = _getXMLDataType()
reacts = _get_all_children(self._node, "react")
for react in reacts:
if int(react.get('id')) == int(vReact):
react_datas = _get_all_children(react, "data")
for react_data in react_datas:
forId = _get_first_child(react_data, "tar")
if forId is not None:
if forId.attrib['id'] == vTar:
_change_subelement(react_data, "excl", dataXMLelements, vExcl, True, "string")
if ver == "1.3":
_change_subelement(react_data, "note", dataXMLelements, vNote, True, "string")
return
def webAppLinRegPCR(self, pcrEfficiencyExl=0.05, updateRDML=False, excludeNoPlateau=True, excludeEfficiency="outlier"):
"""Performs LinRegPCR on the run. Modifies the cq values and returns a json with additional data.
Args:
self: The class self parameter.
pcrEfficiencyExl: Exclude samples with an efficiency outside the given range (0.05).
updateRDML: If true, update the RDML data with the calculated values.
excludeNoPlateau: If true, samples without plateau are excluded from mean PCR efficiency calculation.
excludeEfficiency: Choose "outlier", "mean", "include" to exclude based on indiv PCR eff.
Returns:
A dictionary with the resulting data, presence and format depending on input.
rawData: A 2d array with the raw fluorescence values
baselineCorrectedData: A 2d array with the baseline corrected raw fluorescence values
resultsList: A 2d array object.
resultsCSV: A csv string.
"""
allData = self.getreactjson()
res = self.linRegPCR(pcrEfficiencyExl=pcrEfficiencyExl,
updateRDML=updateRDML,
excludeNoPlateau=excludeNoPlateau,
excludeEfficiency=excludeEfficiency,
saveRaw=False,
saveBaslineCorr=True,
saveResultsList=True,
saveResultsCSV=False,
verbose=False)
if "baselineCorrectedData" in res:
bas_cyc_max = len(res["baselineCorrectedData"][0]) - 5
bas_fluor_min = 99999999
bas_fluor_max = 0.0
for row in range(1, len(res["baselineCorrectedData"])):
bass_json = []
for col in range(5, len(res["baselineCorrectedData"][row])):
cyc = res["baselineCorrectedData"][0][col]
fluor = res["baselineCorrectedData"][row][col]
if not (np.isnan(fluor) or fluor <= 0.0):
bas_fluor_min = min(bas_fluor_min, float(fluor))
bas_fluor_max = max(bas_fluor_max, float(fluor))
in_bas = [cyc, fluor, ""]
bass_json.append(in_bas)
# Fixme do not loop over all, use sorted data and clever moving
for react in allData["reacts"]:
if react["id"] == res["baselineCorrectedData"][row][0]:
for data in react["datas"]:
if data["tar"] == res["baselineCorrectedData"][row][3]:
data["bass"] = list(bass_json)
allData["bas_cyc_max"] = bas_cyc_max
allData["bas_fluor_min"] = bas_fluor_min
allData["bas_fluor_max"] = bas_fluor_max
if "resultsList" in res:
header = res["resultsList"].pop(0)
resList = sorted(res["resultsList"], key=_sort_list_int)
for rRow in range(0, len(resList)):
for rCol in range(0, len(resList[rRow])):
if isinstance(resList[rRow][rCol], np.float64) and np.isnan(resList[rRow][rCol]):
resList[rRow][rCol] = ""
if isinstance(resList[rRow][rCol], float) and math.isnan(resList[rRow][rCol]):
resList[rRow][rCol] = ""
allData["LinRegPCR_Result_Table"] = json.dumps([header] + resList, cls=NpEncoder)
if "noRawData" in res:
allData["error"] = res["noRawData"]
return allData
def linRegPCR(self, pcrEfficiencyExl=0.05, updateRDML=False, excludeNoPlateau=True, excludeEfficiency="outlier",
commaConv=False, ignoreExclusion=False,
saveRaw=False, saveBaslineCorr=False, saveResultsList=False, saveResultsCSV=False,
timeRun=False, verbose=False):
"""Performs LinRegPCR on the run. Modifies the cq values and returns a json with additional data.
Args:
self: The class self parameter.
pcrEfficiencyExl: Exclude samples with an efficiency outside the given range (0.05).
updateRDML: If true, update the RDML data with the calculated values.
excludeNoPlateau: If true, samples without plateau are excluded from mean PCR efficiency calculation.
excludeEfficiency: Choose "outlier", "mean", "include" to exclude based on indiv PCR eff.
commaConv: If true, convert comma separator to dot.
ignoreExclusion: If true, ignore the RDML exclusion strings.
saveRaw: If true, no raw values are given in the returned data
saveBaslineCorr: If true, no baseline corrected values are given in the returned data
saveResultsList: If true, return a 2d array object.
saveResultsCSV: If true, return a csv string.
timeRun: If true, print runtime for baseline and total.
verbose: If true, comment every performed step.
Returns:
A dictionary with the resulting data, presence and format depending on input.
rawData: A 2d array with the raw fluorescence values
baselineCorrectedData: A 2d array with the baseline corrected raw fluorescence values
resultsList: A 2d array object.
resultsCSV: A csv string.
"""
expParent = self._node.getparent()
rootPar = expParent.getparent()
dataVersion = rootPar.get('version')
if dataVersion == "1.0":
raise RdmlError('LinRegPCR requires RDML version > 1.0.')
##############################
# Collect the data in arrays #
##############################
# res is a 2 dimensional array accessed only by
# variables, so columns might be added here
header = [["id", # 0
"well", # 1
"sample", # 2
"sample type", # 3
"sample nucleotide", # 4
"target", # 5
"target chemistry", # 6
"excluded", # 7
"note", # 8
"baseline", # 9
"lower limit", # 10
"upper limit", # 11
"common threshold", # 12
"group threshold", # 13
"n in log phase", # 14
"last log cycle", # 15
"n included", # 16
"log lin cycle", # 17
"log lin fluorescence", # 18
"indiv PCR eff", # 19
"R2", # 20
"N0 (indiv eff - for debug use)", # 21
"Cq (indiv eff - for debug use)", # 22
"Cq with group threshold (indiv eff - for debug use)", # 23
"mean PCR eff", # 24
"standard error of the mean PCR eff", # 25
"N0 (mean eff)", # 26
"Cq (mean eff)", # 27
"mean PCR eff - no plateau", # 28
"standard error of the mean PCR eff - no plateau", # 29
"N0 (mean eff) - no plateau", # 30
"Cq (mean eff) - no plateau", # 31
"mean PCR eff - mean efficiency", # 32
"standard error of the mean PCR eff - mean efficiency", # 33
"N0 (mean eff) - mean efficiency", # 34
"Cq (mean eff) - mean efficiency", # 35
"mean PCR eff - no plateau - mean efficiency", # 36
"standard error of the mean PCR eff - no plateau - mean efficiency", # 37
"N0 (mean eff) - no plateau - mean efficiency", # 38
"Cq (mean eff) - no plateau - mean efficiency", # 39
"mean PCR eff - stat efficiency", # 40
"standard error of the mean PCR eff - stat efficiency", # 41
"N0 (mean eff) - stat efficiency", # 42
"Cq (mean eff) - stat efficiency", # 43
"mean PCR eff - no plateau - stat efficiency", # 44
"standard error of the stat PCR eff - no plateau - stat efficiency", # 45
"N0 (mean eff) - no plateau - stat efficiency", # 46
"Cq (mean eff) - no plateau - stat efficiency", # 47
"amplification", # 48
"baseline error", # 49
"plateau", # 50
"noisy sample", # 51
"PCR efficiency outside mean rage", # 52
"PCR efficiency outside mean rage - no plateau", # 53
"PCR efficiency outlier", # 54
"PCR efficiency outlier - no plateau", # 55
"short log lin phase", # 56
"Cq is shifting", # 57
"too low Cq eff", # 58
"too low Cq N0", # 59
"used for W-o-L setting"]] # 60
rar_id = 0
rar_well = 1
rar_sample = 2
rar_sample_type = 3
rar_sample_nucleotide = 4
rar_tar = 5
rar_tar_chemistry = 6
rar_excl = 7
rar_note = 8
rar_baseline = 9
rar_lower_limit = 10
rar_upper_limit = 11
rar_threshold_common = 12
rar_threshold_group = 13
rar_n_log = 14
rar_stop_log = 15
rar_n_included = 16
rar_log_lin_cycle = 17
rar_log_lin_fluorescence = 18
rar_indiv_PCR_eff = 19
rar_R2 = 20
rar_N0_indiv_eff = 21
rar_Cq_common = 22
rar_Cq_grp = 23
rar_meanEff_Skip = 24
rar_stdEff_Skip = 25
rar_meanN0_Skip = 26
rar_Cq_Skip = 27
rar_meanEff_Skip_Plat = 28
rar_stdEff_Skip_Plat = 29
rar_meanN0_Skip_Plat = 30
rar_Cq_Skip_Plat = 31
rar_meanEff_Skip_Mean = 32
rar_stdEff_Skip_Mean = 33
rar_meanN0_Skip_Mean = 34
rar_Cq_Skip_Mean = 35
rar_meanEff_Skip_Plat_Mean = 36
rar_stdEff_Skip_Plat_Mean = 37
rar_meanN0_Skip_Plat_Mean = 38
rar_Cq_Skip_Plat_Mean = 39
rar_meanEff_Skip_Out = 40
rar_stdEff_Skip_Out = 41
rar_meanN0_Skip_Out = 42
rar_Cq_Skip_Out = 43
rar_meanEff_Skip_Plat_Out = 44
rar_stdEff_Skip_Plat_Out = 45
rar_meanN0_Skip_Plat_Out = 46
rar_Cq_Skip_Plat_Out = 47
rar_amplification = 48
rar_baseline_error = 49
rar_plateau = 50
rar_noisy_sample = 51
rar_effOutlier_Skip_Mean = 52
rar_effOutlier_Skip_Plat_Mean = 53
rar_effOutlier_Skip_Out = 54
rar_effOutlier_Skip_Plat_Out = 55
rar_shortLogLinPhase = 56
rar_CqIsShifting = 57
rar_tooLowCqEff = 58
rar_tooLowCqN0 = 59
rar_isUsedInWoL = 60
res = []
finalData = {}
adp_cyc_max = 0
pcrEfficiencyExl = float(pcrEfficiencyExl)
if excludeEfficiency not in ["outlier", "mean", "include"]:
excludeEfficiency = "outlier"
reacts = _get_all_children(self._node, "react")
# First get the max number of cycles and create the numpy array
for react in reacts:
react_datas = _get_all_children(react, "data")
for react_data in react_datas:
adps = _get_all_children(react_data, "adp")
for adp in adps:
cyc = _get_first_child_text(adp, "cyc")
adp_cyc_max = max(adp_cyc_max, float(cyc))
adp_cyc_max = math.ceil(adp_cyc_max)
# spFl is the shape for all fluorescence numpy data arrays
spFl = (len(reacts), int(adp_cyc_max))
rawFluor = np.zeros(spFl, dtype=np.float64)
rawFluor[rawFluor <= 0.00000001] = np.nan
# Create a matrix with the cycle for each rawFluor value
vecCycles = np.tile(np.arange(1, (spFl[1] + 1), dtype=np.int64), (spFl[0], 1))
# Initialization of the vecNoAmplification vector
vecExcludedByUser = np.zeros(spFl[0], dtype=np.bool_)
rdmlElemData = []
# Now process the data for numpy and create results array
rowCount = 0
for react in reacts:
posId = react.get('id')
pIdNumber = (int(posId) - 1) % int(self["pcrFormat_columns"]) + 1
pIdLetter = chr(ord("A") + int((int(posId) - 1) / int(self["pcrFormat_columns"])))
pWell = pIdLetter + str(pIdNumber)
sample = ""
forId = _get_first_child(react, "sample")
if forId is not None:
if forId.attrib['id'] != "":
sample = forId.attrib['id']
react_datas = _get_all_children(react, "data")
for react_data in react_datas:
forId = _get_first_child(react_data, "tar")
target = ""
if forId is not None:
if forId.attrib['id'] != "":
target = forId.attrib['id']
if ignoreExclusion:
excl = ""
else:
excl = _get_first_child_text(react_data, "excl")
excl = _cleanErrorString(excl, "amp")
excl = re.sub(r'^;|;$', '', excl)
if not excl == "":
vecExcludedByUser[rowCount] = True
noteVal = _get_first_child_text(react_data, "note")
noteVal = _cleanErrorString(noteVal, "amp")
noteVal = re.sub(r'^;|;$', '', noteVal)
rdmlElemData.append(react_data)
res.append([posId, pWell, sample, "", "", target, "", excl, noteVal, "",
"", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "",
""]) # Must match header length
adps = _get_all_children(react_data, "adp")
for adp in adps:
cyc = int(math.ceil(float(_get_first_child_text(adp, "cyc")))) - 1
fluor = _get_first_child_text(adp, "fluor")
if commaConv:
noDot = fluor.replace(".", "")
fluor = noDot.replace(",", ".")
rawFluor[rowCount, cyc] = float(fluor)
rowCount += 1
# Look up sample and target information
parExp = self._node.getparent()
parRoot = parExp.getparent()
dicLU_dyes = {}
luDyes = _get_all_children(parRoot, "dye")
for lu_dye in luDyes:
lu_chemistry = _get_first_child_text(lu_dye, "dyeChemistry")
if lu_chemistry == "":
lu_chemistry = "non-saturating DNA binding dye"
if lu_dye.attrib['id'] != "":
dicLU_dyes[lu_dye.attrib['id']] = lu_chemistry
dicLU_targets = {}
luTargets = _get_all_children(parRoot, "target")
for lu_target in luTargets:
forId = _get_first_child(lu_target, "dyeId")
lu_dyeId = ""
if forId is not None:
if forId.attrib['id'] != "":
lu_dyeId = forId.attrib['id']
if lu_dyeId == "" or lu_dyeId not in dicLU_dyes:
dicLU_targets[lu_target.attrib['id']] = "non-saturating DNA binding dye"
if lu_target.attrib['id'] != "":
dicLU_targets[lu_target.attrib['id']] = dicLU_dyes[lu_dyeId]
dicLU_samSpecType = {}
dicLU_samGenType = {}
dicLU_samNucl = {}
luSamples = _get_all_children(parRoot, "sample")
for lu_sample in luSamples:
lu_Nucl = ""
forUnit = _get_first_child(lu_sample, "templateQuantity")
if forUnit is not None:
lu_Nucl = _get_first_child_text(forUnit, "nucleotide")
if lu_Nucl == "":
lu_Nucl = "cDNA"
if lu_sample.attrib['id'] != "":
dicLU_TypeData = {}
typesList = _get_all_children(lu_sample, "type")
for node in typesList:
if "targetId" in node.attrib:
dicLU_TypeData[node.attrib["targetId"]] = node.text
else:
dicLU_samGenType[lu_sample.attrib['id']] = node.text
dicLU_samSpecType[lu_sample.attrib['id']] = dicLU_TypeData
dicLU_samNucl[lu_sample.attrib['id']] = lu_Nucl
# Update the table with dictionary help
for oRow in range(0, spFl[0]):
if res[oRow][rar_sample] != "":
# Try to get specific type information else general else "unkn"
if res[oRow][rar_tar] in dicLU_samSpecType[res[oRow][rar_sample]]:
res[oRow][rar_sample_type] = dicLU_samSpecType[res[oRow][rar_sample]][res[oRow][rar_tar]]
elif res[oRow][rar_sample] in dicLU_samGenType:
res[oRow][rar_sample_type] = dicLU_samGenType[res[oRow][rar_sample]]
else:
res[oRow][rar_sample_type] = "unkn"
res[oRow][rar_sample_nucleotide] = dicLU_samNucl[res[oRow][rar_sample]]
if res[oRow][rar_tar] != "":
res[oRow][rar_tar_chemistry] = dicLU_targets[res[oRow][rar_tar]]
if saveRaw:
rawTable = [[header[0][rar_id], header[0][rar_well], header[0][rar_sample], header[0][rar_tar], header[0][rar_excl]]]
for oCol in range(0, spFl[1]):
rawTable[0].append(oCol + 1)
for oRow in range(0, spFl[0]):
rawTable.append([res[oRow][rar_id], res[oRow][rar_well], res[oRow][rar_sample], res[oRow][rar_tar], res[oRow][rar_excl]])
for oCol in range(0, spFl[1]):
rawTable[oRow + 1].append(float(rawFluor[oRow, oCol]))
finalData["rawData"] = rawTable
# Count the targets and create the target variables
# Position 0 is for the general over all window without targets
vecTarget = np.zeros(spFl[0], dtype=np.int64)
vecTarget[vecTarget <= 0] = -1
targetsCount = 1
tarWinLookup = {}
for oRow in range(0, spFl[0]):
if res[oRow][rar_tar] not in tarWinLookup:
tarWinLookup[res[oRow][rar_tar]] = targetsCount
targetsCount += 1
vecTarget[oRow] = tarWinLookup[res[oRow][rar_tar]]
upWin = np.zeros(targetsCount, dtype=np.float64)
lowWin = np.zeros(targetsCount, dtype=np.float64)
threshold = np.ones(targetsCount, dtype=np.float64)
# Initialization of the error vectors
vecNoAmplification = np.zeros(spFl[0], dtype=np.bool_)
vecBaselineError = np.zeros(spFl[0], dtype=np.bool_)
vecNoPlateau = np.zeros(spFl[0], dtype=np.bool_)
vecNoisySample = np.zeros(spFl[0], dtype=np.bool_)
vecSkipSample = np.zeros(spFl[0], dtype=np.bool_)
vecShortLogLin = np.zeros(spFl[0], dtype=np.bool_)
vecCtIsShifting = np.zeros(spFl[0], dtype=np.bool_)
vecIsUsedInWoL = np.zeros(spFl[0], dtype=np.bool_)
vecEffOutlier_Skip_Mean = np.zeros(spFl[0], dtype=np.bool_)
vecEffOutlier_Skip_Plat_Mean = np.zeros(spFl[0], dtype=np.bool_)
vecEffOutlier_Skip_Out = np.zeros(spFl[0], dtype=np.bool_)
vecEffOutlier_Skip_Plat_Out = np.zeros(spFl[0], dtype=np.bool_)
vecTooLowCqEff = np.zeros(spFl[0], dtype=np.bool_)
vecTooLowCqN0 = np.zeros(spFl[0], dtype=np.bool_)
# Start and stop cycles of the log lin phase
stopCyc = np.zeros(spFl[0], dtype=np.int64)
startCyc = np.zeros(spFl[0], dtype=np.int64)
startCycFix = np.zeros(spFl[0], dtype=np.int64)
# Initialization of the PCR efficiency vectors
pcrEff = np.ones(spFl[0], dtype=np.float64)
nNulls = np.ones(spFl[0], dtype=np.float64)
nInclu = np.zeros(spFl[0], dtype=np.int64)
correl = np.zeros(spFl[0], dtype=np.float64)
meanEff_Skip = np.zeros(spFl[0], dtype=np.float64)
meanEff_Skip_Plat = np.zeros(spFl[0], dtype=np.float64)
meanEff_Skip_Mean = np.zeros(spFl[0], dtype=np.float64)
meanEff_Skip_Plat_Mean = np.zeros(spFl[0], dtype=np.float64)
meanEff_Skip_Out = np.zeros(spFl[0], dtype=np.float64)
meanEff_Skip_Plat_Out = np.zeros(spFl[0], dtype=np.float64)
stdEff_Skip = np.zeros(spFl[0], dtype=np.float64)
stdEff_Skip_Plat = np.zeros(spFl[0], dtype=np.float64)
stdEff_Skip_Mean = np.zeros(spFl[0], dtype=np.float64)
stdEff_Skip_Plat_Mean = np.zeros(spFl[0], dtype=np.float64)
stdEff_Skip_Out = np.zeros(spFl[0], dtype=np.float64)
stdEff_Skip_Plat_Out = np.zeros(spFl[0], dtype=np.float64)
indMeanX = np.zeros(spFl[0], dtype=np.float64)
indMeanY = np.zeros(spFl[0], dtype=np.float64)
indivCq = np.zeros(spFl[0], dtype=np.float64)
indivCq_Grp = np.zeros(spFl[0], dtype=np.float64)
meanNnull_Skip = np.zeros(spFl[0], dtype=np.float64)
meanNnull_Skip_Plat = np.zeros(spFl[0], dtype=np.float64)
meanNnull_Skip_Mean = np.zeros(spFl[0], dtype=np.float64)
meanNnull_Skip_Plat_Mean = np.zeros(spFl[0], dtype=np.float64)
meanNnull_Skip_Out = np.zeros(spFl[0], dtype=np.float64)
meanNnull_Skip_Plat_Out = np.zeros(spFl[0], dtype=np.float64)
meanCq_Skip = | np.zeros(spFl[0], dtype=np.float64) | numpy.zeros |
import numpy as np
from scipy.constants import pi
from numpy.fft import fftshift
from scipy.fftpack import fft, ifft
from six.moves import builtins
from cython_files.cython_integrand import *
import sys
assert_allclose = np.testing.assert_allclose
import numba
complex128 = numba.complex128
vectorize = numba.vectorize
autojit, jit = numba.autojit, numba.jit
cfunc = numba.cfunc
generated_jit = numba.generated_jit
guvectorize = numba.guvectorize
# Pass through the @profile decorator if line profiler (kernprof) is not in use
# Thanks Paul!
try:
builtins.profile
except AttributeError:
def profile(func):
return func
from time import time
import pickle
#@profile
class Integrator(object):
def __init__(self, int_fwm):
if int_fwm.nm == 1:
self.RK45mm = self.RK45CK_nm1
elif int_fwm.nm == 2:
self.RK45mm = self.RK45CK_nm2
else:
sys.exit('Too many modes!!')
return None
def RK45CK_nm1(self, dAdzmm, u1, dz, M1, M2, Q, tsh, dt, hf, w_tiled, gam_no_aeff):
"""
Propagates the nonlinear operator for 1 step using a 5th order Runge
Kutta method
use: [A delta] = RK5mm(u1, dz)
where u1 is the initial time vector
hf is the Fourier transform of the Raman nonlinear response time
dz is the step over which to propagate
in output: A is new time vector
delta is the norm of the maximum estimated error between a 5th
order and a 4th order integration
"""
(u1, Q, tsh, dt, hf, w_tiled,gam_no_aeff)
A1 = dz*dAdzmm(u1, Q, tsh, dt, hf, w_tiled,gam_no_aeff)
u2 = A2_temp(u1, A1)
A2 = dz*dAdzmm(u1, Q, tsh, dt, hf, w_tiled,gam_no_aeff)
u3 = A3_temp(u1, A1,A2)
A3 = dz*dAdzmm(u1, Q, tsh, dt, hf, w_tiled,gam_no_aeff)
u4 = A4_temp(u1, A1, A2, A3)
A4 = dz*dAdzmm(u1, Q, tsh, dt, hf, w_tiled,gam_no_aeff)
u5 = A5_temp(u1, A1, A2, A3, A4)
A5 = dz*dAdzmm(u1, Q, tsh, dt, hf, w_tiled,gam_no_aeff)
u6 = A6_temp(u1, A1, A2, A3, A4, A5)
A6 = dz*dAdzmm(u1, Q, tsh, dt, hf, w_tiled,gam_no_aeff)
A = A_temp(u1, A1, A3, A4, A6) # Fifth order accuracy
Afourth = Afourth_temp(u1, A1, A3, A4,A5, A6) # Fourth order accuracy
delta = np.linalg.norm(A - Afourth,2, axis = 1).max()
return A, delta
def RK45CK_nm2(self, dAdzmm, u1, dz, M1, M2,Q, tsh, dt, hf, w_tiled, gam_no_aeff):
"""
Propagates the nonlinear operator for 1 step using a 5th order Runge
Kutta method
use: [A delta] = RK5mm(u1, dz)
where u1 is the initial time vector
hf is the Fourier transform of the Raman nonlinear response time
dz is the step over which to propagate
in output: A is new time vector
delta is the norm of the maximum estimated error between a 5th
order and a 4th order integration
"""
A1 = dz*dAdzmm(u1,u1.conj(), M1, M2, Q, tsh, dt, hf, w_tiled, gam_no_aeff)
u2 = A2_temp(u1, A1)
A2 = dz*dAdzmm(u2,u2.conj(), M1, M2, Q, tsh, dt, hf, w_tiled, gam_no_aeff)
u3 = A3_temp(u1, A1,A2)
A3 = dz*dAdzmm(u3,u3.conj(), M1, M2, Q, tsh, dt, hf, w_tiled, gam_no_aeff)
u4 = A4_temp(u1, A1, A2, A3)
A4 = dz*dAdzmm(u4,u4.conj(), M1, M2, Q, tsh, dt, hf, w_tiled, gam_no_aeff)
u5 = A5_temp(u1, A1, A2, A3, A4)
A5 = dz*dAdzmm(u5,u5.conj(), M1, M2, Q, tsh, dt, hf, w_tiled,gam_no_aeff)
u6 = A6_temp(u1, A1, A2, A3, A4, A5)
A6 = dz*dAdzmm(u6,u6.conj(), M1, M2, Q, tsh, dt, hf, w_tiled,gam_no_aeff)
A = A_temp(u1, A1, A3, A4, A6) # Fifth order accuracy
Afourth = Afourth_temp(u1, A1, A3, A4,A5, A6) # Fourth order accuracy
delta = np.linalg.norm(A - Afourth,2, axis = 1).max()
return A, delta
trgt = 'cpu'
#trgt = 'parallel'
#trgt = 'cuda'
@jit(nopython=True,nogil = True)
def Afourth_temp(u1, A1, A3, A4, A5, A6):
return u1 + (2825./27648)*A1 + (18575./48384)*A3 + (13525./55296) * \
A4 + (277./14336)*A5 + (1./4)*A6
@jit(nopython=True,nogil = True)
def A_temp(u1, A1, A3, A4, A6):
return u1 + (37./378)*A1 + (250./621)*A3 + (125./594) * \
A4 + (512./1771)*A6
@jit(nopython=True,nogil = True)
def A2_temp(u1, A1):
return u1 + (1./5)*A1
@jit(nopython=True,nogil = True)
def A3_temp(u1, A1, A2):
return u1 + (3./40)*A1 + (9./40)*A2
@jit(nopython=True,nogil = True)
def A4_temp(u1, A1, A2, A3):
return u1 + (3./10)*A1 - (9./10)*A2 + (6./5)*A3
@jit(nopython=True,nogil = True)
def A5_temp(u1, A1, A2, A3, A4):
return u1 - (11./54)*A1 + (5./2)*A2 - (70./27)*A3 + (35./27)*A4
@jit(nopython=True,nogil = True)
def A6_temp(u1, A1, A2, A3, A4, A5):
return u1 + (1631./55296)*A1 + (175./512)*A2 + (575./13824)*A3 +\
(44275./110592)*A4 + (253./4096)*A5
"""--------------------------Two modes-------------------------------------"""
#@jit(nogil = True)
def dAdzmm_roff_s0_nm2(u0,u0_conj, M1, M2, Q, tsh, dt, hf, w_tiled,gam_no_aeff):
"""
calculates the nonlinear operator for a given field u0
use: dA = dAdzmm(u0)
"""
M3 = uabs_nm2(u0,u0_conj,M2)
N = nonlin_kerr_nm2(M1, Q, u0, M3)
N *= gam_no_aeff
return N
#@jit(nogil = True)
def dAdzmm_roff_s1_nm2(u0,u0_conj, M1, M2, Q, tsh, dt, hf, w_tiled,gam_no_aeff):
"""
calculates the nonlinear operator for a given field u0
use: dA = dAdzmm(u0)
"""
M3 = uabs_nm2(u0,u0_conj,M2)
N = nonlin_kerr_nm2(M1, Q, u0, M3)
N = gam_no_aeff * (N + tsh*ifft(w_tiled * fft(N)))
return N
def dAdzmm_ron_s0_nm2(u0,u0_conj, M1, M2, Q, tsh, dt, hf, w_tiled, gam_no_aeff):
"""
calculates the nonlinear operator for a given field u0
use: dA = dAdzmm(u0)
"""
M3 = uabs_nm2(u0,u0_conj,M2)
M4 = dt*fftshift(ifft(fft(M3)*hf), axes = -1) # creates matrix M4
N = nonlin_ram_nm2(M1, Q, u0, M3, M4)
N *= gam_no_aeff
return N
def dAdzmm_ron_s1_nm2(u0,u0_conj, M1, M2, Q, tsh, dt, hf, w_tiled,gam_no_aeff):
"""
calculates the nonlinear operator for a given field u0
use: dA = dAdzmm(u0)
"""
M3 = uabs_nm2(u0,u0_conj,M2)
M4 = dt*fftshift(ifft(multi(fft(M3),hf)), axes = -1) # creates matrix M4
N = nonlin_ram_nm2(M1, Q, u0, M3, M4)
N = gam_no_aeff * (N + tsh*ifft(multi(w_tiled,fft(N))))
return N
@guvectorize(['void(complex128[:,:],complex128[:,:], int64[:,:], complex128[:,:])'],\
'(n,m),(n,m),(o,l)->(l,m)',target = trgt)
def uabs_nm2(u0,u0_conj,M2,M3):
for ii in range(M2.shape[1]):
M3[ii,:] = u0[M2[0,ii],:]*u0_conj[M2[1,ii],:]
@guvectorize(['void(int64[:,:], complex128[:,:], complex128[:,:],\
complex128[:,:], complex128[:,:], complex128[:,:])'],\
'(w,a),(i,a),(m,n),(l,n),(l,n)->(m,n)',target = trgt)
def nonlin_ram_nm2(M1, Q, u0, M3, M4, N):
N[:,:] = 0
for ii in range(M1.shape[1]):
N[M1[0,ii],:] += u0[M1[1,ii],:]*(0.82*(2*Q[0,ii] + Q[1,ii]) \
*M3[M1[4,ii],:] + \
0.54*Q[0,ii]*M4[M1[4,ii],:])
@guvectorize(['void(int64[:,:], complex128[:,:], complex128[:,:],\
complex128[:,:], complex128[:,:])'],\
'(w,a),(i,a),(m,n),(l,n)->(m,n)',target = trgt)
def nonlin_kerr_nm2(M1, Q, u0, M3, N):
N[:,:] = 0
for ii in range(M1.shape[1]):
N[M1[0,ii],:] += 0.82*(2*Q[0,ii] + Q[1,ii]) \
*u0[M1[1,ii],:]*M3[M1[4,ii],:]
"""------------------------------------------------------------------------"""
"""-----------------------------One mode-----------------------------------"""
#@jit(nogil = True)
def dAdzmm_roff_s0_nm1(u0, Q, tsh, dt, hf, w_tiled,gam_no_aeff):
"""
calculates the nonlinear operator for a given field u0
use: dA = dAdzmm(u0)
"""
M3 = u0.real**2 + u0.imag**2
#M3 = uabs_nm1(u0.real, u0.imag)
N = nonlin_kerr_nm1(Q, u0, M3)
N *= gam_no_aeff
return N
#@jit(nogil = True)
def dAdzmm_roff_s1_nm1(u0, Q, tsh, dt, hf, w_tiled,gam_no_aeff):
"""
calculates the nonlinear operator for a given field u0
use: dA = dAdzmm(u0)
"""
M3 = u0.real**2 + u0.imag**2
#M3 = uabs_nm1(u0.real, u0.imag)
N = nonlin_kerr_nm1(Q, u0, M3)
N = gam_no_aeff * (N + tsh*ifft(w_tiled * fft(N)))
return N
def dAdzmm_ron_s0_nm1(u0, Q, tsh, dt, hf, w_tiled,gam_no_aeff):
"""
calculates the nonlinear operator for a given field u0
use: dA = dAdzmm(u0)
"""
M3 = u0.real**2 + u0.imag**2
#M3 = uabs_nm1(u0.real, u0.imag)
M4 = dt*fftshift(ifft(fft(M3)*hf), axes = -1) # creates matrix M4
N = nonlin_ram_nm1(Q, u0, M3, M4)
N *= gam_no_aeff
return N
def dAdzmm_ron_s1_nm1(u0, Q, tsh, dt, hf, w_tiled,gam_no_aeff):
"""
calculates the nonlinear operator for a given field u0
use: dA = dAdzmm(u0)
"""
M3 = u0.real**2 + u0.imag**2
M3 = uabs_nm1(u0.real, u0.imag)
M4 = dt *fftshift(ifft(fft(M3)*hf), axes = -1)
N = nonlin_ram_nm1(Q, u0, M3, M4)
N = gam_no_aeff * (N + tsh*ifft(w_tiled * fft(N)))
return N
@vectorize(['float64(float64, float64)'], target=trgt)
def uabs_nm1(u0r, u0i):
return u0r**2 + u0i**2
@vectorize(['complex128(complex128, complex128, float64, complex128)'], target=trgt)
def nonlin_ram_nm1(Q, u0, M3, temp):
return Q*u0*(0.82*M3 + 0.18*temp)
@vectorize(['complex128(complex128, complex128, float64)'], target=trgt)
def nonlin_kerr_nm1(Q, u0, M3):
return 0.82*Q*u0*M3
"""------------------------------------------------------------------------"""
@jit(nopython=True,nogil = True)
def multi(a,b):
return a * b
class Integrand(object):
def __init__(self,nm,ram, ss, cython = True, timing = False):
print('number of modes: ', nm)
if nm == 2:
if cython:
if ss == 0 and ram == 'off':
self.dAdzmm = dAdzmm_roff_s0_cython_nm2
elif ss == 0 and ram == 'on':
self.dAdzmm = dAdzmm_ron_s0_cython_nm2
elif ss == 1 and ram == 'off':
self.dAdzmm = dAdzmm_roff_s1_cython_nm2
else:
self.dAdzmm = dAdzmm_ron_s1_cython_nm2
else:
if ss == 0 and ram == 'off':
self.dAdzmm = dAdzmm_roff_s0_nm2
elif ss == 0 and ram == 'on':
self.dAdzmm = dAdzmm_ron_s0_nm2
elif ss == 1 and ram == 'off':
self.dAdzmm = dAdzmm_roff_s1_nm2
else:
self.dAdzmm = dAdzmm_ron_s1_nm2
if timing:
self.dAdzmm = self.timer_nm2
elif nm ==1:
if cython:
if ss == 0 and ram == 'off':
self.dAdzmm = dAdzmm_roff_s0_cython_nm1
elif ss == 0 and ram == 'on':
self.dAdzmm = dAdzmm_ron_s0_cython_nm1
elif ss == 1 and ram == 'off':
self.dAdzmm = dAdzmm_roff_s1_cython_nm1
else:
self.dAdzmm = dAdzmm_ron_s1_cython_nm1
else:
if ss == 0 and ram == 'off':
self.dAdzmm = dAdzmm_roff_s0_nm1
elif ss == 0 and ram == 'on':
self.dAdzmm = dAdzmm_ron_s0_nm1
elif ss == 1 and ram == 'off':
self.dAdzmm = dAdzmm_roff_s1_nm1
else:
self.dAdzmm = dAdzmm_ron_s1_nm1
if timing:
self.dAdzmm = self.timer_nm1
else:
sys.exit('Too many modes!!!')
def timer_nm2(self,u0,u0_conj, M1, M2, Q, tsh, dt, hf, w_tiled,gam_no_aeff):
"""
Times the functions of python, cython etc.
"""
dt1, dt2, dt3, dt4, dt5, dt6, dt7, dt8 = [], [], [], [],\
[], [], [], []
NN = 100
for i in range(NN):
'------No ram, no ss--------'
t = time()
N1 = dAdzmm_roff_s0_cython_nm2(u0,u0_conj, M1, M2, Q, tsh, dt, hf, w_tiled,gam_no_aeff)
dt1.append(time() - t)
t = time()
N2 = dAdzmm_roff_s0_nm2(u0,u0_conj, M1, M2, Q, tsh, dt, hf, w_tiled,gam_no_aeff)
dt2.append(time() - t)
assert_allclose(N1, N2)
'------ ram, no ss--------'
t = time()
N1 = dAdzmm_ron_s0_cython_nm2(u0,u0_conj, M1, M2, Q, tsh, dt, hf, w_tiled,gam_no_aeff)
dt3.append(time() - t)
t = time()
N2 = dAdzmm_ron_s0_nm2(u0,u0_conj, M1, M2, Q, tsh, dt, hf, w_tiled,gam_no_aeff)
dt4.append(time() - t)
assert_allclose(N1, N2)
'------ no ram, ss--------'
t = time()
N1 = dAdzmm_roff_s1_cython_nm2(u0,u0_conj, M1, M2, Q, tsh, dt, hf, w_tiled,gam_no_aeff)
dt5.append(time() - t)
t = time()
N2 = dAdzmm_roff_s1_nm2(u0,u0_conj, M1, M2, Q, tsh, dt, hf, w_tiled,gam_no_aeff)
dt6.append(time() - t)
assert_allclose(N1, N2)
'------ ram, ss--------'
t = time()
N1 = dAdzmm_ron_s1_cython_nm2(u0,u0_conj, M1, M2, Q, tsh, dt, hf, w_tiled,gam_no_aeff)
dt7.append(time() - t)
t = time()
N2 = dAdzmm_ron_s1_nm2(u0,u0_conj, M1, M2, Q, tsh, dt, hf, w_tiled,gam_no_aeff)
dt8.append(time() - t)
assert_allclose(N1, N2)
print('cython_ram(off)_s0: {} +/- {}'.format(np.average(dt1),np.std(dt1)))
print('python_ram(off)_s0: {} +/- {}'.format(np.average(dt2),np.std(dt2)))
print('Cython is {} times faster'.format(np.average(dt2)/np.average(dt1)))
print('--------------------------------------------------------')
print('cython_ram(on)_s0: {} +/- {}'.format(np.average(dt3),np.std(dt3)))
print('python_ram(on)_s0: {} +/- {}'.format(np.average(dt4),np.std(dt4)))
print('Cython is {} times faster'.format( | np.average(dt4) | numpy.average |
import os
import time
import numpy as np
import sys
from utils import *
from NeuralNet import NeuralNet
from .ChessNNet import ChessNNet as onnet
sys.path.append('..')
args = TrainingConfig({
'lr': 0.005,
'dropout': 0.2,
'epochs': 14,
'batch_size': 16,
'cuda': True,
'num_channels': 256,
})
class NNetWrapper(NeuralNet):
def __init__(self, game):
self.nnet = onnet(game, args)
self.board_x, self.board_y = game.getBoardSize()
self.action_size = game.getActionSize()
def train(self, examples):
"""
examples: list of examples, each example is of form (board, pi, v)
"""
input_boards, target_pis, target_vs = list(zip(*examples))
input_boards = | np.asarray(input_boards) | numpy.asarray |
#!/usr/bin/env python3
import cv2
import numpy as np
import pybullet as p
import tensorflow as tf
def normalize(angle):
"""
Normalize the angle to [-pi, pi]
:param float angle: input angle to be normalized
:return float: normalized angle
"""
quaternion = p.getQuaternionFromEuler(np.array([0, 0, angle]))
euler = p.getEulerFromQuaternion(quaternion)
return euler[2]
def calc_odometry(old_pose, new_pose):
"""
Calculate the odometry between two poses
:param ndarray old_pose: pose1 (x, y, theta)
:param ndarray new_pose: pose2 (x, y, theta)
:return ndarray: odometry (odom_x, odom_y, odom_th)
"""
x1, y1, th1 = old_pose
x2, y2, th2 = new_pose
abs_x = (x2 - x1)
abs_y = (y2 - y1)
th1 = normalize(th1)
sin = np.sin(th1)
cos = np.cos(th1)
th2 = normalize(th2)
odom_th = normalize(th2 - th1)
odom_x = cos * abs_x + sin * abs_y
odom_y = cos * abs_y - sin * abs_x
odometry = np.array([odom_x, odom_y, odom_th])
return odometry
def calc_velocity_commands(old_pose, new_pose, dt=0.1):
"""
Calculate the velocity model command between two poses
:param ndarray old_pose: pose1 (x, y, theta)
:param ndarray new_pose: pose2 (x, y, theta)
:param float dt: time interval
:return ndarray: velocity command (linear_vel, angular_vel, final_rotation)
"""
x1, y1, th1 = old_pose
x2, y2, th2 = new_pose
if x1==x2 and y1==y2:
# only angular motion
linear_velocity = 0
angular_velocity = 0
elif x1!=x2 and np.tan(th1) == np.tan( (y1-y2)/(x1-x2) ):
# only linear motion
linear_velocity = (x2-x1)/dt
angular_velocity = 0
else:
# both linear + angular motion
mu = 0.5 * ( ((x1-x2)*np.cos(th1) + (y1-y2)*np.sin(th1))
/ ((y1-y2)*np.cos(th1) - (x1-x2)*np.sin(th1)) )
x_c = (x1+x2) * 0.5 + mu * (y1-y2)
y_c = (y1+y2) * 0.5 - mu * (x1-x2)
r_c = np.sqrt( (x1-x_c)**2 + (y1-y_c)**2 )
delta_th = np.arctan2(y2-y_c, x2-x_c) - np.arctan2(y1-y_c, x1-x_c)
angular_velocity = delta_th/dt
# HACK: to handle unambiguous postive/negative quadrants
if np.arctan2(y1-y_c, x1-x_c) < 0:
linear_velocity = angular_velocity * r_c
else:
linear_velocity = -angular_velocity * r_c
final_rotation = (th2-th1)/dt - angular_velocity
return np.array([linear_velocity, angular_velocity, final_rotation])
def sample_motion_odometry(old_pose, odometry):
"""
Sample new pose based on give pose and odometry
:param ndarray old_pose: given pose (x, y, theta)
:param ndarray odometry: given odometry (odom_x, odom_y, odom_th)
:return ndarray: new pose (x, y, theta)
"""
x1, y1, th1 = old_pose
odom_x, odom_y, odom_th = odometry
th1 = normalize(th1)
sin = np.sin(th1)
cos = np.cos(th1)
x2 = x1 + (cos * odom_x - sin * odom_y)
y2 = y1 + (sin * odom_x + cos * odom_y)
th2 = normalize(th1 + odom_th)
new_pose = np.array([x2, y2, th2])
return new_pose
def sample_motion_velocity(old_pose, velocity, dt=0.1):
"""
Sample new pose based on give pose and velocity commands
:param ndarray old_pose: given pose (x, y, theta)
:param ndarray velocity: velocity model (linear_vel, angular_vel, final_rotation)
:param float dt: time interval
:return ndarray: new pose (x, y, theta)
"""
x1, y1, th1 = old_pose
linear_vel, angular_vel, final_rotation = velocity
if angular_vel == 0:
x2 = x1 + linear_vel*dt
y2 = y1
else:
r = linear_vel/angular_vel
x2 = x1 - r*np.sin(th1) + r*np.sin(th1 + angular_vel*dt)
y2 = y1 + r*np.cos(th1) - r*np.cos(th1 + angular_vel*dt)
th2 = th1 + angular_vel*dt + final_rotation*dt
new_pose = np.array([x2, y2, th2])
return new_pose
def decode_image(img, resize=None):
"""
Decode image
:param img: image encoded as a png in a string
:param resize: tuple of width, height, new size of image (optional)
:return np.ndarray: image (k, H, W, 1)
"""
# TODO
# img = cv2.imdecode(img, -1)
if resize is not None:
img = cv2.resize(img, resize)
return img
def process_raw_map(image):
"""
Decode and normalize image
:param image: floor map image as ndarray (H, W)
:return np.ndarray: image (H, W, 1)
white: empty space, black: occupied space
"""
assert np.min(image)>=0. and np.max(image)>=1. and np.max(image)<=255.
image = normalize_map(np.atleast_3d(image.astype(np.float32)))
assert np.min(image)>=0. and np.max(image)<=2.
return image
def normalize_map(x):
"""
Normalize map input
:param x: map input (H, W, ch)
:return np.ndarray: normalized map (H, W, ch)
"""
# rescale to [0, 2], later zero padding will produce equivalent obstacle
return x * (2.0 / 255.0)
def normalize_observation(x):
"""
Normalize observation input: an rgb image or a depth image
:param x: observation input (56, 56, ch)
:return np.ndarray: normalized observation (56, 56, ch)
"""
# resale to [-1, 1]
if x.ndim == 2 or x.shape[2] == 1: # depth
return x * (2.0 / 100.0) - 1.0
else: # rgb
return x * (2.0 / 255.0) - 1.0
def denormalize_observation(x):
"""
Denormalize observation input to store efficiently
:param x: observation input (B, 56, 56, ch)
:return np.ndarray: denormalized observation (B, 56, 56, ch)
"""
# resale to [0, 255]
if x.ndim == 2 or x.shape[-1] == 1: # depth
x = (x + 1.0) * (100.0 / 2.0)
else: # rgb
x = (x + 1.0) * (255.0 / 2.0)
return x.astype(np.int32)
def process_raw_image(image, resize=(56, 56)):
"""
Decode and normalize image
:param image: image encoded as a png (H, W, ch)
:param resize: resize image (new_H, new_W)
:return np.ndarray: images (new_H, new_W, ch) normalized for training
"""
# assert np.min(image)>=0. and np.max(image)>=1. and np.max(image)<=255.
image = decode_image(image, resize)
image = normalize_observation(np.atleast_3d(image.astype(np.float32)))
assert np.min(image)>=-1. and np.max(image)<=1.
return image
def get_discrete_action(max_lin_vel, max_ang_vel):
"""
Get manual keyboard action
:return int: discrete action for moving forward/backward/left/right
"""
key = input('Enter Key: ')
# default stay still
if key == 'w':
# forward
action = np.array([max_lin_vel, 0.])
elif key == 's':
# backward
action = np.array([-max_lin_vel, 0.])
elif key == 'd':
# right
action = np.array([0., -max_ang_vel])
elif key == 'a':
# left
action = np.array([0., max_ang_vel])
else:
# do nothing
action = np.array([0., 0.])
return action
# def transform_position(position, map_shape, map_pixel_in_meters):
# """
# Transform position from 2D co-ordinate space to pixel space
# :param ndarray position: [x, y] in co-ordinate space
# :param tuple map_shape: [height, width, channel] of the map the co-ordinated need to be transformed
# :param float map_pixel_in_meters: The width (and height) of a pixel of the map in meters
# :return ndarray: position [x, y] in pixel space of map
# """
# x, y = position
# height, width, channel = map_shape
#
# x = (x / map_pixel_in_meters) + width / 2
# y = (y / map_pixel_in_meters) + height / 2
#
# return np.array([x, y])
# def inv_transform_pose(pose, map_shape, map_pixel_in_meters):
# """
# Transform pose from pixel space to 2D co-ordinate space
# :param ndarray pose: [x, y, theta] in pixel space of map
# :param tuple map_shape: [height, width, channel] of the map the co-ordinated need to be transformed
# :param float map_pixel_in_meters: The width (and height) of a pixel of the map in meters
# :return ndarray: pose [x, y, theta] in co-ordinate space
# """
# x, y, theta = pose
# height, width, channel = map_shape
#
# x = (x - width / 2) * map_pixel_in_meters
# y = (y - height / 2) * map_pixel_in_meters
#
# return np.array([x, y, theta])
def obstacle_avoidance(state, max_lin_vel, max_ang_vel):
"""
Choose action by avoiding obstances which highest preference to move forward
"""
assert list(state.shape) == [4]
left, left_front, right_front, right = state # obstacle (not)present area
if not left_front and not right_front:
# move forward
action = np.array([max_lin_vel, 0.])
elif not left or not left_front:
# turn left
action = np.array([0., max_ang_vel])
elif not right or not right_front:
# turn right
action = np.array([0., -max_ang_vel])
else:
# backward
action = np.array([-max_lin_vel, np.random.uniform(low=-max_ang_vel, high=max_ang_vel)])
return action
def gather_episode_stats(env, params, sample_particles=False):
"""
Run the gym environment and collect the required stats
:param env: igibson env instance
:param params: parsed parameters
:param sample_particles: whether or not to sample particles
:return dict: episode stats data containing:
odometry, true poses, observation, particles, particles weights, floor map
"""
agent = params.agent
trajlen = params.trajlen
max_lin_vel = params.max_lin_vel
max_ang_vel = params.max_ang_vel
assert agent in ['manual_agent', 'avoid_agent', 'rnd_agent']
odometry = []
true_poses = []
rgb_observation = []
depth_observation = []
occupancy_grid_observation = []
obs = env.reset() # observations are not processed
# process [0, 1] ->[0, 255] -> [-1, +1] range
rgb = process_raw_image(obs['rgb_obs']*255, resize=(56, 56))
rgb_observation.append(rgb)
# process [0, 1] ->[0, 100] -> [-1, +1] range
depth = process_raw_image(obs['depth_obs']*100, resize=(56, 56))
depth_observation.append(depth)
# process [0, 0.5, 1]
occupancy_grid = np.atleast_3d(decode_image(obs['occupancy_grid'], resize=(56, 56)).astype(np.float32))
occupancy_grid_observation.append(occupancy_grid)
scene_id = env.config.get('scene_id')
floor_num = env.task.floor_num
floor_map, _ = env.get_floor_map() # already processed
obstacle_map, _ = env.get_obstacle_map() # already processed
assert list(floor_map.shape) == list(obstacle_map.shape)
old_pose = env.get_robot_pose(env.robots[0].calc_state(), floor_map.shape)
assert list(old_pose.shape) == [3]
true_poses.append(old_pose)
for _ in range(trajlen - 1):
if agent == 'manual_agent':
action = get_discrete_action(max_lin_vel, max_ang_vel)
else:
action = obstacle_avoidance(obs['obstacle_obs'], max_lin_vel, max_ang_vel)
# take action and get new observation
obs, reward, done, _ = env.step(action)
# process [0, 1] ->[0, 255] -> [-1, +1] range
rgb = process_raw_image(obs['rgb_obs']*255, resize=(56, 56))
rgb_observation.append(rgb)
# process [0, 1] ->[0, 100] -> [-1, +1] range
depth = process_raw_image(obs['depth_obs']*100, resize=(56, 56))
depth_observation.append(depth)
# process [0, 0.5, 1]
occupancy_grid = np.atleast_3d(decode_image(obs['occupancy_grid'], resize=(56, 56)).astype(np.float32))
occupancy_grid_observation.append(occupancy_grid)
left, left_front, right_front, right = obs['obstacle_obs'] # obstacle (not)present
# get new robot state after taking action
new_pose = env.get_robot_pose(env.robots[0].calc_state(), floor_map.shape)
assert list(new_pose.shape) == [3]
true_poses.append(new_pose)
# calculate actual odometry b/w old pose and new pose
odom = calc_odometry(old_pose, new_pose)
assert list(odom.shape) == [3]
odometry.append(odom)
old_pose = new_pose
# end of episode
odom = calc_odometry(old_pose, new_pose)
odometry.append(odom)
if sample_particles:
num_particles = params.num_particles
particles_cov = params.init_particles_cov
particles_distr = params.init_particles_distr
# sample random particles and corresponding weights
init_particles = env.get_random_particles(num_particles, particles_distr, true_poses[0], particles_cov).squeeze(
axis=0)
init_particle_weights = np.full((num_particles,), (1. / num_particles))
assert list(init_particles.shape) == [num_particles, 3]
assert list(init_particle_weights.shape) == [num_particles]
else:
init_particles = None
init_particle_weights = None
episode_data = {
'scene_id': scene_id, # str
'floor_num': floor_num, # int
'floor_map': floor_map, # (height, width, 1)
'obstacle_map': obstacle_map, # (height, width, 1)
'odometry': np.stack(odometry), # (trajlen, 3)
'true_states': np.stack(true_poses), # (trajlen, 3)
'rgb_observation': np.stack(rgb_observation), # (trajlen, height, width, 3)
'depth_observation': np.stack(depth_observation), # (trajlen, height, width, 1)
'occupancy_grid': np.stack(occupancy_grid_observation), # (trajlen, height, width, 1)
'init_particles': init_particles, # (num_particles, 3)
'init_particle_weights': init_particle_weights, # (num_particles,)
}
return episode_data
def get_batch_data(env, params):
"""
Gather batch of episode stats
:param env: igibson env instance
:param params: parsed parameters
:return dict: episode stats data containing:
odometry, true poses, observation, particles, particles weights, floor map
"""
trajlen = params.trajlen
batch_size = params.batch_size
map_size = params.global_map_size
num_particles = params.num_particles
odometry = []
floor_map = []
obstacle_map = []
observation = []
true_states = []
init_particles = []
init_particle_weights = []
for _ in range(batch_size):
episode_data = gather_episode_stats(env, params, sample_particles=True)
odometry.append(episode_data['odometry'])
floor_map.append(episode_data['floor_map'])
obstacle_map.append(episode_data['obstacle_map'])
true_states.append(episode_data['true_states'])
observation.append(episode_data['observation'])
init_particles.append(episode_data['init_particles'])
init_particle_weights.append(episode_data['init_particle_weights'])
batch_data = {}
batch_data['odometry'] = np.stack(odometry)
batch_data['floor_map'] = np.stack(floor_map)
batch_data['obstacle_map'] = np.stack(obstacle_map)
batch_data['true_states'] = np.stack(true_states)
batch_data['observation'] = np.stack(observation)
batch_data['init_particles'] = np.stack(init_particles)
batch_data['init_particle_weights'] = | np.stack(init_particle_weights) | numpy.stack |
"""
Attitude discipline for CADRE.
"""
from six.moves import range
import numpy as np
from openmdao.api import ExplicitComponent
from CADRE.kinematics import computepositionrotd, computepositionrotdjacobian
class Attitude_Angular(ExplicitComponent):
"""
Calculates angular velocity vector from the satellite's orientation
matrix and its derivative.
"""
def __init__(self, n=2):
super(Attitude_Angular, self).__init__()
self.n = n
def setup(self):
n = self.n
# Inputs
self.add_input('O_BI', np.zeros((n, 3, 3)), units=None,
desc='Rotation matrix from body-fixed frame to Earth-centered '
'inertial frame over time')
self.add_input('Odot_BI', np.zeros((n, 3, 3)), units=None,
desc='First derivative of O_BI over time')
# Outputs
self.add_output('w_B', np.zeros((n, 3)), units='1/s',
desc='Angular velocity vector in body-fixed frame over time')
self.dw_dOdot = np.zeros((n, 3, 3, 3))
self.dw_dO = np.zeros((n, 3, 3, 3))
row = np.array([1, 1, 1, 2, 2, 2, 0, 0, 0])
col = np.array([6, 7, 8, 0, 1, 2, 3, 4, 5])
rows = np.tile(row, n) + np.repeat(3*np.arange(n), 9)
cols = np.tile(col, n) + np.repeat(9*np.arange(n), 9)
self.declare_partials('w_B', 'O_BI', rows=rows, cols=cols)
self.dw_dOdot = np.zeros((n, 3, 3, 3))
self.dw_dO = | np.zeros((n, 3, 3, 3)) | numpy.zeros |
from __future__ import print_function
import itertools
import math
import os
import random
import shutil
import tempfile
import unittest
import uuid
import numpy as np
import pytest
import tensorflow as tf
import coremltools
import coremltools.models.datatypes as datatypes
from coremltools.models import _MLMODEL_FULL_PRECISION, _MLMODEL_HALF_PRECISION
from coremltools.models import neural_network as neural_network
from coremltools.models.neural_network import flexible_shape_utils
from coremltools.models.utils import macos_version, is_macos
np.random.seed(10)
MIN_MACOS_VERSION_REQUIRED = (10, 13)
LAYERS_10_15_MACOS_VERSION = (10, 15)
def _get_unary_model_spec(x, mode, alpha=1.0):
input_dim = x.shape
input_features = [('data', datatypes.Array(*input_dim))]
output_features = [('output', datatypes.Array(*input_dim))]
builder = neural_network.NeuralNetworkBuilder(input_features,
output_features)
builder.add_unary(name='unary', input_name='data',
output_name='output', mode=mode, alpha=alpha)
return builder.spec
class CorrectnessTest(unittest.TestCase):
def runTest(self):
pass
def _compare_shapes(self, np_preds, coreml_preds):
return np.squeeze(np_preds).shape == np.squeeze(coreml_preds).shape
def _compare_nd_shapes(self, np_preds, coreml_preds, shape=()):
if shape:
return coreml_preds.shape == shape
else:
# check if shape has 0 valued dimension
if np.prod(np_preds.shape) == 0 and np.prod(coreml_preds.shape) == 0:
return True
return coreml_preds.shape == np_preds.shape
def _compare_predictions(self, np_preds, coreml_preds, delta=.01):
np_preds = np_preds.flatten()
coreml_preds = coreml_preds.flatten()
for i in range(len(np_preds)):
max_den = max(1.0, np_preds[i], coreml_preds[i])
if np.abs(
np_preds[i] / max_den - coreml_preds[i] / max_den) > delta:
return False
return True
@staticmethod
def _compare_moments(model, inputs, expected, use_cpu_only=True, num_moments=10):
"""
This utility function is used for validate random distributions layers.
It validates the first 10 moments of prediction and expected values.
"""
def get_moment(data, k):
return np.mean(np.power(data - np.mean(data), k))
if isinstance(model, str):
model = coremltools.models.MLModel(model)
model = coremltools.models.MLModel(model, useCPUOnly=use_cpu_only)
prediction = model.predict(inputs, useCPUOnly=use_cpu_only)
for output_name in expected:
np_preds = expected[output_name]
coreml_preds = prediction[output_name]
np_moments = [get_moment(np_preds.flatten(), k) for k in range(num_moments)]
coreml_moments = [get_moment(coreml_preds.flatten(), k) for k in range(num_moments)]
np.testing.assert_almost_equal(np_moments, coreml_moments, decimal=2)
# override expected values to allow element-wise compares
for output_name in expected:
expected[output_name] = prediction[output_name]
def _test_model(self,
model,
input,
expected,
model_precision=_MLMODEL_FULL_PRECISION,
useCPUOnly=False,
output_name_shape_dict={},
validate_shapes_only=False):
model_dir = None
# if we're given a path to a model
if isinstance(model, str):
model = coremltools.models.MLModel(model)
# If we're passed in a specification, save out the model
# and then load it back up
elif isinstance(model, coremltools.proto.Model_pb2.Model):
model_dir = tempfile.mkdtemp()
model_name = str(uuid.uuid4()) + '.mlmodel'
model_path = os.path.join(model_dir, model_name)
coremltools.utils.save_spec(model, model_path)
model = coremltools.models.MLModel(model, useCPUOnly=useCPUOnly)
# If we want to test the half precision case
if model_precision == _MLMODEL_HALF_PRECISION:
model = coremltools.utils.convert_neural_network_weights_to_fp16(
model)
try:
prediction = model.predict(input, useCPUOnly=useCPUOnly)
for output_name in expected:
if self.__class__.__name__ == "SimpleTest":
assert (self._compare_shapes(expected[output_name],
prediction[output_name]))
else:
if output_name in output_name_shape_dict:
output_shape = output_name_shape_dict[output_name]
else:
output_shape = []
if len(output_shape) == 0 and len(expected[output_name].shape) == 0:
output_shape = (1,)
assert (self._compare_nd_shapes(expected[output_name],
prediction[output_name],
output_shape))
if not validate_shapes_only:
assert (self._compare_predictions(expected[output_name],
prediction[output_name]))
finally:
# Remove the temporary directory if we created one
if model_dir and os.path.exists(model_dir):
shutil.rmtree(model_dir)
@unittest.skipIf(not is_macos() or macos_version() < MIN_MACOS_VERSION_REQUIRED,
'macOS 10.13+ is required. Skipping tests.')
class SimpleTest(CorrectnessTest):
def test_tiny_upsample_linear_mode(self):
input_dim = (1, 1, 3) # (C,H,W)
input_features = [('data', datatypes.Array(*input_dim))]
output_features = [('output', None)]
builder = neural_network.NeuralNetworkBuilder(input_features,
output_features)
builder.add_upsample(name='upsample',
scaling_factor_h=2, scaling_factor_w=3,
input_name='data', output_name='output',
mode='BILINEAR')
input = {
'data': np.reshape(np.array([1.0, 2.0, 3.0]), (1, 1, 3))
}
expected = {
'output': np.array(
[[1, 1.333, 1.666, 2, 2.333, 2.666, 3, 3, 3],
[1, 1.333, 1.6666, 2, 2.33333, 2.6666, 3, 3, 3]
])
}
self._test_model(builder.spec, input, expected)
self.assertEquals(len(input_dim), builder._get_rank('output'))
def test_LRN(self):
input_dim = (1, 3, 3)
input_features = [('data', datatypes.Array(*input_dim))]
output_features = [('output', datatypes.Array(*input_dim))]
builder = neural_network.NeuralNetworkBuilder(input_features,
output_features)
builder.add_lrn(name='lrn', input_name='data', output_name='output',
alpha=2, beta=3, local_size=1, k=8)
input = {
'data': np.ones((1, 3, 3))
}
expected = {
'output': 1e-3 * np.ones((1, 3, 3))
}
self._test_model(builder.spec, input, expected)
self.assertEqual(len(input_dim), builder._get_rank('output'))
def test_MVN(self):
input_dim = (2, 2, 2)
input_features = [('data', datatypes.Array(*input_dim))]
output_features = [('output', datatypes.Array(*input_dim))]
builder = neural_network.NeuralNetworkBuilder(input_features,
output_features)
builder.add_mvn(name='mvn', input_name='data', output_name='output',
across_channels=False, normalize_variance=False)
input = {
'data': np.reshape(np.arange(8, dtype=np.float32), (2, 2, 2))
}
expected = {
'output': np.reshape(np.arange(8) - np.array(
[1.5, 1.5, 1.5, 1.5, 5.5, 5.5, 5.5, 5.5]), (2, 2, 2))
}
self._test_model(builder.spec, input, expected)
def test_L2_normalize(self):
input_dim = (1, 2, 2)
input_features = [('data', datatypes.Array(*input_dim))]
output_features = [('output', datatypes.Array(*input_dim))]
builder = neural_network.NeuralNetworkBuilder(input_features,
output_features)
builder.add_l2_normalize(name='mvn', input_name='data',
output_name='output')
input = {
'data': np.reshape(np.arange(4, dtype=np.float32), (1, 2, 2))
}
expected = {
'output': np.reshape(np.arange(4, dtype=np.float32),
(1, 2, 2)) / np.sqrt(14)
}
self._test_model(builder.spec, input, expected)
def test_unary_sqrt(self):
x = np.reshape(np.arange(1, 5, dtype=np.float32), (1, 2, 2))
input = {'data': x}
expected = {'output': np.sqrt(x)}
spec = _get_unary_model_spec(x, 'sqrt')
self._test_model(spec, input, expected)
def test_unary_rsqrt(self):
x = np.reshape(np.arange(1, 5, dtype=np.float32), (1, 2, 2))
input = {'data': x}
expected = {'output': 1 / np.sqrt(x)}
spec = _get_unary_model_spec(x, 'rsqrt')
self._test_model(spec, input, expected)
def test_unary_inverse(self):
x = np.reshape(np.arange(1, 5, dtype=np.float32), (1, 2, 2))
input = {'data': x}
expected = {'output': 1 / x}
spec = _get_unary_model_spec(x, 'inverse')
self._test_model(spec, input, expected)
def test_unary_power(self):
x = np.reshape(np.arange(1, 5, dtype=np.float32), (1, 2, 2))
input = {'data': x}
expected = {'output': x ** 3}
spec = _get_unary_model_spec(x, 'power', 3)
self._test_model(spec, input, expected)
def test_unary_exp(self):
x = np.reshape(np.arange(1, 5, dtype=np.float32), (1, 2, 2))
input = {'data': x}
expected = {'output': np.exp(x)}
spec = _get_unary_model_spec(x, 'exp')
self._test_model(spec, input, expected)
def test_unary_log(self):
x = np.reshape(np.arange(1, 5, dtype=np.float32), (1, 2, 2))
input = {'data': x}
expected = {'output': np.log(x)}
spec = _get_unary_model_spec(x, 'log')
self._test_model(spec, input, expected)
def test_unary_abs(self):
x = np.reshape(np.arange(1, 5, dtype=np.float32), (1, 2, 2))
input = {'data': x}
expected = {'output': np.abs(x)}
spec = _get_unary_model_spec(x, 'abs')
self._test_model(spec, input, expected)
def test_unary_threshold(self):
x = np.reshape(np.arange(1, 5, dtype=np.float32), (1, 2, 2))
input = {'data': x}
expected = {'output': np.maximum(x, 2)}
spec = _get_unary_model_spec(x, 'threshold', 2)
self._test_model(spec, input, expected)
def test_split(self):
input_dim = (9, 2, 2)
x = np.random.rand(*input_dim)
input_features = [('data', datatypes.Array(*input_dim))]
output_names = []
output_features = []
for i in range(3):
out = 'out_' + str(i)
output_names.append(out)
output_features.append((out, None))
builder = neural_network.NeuralNetworkBuilder(input_features,
output_features)
builder.add_split(name='split', input_name='data',
output_names=output_names)
input = {'data': x}
expected = {
'out_0': x[0: 3, :, :],
'out_1': x[3: 6, :, :],
'out_2': x[6: 9, :, :]
}
self._test_model(builder.spec, input, expected)
for output_ in output_names:
self.assertEqual(len(input_dim), builder._get_rank(output_))
def test_scale_constant(self):
input_dim = (1, 2, 2)
input_features = [('data', datatypes.Array(*input_dim))]
output_features = [('output', None)]
builder = neural_network.NeuralNetworkBuilder(input_features,
output_features)
builder.add_scale(name='scale', W=5, b=45, has_bias=True,
input_name='data', output_name='output')
x = np.reshape(np.arange(4, dtype=np.float32), (1, 2, 2))
input = {'data': x}
expected = {'output': 5 * x + 45}
self._test_model(builder.spec, input, expected)
def test_scale_matrix(self):
input_dim = (1, 2, 2)
input_features = [('data', datatypes.Array(*input_dim))]
output_features = [('output', None)]
builder = neural_network.NeuralNetworkBuilder(input_features,
output_features)
W = np.reshape(np.arange(5, 9), (1, 2, 2))
builder.add_scale(name='scale', W=W, b=None, has_bias=False,
input_name='data', output_name='output',
shape_scale=[1, 2, 2])
x = np.reshape(np.arange(4, dtype=np.float32), (1, 2, 2))
input = {'data': x}
expected = {'output': W * x}
self._test_model(builder.spec, input, expected)
def test_bias_constant(self):
input_dim = (1, 2, 2)
input_features = [('data', datatypes.Array(*input_dim))]
output_features = [('output', None)]
builder = neural_network.NeuralNetworkBuilder(input_features,
output_features)
builder.add_bias(name='bias', b=45, input_name='data',
output_name='output')
x = np.reshape(np.arange(4, dtype=np.float32), (1, 2, 2))
input = {'data': x}
expected = {'output': x + 45}
self._test_model(builder.spec, input, expected)
def test_bias_matrix(self):
input_dim = (1, 2, 2)
input_features = [('data', datatypes.Array(*input_dim))]
output_features = [('output', None)]
builder = neural_network.NeuralNetworkBuilder(input_features,
output_features)
b = np.reshape(np.arange(5, 9), (1, 2, 2))
builder.add_bias(name='bias', b=b, input_name='data',
output_name='output',
shape_bias=[1, 2, 2])
x = np.reshape(np.arange(4, dtype=np.float32), (1, 2, 2))
input = {'data': x}
expected = {'output': x + b}
self._test_model(builder.spec, input, expected)
def test_load_constant(self, model_precision=_MLMODEL_FULL_PRECISION):
input_dim = (1, 2, 2)
input_features = [('data', datatypes.Array(*input_dim))]
output_features = [('output', None)]
builder = neural_network.NeuralNetworkBuilder(input_features,
output_features)
b = np.reshape(np.arange(5, 9), (1, 2, 2))
builder.add_load_constant(name='load_constant', output_name='bias',
constant_value=b, shape=[1, 2, 2])
builder.add_elementwise(name='add', input_names=['data', 'bias'],
output_name='output', mode='ADD')
x = np.reshape(np.arange(4, dtype=np.float32), (1, 2, 2))
input = {'data': x}
expected = {'output': x + b}
self._test_model(builder.spec, input, expected, model_precision)
self.assertEqual(len(input_dim), builder._get_rank('output'))
def test_load_constant_half_precision(self):
self.test_load_constant(model_precision=_MLMODEL_HALF_PRECISION)
def test_min(self):
input_dim = (1, 2, 2)
input_features = [('data_0', datatypes.Array(*input_dim)),
('data_1', datatypes.Array(*input_dim))]
output_features = [('output', None)]
builder = neural_network.NeuralNetworkBuilder(input_features,
output_features)
builder.add_elementwise(name='min', input_names=['data_0', 'data_1'],
output_name='output', mode='MIN')
x1 = np.reshape( | np.arange(4, dtype=np.float32) | numpy.arange |
import numpy as np
def get_data(model_type, TRAIN, words, EMB, enforce_gen, n_side_pixl):
import numpy as np
EMBEDDINGS, OBJ_ctr_sd_enf_gen = {}, []
# 0. Get dictionary of ALL our embedding words
EMB_dict = build_emb_dict(words, EMB)
# 1. Get the RELEVANT training instances (filtering for 'predicates' and 'complete_only' variables)
OBJ_ctr_sd, rel_ids, TRAIN_relevant = get_TRAIN_relevant(TRAIN, words)
# 2. get dictionaries WORDLISTS (INDICES for the embedding layer!)
EMBEDDINGS['obj_list'] = list(set(TRAIN_relevant['obj']))
EMBEDDINGS['subj_list'] = list(set(TRAIN_relevant['subj']))
EMBEDDINGS['pred_list'] = list(set(TRAIN_relevant['rel']))
allwords = np.concatenate((EMBEDDINGS['subj_list'], EMBEDDINGS['pred_list'], EMBEDDINGS['obj_list']), axis=0)
EMBEDDINGS['allwords_list'] = list(
set(allwords)) # IMPORTANT: The order of this list is what prevails later on as index for embeddings
# 3. Get INITIALIZATION embeddings
EMBEDDINGS['subj_EMB'] = wordlist2emb_matrix(EMBEDDINGS['subj_list'], EMB_dict)
EMBEDDINGS['pred_EMB'] = wordlist2emb_matrix(EMBEDDINGS['pred_list'], EMB_dict)
EMBEDDINGS['obj_EMB'] = wordlist2emb_matrix(EMBEDDINGS['obj_list'], EMB_dict)
EMBEDDINGS['allwords_EMB'] = wordlist2emb_matrix(EMBEDDINGS['allwords_list'],EMB_dict)
# 3.1. Get RANDOM embeddings (of the size of allwords_EMB)
EMBEDDINGS['allwords_EMB_rnd'] = get_random_EMB(EMBEDDINGS['allwords_EMB'])
EMBEDDINGS['subj_EMB_rnd'] = get_random_EMB(EMBEDDINGS['subj_EMB'])
EMBEDDINGS['pred_EMB_rnd'] = get_random_EMB(EMBEDDINGS['pred_EMB'])
EMBEDDINGS['obj_EMB_rnd'] = get_random_EMB(EMBEDDINGS['obj_EMB'])
# 3.2. get ONE-HOT embeddings:
EMBEDDINGS['subj_EMB_onehot'] = np.identity(len(EMBEDDINGS['subj_list']))
EMBEDDINGS['pred_EMB_onehot'] = np.identity(len(EMBEDDINGS['pred_list']))
EMBEDDINGS['obj_EMB_onehot'] = np.identity(len(EMBEDDINGS['obj_list']))
EMBEDDINGS['allwords_EMB_onehot'] = np.identity(len(EMBEDDINGS['allwords_list']))
# 4. Get X data (i.e., get the SEQUENCES of INDICES for the embedding layer)
X, X_extra, y, y_pixl, X_extra_enf_gen, X_enf_gen, y_enf_gen, y_enf_gen_pixl, \
idx_IN_X_and_y, idx_enf_gen = relevant_instances2X_and_y(model_type, TRAIN_relevant, EMBEDDINGS, enforce_gen,
n_side_pixl)
# 5. Get the OBJ_ctr_sd_enf_gen that we need for some performance measures!
if enforce_gen['eval'] is not None:
OBJ_ctr_sd_enf_gen = OBJ_ctr_sd[idx_enf_gen]
# 6. Finally, if we have REDUCED the X and y data by ENFORCING generalization (excluding instances) we have to reduce OBJ_ctr_sd and TRAIN_relevant accordingly
if enforce_gen['eval'] is not None:
for key in TRAIN_relevant:
TRAIN_relevant[key] = | np.array(TRAIN_relevant[key]) | numpy.array |
# Create simulated exponential decay data
# Radioactive decay
from __future__ import division
import numpy as np
import numpy.random
def CreateSimulatedData(N0, tau):
tstart = 2.0
t = | np.arange(tstart, 8.7*tau, 7.0) | numpy.arange |
from __future__ import division, print_function, absolute_import
import numpy as np
from .B_monomer import B, dB_dxhi00, d2B_dxhi00, d3B_dxhi00
from .a1s_monomer import a1s, da1s_dxhi00, d2a1s_dxhi00, d3a1s_dxhi00
def a1sB(xhi00, xhix, xhix_vec, xm, Ikl, Jkl, cictes, a1vdw, a1vdw_cte):
a1 = a1s(xhi00, xhix_vec, xm, cictes, a1vdw)
b = B(xhi00, xhix, xm, Ikl, Jkl, a1vdw_cte)
return a1 + b
def da1sB_dxhi00(xhi00, xhix, xhix_vec, xm, Ikl, Jkl, cictes, a1vdw, a1vdw_cte,
dxhix_dxhi00):
a1, da1 = da1s_dxhi00(xhi00, xhix_vec, xm, cictes, a1vdw, dxhix_dxhi00)
b, db = dB_dxhi00(xhi00, xhix, xm, Ikl, Jkl, a1vdw_cte, dxhix_dxhi00)
return a1 + b, da1 + db
def d2a1sB_dxhi00(xhi00, xhix, xhix_vec, xm, Ikl, Jkl, cictes, a1vdw,
a1vdw_cte, dxhix_dxhi00):
a1, da1, d2a1 = d2a1s_dxhi00(xhi00, xhix_vec, xm, cictes, a1vdw,
dxhix_dxhi00)
b, db, d2b = d2B_dxhi00(xhi00, xhix, xm, Ikl, Jkl, a1vdw_cte, dxhix_dxhi00)
return a1 + b, da1 + db, d2a1 + d2b
def d3a1sB_dxhi00(xhi00, xhix, xhix_vec, xm, Ikl, Jkl, cictes, a1vdw,
a1vdw_cte, dxhix_dxhi00):
a1, da1, d2a1, d3a1 = d3a1s_dxhi00(xhi00, xhix_vec, xm, cictes, a1vdw,
dxhix_dxhi00)
b, db, d2b, d3b = d3B_dxhi00(xhi00, xhix, xm, Ikl, Jkl, a1vdw_cte,
dxhix_dxhi00)
return a1 + b, da1 + db, d2a1 + d2b, d3a1 + d3b
def a1sB_eval(xhi00, xhix, xhix_vec, xs_m, I_lambdaskl, J_lambdaskl,
ccteskl, a1vdwkl, a1vdw_ctekl):
# la_kl, lr_kl, la_kl2, lr_kl2, lar_kl = lambdaskl
cctes_lakl, cctes_lrkl, cctes_2lakl, cctes_2lrkl, cctes_larkl = ccteskl
a1vdw_lakl, a1vdw_lrkl, a1vdw_2lakl, a1vdw_2lrkl, a1vdw_larkl = a1vdwkl
I_lakl, I_lrkl, I_2lakl, I_2lrkl, I_larkl = I_lambdaskl
J_lakl, J_lrkl, J_2lakl, J_2lrkl, J_larkl = J_lambdaskl
a1sb_a = a1sB(xhi00, xhix, xhix_vec, xs_m, I_lakl, J_lakl, cctes_lakl,
a1vdw_lakl, a1vdw_ctekl)
a1sb_r = a1sB(xhi00, xhix, xhix_vec, xs_m, I_lrkl, J_lrkl, cctes_lrkl,
a1vdw_lrkl, a1vdw_ctekl)
a1sb_2a = a1sB(xhi00, xhix, xhix_vec, xs_m, I_2lakl, J_2lakl, cctes_2lakl,
a1vdw_2lakl, a1vdw_ctekl)
a1sb_2r = a1sB(xhi00, xhix, xhix_vec, xs_m, I_2lrkl, J_2lrkl, cctes_2lrkl,
a1vdw_2lrkl, a1vdw_ctekl)
a1sb_ar = a1sB(xhi00, xhix, xhix_vec, xs_m, I_larkl, J_larkl, cctes_larkl,
a1vdw_larkl, a1vdw_ctekl)
a1sb_a1 = np.array([a1sb_a, a1sb_r])
a1sb_a2 = np.array([a1sb_2a, a1sb_ar, a1sb_2r])
return a1sb_a1, a1sb_a2
def da1sB_dxhi00_eval(xhi00, xhix, xhix_vec, xs_m, I_lambdaskl, J_lambdaskl,
ccteskl, a1vdwkl, a1vdw_ctekl, dxhix_dxhi00):
# la_kl, lr_kl, la_kl2, lr_kl2, lar_kl = lambdaskl
cctes_lakl, cctes_lrkl, cctes_2lakl, cctes_2lrkl, cctes_larkl = ccteskl
a1vdw_lakl, a1vdw_lrkl, a1vdw_2lakl, a1vdw_2lrkl, a1vdw_larkl = a1vdwkl
I_lakl, I_lrkl, I_2lakl, I_2lrkl, I_larkl = I_lambdaskl
J_lakl, J_lrkl, J_2lakl, J_2lrkl, J_larkl = J_lambdaskl
a1sb_a, da1sb_a = da1sB_dxhi00(xhi00, xhix, xhix_vec, xs_m, I_lakl, J_lakl,
cctes_lakl, a1vdw_lakl, a1vdw_ctekl,
dxhix_dxhi00)
a1sb_r, da1sb_r = da1sB_dxhi00(xhi00, xhix, xhix_vec, xs_m, I_lrkl, J_lrkl,
cctes_lrkl, a1vdw_lrkl, a1vdw_ctekl,
dxhix_dxhi00)
a1sb_2a, da1sb_2a = da1sB_dxhi00(xhi00, xhix, xhix_vec, xs_m, I_2lakl,
J_2lakl, cctes_2lakl, a1vdw_2lakl,
a1vdw_ctekl, dxhix_dxhi00)
a1sb_2r, da1sb_2r = da1sB_dxhi00(xhi00, xhix, xhix_vec, xs_m, I_2lrkl,
J_2lrkl, cctes_2lrkl, a1vdw_2lrkl,
a1vdw_ctekl, dxhix_dxhi00)
a1sb_ar, da1sb_ar = da1sB_dxhi00(xhi00, xhix, xhix_vec, xs_m, I_larkl,
J_larkl, cctes_larkl, a1vdw_larkl,
a1vdw_ctekl, dxhix_dxhi00)
a1sb_a1 = np.array([[a1sb_a, a1sb_r],
[da1sb_a, da1sb_r]])
a1sb_a2 = np.array([[a1sb_2a, a1sb_ar, a1sb_2r],
[da1sb_2a, da1sb_ar, da1sb_2r]])
return a1sb_a1, a1sb_a2
def d2a1sB_dxhi00_eval(xhi00, xhix, xhix_vec, xs_m, I_lambdaskl, J_lambdaskl,
ccteskl, a1vdwkl, a1vdw_ctekl, dxhix_dxhi00):
# la_kl, lr_kl, la_kl2, lr_kl2, lar_kl = lambdaskl
cctes_lakl, cctes_lrkl, cctes_2lakl, cctes_2lrkl, cctes_larkl = ccteskl
a1vdw_lakl, a1vdw_lrkl, a1vdw_2lakl, a1vdw_2lrkl, a1vdw_larkl = a1vdwkl
I_lakl, I_lrkl, I_2lakl, I_2lrkl, I_larkl = I_lambdaskl
J_lakl, J_lrkl, J_2lakl, J_2lrkl, J_larkl = J_lambdaskl
out_la = d2a1sB_dxhi00(xhi00, xhix, xhix_vec, xs_m, I_lakl, J_lakl,
cctes_lakl, a1vdw_lakl, a1vdw_ctekl, dxhix_dxhi00)
a1sb_a, da1sb_a, d2a1sb_a = out_la
out_lr = d2a1sB_dxhi00(xhi00, xhix, xhix_vec, xs_m, I_lrkl, J_lrkl,
cctes_lrkl, a1vdw_lrkl, a1vdw_ctekl, dxhix_dxhi00)
a1sb_r, da1sb_r, d2a1sb_r = out_lr
out_2la = d2a1sB_dxhi00(xhi00, xhix, xhix_vec, xs_m, I_2lakl, J_2lakl,
cctes_2lakl, a1vdw_2lakl, a1vdw_ctekl,
dxhix_dxhi00)
a1sb_2a, da1sb_2a, d2a1sb_2a = out_2la
out_2lr = d2a1sB_dxhi00(xhi00, xhix, xhix_vec, xs_m, I_2lrkl, J_2lrkl,
cctes_2lrkl, a1vdw_2lrkl, a1vdw_ctekl,
dxhix_dxhi00)
a1sb_2r, da1sb_2r, d2a1sb_2r = out_2lr
out_lar = d2a1sB_dxhi00(xhi00, xhix, xhix_vec, xs_m, I_larkl, J_larkl,
cctes_larkl, a1vdw_larkl, a1vdw_ctekl,
dxhix_dxhi00)
a1sb_ar, da1sb_ar, d2a1sb_ar = out_lar
a1sb_a1 = np.array([[a1sb_a, a1sb_r],
[da1sb_a, da1sb_r],
[d2a1sb_a, d2a1sb_r]])
a1sb_a2 = np.array([[a1sb_2a, a1sb_ar, a1sb_2r],
[da1sb_2a, da1sb_ar, da1sb_2r],
[d2a1sb_2a, d2a1sb_ar, d2a1sb_2r]])
return a1sb_a1, a1sb_a2
def d3a1sB_dxhi00_eval(xhi00, xhix, xhix_vec, xs_m, I_lambdaskl, J_lambdaskl,
ccteskl, a1vdwkl, a1vdw_ctekl, dxhix_dxhi00):
cctes_lakl, cctes_lrkl, cctes_2lakl, cctes_2lrkl, cctes_larkl = ccteskl
a1vdw_lakl, a1vdw_lrkl, a1vdw_2lakl, a1vdw_2lrkl, a1vdw_larkl = a1vdwkl
I_lakl, I_lrkl, I_2lakl, I_2lrkl, I_larkl = I_lambdaskl
J_lakl, J_lrkl, J_2lakl, J_2lrkl, J_larkl = J_lambdaskl
out_la = d3a1sB_dxhi00(xhi00, xhix, xhix_vec, xs_m, I_lakl, J_lakl,
cctes_lakl, a1vdw_lakl, a1vdw_ctekl, dxhix_dxhi00)
a1sb_a, da1sb_a, d2a1sb_a, d3a1sb_a = out_la
out_lr = d3a1sB_dxhi00(xhi00, xhix, xhix_vec, xs_m, I_lrkl, J_lrkl,
cctes_lrkl, a1vdw_lrkl, a1vdw_ctekl, dxhix_dxhi00)
a1sb_r, da1sb_r, d2a1sb_r, d3a1sb_r = out_lr
out_2la = d3a1sB_dxhi00(xhi00, xhix, xhix_vec, xs_m, I_2lakl, J_2lakl,
cctes_2lakl, a1vdw_2lakl, a1vdw_ctekl,
dxhix_dxhi00)
a1sb_2a, da1sb_2a, d2a1sb_2a, d3a1sb_2a = out_2la
out_2lr = d3a1sB_dxhi00(xhi00, xhix, xhix_vec, xs_m, I_2lrkl, J_2lrkl,
cctes_2lrkl, a1vdw_2lrkl, a1vdw_ctekl,
dxhix_dxhi00)
a1sb_2r, da1sb_2r, d2a1sb_2r, d3a1sb_2r = out_2lr
out_lar = d3a1sB_dxhi00(xhi00, xhix, xhix_vec, xs_m, I_larkl, J_larkl,
cctes_larkl, a1vdw_larkl, a1vdw_ctekl,
dxhix_dxhi00)
a1sb_ar, da1sb_ar, d2a1sb_ar, d3a1sb_ar = out_lar
a1sb_a1 = np.array([[a1sb_a, a1sb_r],
[da1sb_a, da1sb_r],
[d2a1sb_a, d2a1sb_r],
[d3a1sb_a, d3a1sb_r]])
a1sb_a2 = np.array([[a1sb_2a, a1sb_ar, a1sb_2r],
[da1sb_2a, da1sb_ar, da1sb_2r],
[d2a1sb_2a, d2a1sb_ar, d2a1sb_2r],
[d3a1sb_2a, d3a1sb_ar, d3a1sb_2r]])
return a1sb_a1, a1sb_a2
def x0lambda_evalm(x0, laij, lrij, larij):
x0la = x0**laij
x0lr = x0**lrij
x02la = x0**(2*laij)
x02lr = x0**(2*lrij)
x0lar = x0**larij
# To be used for a1 and a2 in monomer term
x0_a1 = np.array([x0la, -x0lr])
x0_a2 = np.array([x02la, -2*x0lar, x02lr])
return x0_a1, x0_a2
def x0lambda_evalc(x0, la, lr, lar):
x0la = x0**la
x0lr = x0**lr
x02la = x0**(2*la)
x02lr = x0**(2*lr)
x0lar = x0**lar
# To be used for a1 and a2 in monomer term
x0_a1 = np.array([x0la, -x0lr])
x0_a2 = | np.array([x02la, -2*x0lar, x02lr]) | numpy.array |
from __future__ import division
import os
import numpy as np
import torch
import torch.nn.parallel
import torch.optim
import torch.utils.data
import torchvision.transforms as transforms
from PIL import Image
from torch.utils.data.dataset import Dataset
from .registry import DATASETS
@DATASETS.register_module
class AttrDataset(Dataset):
CLASSES = None
def __init__(self,
img_path,
img_file,
label_file,
cate_file,
bbox_file,
landmark_file,
img_size,
idx2id=None):
self.img_path = img_path
normalize = transforms.Normalize(
mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
self.transform = transforms.Compose([
transforms.RandomResizedCrop(img_size[0]),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
normalize,
])
# read img names
fp = open(img_file, 'r')
self.img_list = [x.strip() for x in fp]
# read attribute labels and category annotations
self.labels = | np.loadtxt(label_file, dtype=np.float32) | numpy.loadtxt |
# -*- coding: utf-8 -*-
"""
Created on Mon Apr 2 11:19:50 2018
@author: mayank
"""
import numpy as np
from sklearn.model_selection import StratifiedKFold
from sklearn.metrics.pairwise import linear_kernel,rbf_kernel,manhattan_distances,polynomial_kernel,sigmoid_kernel,cosine_similarity,laplacian_kernel,paired_euclidean_distances,pairwise_distances
from sklearn.kernel_approximation import RBFSampler, Nystroem
from sklearn.utils import resample
from numpy.matlib import repmat
from sklearn.neighbors import NearestNeighbors
from sklearn.cluster import MiniBatchKMeans
from sklearn.decomposition import IncrementalPCA
from numpy.linalg import eigh
from sklearn.preprocessing import OneHotEncoder
from sparse import COO
from scipy.sparse import csr_matrix, lil_matrix
from scipy.sparse import issparse
from scipy.sparse import hstack
#%%
class utils:
# def __init__(self):
# return None
def add_bias(self,xTrain):
"""
Adds bias to the data
Parameters:
-----------
xTrain: 2D numpy ndarray/csr_matrix of shape (n_samples, n_features)
Returns:
--------
xTrain: 2D numpy ndarray/csr_matrix of shape (n_samples, n_features + 1)
"""
N = xTrain.shape[0]
if(xTrain.size!=0):
if(issparse(xTrain)==True):
xTrain = csr_matrix(hstack([xTrain,np.ones((N,1))]))
else:
xTrain=np.hstack((xTrain,np.ones((N,1))))
return xTrain
def logsig(self,x):
return 1 / (1 + np.exp(-x))
def saturate_fcn1(self,x,a = 2):
y = np.zeros(x.shape)
idx1 = (x <= a)*(x >=-a)
idx2 = x > a
idx3 = x < -a
y[idx1] = x[idx1]/(2*a) + 1.0/2.0
y[idx2] = 1
y[idx3] = 0
return y
def standardize(self,xTrain,centering):
"""
Transform the data so that each column has zero mean and unit standard deviation
Parameters:
-----------
xTrain: 2D numpy ndarray of shape (n_samples, n_features)
centering: bool,
whether to perform standardization,
if False, it returns me = np.zeros((xTrain.shape[1],))
and std_dev = np.ones((xTrain.shape[1],))
Returns:
--------
xTrain: 2D numpy ndarray of shape (n_samples, n_features)
me: mean of the columns
std_dev: standard deviation of the columns
"""
if(centering == True):
me=np.mean(xTrain,axis=0)
std_dev=np.std(xTrain,axis=0)
else:
me = np.zeros((xTrain.shape[1],))
std_dev = np.ones((xTrain.shape[1],))
#remove columns with zero std
idx=(std_dev!=0.0)
# print(idx.shape)
xTrain[:,idx]=(xTrain[:,idx]-me[idx])/std_dev[idx]
return xTrain,me,std_dev
def divide_into_batches_stratified(self,yTrain,batch_sz):
"""
Divides the data into batches such that each batch contains similar proportion of labels in it
Parameters:
----------
yTrain: np.ndarray labels for the datset of shape (n_samples, )
Returns:
--------
idx_batches: list
index of yTrain in each batch
sample_weights: np.ndarray of size (n_samples,)
weights for each sample in batch = 1/#class_j
num_batches: int
number of batches formed
"""
#data should be of the form samples X features
N=yTrain.shape[0]
num_batches=int(np.ceil(N/batch_sz))
sample_weights=list()
numClasses=np.unique(yTrain).size
idx_batches=list()
skf=StratifiedKFold(n_splits=num_batches, random_state=1, shuffle=True)
j=0
for train_index, test_index in skf.split(np.zeros(N), yTrain):
idx_batches.append(test_index)
class_weights=np.zeros((numClasses,))
sample_weights1=np.zeros((test_index.shape[0],))
temp=yTrain[test_index,]
for i in range(numClasses):
idx1=(temp==i)
class_weights[i]=1.0/(np.sum(idx1)+1e-09)#/idx.shape[0]
sample_weights1[idx1]=class_weights[i]
sample_weights.append(sample_weights1)
j+=1
return idx_batches,sample_weights,num_batches
def margin_kernel(self, X1, kernel_type = 'linear', gamma =1.0):
"""
Forms the kernel matrix using the samples X1
Parameters:
----------
X1: np.ndarray
data (n_samples,n_features) to form a kernel of shape (n_samples,n_samples)
kernel_type : str
type of kernel to be used
gamma: float
kernel parameter
Returns:
-------
X: np.ndarray
the kernel of shape (n_samples,n_samples)
"""
if(kernel_type == 'linear'):
X = linear_kernel(X1,X1)
elif(kernel_type == 'rbf'):
X = rbf_kernel(X1,X1,gamma)
elif(kernel_type == 'tanh'):
X = sigmoid_kernel(X1,X1,-gamma)
elif(kernel_type == 'sin'):
# X = np.sin(gamma*manhattan_distances(X1,X1))
X = np.sin(gamma*pairwise_distances(X1,X1)**2)
elif(kernel_type =='TL1'):
X = np.maximum(0,gamma - manhattan_distances(X1,X1))
else:
print('no kernel_type, returning None')
return None
return X
def kernel_transform(self, X1, X2 = None, kernel_type = 'linear_primal', n_components = 100, gamma = 1.0):
"""
Forms the kernel matrix using the samples X1
Parameters:
----------
X1: np.ndarray
data (n_samples1,n_features) to form a kernel of shape (n_samples1,n_samples1)
X2: np.ndarray
data (n_samples2,n_features) to form a kernel of shape (n_samples1,n_samples2)
kernel_type : str
type of kernel to be used
gamma: float
kernel parameter
Returns:
-------
X: np.ndarray
the kernel of shape (n_samples,n_samples)
"""
if(kernel_type == 'linear'):
X = linear_kernel(X1,X2)
elif(kernel_type == 'rbf'):
X = rbf_kernel(X1,X2,gamma)
elif(kernel_type == 'tanh'):
X = sigmoid_kernel(X1,X2,-gamma)
elif(kernel_type == 'sin'):
# X = np.sin(gamma*manhattan_distances(X1,X2))
X = np.sin(gamma*pairwise_distances(X1,X2)**2)
elif(kernel_type =='TL1'):
X = np.maximum(0,gamma - manhattan_distances(X1,X2))
elif(kernel_type == 'rff_primal'):
rbf_feature = RBFSampler(gamma=gamma, random_state=1, n_components = n_components)
X = rbf_feature.fit_transform(X1)
elif(kernel_type == 'nystrom_primal'):
#cannot have n_components more than n_samples1
if(n_components > X1.shape[0]):
raise ValueError('n_samples should be greater than n_components')
rbf_feature = Nystroem(gamma=gamma, random_state=1, n_components = n_components)
X = rbf_feature.fit_transform(X1)
elif(kernel_type == 'linear_primal'):
X = X1
else:
print('No kernel_type passed: using linear primal solver')
X = X1
return X
def generate_samples(self,X_orig,old_imbalance_ratio,new_imbalance_ratio):
"""
Generates samples based on new imbalance ratio, such that new imbalanced ratio is achieved
Parameters:
----------
X_orig: np.array (n_samples , n_features)
data matrix
old_imbalance_ratio: float
old imbalance ratio in the samples
new_imbalance_ratio: float
new imbalance ratio in the samples
Returns:
-------
X_orig: np.array (n_samples , n_features)
data matrix
X1: 2D np.array
newly generated samples of shape (int((new_imbalance_ratio/old_imbalance_ratio)*n_samples - n_samples), n_features )
"""
N=X_orig.shape[0]
M=X_orig.shape[1]
neighbors_thresh=10
if (new_imbalance_ratio < old_imbalance_ratio):
raise ValueError('new ratio should be greater than old ratio')
new_samples=int((new_imbalance_ratio/old_imbalance_ratio)*N - N)
#each point must generate these many samples
new_samples_per_point_orig=new_imbalance_ratio/old_imbalance_ratio - 1
new_samples_per_point=int(new_imbalance_ratio/old_imbalance_ratio - 1)
#check if the number of samples each point has to generate is > 1
X1=np.zeros((0,M))
if(new_samples_per_point_orig>0 and new_samples_per_point_orig<=1):
idx_samples=resample(np.arange(0,N), n_samples=int(N*new_samples_per_point_orig), random_state=1,replace=False)
X=X_orig[idx_samples,]
new_samples_per_point=1
N=X.shape[0]
else:
X=X_orig
if(N==1):
X1=repmat(X,new_samples,1)
elif(N>1):
if(N<=neighbors_thresh):
n_neighbors=int(N/2)
else:
n_neighbors=neighbors_thresh
nbrs = NearestNeighbors(n_neighbors=n_neighbors, algorithm='ball_tree').fit(X)
for i in range(N):
#for each point find its n_neighbors nearest neighbors
inds=nbrs.kneighbors(X[i,:].reshape(1,-1), n_neighbors, return_distance=False)
temp_data=X[inds[0],:]
std=np.std(temp_data,axis=0)
me=np.mean(temp_data,axis=0)
np.random.seed(i)
x_temp=me + std*np.random.randn(new_samples_per_point,M)
X1=np.append(X1,x_temp,axis=0)
return X_orig, X1
def upsample(self,X,Y,new_imbalance_ratio):
"""
Upsamples the data based on label array, for classification only
Parameters:
----------
X: np.array (n_samples, n_features)
2D data matrix
Y: np.array (n_samples, )
label array, takes values between [0, numClasses-1]
new_imbalance_ratio: float
new imbalance ratio in the data, takes values between [0.5,1]
Returns:
-------
X3: np.array (n_samples1, n_features)
new balanced 2D data matrix
Y3: np.array (n_samples1, )
new balanced label array
"""
#xTrain: samples X features
#yTrain : samples,
#for classification only
numClasses=np.unique(Y).size
class_samples=np.zeros((numClasses,))
X3=np.zeros((0,X.shape[1]))
Y3=np.zeros((0,))
#first find the samples per class per class
for i in range(numClasses):
idx1=(Y==i)
class_samples[i]=np.sum(idx1)
max_samples=np.max(class_samples)
# new_imbalance_ratio=0.5
# if(upsample_type==1):
old_imbalance_ratio_thresh=0.5
# else:
# old_imbalance_ratio_thresh=1
for i in range(numClasses):
idx1=(Y==i)
old_imbalance_ratio=class_samples[i]/max_samples
X1=X[idx1,:]
Y1=Y[idx1,]
if(idx1.size==1):
X1=np.reshape(X1,(1,X.shape[1]))
if(old_imbalance_ratio<=old_imbalance_ratio_thresh and class_samples[i]!=0):
X1,X2=self.generate_samples(X1,old_imbalance_ratio,new_imbalance_ratio)
new_samples=X2.shape[0]
Y2=np.ones((new_samples,))
Y2=Y2*Y1[0,]
#append original and generated samples
X3=np.append(X3,X1,axis=0)
X3=np.append(X3,X2,axis=0)
Y3=np.append(Y3,Y1,axis=0)
Y3=np.append(Y3,Y2,axis=0)
else:
#append original samples only
X3=np.append(X3,X1,axis=0)
Y3=np.append(Y3,Y1,axis=0)
Y3=np.array(Y3,dtype=np.int32)
return X3,Y3
def kmeans_select(self,X,represent_points,do_pca=False):
"""
Takes in data and number of prototype vectors and returns the indices of the prototype vectors.
The prototype vectors are selected based on the farthest distance from the kmeans centers
Parameters
----------
X: np.ndarray
shape = n_samples, n_features
represent_points: int
number of prototype vectors to return
do_pca: boolean
whether to perform incremental pca for dimensionality reduction before selecting prototype vectors
Returns
-------
sv: list
list of the prototype vector indices from the data array given by X
"""
# do_pca = self.do_pca_in_selection
N = X.shape[0]
if(do_pca == True):
if(X.shape[1]>50):
n_components = 50
ipca = IncrementalPCA(n_components=n_components, batch_size=np.min([128,X.shape[0]]))
X = ipca.fit_transform(X)
kmeans = MiniBatchKMeans(n_clusters=represent_points, batch_size=np.min([128,X.shape[0]]),random_state=0).fit(X)
centers = kmeans.cluster_centers_
labels = kmeans.labels_
sv= []
unique_labels = np.unique(labels).size
all_ind = np.arange(N)
for j in range(unique_labels):
X1 = X[labels == j,:]
all_ind_temp = all_ind[labels==j]
tempK = pairwise_distances(X1,np.reshape(centers[j,:],(1,X1.shape[1])))**2
inds = np.argmax(tempK,axis=0)
sv.append(all_ind_temp[inds[0]])
return sv
def renyi_select(self,X,represent_points,do_pca=False):
"""
Takes in data and number of prototype vectors and returns the indices of the prototype vectors.
The prototype vectors are selected based on maximization of quadratic renyi entropy, which can be
written in terms of log sum exp which is a tightly bounded by max operator. Now for rbf kernel,
the max_{ij}(-\|x_i-x_j\|^2) is equivalent to min_{ij}(\|x_i-x_j\|^2).
Parameters
----------
X: np.ndarray
shape = n_samples, n_features
represent_points: int
number of prototype vectors to return
do_pca: boolean
whether to perform incremental pca for dimensionality reduction before selecting prototype vectors
Returns
-------
sv: list
list of the prototype vector indices from the data array given by X
"""
# do_pca = self.do_pca_in_selection
N= X.shape[0]
capacity=represent_points
selectionset=set([])
set_full=set(list(range(N)))
np.random.seed(1)
if(len(selectionset)==0):
selectionset = np.random.permutation(N)
sv = list(selectionset)[0:capacity]
else:
extrainputs = represent_points - len(selectionset)
leftindices =list(set_full.difference(selectionset))
info = np.random.permutation(len(leftindices))
info = info[1:extrainputs]
sv = selectionset.append(leftindices[info])
if(do_pca == True):
if(X.shape[1]>50): #takes more time
n_components = 50
ipca = IncrementalPCA(n_components=n_components, batch_size=np.min([128,X.shape[0]]))
X = ipca.fit_transform(X)
svX = X[sv,:]
min_info = np.zeros((capacity,2))
KsV = pairwise_distances(svX,svX)**2 #this is fast
KsV[KsV==0] = np.inf
min_info[:,1] = np.min(KsV,axis=1)
min_info[:,0] = np.arange(capacity)
minimum = np.min(min_info[:,1])
counter = 0
for i in range(N):
# find for which data the value is minimum
replace = np.argmin(min_info[:,1])
ids = int(min_info[min_info[:,0]==replace,0])
#Subtract from totalcrit once for row
tempminimum = minimum - min_info[ids,1]
#Try to evaluate kernel function
tempsvX = np.zeros(svX.shape)
tempsvX[:] = svX[:]
inputX = X[i,:]
tempsvX[replace,:] = inputX
tempK = pairwise_distances(tempsvX,np.reshape(inputX,(1,X.shape[1])))**2 #this is fast
tempK[tempK==0] = np.inf
distance_eval = np.min(tempK)
tempminimum = tempminimum + distance_eval
if (minimum < tempminimum):
minimum = tempminimum
min_info[ids,1] = distance_eval
svX[:] = tempsvX[:]
sv[ids] = i
counter +=1
return sv
def subset_selection(self,X,Y, n_components , PV_scheme , problem_type,do_pca=False):
"""
Takes in data matrix and label matrix and generates the subset (list) of shape n_components based on the problem type
(classification or regression), prototype vector (PV) selection scheme
Parameters:
----------
X: np.array (n_samples, n_features)
data matrix
Y: np.array (n_samples)
label matrix (continuous or discrete)
PV_scheme: str
prototype vector selection scheme ('renyi' or 'kmeans')
problem_type: str
type of the problem ('classification' or 'regression')
Returns:
--------
subset: list
the index of the prototype vectors selected
"""
N = X.shape[0]
if(problem_type == 'regression'):
if(PV_scheme == 'renyi'):
subset = self.renyi_select(X,n_components,do_pca)
elif(PV_scheme == 'kmeans'):
subset = self.kmeans_select(X,n_components,do_pca)
else:
raise ValueError('Select PV_scheme between renyi and kmeans')
else:
numClasses = np.unique(Y).size
all_samples = np.arange(N)
subset=[]
subset_per_class = np.zeros((numClasses,))
class_dist = np.zeros((numClasses,))
for i in range(numClasses):
class_dist[i] = np.sum(Y == i)
subset_per_class[i] = int(np.ceil((class_dist[i]/N)*n_components))
for i in range(numClasses):
xTrain = X[Y == i,]
samples_in_class = all_samples[Y == i]
if(PV_scheme == 'renyi'):
subset1 = self.renyi_select(xTrain,int(subset_per_class[i]),do_pca)
elif(PV_scheme == 'kmeans'):
subset1 = self.kmeans_select(xTrain,int(subset_per_class[i]),do_pca)
else:
raise ValueError('Select PV_scheme between renyi and kmeans')
temp=list(samples_in_class[subset1])
subset.extend(temp)
return subset
def matrix_decomposition(self, X):
"""
Finds the matrices consisting of positive and negative parts of kernel matrix X
Parameters:
----------
X: n_samples X n_samples
Returns:
--------
K_plus: kernel corresponding to +ve part
K_minus: kernel corresponding to -ve part
"""
[D,U]= | eigh(X) | numpy.linalg.eigh |
#!/usr/bin/env python3
"""
Requires:
python-mnist
numpy
sklearn
"""
import sys
sys.path.insert(0, 'src/')
import mnist
import numpy as np
from numpy.linalg import norm as l21_norm
from sklearn.metrics.cluster import normalized_mutual_info_score as nmi
import os
np.random.seed(int(os.environ.get('seed', '42')))
print('Using seed:', os.environ.get('seed', '42'))
epsilon = 0.03
gamma = .1 / 30 / epsilon
# np.random.seed(42)
# Download t10k_* from http://yann.lecun.com/exdb/mnist/
# Change to directory containing unzipped MNIST data
mndata = mnist.MNIST('data/MNIST-10K/')
def welsch_func(x):
result = (1 - np.exp(- epsilon * x ** 2)) / epsilon
return result
from basics.ours._numba import E, solve_U, update_V
def target(U, V, X):
return E(U, V, X, gamma, epsilon)
def NMI(U):
return nmi(labels, np.argmax(U, axis=1))
if __name__ == '__main__':
images, labels = mndata.load_testing()
ndim = 784
N = size = len(labels)
C = 10
X = np.array(images).reshape((size, ndim)) / 255
t = 0
V = np.random.random((C, ndim))
U = np.ones((size, C)) * .1 / (C - 1)
for i in range(size):
xi = np.repeat(X[i, :].reshape((1, ndim)), C, axis=0)
U[i, np.argmin(l21_norm(xi - V, axis=1))] = .9
S = | np.ones((size, C)) | numpy.ones |
# -*- coding: utf-8 -*-
"""
Defines unit tests for :mod:`colour.models.rgb.transfer_functions.itur_bt_1886`
module.
"""
from __future__ import division, unicode_literals
import numpy as np
import unittest
from colour.models.rgb.transfer_functions import (eotf_inverse_BT1886,
eotf_BT1886)
from colour.utilities import domain_range_scale, ignore_numpy_errors
__author__ = 'Colour Developers'
__copyright__ = 'Copyright (C) 2013-2019 - Colour Developers'
__license__ = 'New BSD License - https://opensource.org/licenses/BSD-3-Clause'
__maintainer__ = 'Colour Developers'
__email__ = '<EMAIL>'
__status__ = 'Production'
__all__ = ['TestEotf_inverse_BT1886', 'TestEotf_BT1886']
class TestEotf_inverse_BT1886(unittest.TestCase):
"""
Defines :func:`colour.models.rgb.transfer_functions.itur_bt_1886.\
eotf_inverse_BT1886` definition unit tests methods.
"""
def test_eotf_inverse_BT1886(self):
"""
Tests :func:`colour.models.rgb.transfer_functions.itur_bt_1886.\
eotf_inverse_BT1886` definition.
"""
self.assertAlmostEqual(eotf_inverse_BT1886(0.0), 0.0, places=7)
self.assertAlmostEqual(
eotf_inverse_BT1886(0.016317514686316), 0.18, places=7)
self.assertAlmostEqual(eotf_inverse_BT1886(1.0), 1.0, places=7)
def test_n_dimensional_eotf_inverse_BT1886(self):
"""
Tests :func:`colour.models.rgb.transfer_functions.itur_bt_1886.\
eotf_inverse_BT1886` definition n-dimensional arrays support.
"""
L = 0.016317514686316
V = eotf_inverse_BT1886(L)
L = np.tile(L, 6)
V = np.tile(V, 6)
np.testing.assert_almost_equal(eotf_inverse_BT1886(L), V, decimal=7)
L = np.reshape(L, (2, 3))
V = | np.reshape(V, (2, 3)) | numpy.reshape |
"""
2D MOT2016 Evaluation Toolkit
An python reimplementation of toolkit in
2DMOT16(https://motchallenge.net/data/MOT16/)
This file lists the matching algorithms.
1. clear_mot_hungarian: Compute CLEAR_MOT metrics
- Bernardin, Keni, and <NAME>. "Evaluating multiple object
tracking performance: the CLEAR MOT metrics." Journal on Image and Video
Processing 2008 (2008): 1.
2. idmeasures: Compute MTMC metrics
- Ristani, Ergys, et al. "Performance measures and a data set for multi-target,
multi-camera tracking." European Conference on Computer Vision. Springer,
Cham, 2016.
usage:
python evaluate_tracking.py
--bm Whether to evaluate multiple files(benchmarks)
--seqmap [filename] List of sequences to be evaluated
--track [dirname] Tracking results directory: default path --
[dirname]/[seqname]/res.txt
--gt [dirname] Groundtruth directory: default path --
[dirname]/[seqname]/gt.txt
(C) <NAME>(<EMAIL>), 2020-10
"""
import sys
import numpy as np
# from sklearn.evaluate_utils.linear_assignment_ import linear_assignment
from scipy.optimize import linear_sum_assignment as linear_assignment
from MOTEvaluate.evaluate_utils.bbox import bbox_overlap
from easydict import EasyDict as edict
VERBOSE = False
def clear_mot_metrics(resDB, gtDB, iou_thresh):
"""
compute CLEAR_MOT and other metrics
[recall, precision, FAR, GT, MT, PT, ML, false positives, false negatives,
id switches, FRA, MOTA, MOTP, MOTAL]
@res: results
@gt: fround truth
"""
# result and gt frame inds(start from 1)
res_frames = np.unique(resDB[:, 0])
gt_frames = | np.unique(gtDB[:, 0]) | numpy.unique |
from utils import read_pair as rp
import numpy as np
from scipy.linalg import cho_solve, cholesky
from utils import downscale as ds
from utils import lukas_kanade as lk
from utils import se3
import warnings
import gc
warnings.filterwarnings('ignore')
def pgo(pair_path=None, absolute_poses=None, kf_index=None, loop_closure=False, loop_pairs=None, level=4,
r_p_list=[], s_m_list=[], lambd=0.1):
pose_num = len(absolute_poses)
if loop_closure:
loop_num = len(loop_pairs)
else:
loop_num = 0
loop_ind = 0
b_k = np.zeros(6 * pose_num) # b_k vector
h_k = np.zeros([6 * pose_num, 6 * pose_num]) # H_k matrix
residual = np.zeros([pose_num + loop_num, 6]) # residual vector
relative_pose_list = r_p_list
sigma_matrix_list = s_m_list
for ind in np.arange(pose_num - 1 + loop_num):
if ind >= pose_num - 1:
# add loop closure manually at the end of the trajectory by observing overlap
loop_pair = loop_pairs[loop_ind]
loop_ind += 1
first_pose_ind = loop_pair[0]
second_pose_ind = loop_pair[1]
ref_frame = kf_index[first_pose_ind]
cur_frame = kf_index[second_pose_ind]
first_pose = absolute_poses[first_pose_ind]
second_pose = absolute_poses[second_pose_ind]
else:
first_pose_ind = ind
second_pose_ind = ind + 1
ref_frame = kf_index[first_pose_ind]
cur_frame = kf_index[second_pose_ind]
first_pose = absolute_poses[first_pose_ind]
second_pose = absolute_poses[second_pose_ind]
# calculate the pose difference between keyframes pair
pose_diff = np.linalg.inv(second_pose) @ first_pose
# create relative pose constraint between keyframes pair through direct image alignment in the first pgo iter
if len(relative_pose_list) < ind + 1:
image1, depth1, _ = rp.read_pair(pair_path, ref_frame)
image2, depth2, _ = rp.read_pair(pair_path, cur_frame)
relative_pose, sigma_matrix = create_relative_pose_constraint(image1, depth1, image2, depth2, level,
se3.se3Log(pose_diff))
relative_pose_list.append(relative_pose)
sigma_matrix_list.append(sigma_matrix)
else:
relative_pose = relative_pose_list[ind]
sigma_matrix = sigma_matrix_list[ind]
# convert twist coordinate to 4*4 transformation matrix
relative_pose = se3.se3Exp(relative_pose)
# calculate relative pose residual between this key-frame pair
resid = se3.se3Log(np.linalg.inv(relative_pose) @ pose_diff)
# print(resid)
# stack residual vector
residual[ind + 1] = resid
# calculate jacobian matrix
jacobian = calculatejacobian(pose_num, first_pose, second_pose, relative_pose, first_pose_ind, second_pose_ind,
resid)
# accumulate b_k and h_k for gauss newton step
b_k += jacobian.T @ sigma_matrix @ resid
h_k += jacobian.T @ sigma_matrix @ jacobian
# print('keyframes pair:{}'.format(ind + 1))
# add another term for first pose in b_k and h_k
resid_0 = se3.se3Log(absolute_poses[0])
residual[0] = resid_0
jaco_0 = calculate_jaco_single_frame(pose_num, absolute_poses[0], resid_0)
sigma_matrix = np.identity(6) * 1e6
b_k += jaco_0.T @ sigma_matrix @ resid_0
h_k += jaco_0.T @ sigma_matrix @ jaco_0
residual = residual.reshape(-1)
# update all key frame poses with Levenberg-Marquardt method
# upd = - np.linalg.inv(h_k + lambd * np.diag(np.diag(h_k))) @ b_k
# with gauss newton method
# upd = - np.linalg.inv(h_k) @ b_k
# use cholesky factorization to solve the linear system -h_k * upd = b_k
c = cholesky(h_k)
upd = - cho_solve((c, False), b_k)
upd = upd.reshape(-1, 6)
for jj in range(pose_num):
absolute_poses[jj] = se3.se3Exp(upd[jj]) @ absolute_poses[jj]
residual_after_update = calculate_residual(absolute_poses, relative_pose_list, loop_pairs, loop_num)
return absolute_poses, residual, relative_pose_list, sigma_matrix_list, residual_after_update
def calculate_residual(absolute_poses, relative_poses, loop_pairs, loop_num):
pose_num = len(absolute_poses)
loop_ind = 0
residual = np.zeros([pose_num + loop_num, 6])
for ind in range(pose_num - 1 + loop_num):
if ind >= pose_num - 1:
# add loop closure manually at the end of the trajectory by observing overlap
loop_pair = loop_pairs[loop_ind]
loop_ind += 1
first_pose_ind = loop_pair[0]
second_pose_ind = loop_pair[1]
first_pose = absolute_poses[first_pose_ind]
second_pose = absolute_poses[second_pose_ind]
else:
first_pose_ind = ind
second_pose_ind = ind + 1
first_pose = absolute_poses[first_pose_ind]
second_pose = absolute_poses[second_pose_ind]
# calculate the pose difference between keyframes pair
pose_diff = np.linalg.inv(second_pose) @ first_pose
relative_pose = se3.se3Exp(relative_poses[ind])
residual[ind + 1] = se3.se3Log(np.linalg.inv(relative_pose) @ pose_diff)
residual[0] = se3.se3Log(absolute_poses[0])
residual = residual.reshape(-1)
return residual
def calculate_jaco_single_frame(pose_num, absolute_pose, resid):
jacobian = np.zeros([6, 6 * pose_num])
for j in range(6):
epsVec = np.zeros(6)
eps = 1e-6
epsVec[j] = eps
# multiply pose increment from left onto the absolute poses
first_pose_eps = se3.se3Exp(epsVec) @ absolute_pose
resid_eps = se3.se3Log(first_pose_eps)
# calculate jacobian at first and second pose position
jacobian[:, j] = (resid_eps - resid) / eps
return jacobian
def pgo_with_auto_loop_closure(pair_path=None, absolute_poses=None, kf_index=None, loop_pairs=None, level=4,
r_p_list=[], s_m_list=[], lambd=0.1):
pose_num = len(absolute_poses)
pair_num = len(loop_pairs)
b_k = np.zeros(6 * pose_num) # b_k vector
h_k = np.zeros([6 * pose_num, 6 * pose_num]) # H_k matrix
residual = np.zeros([pair_num + 1, 6]) # residual vector
relative_pose_list = r_p_list
sigma_matrix_list = s_m_list
for i in np.arange(pair_num):
ref_frame = loop_pairs[i][0]
cur_frame = loop_pairs[i][1]
first_pose_ind = np.where(kf_index == ref_frame)[0][0]
second_pose_ind = np.where(kf_index == cur_frame)[0][0]
first_pose = absolute_poses[first_pose_ind]
second_pose = absolute_poses[second_pose_ind]
image1, depth1, _ = rp.read_pair(pair_path, ref_frame)
image2, depth2, _ = rp.read_pair(pair_path, cur_frame)
# calculate the pose difference between keyframes pair
pose_diff = np.linalg.inv(second_pose) @ first_pose
# create relative pose constraint between keyframes pair through direct image alignment in the first pgo iter
if len(relative_pose_list) < i + 1:
image1, depth1, _ = rp.read_pair(pair_path, ref_frame)
image2, depth2, _ = rp.read_pair(pair_path, cur_frame)
relative_pose, sigma_matrix = create_relative_pose_constraint(image1, depth1, image2, depth2, level,
se3.se3Log(pose_diff))
relative_pose_list.append(relative_pose)
sigma_matrix_list.append(sigma_matrix)
else:
relative_pose = relative_pose_list[i]
sigma_matrix = sigma_matrix_list[i]
# convert twist coordinate to 4*4 transformation matrix
relative_pose = se3.se3Exp(relative_pose)
# calculate relative pose residual between this key-frame pair
resid = se3.se3Log(np.linalg.inv(relative_pose) @ pose_diff)
# stack residual vector
residual[i + 1] = resid
# calculate jacobian matrix
jacobian = calculatejacobian(pose_num, first_pose, second_pose, relative_pose, first_pose_ind, second_pose_ind,
resid)
# accumulate b_k and h_k for gauss newton step
b_k += jacobian.T @ sigma_matrix @ resid
h_k += jacobian.T @ sigma_matrix @ jacobian
# print('keyframes pair:{}'.format(i + 1))
print(i , np.all(np.linalg.eigvals(h_k) > 0))
gc.collect()
# add another term for first pose in b_k and h_k
resid_0 = se3.se3Log(absolute_poses[0])
residual[0] = resid_0
jaco_0 = calculate_jaco_single_frame(pose_num, absolute_poses[0], resid_0)
sigma_matrix = np.identity(6) * 1e6
b_k += jaco_0.T @ sigma_matrix @ resid_0
h_k += jaco_0.T @ sigma_matrix @ jaco_0
# update all key frame poses
# upd = - np.linalg.inv(h_k) @ b_k # use gauss-newton
# use cholesky factorization to solve the linear system H x = b
c = cholesky(h_k + lambd * np.diag(np.diag(h_k))) # use <NAME>
upd = - cho_solve((c, False), b_k)
upd = upd.reshape(-1, 6)
for jj in range(pose_num):
absolute_poses[jj] = se3.se3Exp(upd[jj]) @ absolute_poses[jj]
residual = residual.reshape(-1)
residual_after_update = calculate_residual_with_auto_lc(absolute_poses, relative_pose_list, loop_pairs, kf_index)
return absolute_poses, residual, relative_pose_list, sigma_matrix_list, residual_after_update
def calculate_residual_with_auto_lc(absolute_poses, relative_poses, loop_pairs, kf_index):
pair_num = len(loop_pairs)
residual = np.zeros([pair_num + 1, 6]) # residual vector
for i in np.arange(pair_num):
ref_frame = loop_pairs[i][0]
cur_frame = loop_pairs[i][1]
first_pose_ind = np.where(kf_index == ref_frame)[0][0]
second_pose_ind = np.where(kf_index == cur_frame)[0][0]
first_pose = absolute_poses[first_pose_ind]
second_pose = absolute_poses[second_pose_ind]
# calculate the pose difference between keyframes pair
pose_diff = np.linalg.inv(second_pose) @ first_pose
relative_pose = se3.se3Exp(relative_poses[i])
residual[i + 1] = se3.se3Log(np.linalg.inv(relative_pose) @ pose_diff)
residual[0] = se3.se3Log(absolute_poses[0])
residual = residual.reshape(-1)
return residual
def create_relative_pose_constraint(image1, depth1, image2, depth2, level, initial_rela_pose):
# camera calibration matrix
fx = 520.9 # focal length x
fy = 521.0 # focal length y
cx = 325.1 # optical center x
cy = 249.7 # optical center y
K = np.array([[fx, 0, cx], [0, fy, cy], [0, 0, 1]])
use_hubernorm = 1
norm_param = 0.2
# perform level times down_sampling and display the downscaled image
Id = image1
Dd = depth1
Kd = K
for i in range(level):
Id, Dd, Kd = ds.downscale(Id, Dd, Kd)
Iref = Id
Dref = Dd
Id = image2
Dd = depth2
Kd = K
for i in range(level):
Id, Dd, Kd = ds.downscale(Id, Dd, Kd)
# do direct image alignment between this key-frame pair
xi = initial_rela_pose
relative_pose, sigma_matrix = lk.do_alignment(Iref, Dref, Kd, Id, Dd, xi, norm_param,
use_hubernorm)
return relative_pose, sigma_matrix
def calculatejacobian(pose_num, first_pose, second_pose, relative_pose, first_pose_ind, second_pose_ind, resid):
jacobian = np.zeros([6, 6 * pose_num])
for j in range(6):
epsVec = np.zeros(6)
eps = 1e-6
epsVec[j] = eps
# multiply pose increment from left onto the absolute poses
first_pose_eps = se3.se3Exp(epsVec) @ first_pose
second_pose_eps = se3.se3Exp(epsVec) @ second_pose
# calculate new pose difference after eps pose increment and new relative pose residual
# first key frame, fix second_pose
pose_diff_eps = np.linalg.inv(second_pose) @ first_pose_eps
resid_first_eps = se3.se3Log(np.linalg.inv(relative_pose) @ pose_diff_eps)
# second key frame, fix first pose
pose_diff_eps = np.linalg.inv(second_pose_eps) @ first_pose
resid_second_eps = se3.se3Log( | np.linalg.inv(relative_pose) | numpy.linalg.inv |
def cvar(x, f, ys, alpha):
'''
Returns CVaR of a decision x. f is the objective function which is a parameter
of both x and a random scenario y. ys is a list of scenarios. alpha is
the parameter giving the degree of risk-aversion.
'''
import numpy as np
fvals = [f(x, y) for y in ys]
fvals.sort()
return np.mean(fvals[:int(alpha*len(ys))])
def var(x, f, ys, alpha):
'''
Returns the value at risk of decision x.
'''
fvals = [f(x, y) for y in ys]
fvals.sort()
return fvals[int(alpha*len(ys))-1]
def rascal(x0, tau0, K, FO, LO, ys, f, M, alpha, u):
'''
Stochastic Frank-Wolfe algorithm.
x0: initial point in R^n
K: number of iterations
FO: stochastic first-order oracle (returns unbiased estimate of gradient)
LO: linear optimization oracle over the feasible set
ys: list or array of scenarios, such that any entry can be passed to f
f: objective function f(x, y)
M: upper bound on the value of f
alpha: CVaR parameter
u: smoothing parameter
'''
import numpy as np
x = np.array(x0)
tau = tau0
#tie breaker random noise
r = np.random.random((len(ys))) * 0.00001
all_x = []
for k in range(K):
print(k)
all_x.append(x.copy())
#compute gradient with respect to x
grad = smooth_grad(x, tau, ys, f, FO, r, u, alpha)
#update x
v = LO(grad)
x = x + (1./K)*v
#update tau
fvals = np.array([f(x,y) + r[j] for j,y in enumerate(ys)])
tau = smooth_tau(fvals, alpha, u)
return x, all_x
def smooth_grad(x, tau, ys, f, FO, r, u, alpha):
'''
Computes smoothed estimate of gradient at x. See rascal for parameters.
'''
import numpy as np
fvals = np.array([f(x, y) for y in ys])
if u > 0:
interval_length = tau + u - fvals
interval_length = np.maximum(interval_length, 0)
interval_length = np.minimum(interval_length, u)
interval_length /= u
else:
interval_length = np.zeros((len(ys)))
interval_length[fvals <= tau] = 1
grad = np.zeros(len(x))
for i,y in enumerate(ys):
if fvals[i] <= tau + u:
grad += interval_length[i] * FO(x, y)
return 1./(u * alpha * len(ys)) * grad
def smooth_tau(fvals, alpha, u):
'''
Computes optimal value of tau over smoothed interval of size u via binary
search.
'''
upper = fvals.max()
lower = fvals.min()
tau = (upper - lower)/2
while upper - lower > 0.001:
if smooth_fraction_under(fvals, tau, u) > alpha:
upper = tau
else:
lower = tau
tau = (upper + lower)/2
return tau
def smooth_fraction_under(fvals, tau, u):
'''
Helper function for smooth_tau
'''
import numpy as np
if u > 0:
interval_length = tau + u - fvals
interval_length = np.maximum(interval_length, 0)
interval_length = np.minimum(interval_length, u)
interval_length /= u
else:
interval_length = np.zeros((len(fvals)))
interval_length[fvals <= tau] = 1
return interval_length.mean()
def sfw(x0, K, FO, LO, ys):
'''
Stochastic Frank-Wolfe algorithm for maximizing the expected value of f(x,y)
x0: initial point in R^n
K: number of iterations
FO: stochastic first-order oracle (returns unbiased estimate of gradient)
LO: linear optimization oracle over the feasible set
ys: list or array of scenarios, such that any entry can be passed to f
'''
import numpy as np
x = | np.array(x0) | numpy.array |
# Vendor
import numpy as np
# Project
from tasks.Task import Task
class TaskListSearch(Task):
""" [ListSearch]
Given a pointer to the head of a linked list and a value `v` to find return a pointer
to the first node on the list with the value `v`. The list is placed in memory in the same way
as in the task ListK. We fill empty memory with “trash” values to prevent the network from
“cheating” and just iterating over the whole memory.
"""
def create(self) -> (np.ndarray, np.ndarray, np.ndarray):
list_size = int((self.max_int - 2) / 2)
list_elements = np.random.randint(0, self.max_int, size=(self.batch_size, list_size))
lists_elements_permutations = np.stack([np.random.permutation(list_size) for _ in range(self.batch_size)], axis=0)
init_mem = np.zeros((self.batch_size, self.max_int), dtype=np.int32)
# Create for each example the list
for example in range(self.batch_size):
for j, permidx in enumerate(lists_elements_permutations[example]):
next_element_pointer = np.where(lists_elements_permutations[example] == permidx + 1)[0]
if permidx == 0: # If the node is the first than set the pointer in the first memory position
init_mem[example, 0] = 2 + 2 * j
init_mem[example, 2 + (2 * j)] = \
-1.0 if len(next_element_pointer) == 0 else 2 + (2 * next_element_pointer[0]) # Set the pointer to the next list node
init_mem[example, 2 + (2 * j) + 1] = list_elements[example, j] # Set the value of the list node
init_mem[:, 1] = list_elements[:, 0] # Set the elements to search in the list
if self.max_int % 2 != 0:
init_mem[:, -1] = -1
out_mem = init_mem.copy()
for example in range(self.batch_size):
found = False
pointer = out_mem[example, 0]
while not found and pointer != -1:
if out_mem[example, pointer + 1] == out_mem[example, 1]:
out_mem[example, 0] = pointer
found = True
else:
pointer = out_mem[example, pointer]
cost_mask = | np.zeros((self.batch_size, self.max_int), dtype=np.int8) | numpy.zeros |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 5 17:55:12 2018
@author: jsevillamol
"""
import logging, time
from datetime import timedelta
import math
import threading
import tables
import pandas as pd
import numpy as np
from tensorflow.keras.utils import Sequence, to_categorical
from ctalearn.data.image_mapping import ImageMapper
from ctalearn.data.data_processing import DataProcessor
class DataManager():
"""
Manages access to the datafiles
:method get_train_val_gen:
:method get_pred_gen:
"""
def __init__(self, file_list_fn,
image_mapping_config = {},
preprocessing_config = {},
selected_tel_types=['LST'],
data_type='array',
img_size=(120,120),
channels=['image_charge'],
min_triggers_per_event=1
):
"""
:param file_list_fn: path to .txt file which lists paths to all .h5 files containing data
:param imageMapper_config = {}
:param dataProcessor_config = {}
:param img_shape:
:param channels:
:param selected_tel_types:
"""
logging.info('initializing DataManager...')
t_start = time.time()
# Set class fields
self._selected_tel_types = selected_tel_types
self._data_type = data_type
self._img_size = img_size
self._channels = channels
self._min_triggers_per_event = min_triggers_per_event
self._keep_telescope_position = False #TODO choose better name
self._classes = list(PARTICLE_ID_TO_CLASS_NAME.values())
self._class_name_to_class_label = {'proton':0, 'gamma':1} #TODO fix hardcoding
# Load files
self._load_files_(file_list_fn)
# Create a common index of events
self._load_dataset_info_()
# Compute dataset statistics
self.dataset_metadata = self._compute_dataset_metadata()
# Load telescope array info
self.tel_array_metadata = self._compute_telescope_array_metadata()
# Initialize ImageMapper and DataProcessor
self._imageMapper = ImageMapper(**image_mapping_config)
self._dataProcessor = DataProcessor(dataset_metadata = self.dataset_metadata, **preprocessing_config)
# Logging end of initialization
t_end = time.time()
t_delta = timedelta(seconds=t_end - t_start)
logging.info('DataManager initialized')
logging.info(f"Time elapsed during DataManager initialization: {t_delta}")
def _load_files_(self, file_list_fn):
"""
Loads the .hdf5 files containing the data
:param file_list_fn: filename of the .txt file containing
the paths of the .h5 datafiles
"""
# Load file list
data_files = []
with open(file_list_fn) as file_list:
aux = [line.strip() for line in file_list]
# Filter empty and commented lines
data_files = [line for line in aux if line and line[0] != '#']
# Load data files
self.files = {filename: self.__synchronized_open_file(filename, mode='r')
for filename in data_files}
@staticmethod
def __synchronized_open_file(*args, **kwargs):
with threading.Lock() as lock:
return tables.open_file(*args, **kwargs)
@staticmethod
def __synchronized_close_file(self, *args, **kwargs):
with threading.Lock() as lock:
return self.close(*args, **kwargs)
def _load_dataset_info_(self):
"""
Creates two pandas dataframes indexing all events from all files
and the images from the selected telescope types that pass the specified filters
:returns image_index:
:returns event_index:
"""
image_index = []
event_index = []
for fn in self.files:
datafile = self.files[fn]
# All events in the same file have the same particle type
particle_type = datafile.root._v_attrs.particle_type
class_name = PARTICLE_ID_TO_CLASS_NAME[particle_type]
# Each row of each datafile is a different event
for row in datafile.root.Event_Info.iterrows():
# skip the row if the event associated does not pass the filter
if not self._filter_event(fn, row): continue
event_img_idxs = []
for tel_type in self._selected_tel_types:
try:
img_rows_tel = row[tel_type + '_indices']
except KeyError:
logging.warning(f"No such telescope {tel_type} in file {fn}")
continue
img_idxs = []
for img_row in img_rows_tel:
# If the image was not triggered or does not pass the filter
if img_row == 0 or not self._filter_img(fn, tel_type, img_row):
if self._keep_telescope_position:
img_idxs.append(-1)
continue
# Compute image statistics
record = datafile.root._f_get_child(tel_type)[img_row]
energy_trace = record['image_charge']
min_energy = np.min(energy_trace)
max_energy = np.max(energy_trace)
total_energy = np.sum(energy_trace)
img_idxs.append(len(image_index))
image_index.append({
'filename': fn,
'tel_type': tel_type,
'img_row': img_row,
'event_index': len(event_index),
'class_name': class_name,
'min_energy': min_energy,
'max_energy': max_energy,
'total_energy' : total_energy
})
# Add global image indices to the event indices
event_img_idxs += img_idxs
# If there is at least one non-dummy image associated to this event
# add it to the event index
if len([idx for idx in event_img_idxs if idx != -1]) >= self._min_triggers_per_event:
event_index.append({
'filename': fn,
'image_indices': event_img_idxs,
'class_name': class_name
})
# Create pandas dataframes
self._image_index_df = pd.DataFrame(image_index)
self._event_index_df = pd.DataFrame(event_index)
def _filter_event(self, fn, event_row):
"""
Returns True if the event passes the specified filters
"""
return True #TODO implement event filter
def _filter_img(self, fn, tel_type, img_row):
"""
Returns True if the image passes the specified filters
"""
# if the img_row == 0 then the telescope did not trigger,
# so there is no such image
if img_row == 0: return False
return True #TODO
def _compute_dataset_metadata(self, selected_indices=None):
"""
Computes some handy data of the chosen indices of the dataset
:param event_indices: indices of the rows to be used to compute the metadata
if None, the whole dataset is used
This allows us to compute metadata for the train / val sets
:return metadata: container object whose fields store information about the dataset
"""
if selected_indices is not None and self._data_type == 'array':
# Select chosen rows of event and image index
event_index_df = self._event_index_df.iloc[selected_indices]
image_indices = event_index_df.image_indices.sum()
image_index_df = self._image_index_df.iloc[image_indices]
elif selected_indices is not None and self._data_type == 'single_tel':
image_index_df = self._image_index_df.iloc[selected_indices]
event_index_df = self._event_index_df
else:
# Use the whole dataset
event_index_df = self._event_index_df
image_index_df = self._image_index_df
# Create a empty object to store the data
metadata = type('', (), {})()
# Event metadata
metadata.n_events_per_class = event_index_df.groupby(['class_name']).size()
metadata.max_seq_length = event_index_df.image_indices.map(len).max()
# Image metadata
metadata.n_images_per_telescope = image_index_df.groupby(['tel_type']).size()
metadata.n_images_per_class = image_index_df.groupby(['class_name']).size()
metadata.image_charge_min = image_index_df.min_energy.min()
metadata.image_charge_max = image_index_df.min_energy.max()
# Class weights
if self._data_type == 'array':
count_by_class = metadata.n_events_per_class
elif self._data_type == 'single_tel':
count_by_class = metadata.n_images_per_class
total = count_by_class.sum()
metadata.class_weight = \
{self._class_name_to_class_label[class_name]: count_by_class[class_name] / total
for class_name in count_by_class.keys()}
return metadata
def _compute_telescope_array_metadata(self):
# Create empty object to hold the relevant information
tel_array_metadata = type('', (), {})()
tel_array_metadata.n_telescopes_per_type = {}
tel_array_metadata.max_telescope_position = [0,0,0]
# all files contain the same array information
f = next(iter(self.files.values()))
for row in f.root.Array_Info.iterrows():
tel_type = row['tel_type']
if tel_type not in tel_array_metadata.n_telescopes_per_type:
tel_array_metadata.n_telescopes_per_type[tel_type] = 0
tel_array_metadata.n_telescopes_per_type[tel_type] += 1
tel_pos = row['tel_x'], row['tel_y'], row['tel_z']
for i in range(3):
if tel_array_metadata.max_telescope_position[i] < tel_pos[i]:
tel_array_metadata.max_telescope_position[i] = tel_pos[i]
return tel_array_metadata
###################################
# EVENT AND IMAGE GETTERS
###################################
def _get_batch(self, batch_idxs):
"""
Returns the data and labels associated to an example
:param example_id: unique identifier of an example
:returns data:
:returns labels:
"""
if self._data_type == 'array':
# Get and stack img data, padding shorter sequences with 0 values
events = [self._get_event_imgs(example_idx) for example_idx in batch_idxs]
data = self._dataProcessor.preprocess_event_batch(events)
elif self._data_type == 'single_tel':
imgs = [self._get_image(img_id) for img_id in batch_idxs]
data = np.stack(imgs)
# Get and stack labels
labels = [self._get_labels(example_idx) for example_idx in batch_idxs]
labels = np.stack(labels)
return data, labels
def _get_event_imgs(self, event_id):
"""
Returns the imgs associated to an event
:param event_id: unique identifier of an event in the dataset
:return imgs: numpy array of shape (n_triggers, width, heigth, n_channels)
"""
# get indices of images associated to this event
img_idxs = self._event_index_df.at[event_id, 'image_indices']
# get images
imgs = [self._get_image(img_id) for img_id in img_idxs]
# Preprocess event
imgs = self._dataProcessor.preprocess_event(imgs)
return imgs
def _get_image(self, img_id):
"""
Loads and prepares an image for Keras consumption
:param img_id: id of the image in the global image index
"""
# If the image has index -1 it is replaced by dummy data
if img_id == -1:
output_shape = self._img_size + (len(self._channels),)
return np.zeros(output_shape)
# load vector trace
trace = self._load_trace(img_id)
# tranform vector data to 2D img
tel_type = self._image_index_df.at[img_id, 'tel_type']
img = self._imageMapper.vector2image(trace, tel_type)
# preprocess img
img = self._dataProcessor.preprocess_img(img, self._img_size)
return img
def _load_trace(self, img_id):
"""
Loads a vector trace from the .hdf5 datafiles
:param fn: filename of datafile containing the trace of a img
:param tel_type: type of telescope of image
:param idx: row where the trace is stored
:returns: np array of shape (n_pix, n_channels)
"""
# retrieve index data
fn = self._image_index_df.at[img_id, 'filename']
tel_type = self._image_index_df.at[img_id, 'tel_type']
img_idx = self._image_index_df.at[img_id, 'img_row' ]
# retrieve image entry
f = self.files[fn]
record = f.root._f_get_child(tel_type)[img_idx]
# Load channels
shape = (record['image_charge'].shape[0] + 1, len(self._channels))
trace = | np.empty(shape, dtype=np.float32) | numpy.empty |
"""
test_distance.py
Tests distance module.
Copyright 2018 Spectre Team
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 unittest
from unittest.mock import patch
import numpy as np
import spdivik.distance as dist
class IntradistanceCall(NotImplementedError):
pass
class InterdistanceCall(NotImplementedError):
pass
class DummyDistanceMetric(dist.DistanceMetric):
def _intradistance(self, *_):
raise IntradistanceCall(self._intradistance.__name__)
def _interdistance(self, *_):
raise InterdistanceCall(self._interdistance.__name__)
# noinspection PyCallingNonCallable
class DistanceMetricTest(unittest.TestCase):
def setUp(self):
self.metric = DummyDistanceMetric()
self.first = np.array([[1], [2], [3]])
self.second = np.array([[4], [5]])
def test_throws_when_input_is_not_an_array(self):
with self.assertRaises(ValueError):
self.metric([[1]], np.array([[1]]))
with self.assertRaises(ValueError):
self.metric(np.array([[1]]), [[1]])
def test_throws_when_input_is_not_2D(self):
with self.assertRaises(ValueError):
self.metric(np.array([1]), np.array([[1]]))
with self.assertRaises(ValueError):
self.metric( | np.array([[1]]) | numpy.array |
from torch.utils.data import Dataset
from utils import read_pfm
import os
import numpy as np
import cv2
from PIL import Image
import torch
from torchvision import transforms as T
import torchvision.transforms.functional as F
def colorjitter(img, factor):
# brightness_factor,contrast_factor,saturation_factor,hue_factor
# img = F.adjust_brightness(img, factor[0])
# img = F.adjust_contrast(img, factor[1])
img = F.adjust_saturation(img, factor[2])
img = F.adjust_hue(img, factor[3]-1.0)
return img
class MVSDatasetDTU(Dataset):
def __init__(self, root_dir, split, n_views=3, levels=1, img_wh=None, downSample=1.0, max_len=-1):
"""
img_wh should be set to a tuple ex: (1152, 864) to enable test mode!
"""
self.root_dir = root_dir
self.split = split
assert self.split in ['train', 'val', 'test'], \
'split must be either "train", "val" or "test"!'
self.img_wh = img_wh
self.downSample = downSample
self.scale_factor = 1.0 / 200
self.max_len = max_len
if img_wh is not None:
assert img_wh[0] % 32 == 0 and img_wh[1] % 32 == 0, \
'img_wh must both be multiples of 32!'
self.build_metas()
self.n_views = n_views
self.levels = levels # FPN levels
self.build_proj_mats()
self.define_transforms()
print(f'==> image down scale: {self.downSample}')
def define_transforms(self):
self.transform = T.Compose([T.ToTensor(),
T.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225]),
])
def build_metas(self):
self.metas = []
with open(f'configs/lists/dtu_{self.split}_all.txt') as f:
self.scans = [line.rstrip() for line in f.readlines()]
# light conditions 0-6 for training
# light condition 3 for testing (the brightest?)
light_idxs = [3] if 'train' != self.split else range(7)
self.id_list = []
for scan in self.scans:
with open(f'configs/dtu_pairs.txt') as f:
num_viewpoint = int(f.readline())
# viewpoints (49)
for _ in range(num_viewpoint):
ref_view = int(f.readline().rstrip())
src_views = [int(x) for x in f.readline().rstrip().split()[1::2]]
for light_idx in light_idxs:
self.metas += [(scan, light_idx, ref_view, src_views)]
self.id_list.append([ref_view] + src_views)
self.id_list = np.unique(self.id_list)
self.build_remap()
def build_proj_mats(self):
proj_mats, intrinsics, world2cams, cam2worlds = [], [], [], []
for vid in self.id_list:
proj_mat_filename = os.path.join(self.root_dir,
f'Cameras/train/{vid:08d}_cam.txt')
intrinsic, extrinsic, near_far = self.read_cam_file(proj_mat_filename)
intrinsic[:2] *= 4
extrinsic[:3, 3] *= self.scale_factor
intrinsic[:2] = intrinsic[:2] * self.downSample
intrinsics += [intrinsic.copy()]
# multiply intrinsics and extrinsics to get projection matrix
proj_mat_l = np.eye(4)
intrinsic[:2] = intrinsic[:2] / 4
proj_mat_l[:3, :4] = intrinsic @ extrinsic[:3, :4]
proj_mats += [(proj_mat_l, near_far)]
world2cams += [extrinsic]
cam2worlds += [np.linalg.inv(extrinsic)]
self.proj_mats, self.intrinsics = np.stack(proj_mats), np.stack(intrinsics)
self.world2cams, self.cam2worlds = np.stack(world2cams), np.stack(cam2worlds)
def read_cam_file(self, filename):
with open(filename) as f:
lines = [line.rstrip() for line in f.readlines()]
# extrinsics: line [1,5), 4x4 matrix
extrinsics = np.fromstring(' '.join(lines[1:5]), dtype=np.float32, sep=' ')
extrinsics = extrinsics.reshape((4, 4))
# intrinsics: line [7-10), 3x3 matrix
intrinsics = np.fromstring(' '.join(lines[7:10]), dtype=np.float32, sep=' ')
intrinsics = intrinsics.reshape((3, 3))
# depth_min & depth_interval: line 11
depth_min = float(lines[11].split()[0]) * self.scale_factor
depth_max = depth_min + float(lines[11].split()[1]) * 192 * self.scale_factor
self.depth_interval = float(lines[11].split()[1])
return intrinsics, extrinsics, [depth_min, depth_max]
def read_depth(self, filename):
depth_h = np.array(read_pfm(filename)[0], dtype=np.float32) # (800, 800)
depth_h = cv2.resize(depth_h, None, fx=0.5, fy=0.5,
interpolation=cv2.INTER_NEAREST) # (600, 800)
depth_h = depth_h[44:556, 80:720] # (512, 640)
depth_h = cv2.resize(depth_h, None, fx=self.downSample, fy=self.downSample,
interpolation=cv2.INTER_NEAREST) # !!!!!!!!!!!!!!!!!!!!!!!!!
depth = cv2.resize(depth_h, None, fx=1.0 / 4, fy=1.0 / 4,
interpolation=cv2.INTER_NEAREST) # !!!!!!!!!!!!!!!!!!!!!!!!!
mask = depth > 0
return depth, mask, depth_h
def build_remap(self):
self.remap = np.zeros(np.max(self.id_list) + 1).astype('int')
for i, item in enumerate(self.id_list):
self.remap[item] = i
def __len__(self):
return len(self.metas) if self.max_len <= 0 else self.max_len
def __getitem__(self, idx):
sample = {}
scan, light_idx, target_view, src_views = self.metas[idx]
if self.split=='train':
ids = torch.randperm(5)[:3]
view_ids = [src_views[i] for i in ids] + [target_view]
else:
view_ids = [src_views[i] for i in range(3)] + [target_view]
affine_mat, affine_mat_inv = [], []
imgs, depths_h = [], []
proj_mats, intrinsics, w2cs, c2ws, near_fars = [], [], [], [], [] # record proj mats between views
for i, vid in enumerate(view_ids):
# NOTE that the id in image file names is from 1 to 49 (not 0~48)
img_filename = os.path.join(self.root_dir,
f'Rectified/{scan}_train/rect_{vid + 1:03d}_{light_idx}_r5000.png')
depth_filename = os.path.join(self.root_dir,
f'Depths/{scan}/depth_map_{vid:04d}.pfm')
img = Image.open(img_filename)
img_wh = np.round(np.array(img.size) * self.downSample).astype('int')
img = img.resize(img_wh, Image.BILINEAR)
img = self.transform(img)
imgs += [img]
index_mat = self.remap[vid]
proj_mat_ls, near_far = self.proj_mats[index_mat]
intrinsics.append(self.intrinsics[index_mat])
w2cs.append(self.world2cams[index_mat])
c2ws.append(self.cam2worlds[index_mat])
affine_mat.append(proj_mat_ls)
affine_mat_inv.append(np.linalg.inv(proj_mat_ls))
if i == 0: # reference view
ref_proj_inv = np.linalg.inv(proj_mat_ls)
proj_mats += [np.eye(4)]
else:
proj_mats += [proj_mat_ls @ ref_proj_inv]
if os.path.exists(depth_filename):
depth, mask, depth_h = self.read_depth(depth_filename)
depth_h *= self.scale_factor
depths_h.append(depth_h)
else:
depths_h.append(np.zeros((1, 1)))
near_fars.append(near_far)
imgs = torch.stack(imgs).float()
# if self.split == 'train':
# imgs = colorjitter(imgs, 1.0+(torch.rand((4,))*2-1.0)*0.5)
# imgs = F.normalize(imgs,mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
depths_h = np.stack(depths_h)
proj_mats = np.stack(proj_mats)[:, :3]
affine_mat, affine_mat_inv = np.stack(affine_mat), np.stack(affine_mat_inv)
intrinsics, w2cs, c2ws, near_fars = | np.stack(intrinsics) | numpy.stack |
from __future__ import print_function
from utilities import nifty, block_matrix, math_utils
# standard library imports
from sys import exit
from time import time
# third party
import networkx as nx
from collections import OrderedDict, defaultdict
from numpy.linalg import multi_dot
import numpy as np
np.set_printoptions(precision=4, suppress=True)
# local application imports
try:
from .internal_coordinates import InternalCoordinates
from .primitive_internals import PrimitiveInternalCoordinates
from .topology import Topology
from .slots import *
except:
from internal_coordinates import InternalCoordinates
from primitive_internals import PrimitiveInternalCoordinates
from topology import Topology
from slots import *
class DelocalizedInternalCoordinates(InternalCoordinates):
def __init__(self,
options
):
super(DelocalizedInternalCoordinates, self).__init__(options)
# Cache some useful attributes
self.options = options
constraints = options['constraints']
cvals = options['cVals']
self.atoms = options['atoms']
self.natoms = len(self.atoms)
# The DLC contains an instance of primitive internal coordinates.
if self.options['primitives'] is None:
print(" making primitives ")
t1 = time()
self.Prims = PrimitiveInternalCoordinates(options.copy())
dt = time() - t1
print(" Time to make prims %.3f" % dt)
self.options['primitives'] = self.Prims
else:
print(" setting primitives from options!")
# print(" warning: not sure if a deep copy prims")
# self.Prims=self.options['primitives']
t0 = time()
self.Prims = PrimitiveInternalCoordinates.copy(self.options['primitives'])
print(" num of primitives {}".format(len(self.Prims.Internals)))
dt = time() - t0
print(" Time to copy prims %.3f" % dt)
self.Prims.clearCache()
# print "in constructor",len(self.Prims.Internals)
xyz = options['xyz']
xyz = xyz.flatten()
connect = options['connect']
addcart = options['addcart']
addtr = options['addtr']
if addtr:
if connect:
raise RuntimeError(" Intermolecular displacements are defined by translation and rotations! \
Don't add connect!")
elif addcart:
if connect:
raise RuntimeError(" Intermolecular displacements are defined by cartesians! \
Don't add connect!")
else:
pass
self.build_dlc(xyz)
# print("vecs after build")
# print(self.Vecs)
def clearCache(self):
super(DelocalizedInternalCoordinates, self).clearCache()
self.Prims.clearCache()
def __repr__(self):
return self.Prims.__repr__()
def update(self, other):
return self.Prims.update(other.Prims)
def join(self, other):
return self.Prims.join(other.Prims)
def copy(self, xyz):
return type(self)(self.options.copy().set_values({'xyz': xyz}))
def addConstraint(self, cPrim, cVal, xyz):
self.Prims.addConstraint(cPrim, cVal, xyz)
def getConstraints_from(self, other):
self.Prims.getConstraints_from(other.Prims)
def haveConstraints(self):
return len(self.Prims.cPrims) > 0
def getConstraintViolation(self, xyz):
return self.Prims.getConstraintViolation(xyz)
def printConstraints(self, xyz, thre=1e-5):
self.Prims.printConstraints(xyz, thre=thre)
def getConstraintTargetVals(self):
return self.Prims.getConstraintTargetVals()
def augmentGH(self, xyz, G, H):
"""
Add extra dimensions to the gradient and Hessian corresponding to the constrained degrees of freedom.
The Hessian becomes: H c
cT 0
where the elements of cT are the first derivatives of the constraint function
(typically a single primitive minus a constant) with respect to the DLCs.
Since we picked a DLC to represent the constraint (cProj), we only set one element
in each row of cT to be nonzero. Because cProj = a_i * Prim_i + a_j * Prim_j, we have
d(Prim_c)/d(cProj) = 1.0/a_c where "c" is the index of the primitive being constrained.
The extended elements of the Gradient are equal to the constraint violation.
Parameters
----------
xyz : np.ndarray
Flat array containing Cartesian coordinates in atomic units
G : np.ndarray
Flat array containing internal coordinate gradient
H : np.ndarray
Square array containing internal coordinate Hessian
Returns
-------
GC : np.ndarray
Flat array containing gradient extended by constraint violations
HC : np.ndarray
Square matrix extended by partial derivatives d(Prim)/d(cProj)
"""
# Number of internals (elements of G)
ni = len(G)
# Number of constraints
nc = len(self.Prims.cPrims)
# Total dimension
nt = ni+nc
# Lower block of the augmented Hessian
cT = np.zeros((nc, ni), dtype=float)
c0 = np.zeros(nc, dtype=float)
for ic, c in enumerate(self.Prims.cPrims):
# Look up the index of the primitive that is being constrained
iPrim = self.Prims.Internals.index(c)
# The DLC corresponding to the constrained primitive (a.k.a. cProj) is self.Vecs[self.cDLC[ic]].
# For a differential change in the DLC, the primitive that we are constraining changes by:
cT[ic, self.cDLC[ic]] = 1.0/self.Vecs[iPrim, self.cDLC[ic]]
# Calculate the further change needed in this constrained variable
c0[ic] = self.Prims.cVals[ic] - c.value(xyz)
if c.isPeriodic:
Plus2Pi = c0[ic] + 2*np.pi
Minus2Pi = c0[ic] - 2*np.pi
if np.abs(c0[ic]) > np.abs(Plus2Pi):
c0[ic] = Plus2Pi
if np.abs(c0[ic]) > np.abs(Minus2Pi):
c0[ic] = Minus2Pi
# Construct augmented Hessian
HC = np.zeros((nt, nt), dtype=float)
HC[0:ni, 0:ni] = H[:, :]
HC[ni:nt, 0:ni] = cT[:, :]
HC[0:ni, ni:nt] = cT.T[:, :]
# Construct augmented gradient
GC = np.zeros(nt, dtype=float)
GC[0:ni] = G[:]
GC[ni:nt] = -c0[:]
return GC, HC
def applyConstraints(self, xyz):
"""
Pass in Cartesian coordinates and return new coordinates that satisfy the constraints exactly.
This is not used in the current constrained optimization code that uses Lagrange multipliers instead.
"""
xyz1 = xyz.copy()
niter = 0
while True:
dQ = np.zeros(len(self.Internals), dtype=float)
for ic, c in enumerate(self.Prims.cPrims):
# Look up the index of the primitive that is being constrained
iPrim = self.Prims.Internals.index(c)
# Look up the index of the DLC that corresponds to the constraint
iDLC = self.cDLC[ic]
# Calculate the further change needed in this constrained variable
dQ[iDLC] = (self.Prims.cVals[ic] - c.value(xyz1))/self.Vecs[iPrim, iDLC]
if c.isPeriodic:
Plus2Pi = dQ[iDLC] + 2*np.pi
Minus2Pi = dQ[iDLC] - 2*np.pi
if np.abs(dQ[iDLC]) > np.abs(Plus2Pi):
dQ[iDLC] = Plus2Pi
if np.abs(dQ[iDLC]) > np.abs(Minus2Pi):
dQ[iDLC] = Minus2Pi
# print "applyConstraints calling newCartesian (%i), |dQ| = %.3e" % (niter, np.linalg.norm(dQ))
xyz2 = self.newCartesian(xyz1, dQ, verbose=False)
if np.linalg.norm(dQ) < 1e-6:
return xyz2
if niter > 1 and np.linalg.norm(dQ) > np.linalg.norm(dQ0):
# logger.warning("\x1b[1;93mWarning: Failed to apply Constraint\x1b[0m")
return xyz1
xyz1 = xyz2.copy()
niter += 1
dQ0 = dQ.copy()
def newCartesian_withConstraint(self, xyz, dQ, thre=0.1, verbose=False):
xyz2 = self.newCartesian(xyz, dQ, verbose)
constraintSmall = len(self.Prims.cPrims) > 0
for ic, c in enumerate(self.Prims.cPrims):
w = c.w if type(c) in [RotationA, RotationB, RotationC] else 1.0
current = c.value(xyz)/w
reference = self.Prims.cVals[ic]/w
diff = (current - reference)
if np.abs(diff-2*np.pi) < np.abs(diff):
diff -= 2*np.pi
if np.abs(diff+2*np.pi) < np.abs(diff):
diff += 2*np.pi
if np.abs(diff) > thre:
constraintSmall = False
if constraintSmall:
xyz2 = self.applyConstraints(xyz2)
return xyz2
def wilsonB(self, xyz):
Bp = self.Prims.wilsonB(xyz)
return block_matrix.dot(block_matrix.transpose(self.Vecs), Bp)
#def calcGrad(self, xyz, gradx):
# #q0 = self.calculate(xyz)
# Ginv = self.GInverse(xyz)
# Bmat = self.wilsonB(xyz)
# if self.frozen_atoms is not None:
# for a in [3*i for i in self.frozen_atoms]:
# gradx[a:a+3,0]=0.
# # Internal coordinate gradient
# # Gq = np.matrix(Ginv)*np.matrix(Bmat)*np.matrix(gradx)
# nifty.click()
# #Gq = multi_dot([Ginv, Bmat, gradx])
# Bg = block_matrix.dot(Bmat,gradx)
# Gq = block_matrix.dot( Ginv, Bg)
# #print("time to do block mult %.3f" % nifty.click())
# #Gq = np.dot(np.multiply(np.diag(Ginv)[:,None],Bmat),gradx)
# #print("time to do efficient mult %.3f" % nifty.click())
# return Gq
def calcGradProj(self, xyz, gradx):
"""
Project out the components of the internal coordinate gradient along the
constrained degrees of freedom. This is used to calculate the convergence
criteria for constrained optimizations.
Parameters
----------
xyz : np.ndarray
Flat array containing Cartesian coordinates in atomic units
gradx : np.ndarray
Flat array containing gradient in Cartesian coordinates
"""
if len(self.Prims.cPrims) == 0:
return gradx
q0 = self.calculate(xyz)
Ginv = self.GInverse(xyz)
Bmat = self.wilsonB(xyz)
# Internal coordinate gradient
# Gq = np.matrix(Ginv)*np.matrix(Bmat)*np.matrix(gradx).T
Gq = multi_dot([Ginv, Bmat, gradx.T])
Gqc = np.array(Gq).flatten()
# Remove the directions that are along the DLCs that we are constraining
for i in self.cDLC:
Gqc[i] = 0.0
# Gxc = np.array(np.matrix(Bmat.T)*np.matrix(Gqc).T).flatten()
Gxc = multi_dot([Bmat.T, Gqc.T]).flatten()
return Gxc
def build_dlc(self, xyz, C=None):
"""
Build the delocalized internal coordinates (DLCs) which are linear
combinations of the primitive internal coordinates. Each DLC is stored
as a column in self.Vecs.
In short, each DLC is an eigenvector of the G-matrix, and the number of
nonzero eigenvalues of G should be equal to 3*N.
After creating the DLCs, we construct special ones corresponding to primitive
coordinates that are constrained (cProj). These are placed in the front (i.e. left)
of the list of DLCs, and then we perform a Gram-Schmidt orthogonalization.
This function is called at the end of __init__ after the coordinate system is already
specified (including which primitives are constraints).
Parameters
----------
xyz : np.ndarray
Flat array containing Cartesian coordinates in atomic units
C : np.ndarray
Float array containing difference in primitive coordinates
"""
nifty.click()
# print(" Beginning to build G Matrix")
G = self.Prims.GMatrix(xyz) # in primitive coords
time_G = nifty.click()
# print(" Timings: Build G: %.3f " % (time_G))
tmpvecs = []
for A in G.matlist:
L, Q = np.linalg.eigh(A)
LargeVals = 0
LargeIdx = []
for ival, value in enumerate(L):
# print("val=%.4f" %value,end=' ')
if np.abs(value) > 1e-6:
LargeVals += 1
LargeIdx.append(ival)
# print('\n')
# print("LargeVals %i" % LargeVals)
tmpvecs.append(Q[:, LargeIdx])
self.Vecs = block_matrix(tmpvecs)
# print(" shape of DLC")
# print(self.Vecs.shape)
time_eig = nifty.click()
print(" Timings: Build G: %.3f Eig: %.3f" % (time_G, time_eig))
self.Internals = ["DLC %i" % (i+1) for i in range(self.Vecs.shape[1])]
# Vecs has number of rows equal to the number of primitives, and
# number of columns equal to the number of delocalized internal coordinates.
if self.haveConstraints():
assert cVec is None, "can't have vector constraint and cprim."
cVec = self.form_cVec_from_cPrims()
if C is not None:
# orthogonalize
if (C[:] == 0.).all():
raise RuntimeError
Cn = math_utils.orthogonalize(C)
# transform C into basis of DLC
# CRA 3/2019 NOT SURE WHY THIS IS DONE
# couldn't Cn just be used?
cVecs = block_matrix.dot(block_matrix.dot(self.Vecs, block_matrix.transpose(self.Vecs)), Cn)
# normalize C_U
try:
# print(cVecs.T)
cVecs = math_utils.orthogonalize(cVecs)
except:
print(cVecs)
print("error forming cVec")
exit(-1)
# project constraints into vectors
self.Vecs = block_matrix.project_constraint(self.Vecs, cVecs)
# print(" shape of DLC")
# print(self.Vecs.shape)
return self.Vecs
def build_dlc_conjugate(self, xyz, C=None):
"""
Build the delocalized internal coordinates (DLCs) which are linear
combinations of the primitive internal coordinates. Each DLC is stored
as a column in self.Vecs.
In short, each DLC is an eigenvector of the G-matrix, and the number of
nonzero eigenvalues of G should be equal to 3*N.
After creating the DLCs, we construct special ones corresponding to primitive
coordinates that are constrained (cProj). These are placed in the front (i.e. left)
of the list of DLCs, and then we perform a Gram-Schmidt orthogonalization.
This function is called at the end of __init__ after the coordinate system is already
specified (including which primitives are constraints).
Parameters
----------
xyz : np.ndarray
Flat array containing Cartesian coordinates in atomic units
C : np.ndarray
Float array containing difference in primitive coordinates
"""
print(" starting to build G prim")
nifty.click()
G = self.Prims.GMatrix(xyz) # in primitive coords
time_G = nifty.click()
print(" Timings: Build G: %.3f " % (time_G))
tmpvecs = []
for A in G.matlist:
L, Q = np.linalg.eigh(A)
LargeVals = 0
LargeIdx = []
for ival, value in enumerate(L):
# print("val=%.4f" %value,end=' ')
if np.abs(value) > 1e-6:
LargeVals += 1
LargeIdx.append(ival)
# print("LargeVals %i" % LargeVals)
tmpvecs.append(Q[:, LargeIdx])
self.Vecs = block_matrix(tmpvecs)
time_eig = nifty.click()
# print(" Timings: Build G: %.3f Eig: %.3f" % (time_G, time_eig))
self.Internals = ["DLC %i" % (i+1) for i in range(len(LargeIdx))]
# Vecs has number of rows equal to the number of primitives, and
# number of columns equal to the number of delocalized internal coordinates.
# if self.haveConstraints():
# assert cVec is None, "can't have vector constraint and cprim."
# cVec = self.form_cVec_from_cPrims()
# TODO use block diagonal
if C is not None:
# orthogonalize
if (C[:] == 0.).all():
raise RuntimeError
G = block_matrix.full_matrix(self.Prims.GMatrix(xyz))
Cn = math_utils.conjugate_orthogonalize(C, G)
# transform C into basis of DLC
# CRA 3/2019 NOT SURE WHY THIS IS DONE
# couldn't Cn just be used?
cVecs = block_matrix.dot(block_matrix.dot(self.Vecs, block_matrix.transpose(self.Vecs)), Cn)
# normalize C_U
try:
cVecs = math_utils.conjugate_orthogonalize(cVecs, G)
except:
print(cVecs)
print("error forming cVec")
exit(-1)
# project constraints into vectors
self.Vecs = block_matrix.project_conjugate_constraint(self.Vecs, cVecs, G)
return
def build_dlc_0(self, xyz):
"""
Build the delocalized internal coordinates (DLCs) which are linear
combinations of the primitive internal coordinates. Each DLC is stored
as a column in self.Vecs.
In short, each DLC is an eigenvector of the G-matrix, and the number of
nonzero eigenvalues of G should be equal to 3*N.
After creating the DLCs, we construct special ones corresponding to primitive
coordinates that are constrained (cProj). These are placed in the front (i.e. left)
of the list of DLCs, and then we perform a Gram-Schmidt orthogonalization.
This function is called at the end of __init__ after the coordinate system is already
specified (including which primitives are constraints).
Parameters
----------
xyz : np.ndarray
Flat array containing Cartesian coordinates in atomic units
"""
# Perform singular value decomposition
nifty.click()
G = self.Prims.GMatrix(xyz)
# Manipulate G-Matrix to increase weight of constrained coordinates
if self.haveConstraints():
for ic, c in enumerate(self.Prims.cPrims):
iPrim = self.Prims.Internals.index(c)
G[:, iPrim] *= 1.0
G[iPrim, :] *= 1.0
ncon = len(self.Prims.cPrims)
# Water Dimer: 100.0, no check -> -151.1892668451
time_G = nifty.click()
L, Q = np.linalg.eigh(G)
time_eig = nifty.click()
# print "Build G: %.3f Eig: %.3f" % (time_G, time_eig)
LargeVals = 0
LargeIdx = []
for ival, value in enumerate(L):
# print ival, value
if np.abs(value) > 1e-6:
LargeVals += 1
LargeIdx.append(ival)
Expect = 3*self.na
# print "%i atoms (expect %i coordinates); %i/%i singular values are > 1e-6" % (self.na, Expect, LargeVals, len(L))
# if LargeVals <= Expect:
self.Vecs = Q[:, LargeIdx]
# Vecs has number of rows equal to the number of primitives, and
# number of columns equal to the number of delocalized internal coordinates.
if self.haveConstraints():
nifty.click()
# print "Projecting out constraints...",
V = []
for ic, c in enumerate(self.Prims.cPrims):
# Look up the index of the primitive that is being constrained
iPrim = self.Prims.Internals.index(c)
# Pick a row out of the eigenvector space. This is a linear combination of the DLCs.
cVec = self.Vecs[iPrim, :]
cVec = np.array(cVec)
cVec /= np.linalg.norm(cVec)
# This is a "new DLC" that corresponds to the primitive that we are constraining
cProj = np.dot(self.Vecs, cVec.T)
cProj /= np.linalg.norm(cProj)
V.append(np.array(cProj).flatten())
# print c, cProj[iPrim]
# V contains the constraint vectors on the left, and the original DLCs on the right
V = np.hstack((np.array(V).T, np.array(self.Vecs)))
# Apply Gram-Schmidt to V, and produce U.
# The Gram-Schmidt process should produce a number of orthogonal DLCs equal to the original number
thre = 1e-6
while True:
U = []
for iv in range(V.shape[1]):
v = V[:, iv].flatten()
U.append(v.copy())
for ui in U[:-1]:
U[-1] -= ui * np.dot(ui, v)
if np.linalg.norm(U[-1]) < thre:
U = U[:-1]
continue
U[-1] /= np.linalg.norm(U[-1])
if len(U) > self.Vecs.shape[1]:
thre *= 10
elif len(U) == self.Vecs.shape[1]:
break
elif len(U) < self.Vecs.shape[1]:
raise RuntimeError('Gram-Schmidt orthogonalization has failed (expect %i length %i)' % (self.Vecs.shape[1], len(U)))
# print "Gram-Schmidt completed with thre=%.0e" % thre
self.Vecs = np.array(U).T
# Constrained DLCs are on the left of self.Vecs.
self.cDLC = [i for i in range(len(self.Prims.cPrims))]
# Now self.Internals is no longer a list of InternalCoordinate objects but only a list of strings.
# We do not create objects for individual DLCs but
self.Internals = ["Constraint-DLC" if i < ncon else "DLC" + " %i" % (i+1) for i in range(self.Vecs.shape[1])]
def build_dlc_1(self, xyz):
"""
Build the delocalized internal coordinates (DLCs) which are linear
combinations of the primitive internal coordinates. Each DLC is stored
as a column in self.Vecs.
After some thought, build_dlc_0 did not implement constraint satisfaction
in the most correct way. Constraint satisfaction was rather slow and
the --enforce 0.1 may be passed to improve performance. Rethinking how the
G matrix is constructed provides a more fundamental solution.
In the new approach implemented here, constrained primitive ICs (PICs) are
first set aside from the rest of the PICs. Next, a G-matrix is constructed
from the rest of the PICs and diagonalized to form DLCs, called "residual" DLCs.
The union of the cPICs and rDLCs forms a generalized set of DLCs, but the
cPICs are not orthogonal to each other or to the rDLCs.
A set of orthogonal DLCs is constructed by carrying out Gram-Schmidt
on the generalized set. Orthogonalization is carried out on the cPICs in order.
Next, orthogonalization is carried out on the rDLCs using a greedy algorithm
that carries out projection for each cPIC, then keeps the one with the largest
remaining norm. This way we avoid keeping rDLCs that are almost redundant with
the cPICs. The longest projected rDLC is added to the set and continued until
the expected number is reached.
One special note in orthogonalization is that the "overlap" between internal
coordinates corresponds to the G matrix element. Thus, for DLCs that's a linear
combination of PICs, then the overlap is given by:
v_i * B * B^T * v_j = v_i * G * v_j
Notes on usage: 1) When this is activated, constraints tend to be satisfied very
rapidly even if the current coordinates are very far from the constraint values,
leading to possible blowing up of the energies. In augment_GH, maximum steps in
constrained degrees of freedom are restricted to 0.1 a.u./radian for this reason.
2) Although the performance of this method is generally superior to the old method,
the old method with --enforce 0.1 is more extensively tested and recommended.
Thus, this method isn't enabled by default but provided as an optional feature.
Parameters
----------
xyz : np.ndarray
Flat array containing Cartesian coordinates in atomic units
"""
nifty.click()
G = self.Prims.GMatrix(xyz)
nprim = len(self.Prims.Internals)
cPrimIdx = []
if self.haveConstraints():
for ic, c in enumerate(self.Prims.cPrims):
iPrim = self.Prims.Internals.index(c)
cPrimIdx.append(iPrim)
ncon = len(self.Prims.cPrims)
if cPrimIdx != list(range(ncon)):
raise RuntimeError("The constraint primitives should be at the start of the list")
# Form a sub-G-matrix that doesn't include the constrained primitives and diagonalize it to form DLCs.
Gsub = G[ncon:, ncon:]
time_G = nifty.click()
L, Q = np.linalg.eigh(Gsub)
# Sort eigenvalues and eigenvectors in descending order (for cleanliness)
L = L[::-1]
Q = Q[:, ::-1]
time_eig = click()
# print "Build G: %.3f Eig: %.3f" % (time_G, time_eig)
# Figure out which eigenvectors from the G submatrix to include
LargeVals = 0
LargeIdx = []
GEigThre = 1e-6
for ival, value in enumerate(L):
if np.abs(value) > GEigThre:
LargeVals += 1
LargeIdx.append(ival)
# This is the number of nonredundant DLCs that we expect to have at the end
Expect = np.sum(np.linalg.eigh(G)[0] > 1e-6)
if (ncon + len(LargeIdx)) < Expect:
raise RuntimeError("Expected at least %i delocalized coordinates, but got only %i" % (Expect, ncon + len(LargeIdx)))
# print("%i atoms (expect %i coordinates); %i/%i singular values are > 1e-6" % (self.na, Expect, LargeVals, len(L)))
# Create "generalized" DLCs where the first six columns are the constrained primitive ICs
# and the other columns are the DLCs formed from the rest
self.Vecs = np.zeros((nprim, ncon+LargeVals), dtype=float)
for i in range(ncon):
self.Vecs[i, i] = 1.0
self.Vecs[ncon:, ncon:ncon+LargeVals] = Q[:, LargeIdx]
# Perform Gram-Schmidt orthogonalization
def ov(vi, vj):
return multi_dot([vi, G, vj])
if self.haveConstraints():
nifty.click()
V = self.Vecs.copy()
nv = V.shape[1]
Vnorms = np.array([np.sqrt(ov(V[:, ic], V[:, ic])) for ic in range(nv)])
# U holds the Gram-Schmidt orthogonalized DLCs
U = np.zeros((V.shape[0], Expect), dtype=float)
Unorms = np.zeros(Expect, dtype=float)
for ic in range(ncon):
# At the top of the loop, V columns are orthogonal to U columns up to ic.
# Copy V column corresponding to the next constraint to U.
U[:, ic] = V[:, ic].copy()
ui = U[:, ic]
Unorms[ic] = np.sqrt(ov(ui, ui))
if Unorms[ic]/Vnorms[ic] < 0.1:
print("Constraint %i is almost redundant; after projection norm is %.3f of original\n" % (ic, Unorms[ic]/Vnorms[ic]))
# Project out newest U column from all remaining V columns.
for jc in range(ic+1, nv):
vj = V[:, jc]
vj -= ui * ov(ui, vj)/Unorms[ic]**2
for ic in range(ncon, Expect):
# Pick out the V column with the largest norm
norms = np.array([np.sqrt(ov(V[:, jc], V[:, jc])) for jc in range(ncon, nv)])
imax = ncon+np.argmax(norms)
# Add this column to U
U[:, ic] = V[:, imax].copy()
ui = U[:, ic]
Unorms[ic] = np.sqrt(ov(ui, ui))
# Project out the newest U column from all V columns
for jc in range(ncon, nv):
V[:, jc] -= ui * ov(ui, V[:, jc])/Unorms[ic]**2
# self.Vecs contains the linear combination coefficients that are our new DLCs
self.Vecs = U.copy()
# Constrained DLCs are on the left of self.Vecs.
self.cDLC = [i for i in range(len(self.Prims.cPrims))]
self.Internals = ["Constraint" if i < ncon else "DLC" + " %i" % (i+1) for i in range(self.Vecs.shape[1])]
# # LPW: Coefficients of DLC's are in each column and DLCs corresponding to constraints should basically be like (0 1 0 0 0 ..)
# pmat2d(self.Vecs, format='f', precision=2)
# B = self.Prims.wilsonB(xyz)
# Bdlc = np.einsum('ji,jk->ik', self.Vecs, B)
# Gdlc = np.dot(Bdlc, Bdlc.T)
# # Expect to see a diagonal matrix here
# print("Gdlc")
# pmat2d(Gdlc, format='e', precision=2)
# # Expect to see "large" eigenvalues here (no less than 0.1 ideally)
# print("L, Q")
# L, Q = np.linalg.eigh(Gdlc)
# print(L)
def form_cVec_from_cPrims(self):
""" forms the constraint vector from self.cPrim -- not used in GSM"""
# CRA 3/2019 warning:
# I'm not sure how this works!!!
# multiple constraints appears to be problematic!!!
self.cDLC = [i for i in range(len(self.Prims.cPrims))]
# print "Projecting out constraints...",
# V=[]
for ic, c in enumerate(self.Prims.cPrims):
# Look up the index of the primitive that is being constrained
iPrim = self.Prims.Internals.index(c)
# Pick a row out of the eigenvector space. This is a linear combination of the DLCs.
cVec = self.Vecs[iPrim, :]
cVec = np.array(cVec)
cVec /= np.linalg.norm(cVec)
# This is a "new DLC" that corresponds to the primitive that we are constraining
cProj = np.dot(self.Vecs, cVec.T)
cProj /= | np.linalg.norm(cProj) | numpy.linalg.norm |
import pickle
import copy
import utiltools.thirdparty.o3dhelper as o3dh
import utiltools.robotmath as rm
import utiltools.thirdparty.p3dhelper as p3dh
import numpy as np
import environment.collisionmodel as cm
class Locator(object):
def __init__(self, directory=None, standtype = "light"):
"""
standtype could be normal, light, ...
:param directory:
:param standtype:
"""
if standtype is "normal":
tsfilename = "tubestand.stl"
tspcdfilename = "tubestandtemplatepcd.pkl"
# down x, right y
tubeholecenters = []
for x in [-38,-19,0,19,38]:
tubeholecenters.append([])
for y in [-81, -63, -45, -27, -9, 9, 27, 45, 63, 81]:
tubeholecenters[-1].append([x,y])
self.tubeholecenters = np.array(tubeholecenters)
self.tubeholesize = np.array([15, 16])
self.tubestandsize = np.array([96, 192])
elif standtype is "light":
tsfilename = "tubestand_light.stl"
tspcdfilename = "tubestand_light_templatepcd.pkl"
tubeholecenters = []
for x in [-36, -18, 0, 18, 36]:
tubeholecenters.append([])
for y in [-83.25, -64.75, -46.25, -27.75, -9.25, 9.25, 27.75, 46.25, 64.75, 83.25]:
tubeholecenters[-1].append([x, y])
self.tubeholecenters = np.array(tubeholecenters)
self.tubeholesize = np.array([17, 16.5])
self.tubestandsize = np.array([97, 191])
self.__directory = directory
if directory is None:
self.bgdepth = pickle.load(open("./databackground/bgdepth.pkl", "rb"))
self.bgpcd = pickle.load(open("./databackground/bgpcd.pkl", "rb"))
self.sensorhomomat = pickle.load(open("./datacalibration/calibmat.pkl", "rb"))
self.tstpcdnp = pickle.load(open("./dataobjtemplate/"+tspcdfilename, "rb"))# tstpcd, tube stand template
self.tubestandcm = cm.CollisionModel("./objects/"+tsfilename)
self.tubebigcm = cm.CollisionModel("./objects/tubebig_capped.stl", type="cylinder", expand_radius=0)
self.tubesmallcm = cm.CollisionModel("./objects/tubesmall_capped.stl", type="cylinder", expand_radius=0)
else:
self.bgdepth = pickle.load(open(directory+"/databackground/bgdepth.pkl", "rb"))
self.bgpcd = pickle.load(open(directory+"/databackground/bgpcd.pkl", "rb"))
self.sensorhomomat = pickle.load(open(directory+"/datacalibration/calibmat.pkl", "rb"))
self.tstpcdnp = pickle.load(open(directory+"/dataobjtemplate/"+tspcdfilename, "rb"))# tstpcd, tube stand template
self.tubestandcm = cm.CollisionModel(directory+"/objects/"+tsfilename)
self.tubebigcm = cm.CollisionModel(directory +"/objects/tubebig_capped.stl", type="cylinder", expand_radius=0)
self.tubesmallcm = cm.CollisionModel(directory +"/objects/tubesmall_capped.stl", type="cylinder", expand_radius=0)
# for compatibility with locatorfixed
self.tubestandhomomat = None
def findtubestand_matchonobb(self, tgtpcdnp, toggledebug=False):
"""
match self.tstpcd from tgtpcdnp
using the initilization by findtubestand_obb
:param tgtpcdnp:
:param toggledebug:
:return:
author: weiwei
date:20191229osaka
"""
# toggle the following command to crop the point cloud
# tgtpcdnp = tgtpcdnp[np.logical_and(tgtpcdnp[:,2]>40, tgtpcdnp[:,2]<60)]
# 20200425 cluster is further included
pcdarraylist, _ = o3dh.cluster_pcd(tgtpcdnp)
tgtpcdnp = max(pcdarraylist, key = lambda x:len(x))
# for pcdarray in pcdarraylist:
# rgb = np.random.rand(3)
# rgba = np.array([rgb[0], rgb[1], rgb[2], 1])
# pcdnp = p3dh.genpointcloudnodepath(pcdarray, pntsize=5, colors=rgba)
# pcdnp.reparentTo(base.render)
# break
# base.run()
inithomomat = self.findtubestand_obb(tgtpcdnp, toggledebug)
inlinnerrmse, homomat = o3dh.registration_icp_ptpt(self.tstpcdnp, tgtpcdnp, inithomomat, maxcorrdist=5, toggledebug=toggledebug)
inithomomatflipped = copy.deepcopy(inithomomat)
inithomomatflipped[:3,0] = -inithomomatflipped[:3,0]
inithomomatflipped[:3,1] = -inithomomatflipped[:3,1]
inlinnerrmseflipped, homomatflipped = o3dh.registration_icp_ptpt(self.tstpcdnp, tgtpcdnp, inithomomatflipped, maxcorrdist=5, toggledebug=toggledebug)
print(inlinnerrmse, inlinnerrmseflipped)
if inlinnerrmseflipped < inlinnerrmse:
homomat = homomatflipped
# for compatibility with locactorfixed
self.tubestandhomomat = homomat
return copy.deepcopy(homomat)
def findtubestand_match(self, tgtpcdnp, toggledebug = False):
"""
match self.tstpcd from tgtpcdnp
NOTE: tgtpcdnp must be in global frame, use getglobalpcd to convert if local
:param tgtpcdnp:
:return:
author: weiwei
date: 20191229osaka
"""
_, homomat = o3dh.registration_ptpln(self.tstpcdnp, tgtpcdnp, downsampling_voxelsize=5,
toggledebug=toggledebug)
return copy.deepcopy(homomat)
def findtubestand_obb(self, tgtpcdnp, toggledebug = False):
"""
match self.tstpcd from tgtpcdnp
NOTE: tgtpcdnp must be in global frame, use getglobalpcd to convert if local
:param tgtpcdnp:
:return:
author: weiwei
date: 20191229osaka
"""
# clustering has been included
# removing outlier is not longer needed, 20200425
# tgtpcdnp = o3dh.removeoutlier(tgtpcdnp, nb_points=20, radius=10)
tgtpcdnp2d = tgtpcdnp[:,:2] # TODO clip using sensor z
ca = np.cov(tgtpcdnp2d, y=None, rowvar=0, bias=1)
v, vect = np.linalg.eig(ca)
tvect = np.transpose(vect)
# use the inverse of the eigenvectors as a rotation matrix and
# rotate the points so they align with the x and y axes
ar = np.dot(tgtpcdnp2d, np.linalg.inv(tvect))
# get the minimum and maximum x and y
mina = np.min(ar, axis=0)
maxa = np.max(ar, axis=0)
diff = (maxa - mina) * 0.5
# the center is just half way between the min and max xy
center = mina + diff
# get the 4 corners by subtracting and adding half the bounding boxes height and width to the center
corners = np.array([center + [-diff[0], -diff[1]], center + [diff[0], -diff[1]], center + [diff[0], diff[1]],
center + [-diff[0], diff[1]], center + [-diff[0], -diff[1]]])
# use the the eigenvectors as a rotation matrix and
# rotate the corners and the centerback
corners = np.dot(corners, tvect)
center = np.dot(center, tvect)
if toggledebug:
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(12, 12))
ax = fig.add_subplot(111)
ax.scatter(tgtpcdnp2d[:, 0], tgtpcdnp2d[:, 1])
ax.scatter([center[0]], [center[1]])
ax.plot(corners[:, 0], corners[:, 1], '-')
plt.axis('equal')
plt.show()
axind = np.argsort(v)
homomat = np.eye(4)
homomat[:3,axind[0]] = np.array([vect[0,0], vect[1,0], 0])
homomat[:3,axind[1]] = np.array([vect[0,1], vect[1,1], 0])
homomat[:3,2] = np.array([0,0,1])
if np.cross(homomat[:3,0], homomat[:3,1])[2] < -.5:
homomat[:3,1] = -homomat[:3,1]
homomat[:3, 3] = np.array([center[0], center[1], -15])
return homomat
def _crop_pcd_overahole(self, tgtpcd_intsframe, holecenter_x, holecenter_y, crop_ratio = .9, crop_height = 70):
"""
crop the point cloud over a hole in the tubestand frame
:param tgtpcd_intsframe:
:param holecenter_x, holecenter_y:
:param crop_ratio:
:param crop_height:
:return:
author: weiwei
date: 20200318
"""
# squeeze the hole size by half, make it a bit smaller than a half
tmppcd = tgtpcd_intsframe[tgtpcd_intsframe[:, 0] < (holecenter_x + self.tubeholesize[0]*crop_ratio/2)]
tmppcd = tmppcd[tmppcd[:, 0] > (holecenter_x - self.tubeholesize[0]*crop_ratio/2)]
tmppcd = tmppcd[tmppcd[:, 1] < (holecenter_y + self.tubeholesize[1]*crop_ratio/2)]
tmppcd = tmppcd[tmppcd[:, 1] > (holecenter_y - self.tubeholesize[1]*crop_ratio/2)]
tmppcd = tmppcd[tmppcd[:, 2] > crop_height]
return tmppcd
def findtubes(self, tubestand_homomat, tgtpcdnp, toggledebug=False):
"""
:param tgtpcdnp:
:return:
author: weiwei
date: 20200317
"""
elearray = np.zeros((5, 10))
eleconfidencearray = np.zeros((5, 10))
tgtpcdnp = o3dh.remove_outlier(tgtpcdnp, downsampling_voxelsize=None, nb_points=90, radius=5)
# transform back to the local frame of the tubestand
tgtpcdnp_normalized = rm.homotransformpointarray(rm.homoinverse(tubestand_homomat), tgtpcdnp)
if toggledebug:
cm.CollisionModel(tgtpcdnp_normalized).reparentTo(base.render)
tscm2 = copy.deepcopy(self.tubestandcm)
tscm2.reparentTo(base.render)
for i in range(5):
for j in range(10):
holepos = self.tubeholecenters[i][j]
tmppcd = self._crop_pcd_overahole(tgtpcdnp_normalized, holepos[0], holepos[1])
if len(tmppcd) > 50:
if toggledebug:
print("------more than 50 raw points, start a new test------")
tmppcdover100 = tmppcd[tmppcd[:, 2] > 100]
tmppcdbelow90 = tmppcd[tmppcd[:, 2] < 90]
tmppcdlist = [tmppcdover100, tmppcdbelow90]
if toggledebug:
print("rotate around...")
rejflaglist = [False, False]
allminstdlist = [[], []]
newtmppcdlist = [None, None]
minstdlist = [None, None]
for k in range(2):
if toggledebug:
print("checking over 100 and below 90, now: ", j)
if len(tmppcdlist[k]) < 10:
rejflaglist[k] = True
continue
for angle in np.linspace(0, 180, 10):
tmphomomat = np.eye(4)
tmphomomat[:3, :3] = rm.rodrigues(tubestand_homomat[:3, 2], angle)
newtmppcdlist[k] = rm.homotransformpointarray(tmphomomat, tmppcdlist[k])
minstdlist[k] = np.min(np.std(newtmppcdlist[k][:, :2], axis=0))
if toggledebug:
print(minstdlist[k])
allminstdlist[k].append(minstdlist[k])
if minstdlist[k] < 1.5:
rejflaglist[k] = True
if toggledebug:
print("rotate round done")
print("minstd ", np.min(np.asarray(allminstdlist[k])))
if all(item for item in rejflaglist):
continue
elif all(not item for item in rejflaglist):
print("CANNOT tell if the tube is big or small")
raise ValueError()
else:
tmppcd = tmppcdbelow90 if rejflaglist[0] else tmppcdover100
candidatetype = 2 if rejflaglist[0] else 1
tmpangles = np.arctan2(tmppcd[:, 1], tmppcd[:, 0])
tmpangles[tmpangles < 0] = 360 + tmpangles[tmpangles < 0]
if toggledebug:
print(np.std(tmpangles))
print("ACCEPTED! ID: ", i, j)
elearray[i][j] = candidatetype
eleconfidencearray[i][j] = 1
if toggledebug:
# normalized
objnp = p3dh.genpointcloudnodepath(tmppcd, pntsize=5)
rgb = np.random.rand(3)
objnp.setColor(rgb[0], rgb[1], rgb[2], 1)
objnp.reparentTo(base.render)
stick = p3dh.gendumbbell(spos=np.array([holepos[0], holepos[1], 10]),
epos=np.array([holepos[0], holepos[1], 60]))
stick.setColor(rgb[0], rgb[1], rgb[2], 1)
stick.reparentTo(base.render)
# original
tmppcd_tr = rm.homotransformpointarray(tubestand_homomat, tmppcd)
objnp_tr = p3dh.genpointcloudnodepath(tmppcd_tr, pntsize=5)
objnp_tr.setColor(rgb[0], rgb[1], rgb[2], 1)
objnp_tr.reparentTo(base.render)
spos_tr = rm.homotransformpoint(tubestand_homomat, np.array([holepos[0], holepos[1], 0]))
stick_tr = p3dh.gendumbbell(spos=np.array([spos_tr[0], spos_tr[1], 10]),
epos=np.array([spos_tr[0], spos_tr[1], 60]))
stick_tr.setColor(rgb[0], rgb[1], rgb[2], 1)
stick_tr.reparentTo(base.render)
# box normalized
center, bounds = rm.getaabb(tmppcd)
boxextent = np.array(
[bounds[0, 1] - bounds[0, 0], bounds[1, 1] - bounds[1, 0], bounds[2, 1] - bounds[2, 0]])
boxhomomat = np.eye(4)
boxhomomat[:3, 3] = center
box = p3dh.genbox(extent=boxextent, homomat=boxhomomat,
rgba=np.array([rgb[0], rgb[1], rgb[2], .3]))
box.reparentTo(base.render)
# box original
center_r = rm.homotransformpoint(tubestand_homomat, center)
boxhomomat_tr = copy.deepcopy(tubestand_homomat)
boxhomomat_tr[:3, 3] = center_r
box_tr = p3dh.genbox(extent=boxextent, homomat=boxhomomat_tr,
rgba=np.array([rgb[0], rgb[1], rgb[2], .3]))
box_tr.reparentTo(base.render)
if toggledebug:
print("------the new test is done------")
return elearray, eleconfidencearray
def capturecorrectedpcd(self, pxc, ncapturetimes = 1):
"""
capture a poind cloud and transform it from its sensor frame to global frame
:param pcdnp:
:return:
author: weiwei
date: 20200108
"""
objpcdmerged = None
for i in range(ncapturetimes):
pxc.triggerframe()
fgdepth = pxc.getdepthimg()
fgpcd = pxc.getpcd()
substracteddepth = self.bgdepth - fgdepth
substracteddepth = substracteddepth.clip(50, 300)
substracteddepth[substracteddepth == 50] = 0
substracteddepth[substracteddepth == 300] = 0
tempdepth = substracteddepth.flatten()
objpcd = fgpcd[np.nonzero(tempdepth)]
objpcd = self.getcorrectedpcd(objpcd)
if objpcdmerged is None:
objpcdmerged = objpcd
else:
objpcdmerged = np.vstack((objpcdmerged, objpcd))
# further crop x
objpcdmerged = objpcdmerged[objpcdmerged[:,0]>200]
return objpcdmerged
def getcorrectedpcd(self, pcdarray):
"""
convert a poind cloud from its sensor frame to global frame
:param pcdarray:
:return:
author: weiwei
date: 20191229osaka
"""
return rm.homotransformpointarray(self.sensorhomomat, pcdarray)
def gentubestand(self, homomat):
"""
:param homomat:
:return:
author: weiwei
date: 20191229osaka
"""
tubestandcm = copy.deepcopy(self.tubestandcm)
tubestandcm.set_homomat(homomat)
tubestandcm.setColor(0,.5,.7,1)
return tubestandcm
def gentubeandstandboxcm(self, homomat, wrapheight = 120, rgba = np.array([.5, .5, .5, .3])):
"""
gen a solid box to wrap both a stand and the tubes in it
:param homomat:
:return:
author: weiwei
date: 20191229osaka
"""
homomat_copy = copy.deepcopy(homomat)
homomat_copy[:3, 3] = homomat_copy[:3, 3] + homomat_copy[:3,2]* wrapheight/2
tubeandstandboxcm = cm.CollisionModel(p3dh.genbox(np.array([self.tubestandsize[0], self.tubestandsize[1], 120]), homomat_copy))
tubeandstandboxcm.setColor(rgba[0], rgba[1], rgba[2], rgba[3])
return tubeandstandboxcm
def gentubes(self, elearray, tubestand_homomat, eleconfidencearray=None, alpha=.3):
"""
:param elearray:
:param tubestand_homomat:
:param eleconfidencearray: None by default
:param alpha: only works when eleconfidencearray is None, it renders the array transparently
:return:
author: weiwei
date: 20191229osaka
"""
if eleconfidencearray is None:
eleconfidencearray = | np.ones_like(elearray) | numpy.ones_like |
import matplotlib.pyplot as plt
import numpy as np
def read_file(path):
dt = []
lf = open(path, 'r+', encoding='utf-8')
lines = lf.readlines()
for line in lines:
dt.append(line.strip())
return dt
def analysis():
labels = read_file(path='./labels_mmodel1.txt')
predictions = read_file(path='./predicteds_mmodel1.txt')
ss = {}
wf = open('./compares.txt', 'w', encoding='utf-8')
for i in range(len(labels)):
lb = labels[i].split(' ')
pd = predictions[i].split(' ')
for j in range(len(lb)):
try:
s1 = lb[j]
except IndexError:
s1 = 'null'
try:
s2 = pd[j]
except IndexError:
s2 = 'null'
if s1 != s2:
wf.writelines(s1 + ' - ' + s2 + '\n')
wf.close()
return None
def plot():
peoples = ["DTM1", "DTM2", "DTM3"]
cers = [10.79, 4.51, 9.14]
wers = [25.96, 12.62, 23.19]
sers = [26.30, 12.97, 23.97]
index = | np.arange(3) | numpy.arange |
from __future__ import absolute_import, division, print_function, unicode_literals
from mxnet import init, gluon
from mxnet.gluon import nn
import numpy as np
import unittest
from art.classifiers import MXClassifier
from art.utils import load_mnist
NB_TRAIN = 1000
NB_TEST = 20
class TestMXClassifier(unittest.TestCase):
def setUp(self):
# Get MNIST
(x_train, y_train), (x_test, y_test), _, _ = load_mnist()
x_train, y_train = x_train[:NB_TRAIN], y_train[:NB_TRAIN]
x_test, y_test = x_test[:NB_TEST], y_test[:NB_TEST]
x_train = np.swapaxes(x_train, 1, 3)
x_test = np.swapaxes(x_test, 1, 3)
self._mnist = (x_train, y_train), (x_test, y_test)
# Create a simple CNN - this one comes from the Gluon tutorial
net = nn.Sequential()
with net.name_scope():
net.add(
nn.Conv2D(channels=6, kernel_size=5, activation='relu'),
nn.MaxPool2D(pool_size=2, strides=2),
nn.Conv2D(channels=16, kernel_size=3, activation='relu'),
nn.MaxPool2D(pool_size=2, strides=2),
nn.Flatten(),
nn.Dense(120, activation="relu"),
nn.Dense(84, activation="relu"),
nn.Dense(10)
)
net.initialize(init=init.Xavier())
# Create optimizer
self._model = net
self._trainer = gluon.Trainer(net.collect_params(), 'sgd', {'learning_rate': 0.1})
def test_fit_predict(self):
(x_train, y_train), (x_test, y_test) = self._mnist
# Fit classifier
classifier = MXClassifier((0, 1), self._model, (1, 28, 28), 10, self._trainer)
classifier.fit(x_train, y_train, batch_size=128, nb_epochs=2)
preds = classifier.predict(x_test)
acc = np.sum(np.argmax(preds, axis=1) == np.argmax(y_test, axis=1)) / len(y_test)
print("\nAccuracy: %.2f%%" % (acc * 100))
self.assertGreater(acc, 0.1)
def test_nb_classes(self):
classifier = MXClassifier((0, 1), self._model, (1, 28, 28), 10, self._trainer)
self.assertEqual(classifier.nb_classes, 10)
def test_input_shape(self):
classifier = MXClassifier((0, 1), self._model, (1, 28, 28), 10, self._trainer)
self.assertEqual(classifier.input_shape, (1, 28, 28))
# def test_class_gradient(self):
# # Get MNIST
# (_, _), (x_test, _) = self._mnist
#
# # Create classifier
# classifier = MXClassifier((0, 1), self._model, (1, 28, 28), 10, self._trainer)
# grads = classifier.class_gradient(x_test)
#
# self.assertTrue(np.array(grads.shape == (NB_TEST, 10, 1, 28, 28)).all())
# self.assertTrue(np.sum(grads) != 0)
def test_loss_gradient(self):
# Get MNIST
(_, _), (x_test, y_test) = self._mnist
# Create classifier
classifier = MXClassifier((0, 1), self._model, (1, 28, 28), 10, self._trainer)
grads = classifier.loss_gradient(x_test, y_test)
self.assertTrue( | np.array(grads.shape == (NB_TEST, 1, 28, 28)) | numpy.array |
import datetime
import numpy as np
import pandas as pd
import xarray as xr
import primap2 # noqa: F401
from primap2 import ureg
def minimal_ds():
"""A valid, minimal dataset."""
time = pd.date_range("2000-01-01", "2020-01-01", freq="AS")
area_iso3 = np.array(["COL", "ARG", "MEX", "BOL"])
# seed the rng with a constant to achieve predictable "randomness"
rng = np.random.default_rng(1)
minimal = xr.Dataset(
{
ent: xr.DataArray(
data=rng.random((len(time), len(area_iso3), 1)),
coords={
"time": time,
"area (ISO3)": area_iso3,
"source": ["RAND2020"],
},
dims=["time", "area (ISO3)", "source"],
attrs={"units": f"{ent} Gg / year", "entity": ent},
)
for ent in ("CO2", "SF6", "CH4")
},
attrs={"area": "area (ISO3)"},
).pr.quantify()
with ureg.context("SARGWP100"):
minimal["SF6 (SARGWP100)"] = minimal["SF6"].pint.to("CO2 Gg / year")
minimal["SF6 (SARGWP100)"].attrs["gwp_context"] = "SARGWP100"
return minimal
COORDS = {
"time": pd.date_range("2000-01-01", "2020-01-01", freq="AS"),
"area (ISO3)": np.array(["COL", "ARG", "MEX", "BOL"]),
"category (IPCC 2006)": np.array(["0", "1", "2", "3", "4", "5", "1.A", "1.B"]),
"animal (FAOSTAT)": np.array(["cow", "swine", "goat"]),
"product (FAOSTAT)": | np.array(["milk", "meat"]) | numpy.array |
# 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]) | numpy.array |
import numpy as np
import random
import matplotlib.pyplot as plt
class ECGDataset:
def __init__(self, file_path):
"""
:rtype: ECGDataset
:param file_path: A file containing a numpy array with electrode data.
"""
# Load data and create electrode index mapping
self.file_path = file_path
self.data = np.load(self.file_path) * 0.000625
self.mapping = np.arange(0, len(self.data), 1)
# Remove redundant electrodes (corners)
self.data = np.delete(self.data, [0, 7, 127, 120], axis=0)
self.mapping = np.delete(self.mapping, [0, 7, 127, 120], axis=0)
# Declare peaks variable.
self.peaks = None
def invert(dataset):
# Multiply by -1 to invert data
dataset.data = dataset.data * -1
return dataset
def zoom(dataset, time_range):
# Loop through all electrodes
# and slice on x-axis to create zoom effect
res = []
for count in range((len(dataset.data))):
res.append(dataset.data[count][time_range[0]: time_range[1]])
dataset.data = np.array(res)
return dataset
def sample(dataset, size=0.1):
# Generate random indices based on input size
# and use those indices to get a sample of the dataset.
s_indices = random.sample(range(0, len(dataset.data)), int(size * len(dataset.data)))
dataset.mapping = dataset.mapping[s_indices]
dataset.data = dataset.data[s_indices]
if dataset.peaks is not None:
dataset.peaks = dataset.peaks[s_indices]
return dataset
def slice_d(dataset, start, end):
# Slice the mapping and the electrode data from start to end
dataset.mapping = dataset.mapping[start: end]
dataset.data = dataset.data[start: end]
if dataset.peaks is not None:
dataset.peaks = dataset.peaks[start: end]
return dataset
def index(dataset, idx=None):
# Select a single electrode from the dataset
if not idx:
# If index is not specified, choose a random electrode
idx = dataset.mapping[random.randint(0, len(dataset.data))]
else:
idx = np.where(dataset.mapping == idx)[0][0]
dataset.mapping = np.array([dataset.mapping[idx]])
dataset.data = np.array([dataset.data[idx]])
if dataset.peaks is not None:
dataset.peaks = | np.array([dataset.peaks[idx]]) | numpy.array |
from scvelo.plotting.docs import doc_scatter, doc_params
from scvelo.plotting.utils import *
from inspect import signature
import matplotlib.pyplot as pl
import numpy as np
import pandas as pd
@doc_params(scatter=doc_scatter)
def scatter(
adata=None,
basis=None,
x=None,
y=None,
vkey=None,
color=None,
use_raw=None,
layer=None,
color_map=None,
colorbar=None,
palette=None,
size=None,
alpha=None,
linewidth=None,
linecolor=None,
perc=None,
groups=None,
sort_order=True,
components=None,
projection=None,
legend_loc=None,
legend_loc_lines=None,
legend_fontsize=None,
legend_fontweight=None,
legend_fontoutline=None,
xlabel=None,
ylabel=None,
title=None,
fontsize=None,
figsize=None,
xlim=None,
ylim=None,
add_density=None,
add_assignments=None,
add_linfit=None,
add_polyfit=None,
add_rug=None,
add_text=None,
add_text_pos=None,
add_quiver=None,
quiver_size=None,
add_outline=None,
outline_width=None,
outline_color=None,
n_convolve=None,
smooth=None,
rescale_color=None,
color_gradients=None,
dpi=None,
frameon=None,
zorder=None,
ncols=None,
nrows=None,
wspace=None,
hspace=None,
show=None,
save=None,
ax=None,
**kwargs,
):
"""\
Scatter plot along observations or variables axes.
Arguments
---------
adata: :class:`~anndata.AnnData`
Annotated data matrix.
x: `str`, `np.ndarray` or `None` (default: `None`)
x coordinate
y: `str`, `np.ndarray` or `None` (default: `None`)
y coordinate
{scatter}
Returns
-------
If `show==False` a `matplotlib.Axis`
"""
if adata is None and (x is not None and y is not None):
adata = AnnData(np.stack([x, y]).T)
# restore old conventions
add_assignments = kwargs.pop("show_assignments", add_assignments)
add_linfit = kwargs.pop("show_linear_fit", add_linfit)
add_polyfit = kwargs.pop("show_polyfit", add_polyfit)
add_density = kwargs.pop("show_density", add_density)
add_rug = kwargs.pop("rug", add_rug)
basis = kwargs.pop("var_names", basis)
# keys for figures (fkeys) and multiple plots (mkeys)
fkeys = ["adata", "show", "save", "groups", "ncols", "nrows", "wspace", "hspace"]
fkeys += ["ax", "kwargs"]
mkeys = ["color", "layer", "basis", "components", "x", "y", "xlabel", "ylabel"]
mkeys += ["title", "color_map", "add_text"]
scatter_kwargs = {"show": False, "save": False}
for key in signature(scatter).parameters:
if key not in mkeys + fkeys:
scatter_kwargs[key] = eval(key)
mkwargs = {}
for key in mkeys: # mkwargs[key] = key for key in mkeys
mkwargs[key] = eval("{0}[0] if is_list({0}) else {0}".format(key))
# use c & color and cmap & color_map interchangeably,
# and plot each group separately if groups is 'all'
if "c" in kwargs:
color = kwargs.pop("c")
if "cmap" in kwargs:
color_map = kwargs.pop("cmap")
if "rasterized" not in kwargs:
kwargs["rasterized"] = settings._vector_friendly
if isinstance(color_map, (list, tuple)) and all(
[is_color_like(c) or c == "transparent" for c in color_map]
):
color_map = rgb_custom_colormap(colors=color_map)
if isinstance(groups, str) and groups == "all":
if color is None:
color = default_color(adata)
if is_categorical(adata, color):
vc = adata.obs[color].value_counts()
groups = [[c] for c in vc[vc > 0].index]
if isinstance(add_text, (list, tuple, np.ndarray, np.record)):
add_text = list(np.array(add_text, dtype=str))
# create list of each mkey and check if all bases are valid.
color, layer, components = to_list(color), to_list(layer), to_list(components)
x, y, basis = to_list(x), to_list(y), to_valid_bases_list(adata, basis)
# get multikey (with more than one element)
multikeys = eval(f"[{','.join(mkeys)}]")
if is_list_of_list(groups):
multikeys.append(groups)
key_lengths = np.array([len(key) if is_list(key) else 1 for key in multikeys])
multikey = (
multikeys[np.where(key_lengths > 1)[0][0]] if np.max(key_lengths) > 1 else None
)
# gridspec frame for plotting multiple keys (mkeys: list or tuple)
if multikey is not None:
if np.sum(key_lengths > 1) == 1 and is_list_of_str(multikey):
multikey = unique(multikey) # take unique set if no more than one multikey
if len(multikey) > 20:
raise ValueError("Please restrict the passed list to max 20 elements.")
if ax is not None:
logg.warn("Cannot specify `ax` when plotting multiple panels.")
if is_list(title):
title *= int(np.ceil(len(multikey) / len(title)))
if nrows is None:
ncols = len(multikey) if ncols is None else min(len(multikey), ncols)
nrows = int(np.ceil(len(multikey) / ncols))
else:
ncols = int(np.ceil(len(multikey) / nrows))
if not frameon:
lloc, llines = "legend_loc", "legend_loc_lines"
if lloc in scatter_kwargs and scatter_kwargs[lloc] is None:
scatter_kwargs[lloc] = "none"
if llines in scatter_kwargs and scatter_kwargs[llines] is None:
scatter_kwargs[llines] = "none"
grid_figsize, dpi = get_figure_params(figsize, dpi, ncols)
grid_figsize = (grid_figsize[0] * ncols, grid_figsize[1] * nrows)
fig = pl.figure(None, grid_figsize, dpi=dpi)
hspace = 0.3 if hspace is None else hspace
gspec = pl.GridSpec(nrows, ncols, fig, hspace=hspace, wspace=wspace)
ax = []
for i, gs in enumerate(gspec):
if i < len(multikey):
g = groups[i * (len(groups) > i)] if is_list_of_list(groups) else groups
multi_kwargs = {"groups": g}
for key in mkeys: # multi_kwargs[key] = key[i] if is multikey else key
multi_kwargs[key] = eval(
"{0}[i * (len({0}) > i)] if is_list({0}) else {0}".format(key)
)
ax.append(
scatter(
adata,
ax=pl.subplot(gs),
**multi_kwargs,
**scatter_kwargs,
**kwargs,
)
)
if not frameon and isinstance(ylabel, str):
set_label(xlabel, ylabel, fontsize, ax=ax[0], fontweight="bold")
savefig_or_show(dpi=dpi, save=save, show=show)
if show is False:
return ax
else:
# make sure that there are no more lists, e.g. ['clusters'] becomes 'clusters'
color_map = to_val(color_map)
color, layer, basis = to_val(color), to_val(layer), to_val(basis)
x, y, components = to_val(x), to_val(y), to_val(components)
xlabel, ylabel, title = to_val(xlabel), to_val(ylabel), to_val(title)
# multiple plots within one ax for comma-separated y or layers (string).
if any([isinstance(key, str) and "," in key for key in [y, layer]]):
# comma split
y, layer, color = [
[k.strip() for k in key.split(",")]
if isinstance(key, str) and "," in key
else to_list(key)
for key in [y, layer, color]
]
multikey = y if len(y) > 1 else layer if len(layer) > 1 else None
if multikey is not None:
for i, mi in enumerate(multikey):
ax = scatter(
adata,
x=x,
y=y[i * (len(y) > i)],
color=color[i * (len(color) > i)],
layer=layer[i * (len(layer) > i)],
basis=basis,
components=components,
groups=groups,
xlabel=xlabel,
ylabel="expression" if ylabel is None else ylabel,
color_map=color_map,
title=y[i * (len(y) > i)] if title is None else title,
ax=ax,
**scatter_kwargs,
)
if legend_loc is None:
legend_loc = "best"
if legend_loc and legend_loc != "none":
multikey = [key.replace("Ms", "spliced") for key in multikey]
multikey = [key.replace("Mu", "unspliced") for key in multikey]
ax.legend(multikey, fontsize=legend_fontsize, loc=legend_loc)
savefig_or_show(dpi=dpi, save=save, show=show)
if show is False:
return ax
elif color_gradients is not None and color_gradients is not False:
vals, names, color, scatter_kwargs = gets_vals_from_color_gradients(
adata, color, **scatter_kwargs
)
cols = zip(adata.obs[color].cat.categories, adata.uns[f"{color}_colors"])
c_colors = {cat: col for (cat, col) in cols}
mkwargs.pop("color")
ax = scatter(
adata,
color="grey",
ax=ax,
**mkwargs,
**get_kwargs(scatter_kwargs, {"alpha": 0.05}),
) # background
ax = scatter(
adata,
color=color,
ax=ax,
**mkwargs,
**get_kwargs(scatter_kwargs, {"s": 0}),
) # set legend
sorted_idx = np.argsort(vals, 1)[:, ::-1][:, :2]
for id0 in range(len(names)):
for id1 in range(id0 + 1, len(names)):
cmap = rgb_custom_colormap(
[c_colors[names[id0]], "white", c_colors[names[id1]]],
alpha=[1, 0, 1],
)
mkwargs.update({"color_map": cmap})
c_vals = np.array(vals[:, id1] - vals[:, id0]).flatten()
c_bool = np.array([id0 in c and id1 in c for c in sorted_idx])
if np.sum(c_bool) > 1:
_adata = adata[c_bool] if np.sum(~c_bool) > 0 else adata
mkwargs["color"] = c_vals[c_bool]
ax = scatter(
_adata, ax=ax, **mkwargs, **scatter_kwargs, **kwargs
)
savefig_or_show(dpi=dpi, save=save, show=show)
if show is False:
return ax
# actual scatter plot
else:
# set color, color_map, edgecolor, basis, linewidth, frameon, use_raw
if color is None:
color = default_color(adata, add_outline)
if "cmap" not in kwargs:
kwargs["cmap"] = (
default_color_map(adata, color) if color_map is None else color_map
)
if "s" not in kwargs:
kwargs["s"] = default_size(adata) if size is None else size
if "edgecolor" not in kwargs:
kwargs["edgecolor"] = "none"
is_embedding = ((x is None) | (y is None)) and basis not in adata.var_names
if basis is None and is_embedding:
basis = default_basis(adata)
if linewidth is None:
linewidth = 1
if linecolor is None:
linecolor = "k"
if frameon is None:
frameon = True if not is_embedding else settings._frameon
if isinstance(groups, str):
groups = [groups]
if use_raw is None and basis not in adata.var_names:
use_raw = layer is None and adata.raw is not None
if projection == "3d":
from mpl_toolkits.mplot3d import Axes3D
ax, show = get_ax(ax, show, figsize, dpi, projection)
# phase portrait: get x and y from .layers (e.g. spliced vs. unspliced)
# NOTE(Haotian): true phase portrait plot here
if basis in adata.var_names:
if title is None:
title = basis
if x is None and y is None:
x = default_xkey(adata, use_raw=use_raw)
y = default_ykey(adata, use_raw=use_raw)
elif x is None or y is None:
raise ValueError("Both x and y have to specified.")
if isinstance(x, str) and isinstance(y, str):
layers_keys = list(adata.layers.keys()) + ["X"]
if any([key not in layers_keys for key in [x, y]]):
raise ValueError("Could not find x or y in layers.")
if xlabel is None:
xlabel = x
if ylabel is None:
ylabel = y
# NOTE(Haotian): the data to plot is retrieved here
x = get_obs_vector(adata, basis, layer=x, use_raw=use_raw)
y = get_obs_vector(adata, basis, layer=y, use_raw=use_raw)
if legend_loc is None:
legend_loc = "none"
if use_raw and perc is not None:
ub = np.percentile(x, 99.9 if not isinstance(perc, int) else perc)
ax.set_xlim(right=ub * 1.05)
ub = np.percentile(y, 99.9 if not isinstance(perc, int) else perc)
ax.set_ylim(top=ub * 1.05)
# velocity model fits (full dynamics and steady-state ratios)
if any(["gamma" in key or "alpha" in key for key in adata.var.keys()]):
plot_velocity_fits(
adata,
basis,
vkey,
use_raw,
linewidth,
linecolor,
legend_loc_lines,
legend_fontsize,
add_assignments,
ax=ax,
)
# embedding: set x and y to embedding coordinates
elif is_embedding:
X_emb = adata.obsm[f"X_{basis}"][:, get_components(components, basis)]
x, y = X_emb[:, 0], X_emb[:, 1]
# todo: 3d plotting
# z = X_emb[:, 2] if projection == "3d" and X_emb.shape[1] > 2 else None
elif isinstance(x, str) and isinstance(y, str):
var_names = (
adata.raw.var_names
if use_raw and adata.raw is not None
else adata.var_names
)
if layer is None:
layer = default_xkey(adata, use_raw=use_raw)
x_keys = list(adata.obs.keys()) + list(adata.layers.keys())
is_timeseries = y in var_names and x in x_keys
if xlabel is None:
xlabel = x
if ylabel is None:
ylabel = layer if is_timeseries else y
if title is None:
title = y if is_timeseries else color
if legend_loc is None:
legend_loc = "none"
# gene trend: x and y as gene along obs/layers (e.g. pseudotime)
if is_timeseries:
x = (
adata.obs[x]
if x in adata.obs.keys()
else adata.obs_vector(y, layer=x)
)
y = get_obs_vector(adata, basis=y, layer=layer, use_raw=use_raw)
# get x and y from var_names, var or obs
else:
if x in var_names and y in var_names:
if layer in adata.layers.keys():
x = adata.obs_vector(x, layer=layer)
y = adata.obs_vector(y, layer=layer)
else:
data = adata.raw if use_raw else adata
x, y = data.obs_vector(x), data.obs_vector(y)
elif x in adata.var.keys() and y in adata.var.keys():
x, y = adata.var[x], adata.var[y]
elif x in adata.obs.keys() and y in adata.obs.keys():
x, y = adata.obs[x], adata.obs[y]
elif np.any(
[var_key in x or var_key in y for var_key in adata.var.keys()]
):
var_keys = [
k
for k in adata.var.keys()
if not isinstance(adata.var[k][0], str)
]
var = adata.var[var_keys]
x = var.astype(np.float32).eval(x)
y = var.astype(np.float32).eval(y)
elif np.any(
[obs_key in x or obs_key in y for obs_key in adata.obs.keys()]
):
obs_keys = [
k
for k in adata.obs.keys()
if not isinstance(adata.obs[k][0], str)
]
obs = adata.obs[obs_keys]
x = obs.astype(np.float32).eval(x)
y = obs.astype(np.float32).eval(y)
else:
raise ValueError(
"x or y is invalid! pass valid observation or a gene name"
)
x, y = make_dense(x).flatten(), make_dense(y).flatten()
# convolve along x axes (e.g. pseudotime)
if n_convolve is not None:
vec_conv = np.ones(n_convolve) / n_convolve
y[np.argsort(x)] = np.convolve(y[np.argsort(x)], vec_conv, mode="same")
# if color is set to a cell index, plot that cell on top
if is_int(color) or is_list_of_int(color) and len(color) != len(x):
color = np.array(np.isin(np.arange(len(x)), color), dtype=bool)
size = kwargs["s"] * 2 if | np.sum(color) | numpy.sum |
import matplotlib
matplotlib.use('tkagg')
import matplotlib.pyplot as plt
import sys
import os
import pickle
import seaborn as sns
import scipy.stats as ss
import numpy as np
import core_compute as cc
import core_plot as cp
from scipy.integrate import simps, cumtrapz
def deb_Cp(theta, T):
T = np.array(T)
T[T < 1e-70] = 1e-70
# ub: array of upper bounds for integral
TT = np.array(theta)[..., None] / \
np.array(T)[None, ...]
# nx: number of steps in x integration
nx = 100
# x: array for variable of integration
# integration will be performed along
# last axis of array
x = np.ones(list(TT.shape)+[nx]) * \
np.linspace(0, 1, nx)[None, ...]
x *= x*TT[..., None]
R = 8.314459848 # J/mol*K
expx = np.exp(x)
# if any elements of expx are infinite or equal to 1,
# replace them with zero. This doesn't change the result
# of the integration and avoids numerical issues
expx[expx > 1e100] = 0
expx[expx - 1 < 1e-100] = 0
# perform integration over
# the equispace data points along the last
# axis of the arrays
integrand = (x**4)*expx / (expx-1.)**2
integral = simps(y=integrand, x=x, axis=-1)
return np.squeeze(9*R*((1/TT)**3)*integral)
def feval_Cp(param, T):
theta = param[..., 0]
a_2 = param[..., 1]
a_3 = param[..., 2]
a_4 = param[..., 3]
a_5 = param[..., 4]
# R = 8.314459848 # J/mol*K
# frac = theta/T
# expf = np.exp(frac)
# lowT = 3*R*(frac**2)*(expf/(expf-1)**2)
lowT = deb_Cp(theta, T)
A = lowT + a_2*T + a_3*T**2 + a_4*T**3 + \
a_5*T**4
return A
def feval_Cp_plt(param, T, deb):
# theta = param[..., 0, None]
a_2 = param[..., 1, None]
a_3 = param[..., 2, None]
a_4 = param[..., 3, None]
a_5 = param[..., 4, None]
"""Cp for alpha phase"""
# R = 8.314459848 # J/mol*K
# frac = theta/T
# expf = np.exp(frac)
# lowT = 3*R*(frac**2)*(expf/(expf-1)**2)
lowT = deb
A = lowT + a_2*T + a_3*T**2 + a_4*T**3 + \
a_5*T**4
return A
def feval_H(param, T):
theta = param[..., 0, None]
a_2 = param[..., 1, None]
a_3 = param[..., 2, None]
a_4 = param[..., 3, None]
a_5 = param[..., 4, None]
"""compute the enthalpy for the alpha phase"""
# R = 8.314459848 # J/mol*K
# lowT = 3*R*theta/(np.exp(theta/T)-1.)
# add on 298.15K to T so that H_298.15 = 0 is enforced
T_ = np.array(list(T) + [298.15])
T = np.atleast_1d(T)
T_ = np.atleast_1d(T_)
thetam = np.mean(theta)
# first create equispaced temps at which to eval Cp
T_v1 = np.linspace(1e-10, thetam/8, 30)[:-1]
T_v2 = np.linspace(thetam/8, 3*thetam, 50)[:-1]
T_v3 = np.linspace(3*thetam, 2100, 20)
T_v = np.concatenate([T_v1, T_v2, T_v3])
# evaluate Debye-Cp term at equispaced points
DebCp_v = deb_Cp(theta, T_v)
# evaluate Debye-Cp term at actual temps
DebCp = deb_Cp(theta, T_)
# array for H-Debye terms
DebH = np.zeros((theta.size, T_.size))
# split it up by each temp
for ii in range(T_.size):
# identify number of Temps in T_v less than actual
# temp
idx = np.sum(T_v < T_[ii])
T__ = np.zeros((idx+1))
T__[:idx+1] = T_v[:idx+1]
DebCp_ = np.zeros((theta.size, idx+1))
DebCp_[..., :idx+1] = DebCp_v[..., :idx+1]
# last temp and Cp are for the actual temp
# of interest
T__[-1] = T_[ii]
DebCp_[..., -1] = DebCp[..., ii]
# perform numerical integration
DebH_ = np.squeeze(simps(y=DebCp_, x=T__, axis=-1))
DebH[:, ii] = DebH_
# we subtract debH at 298.15K from debH at all other temps
lowT = | np.squeeze(DebH[..., :-1]) | numpy.squeeze |
# python simulation of draw.sv
import numpy as np
def get_model_matrix(angle, scale, x, y, z):
R = np.array([[np.cos(angle), 0, np.sin(angle), 0], [0, 1, 0, 0], [-1*np.sin(angle), 0, | np.cos(angle) | numpy.cos |
# -*- coding: utf-8 -*-
import math
import os
from collections import defaultdict
from pprint import pprint
import numpy as np
from tqdm import tqdm
from configs import total_info
from utils.misc import get_gt_pre_with_name, get_name_with_group_list, make_dir
from utils.recorders import (
CurveDrawer,
MetricExcelRecorder,
MetricRecorder,
TxtRecorder,
)
"""
Include: Fm Curve/PR Curves/MAE/(max/mean/weighted) Fmeasure/Smeasure/Emeasure
NOTE:
* Our method automatically calculates the intersection of `pre` and `gt`.
But it needs to have uniform naming rules for `pre` and `gt`.
"""
def group_names(names: list) -> dict:
grouped_name_list = defaultdict(list)
for name in names:
group_name, file_name = name.split("/")
grouped_name_list[group_name].append(file_name)
return grouped_name_list
def mean_all_group_metrics(group_metric_recorder: dict):
recorder = defaultdict(list)
for group_name, metrics in group_metric_recorder.items():
for metric_name, metric_array in metrics.items():
recorder[metric_name].append(metric_array)
results = {k: np.mean(np.vstack(v), axis=0) for k, v in recorder.items()}
return results
def cal_all_metrics():
"""
Save the results of all models on different datasets in a `npy` file in the form of a
dictionary.
{
dataset1:{
method1:[(ps, rs), fs],
method2:[(ps, rs), fs],
.....
},
dataset2:{
method1:[(ps, rs), fs],
method2:[(ps, rs), fs],
.....
},
....
}
"""
qualitative_results = defaultdict(dict) # Two curve metrics
quantitative_results = defaultdict(dict) # Six numerical metrics
txt_recoder = TxtRecorder(
txt_path=cfg["record_path"],
resume=cfg["resume_record"],
max_method_name_width=max([len(x) for x in cfg["drawing_info"].keys()]), # 显示完整名字
# max_method_name_width=10, # 指定长度
)
excel_recorder = MetricExcelRecorder(
xlsx_path=cfg["xlsx_path"],
sheet_name=data_type,
row_header=["methods"],
dataset_names=sorted(list(cfg["dataset_info"].keys())),
metric_names=["sm", "wfm", "mae", "adpf", "avgf", "maxf", "adpe", "avge", "maxe"],
)
for dataset_name, dataset_path in cfg["dataset_info"].items():
if dataset_name in cfg["skipped_names"]:
print(f" ++>> {dataset_name} will be skipped.")
continue
txt_recoder.add_row(row_name="Dataset", row_data=dataset_name, row_start_str="\n")
# 获取真值图片信息
gt_info = dataset_path["mask"]
gt_root = gt_info["path"]
gt_ext = gt_info["suffix"]
# 真值名字列表
gt_index_file = dataset_path.get("index_file")
if gt_index_file:
gt_name_list = get_name_with_group_list(data_path=gt_index_file, file_ext=gt_ext)
else:
gt_name_list = get_name_with_group_list(data_path=gt_root, file_ext=gt_ext)
assert len(gt_name_list) > 0, "there is not ground truth."
# ==>> test the intersection between pre and gt for each method <<==
for method_name, method_info in cfg["drawing_info"].items():
method_root = method_info["path_dict"]
method_dataset_info = method_root.get(dataset_name, None)
if method_dataset_info is None:
print(f" ==>> {method_name} does not have results on {dataset_name} <<== ")
continue
# 预测结果存放路径下的图片文件名字列表和扩展名称
pre_ext = method_dataset_info["suffix"]
pre_root = method_dataset_info["path"]
pre_name_list = get_name_with_group_list(data_path=pre_root, file_ext=pre_ext)
# get the intersection
eval_name_list = sorted(list(set(gt_name_list).intersection(set(pre_name_list))))
if len(eval_name_list) == 0:
print(f" ==>> {method_name} does not have results on {dataset_name} <<== ")
continue
grouped_name_list = group_names(names=eval_name_list)
print(
f" ==>> It is evaluating {method_name} with"
f" {len(eval_name_list)} images and {len(grouped_name_list)} groups"
f" (G:{len(gt_name_list)},P:{len(pre_name_list)}) images <<== "
)
total_metric_recorder = {}
inter_group_bar = tqdm(
grouped_name_list.items(), total=len(grouped_name_list), leave=False, ncols=119
)
for group_name, names_in_group in inter_group_bar:
inter_group_bar.set_description(f"({dataset_name}) group => {group_name}")
metric_recoder = MetricRecorder()
intra_group_bar = tqdm(
names_in_group, total=len(names_in_group), leave=False, ncols=119
)
for img_name in intra_group_bar:
intra_group_bar.set_description(f"processing => {img_name}")
img_name = "/".join([group_name, img_name])
gt, pre = get_gt_pre_with_name(
gt_root=gt_root,
pre_root=pre_root,
img_name=img_name,
pre_ext=pre_ext,
gt_ext=gt_ext,
to_normalize=False,
)
metric_recoder.update(pre=pre, gt=gt)
total_metric_recorder[group_name] = metric_recoder.show(bit_num=None)
# 保留原始数据每组的结果
all_results = mean_all_group_metrics(group_metric_recorder=total_metric_recorder)
all_results["meanFm"] = all_results["fm"].mean()
all_results["maxFm"] = all_results["fm"].max()
all_results["meanEm"] = all_results["em"].mean()
all_results["maxEm"] = all_results["em"].max()
all_results = {k: v.round(cfg["bit_num"]) for k, v in all_results.items()}
method_curve = {
"prs": (np.flip(all_results["p"]), np.flip(all_results["r"])),
"fm": | np.flip(all_results["fm"]) | numpy.flip |
# External
import math
import numpy
import matplotlib.pyplot as plt
from matplotlib.colors import LogNorm
from mpl_toolkits.axes_grid1.axes_divider import make_axes_locatable
from matplotlib.offsetbox import AnchoredText
# Local
from .utils import gaussian_fit, freq_content
plt.style.use('seaborn')
plt.rc('font', size=15)
plt.rc('axes', labelsize=15)
plt.rc('legend', fontsize=15)
plt.rc('xtick', labelsize=15)
plt.rc('ytick', labelsize=15)
def full_fiber(data):
# Initialize the figure
fig,ax = plt.subplots(figsize=(9,6))
ax.grid(False)
# Plot original image
plt.imshow(abs(numpy.array(data).T),extent=[0,data.shape[0],data.shape[1]/500,0],cmap='inferno',aspect='auto',norm=LogNorm())
ax.axvline(4650,color='cyan',lw=3)
ax.axvline(4850,color='cyan',lw=3)
ax.axvline(5500,color='yellow',lw=3)
ax.axvline(6000,color='yellow',lw=3)
ax.xaxis.set_ticks_position('top')
ax.xaxis.set_label_position('top')
plt.xlabel('Channels',labelpad=10)
plt.ylabel('Time [second]')
plt.colorbar(pad=0.02,orientation="horizontal").set_label('DAS units (proportional to strain rate)')
plt.tight_layout()
plt.savefig('abs_data.png')
plt.show()
plt.close()
def regions(data1,data2):
# Initialize figure
fig,ax = plt.subplots(1,2,figsize=(18,5.5))
# Plot coherent surface wave patterns
im = ax[0].imshow(data1,extent=[0,data1.shape[1],200,0],cmap='seismic',aspect='auto',vmin=-1000,vmax=1000,interpolation='bicubic')
ax[0].xaxis.set_ticks_position('top')
ax[0].xaxis.set_label_position('top')
ax[0].set_xlabel('Samples',labelpad=10)
ax[0].set_ylabel('Channels')
# Display colorbar
divider = make_axes_locatable(ax[0])
cax = divider.append_axes('bottom', size='5%', pad=0.05)
plt.colorbar(im, pad=0.02, cax=cax, orientation='horizontal').set_label('Raw measurement amplitude')
# Plot non-coherent signals
im = ax[1].imshow(data2,extent=[0,data2.shape[1],200,0],cmap='seismic',aspect='auto',vmin=-1000,vmax=1000,interpolation='bicubic')
ax[1].xaxis.set_ticks_position('top')
ax[1].xaxis.set_label_position('top')
ax[1].set_xlabel('Samples',labelpad=10)
ax[1].set_ylabel('Channels')
# Display colorbar
divider = make_axes_locatable(ax[1])
cax = divider.append_axes('bottom', size='5%', pad=0.05)
plt.colorbar(im, pad=0.02, cax=cax, orientation='horizontal').set_label('Raw measurement amplitude')
# Save and show figure
plt.tight_layout()
plt.savefig('raw_data.pdf')
plt.show()
plt.close()
def plot_dist(data,bins=400,xlim=[-1000,1000]):
fig,ax = plt.subplots(2,1,figsize=(9,8),sharey=True,sharex=True)
for i,order in enumerate([1,2]):
hist = ax[i].hist(data.reshape(numpy.prod(data.shape)),bins=bins,range=xlim,color='white',histtype='stepfilled',edgecolor='black',lw=0.5)
# Fit double gaussian
x = numpy.array([0.5 * (hist[1][i] + hist[1][i+1]) for i in range(len(hist[1])-1)])
y = hist[0]
x, y, chisq, aic, popt = gaussian_fit(x,y,order)
if order==1:
ax[i].plot(x, y[0], lw=2,label='Single-gaussian fit\n$\chi^2_\mathrm{red}=$%.1e / $\mathrm{AIC}=%i$\n$\mu=%.2f, \sigma=%.3f$'%(chisq,aic,popt[1],abs(popt[2])))
if order==2:
ax[i].plot(x, y[0], lw=2,label='Double-gaussian fit\n$\chi^2_\mathrm{red}=$%.1e / $\mathrm{AIC}=%i$'%(chisq,aic))
# Plot first gaussian
# y = gauss_single(x, *popt[:3])
ax[i].plot(x, y[1], lw=2,label=r'$\mu=%.2f, \sigma=%.3f$'%(popt[1],abs(popt[2])))
# Plot second gaussian
# y = gauss_single(x, *popt[3:])
ax[i].plot(x, y[2], lw=2,label=r'$\mu=%.2f, \sigma=%.3f$'%(popt[4],abs(popt[5])))
ax[i].ticklabel_format(axis="y", style="sci", scilimits=(0,0))
ax[i].set_xlim(-1000,1000)
ax[i].legend(loc='upper left')
ax[i].set_ylabel('Density')
plt.xlabel('Raw measurement amplitude')
plt.tight_layout()
plt.savefig('distribution.pdf')
def plot_freq_content(data,img_size=200,sample_rate=500):
plt.rc('font', size=12)
plt.rc('axes', labelsize=12)
plt.rc('legend', fontsize=12)
plt.rc('xtick', labelsize=12)
plt.rc('ytick', labelsize=12)
fig,ax = plt.subplots(4,4,figsize=(12,12))
for n,img in enumerate(data):
ffts, freqs, avg_fft = freq_content(img,img_size,sample_rate)
img_max = abs(img).max()
# Show larger image
ax[0][n].imshow(img,cmap='seismic',extent=[0,img_size,img_size,0],vmin=-img_max,vmax=img_max,interpolation='bicubic')
ax[0][n].set_xlabel('Sample')
if n==0: ax[0][n].set_ylabel('Channel')
# Plotting data distribution
ax[1][n].hist(img.reshape(numpy.prod(img.shape)),bins=50)
at = AnchoredText('$\sigma=%i$'%numpy.std(img),prop=dict(size=12),loc='upper left')
ax[1][n].add_artist(at)
ax[1][n].set_xlabel('Strain Measurement')
if n==0: ax[1][n].set_ylabel('Density')
# D2 and plot FFT for each channel
ax[2][n].imshow(ffts,extent=[0,sample_rate//2,img.shape[0],0],aspect='auto',norm=LogNorm(vmin=ffts.min(),vmax=ffts.max()),cmap='jet')
ax[2][n].set_xlabel('Frequency (Hz)')
if n==0: ax[2][n].set_ylabel('Channels')\
# Plot average amplitude for each frequency
ax[3][n].plot(freqs,avg_fft)
ax[3][n].set_xlabel('Frequency (Hz)')
ax[3][n].set_xlim(0,sample_rate//2)
ax[3][n].axvline(40,ls='--',color='black',lw=1.3)
ax[3][n].set_ylabel('Average Spectral Amplitude')
plt.tight_layout(h_pad=0,w_pad=0)
plt.savefig('signal_types.pdf')
plt.show()
def latent_plot(models,loader):
fig, ax = plt.subplots(3,2,figsize=(10,12),sharex=True,sharey=True)
for n,(i,j) in enumerate([[0,0],[0,1],[1,0],[1,1],[2,0],[2,1]]):
model_epoch = models[n]
model_epoch.eval()
for batch_idx, (data,target) in enumerate(loader):
data = data.float()
z, recon_batch, mu, logvar = model_epoch(data.view(-1, | numpy.prod(data.shape[-2:]) | numpy.prod |
__authors__ = ["<NAME> - ESRF ISDD Advanced Analysis and Modelling"]
__license__ = "MIT"
__date__ = "30-08-2018"
"""
Wiggler code: computes wiggler radiation distributions and samples rays according to them.
Fully replaces and upgrades the shadow3 wiggler model.
The radiation is calculating using sr-xraylib
"""
import numpy
from srxraylib.util.inverse_method_sampler import Sampler1D
from srxraylib.sources.srfunc import wiggler_trajectory, wiggler_spectrum, wiggler_cdf, sync_f
import scipy
from scipy.interpolate import interp1d
import scipy.constants as codata
from shadow4.sources.s4_electron_beam import S4ElectronBeam
from shadow4.sources.s4_light_source import S4LightSource
from shadow4.sources.wiggler.s4_wiggler import S4Wiggler
from shadow4.beam.beam import Beam
# This is similar to sync_f in srxraylib but faster
def sync_f_sigma_and_pi(rAngle, rEnergy):
r""" angular dependency of synchrotron radiation emission
NAME:
sync_f_sigma_and_pi
PURPOSE:
Calculates the function used for calculating the angular
dependence of synchrotron radiation.
CATEGORY:
Mathematics.
CALLING SEQUENCE:
Result = sync_f_sigma_and_pi(rAngle,rEnergy)
INPUTS:
rAngle: (array) the reduced angle, i.e., angle[rads]*Gamma. It can be a
scalar or a vector.
rEnergy: (scalar) a value for the reduced photon energy, i.e.,
energy/critical_energy.
KEYWORD PARAMETERS:
OUTPUTS:
returns the value of the sync_f for sigma and pi polarizations
The result is an array of the same dimension as rAngle.
PROCEDURE:
The number of emitted photons versus vertical angle Psi is
proportional to sync_f, which value is given by the formulas
in the references.
References:
<NAME>, "Spectra and optics of synchrotron radiation"
BNL 50522 report (1976)
<NAME> and <NAME>, Synchrotron Radiation,
Akademik-Verlag, Berlin, 1968
OUTPUTS:
returns the value of the sync_f function
PROCEDURE:
Uses BeselK() function
MODIFICATION HISTORY:
Written by: <NAME>, <EMAIL>, 2002-05-23
2002-07-12 <EMAIL> adds circular polarization term for
wavelength integrated spectrum (S&T formula 5.25)
2012-02-08 <EMAIL>: python version
2019-10-31 <EMAIL> speed-up changes for shadow4
"""
#
# ; For 11 in Pag 6 in Green 1975
#
ji = numpy.sqrt((1.0 + rAngle**2)**3) * rEnergy / 2.0
efe_sigma = scipy.special.kv(2.0 / 3.0, ji) * (1.0 + rAngle**2)
efe_pi = rAngle * scipy.special.kv(1.0 / 3.0, ji) / numpy.sqrt(1.0 + rAngle ** 2) * (1.0 + rAngle ** 2)
return efe_sigma**2,efe_pi**2
class S4WigglerLightSource(S4LightSource):
def __init__(self, name="Undefined", electron_beam=None, magnetic_structure=None):
super().__init__(name,
electron_beam=electron_beam if not electron_beam is None else S4ElectronBeam(),
magnetic_structure=magnetic_structure if not magnetic_structure is None else S4Wiggler())
# results of calculations
self.__result_trajectory = None
self.__result_parameters = None
self.__result_cdf = None
def get_trajectory(self):
return self.__result_trajectory, self.__result_parameters
def __calculate_radiation(self):
wiggler = self.get_magnetic_structure()
electron_beam = self.get_electron_beam()
if wiggler._magnetic_field_periodic == 1:
(traj, pars) = wiggler_trajectory(b_from=0,
inData="",
nPer=wiggler.number_of_periods(),
nTrajPoints=wiggler._NG_J,
ener_gev=electron_beam._energy_in_GeV,
per=wiggler.period_length(),
kValue=wiggler.K_vertical(),
trajFile="",)
elif wiggler._magnetic_field_periodic == 0:
print(">>>>>>>>>>>>>>>>>>>>>>",
"shift_x_flag = ",wiggler._shift_x_flag,
"shift_x_value = ",wiggler._shift_x_value,
"shift_betax_flag = ",wiggler._shift_betax_flag,
"shift_betax_value = ",wiggler._shift_betax_value
)
(traj, pars) = wiggler_trajectory(b_from=1,
inData=wiggler._file_with_magnetic_field,
nPer=1,
nTrajPoints=wiggler._NG_J,
ener_gev=electron_beam._energy_in_GeV,
# per=self.syned_wiggler.period_length(),
# kValue=self.syned_wiggler.K_vertical(),
trajFile="",
shift_x_flag = wiggler._shift_x_flag ,
shift_x_value = wiggler._shift_x_value ,
shift_betax_flag = wiggler._shift_betax_flag ,
shift_betax_value = wiggler._shift_betax_value,)
self.__result_trajectory = traj
self.__result_parameters = pars
# print(">>>>>>>>>> traj pars: ",traj.shape,pars)
#
# plot(traj[1, :], traj[0, :], xtitle="Y", ytitle="X")
# plot(traj[1, :], traj[3, :], xtitle="Y", ytitle="BetaX")
# plot(traj[1, :], traj[6, :], xtitle="Y", ytitle="Curvature")
# plot(traj[1, :], traj[7, :], xtitle="Y", ytitle="B")
# traj[0,ii] = yx[i]
# traj[1,ii] = yy[i]+j * per - start_len
# traj[2,ii] = 0.0
# traj[3,ii] = betax[i]
# traj[4,ii] = betay[i]
# traj[5,ii] = 0.0
# traj[6,ii] = curv[i]
# traj[7,ii] = bz[i]
#
# calculate cdf and write file for Shadow/Source
#
print(">>>>>>>>>>>>>>>>>>>> wiggler._EMIN,wiggler._EMAX,wiggler._NG_E",wiggler._EMIN,wiggler._EMAX,wiggler._NG_E)
self.__result_cdf = wiggler_cdf(self.__result_trajectory,
enerMin=wiggler._EMIN,
enerMax=wiggler._EMAX,
enerPoints=wiggler._NG_E,
outFile="tmp.cdf",
elliptical=False)
def __calculate_rays(self,user_unit_to_m=1.0,F_COHER=0,NRAYS=5000,SEED=123456,EPSI_DX=0.0,EPSI_DZ=0.0,
psi_interval_in_units_one_over_gamma=None,
psi_interval_number_of_points=1001,
verbose=True):
"""
compute the rays in SHADOW matrix (shape (npoints,18) )
:param F_COHER: set this flag for coherent beam
:param user_unit_to_m: default 1.0 (m)
:return: rays, a numpy.array((npoits,18))
"""
if self.__result_cdf is None:
self.__calculate_radiation()
if verbose:
print(">>> Results of calculate_radiation")
print(">>> trajectory.shape: ", self.__result_trajectory.shape)
print(">>> cdf: ", self.__result_cdf.keys())
wiggler = self.get_magnetic_structure()
syned_electron_beam = self.get_electron_beam()
sampled_photon_energy,sampled_theta,sampled_phi = self._sample_photon_energy_theta_and_phi(NRAYS)
if verbose:
print(">>> sampled sampled_photon_energy,sampled_theta,sampled_phi: ",sampled_photon_energy,sampled_theta,sampled_phi)
if SEED != 0:
numpy.random.seed(SEED)
sigmas = syned_electron_beam.get_sigmas_all()
rays = numpy.zeros((NRAYS,18))
#
# sample sizes (cols 1-3)
#
#
if wiggler._FLAG_EMITTANCE:
if numpy.array(numpy.abs(sigmas)).sum() == 0:
wiggler._FLAG_EMITTANCE = False
if wiggler._FLAG_EMITTANCE:
x_electron = numpy.random.normal(loc=0.0,scale=sigmas[0],size=NRAYS)
y_electron = 0.0
z_electron = numpy.random.normal(loc=0.0,scale=sigmas[2],size=NRAYS)
else:
x_electron = 0.0
y_electron = 0.0
z_electron = 0.0
# traj[0,ii] = yx[i]
# traj[1,ii] = yy[i]+j * per - start_len
# traj[2,ii] = 0.0
# traj[3,ii] = betax[i]
# traj[4,ii] = betay[i]
# traj[5,ii] = 0.0
# traj[6,ii] = curv[i]
# traj[7,ii] = bz[i]
PATH_STEP = self.__result_cdf["step"]
X_TRAJ = self.__result_cdf["x"]
Y_TRAJ = self.__result_cdf["y"]
SEEDIN = self.__result_cdf["cdf"]
ANGLE = self.__result_cdf["angle"]
CURV = self.__result_cdf["curv"]
EPSI_PATH = numpy.arange(CURV.size) * PATH_STEP # self._result_trajectory[7,:]
# ! C We define the 5 arrays:
# ! C Y_X(5,N) ---> X(Y)
# ! C Y_XPRI(5,N) ---> X'(Y)
# ! C Y_CURV(5,N) ---> CURV(Y)
# ! C Y_PATH(5,N) ---> PATH(Y)
# ! C F(1,N) contains the array of Y values where the nodes are located.
# CALL PIECESPL(SEED_Y, Y_TEMP, NP_SY, IER)
# CALL CUBSPL (Y_X, X_TEMP, NP_TRAJ, IER)
# CALL CUBSPL (Y_Z, Z_TEMP, NP_TRAJ, IER)
# CALL CUBSPL (Y_XPRI, ANG_TEMP, NP_TRAJ, IER)
# CALL CUBSPL (Y_ZPRI, ANG2_TEMP, NP_TRAJ, IER)
# CALL CUBSPL (Y_CURV, C_TEMP, NP_TRAJ, IER)
# CALL CUBSPL (Y_PATH, P_TEMP, NP_TRAJ, IER)
SEED_Y = interp1d(SEEDIN,Y_TRAJ,kind='linear')
Y_X = interp1d(Y_TRAJ,X_TRAJ,kind='cubic')
Y_XPRI = interp1d(Y_TRAJ,ANGLE,kind='cubic')
Y_CURV = interp1d(Y_TRAJ,CURV,kind='cubic')
Y_PATH = interp1d(Y_TRAJ,EPSI_PATH,kind='cubic')
# ! C+++
# ! C Compute the path length to the middle (origin) of the wiggler.
# ! C We need to know the "center" of the wiggler coordinate.
# ! C input: Y_PATH ---> spline array
# ! C NP_TRAJ ---> # of points
# ! C Y_TRAJ ---> calculation point (ind. variable)
# ! C output: PATH0 ---> value of Y_PATH at X = Y_TRAJ. If
# ! C Y_TRAJ = 0, then PATH0 = 1/2 length
# ! C of trajectory.
# ! C+++
Y_TRAJ = 0.0
# CALL SPL_INT (Y_PATH, NP_TRAJ, Y_TRAJ, PATH0, IER)
PATH0 = Y_PATH(Y_TRAJ)
# ! C
# ! C These flags are set because of the original program structure.
# ! C
# F_PHOT = 0
# F_COLOR = 3
# FSOUR = 3
# FDISTR = 4
ws_ev,ws_f,tmp = wiggler_spectrum(self.__result_trajectory,
enerMin=wiggler._EMIN, enerMax=wiggler._EMAX, nPoints=500,
# per=self.syned_wiggler.period_length(),
electronCurrent=syned_electron_beam._current,
outFile="", elliptical=False)
ws_flux_per_ev = ws_f / (ws_ev*1e-3)
samplerE = Sampler1D(ws_flux_per_ev,ws_ev)
sampled_energies,h,h_center = samplerE.get_n_sampled_points_and_histogram(NRAYS)
###############################################
gamma = syned_electron_beam.gamma()
m2ev = codata.c * codata.h / codata.e
TOANGS = m2ev * 1e10
#####################################################
RAD_MIN = 1.0 / numpy.abs(self.__result_cdf["curv"]).max()
critical_energy = TOANGS * 3.0 * numpy.power(gamma, 3) / 4.0 / numpy.pi / 1.0e10 * (1.0 / RAD_MIN)
if psi_interval_in_units_one_over_gamma is None:
c = numpy.array([-0.3600382, 0.11188709]) # see file fit_psi_interval.py
# x = numpy.log10(self._EMIN / critical_energy)
x = numpy.log10(wiggler._EMIN / (4 * critical_energy)) # the wiggler that does not have an unique
# Ec. To be safe, I use 4 times the
# Ec vale to make the interval wider than for the BM
y_fit = c[1] + c[0] * x
psi_interval_in_units_one_over_gamma = 10 ** y_fit # this is the semi interval
psi_interval_in_units_one_over_gamma *= 4 # doubled interval
if psi_interval_in_units_one_over_gamma < 2:
psi_interval_in_units_one_over_gamma = 2
if verbose:
print(">>> psi_interval_in_units_one_over_gamma: ",psi_interval_in_units_one_over_gamma)
angle_array_mrad = numpy.linspace(-0.5*psi_interval_in_units_one_over_gamma * 1e3 / gamma,
0.5*psi_interval_in_units_one_over_gamma * 1e3 / gamma,
psi_interval_number_of_points)
# a = numpy.linspace(-0.6,0.6,150)
a = angle_array_mrad
#####################################################################
a8 = 1.0
hdiv_mrad = 1.0
# i_a = self.syned_electron_beam._current
#
# fm = sync_f(a*self.syned_electron_beam.gamma()/1e3,eene,polarization=0) * \
# numpy.power(eene,2)*a8*i_a*hdiv_mrad*numpy.power(self.syned_electron_beam._energy_in_GeV,2)
#
# plot(a,fm,title="sync_f")
#
# samplerAng = Sampler1D(fm,a)
#
# sampled_theta,hx,h = samplerAng.get_n_sampled_points_and_histogram(10*NRAYS)
# plot(h,hx)
for itik in range(NRAYS):
# ARG_Y = GRID(2,ITIK)
# CALL SPL_INT (SEED_Y, NP_SY, ARG_Y, Y_TRAJ, IER)
arg_y = numpy.random.random() # ARG_Y[itik]
Y_TRAJ = SEED_Y(arg_y)
# ! <EMAIL> 2014-05-19
# ! in wiggler some problems arise because spl_int
# ! does not return a Y value in the correct range.
# ! In those cases, we make a linear interpolation instead.
# if ((y_traj.le.y_temp(1)).or.(y_traj.gt.y_temp(NP_SY))) then
# y_traj_old = y_traj
# CALL LIN_INT (SEED_Y, NP_SY, ARG_Y, Y_TRAJ, IER)
# print*,'SOURCESYNC: bad y_traj from SPL_INT, corrected with LIN_SPL: ',y_traj_old,'=>',y_traj
# endif
#
# CALL SPL_INT (Y_X, NP_TRAJ, Y_TRAJ, X_TRAJ, IER)
# CALL SPL_INT (Y_XPRI, NP_TRAJ, Y_TRAJ, ANGLE, IER)
# CALL SPL_INT (Y_CURV, NP_TRAJ, Y_TRAJ, CURV, IER)
# CALL SPL_INT (Y_PATH, NP_TRAJ, Y_TRAJ, EPSI_PATH, IER)
# END IF
X_TRAJ = Y_X(Y_TRAJ)
ANGLE = Y_XPRI(Y_TRAJ)
CURV = Y_CURV(Y_TRAJ)
EPSI_PATH = Y_PATH(Y_TRAJ)
# print("\n>>><<<",arg_y,Y_TRAJ,X_TRAJ,ANGLE,CURV,EPSI_PATH)
# EPSI_PATH = EPSI_PATH - PATH0 ! now refer to wiggler's origin
# IF (CURV.LT.0) THEN
# POL_ANGLE = 90.0D0 ! instant orbit is CW
# ELSE
# POL_ANGLE = -90.0D0 ! CCW
# END IF
# IF (CURV.EQ.0) THEN
# R_MAGNET = 1.0D+20
# ELSE
# R_MAGNET = ABS(1.0D0/CURV)
# END IF
# POL_ANGLE = TORAD*POL_ANGLE
EPSI_PATH = EPSI_PATH - PATH0 # now refer to wiggler's origin
if CURV < 0:
POL_ANGLE = 90.0 # instant orbit is CW
else:
POL_ANGLE = -90.0 # CCW
if CURV == 0.0:
R_MAGNET = 1.0e20
else:
R_MAGNET = numpy.abs(1.0/CURV)
POL_ANGLE = POL_ANGLE * numpy.pi / 180.0
# ! C
# ! C Compute the actual distance (EPSI_W*) from the orbital focus
# ! C
EPSI_WX = EPSI_DX + EPSI_PATH
EPSI_WZ = EPSI_DZ + EPSI_PATH
# ! BUG <EMAIL> found that these routine does not make the
# ! calculation correctly. Changed to new one BINORMAL
# !CALL GAUSS (SIGMAX, EPSI_X, EPSI_WX, XXX, E_BEAM(1), istar1)
# !CALL GAUSS (SIGMAZ, EPSI_Z, EPSI_WZ, ZZZ, E_BEAM(3), istar1)
# !
# ! calculation of the electrom beam moments at the current position
# ! (sX,sZ) = (epsi_wx,epsi_ez):
# ! <x2> = sX^2 + sigmaX^2
# ! <x x'> = sX sigmaXp^2
# ! <x'2> = sigmaXp^2 (same for Z)
#
# ! then calculate the new recalculated sigmas (rSigmas) and correlation rho of the
# ! normal bivariate distribution at the point in the electron trajectory
# ! rsigmaX = sqrt(<x2>)
# ! rsigmaXp = sqrt(<x'2>)
# ! rhoX = <x x'>/ (rsigmaX rsigmaXp) (same for Z)
#
# if (abs(sigmaX) .lt. 1e-15) then !no emittance
# sigmaXp = 0.0d0
# XXX = 0.0
# E_BEAM(1) = 0.0
# else
# sigmaXp = epsi_Xold/sigmaX ! true only at waist, use epsi_xOld as it has been redefined :(
# rSigmaX = sqrt( (epsi_wX**2) * (sigmaXp**2) + sigmaX**2 )
# rSigmaXp = sigmaXp
# if (abs(rSigmaX*rSigmaXp) .lt. 1e-15) then !no emittance
# rhoX = 0.0
# else
# rhoX = epsi_wx * sigmaXp**2 / (rSigmaX * rSigmaXp)
# endif
#
# CALL BINORMAL (rSigmaX, rSigmaXp, rhoX, XXX, E_BEAM(1), istar1)
# endif
#
if wiggler._FLAG_EMITTANCE:
# CALL BINORMAL (rSigmaX, rSigmaXp, rhoX, XXX, E_BEAM(1), istar1)
# [ c11 c12 ] [ sigma1^2 rho*sigma1*sigma2 ]
# [ c21 c22 ] = [ rho*sigma1*sigma2 sigma2^2 ]
sigmaX,sigmaXp,sigmaZ,sigmaZp = syned_electron_beam.get_sigmas_all()
epsi_wX = sigmaX * sigmaXp
rSigmaX = numpy.sqrt( (epsi_wX**2) * (sigmaXp**2) + sigmaX**2 )
rSigmaXp = sigmaXp
rhoX = epsi_wX * sigmaXp**2 / (rSigmaX * rSigmaXp)
mean = [0, 0]
cov = [[sigmaX**2, rhoX*sigmaX*sigmaXp], [rhoX*sigmaX*sigmaXp, sigmaXp**2]] # diagonal covariance
sampled_x, sampled_xp = numpy.random.multivariate_normal(mean, cov, 1).T
# plot_scatter(sampled_x,sampled_xp)
XXX = sampled_x
E_BEAM1 = sampled_xp
epsi_wZ = sigmaZ * sigmaZp
rSigmaZ = numpy.sqrt( (epsi_wZ**2) * (sigmaZp**2) + sigmaZ**2 )
rSigmaZp = sigmaZp
rhoZ = epsi_wZ * sigmaZp**2 / (rSigmaZ * rSigmaZp)
mean = [0, 0]
cov = [[sigmaZ**2, rhoZ*sigmaZ*sigmaZp], [rhoZ*sigmaZ*sigmaZp, sigmaZp**2]] # diagonal covariance
sampled_z, sampled_zp = numpy.random.multivariate_normal(mean, cov, 1).T
ZZZ = sampled_z
E_BEAM3 = sampled_zp
else:
sigmaXp = 0.0
XXX = 0.0
E_BEAM1 = 0.0
rhoX = 0.0
sigmaZp = 0.0
ZZZ = 0.0
E_BEAM3 = 0.0
#
# ! C
# ! C For normal wiggler, XXX is perpendicular to the electron trajectory at
# ! C the point defined by (X_TRAJ,Y_TRAJ,0).
# ! C
# IF (F_WIGGLER.EQ.1) THEN ! normal wiggler
# YYY = Y_TRAJ - XXX*SIN(ANGLE)
# XXX = X_TRAJ + XXX*COS(ANGLE)
YYY = Y_TRAJ - XXX * numpy.sin(ANGLE)
XXX = X_TRAJ + XXX * numpy.cos(ANGLE)
rays[itik,0] = XXX
rays[itik,1] = YYY
rays[itik,2] = ZZZ
#
# directions
#
# ! C
# ! C Synchrotron source
# ! C Note. The angle of emission IN PLANE is the same as the one used
# ! C before. This will give rise to a source curved along the orbit.
# ! C The elevation angle is instead characteristic of the SR distribution.
# ! C The electron beam emittance is included at this stage. Note that if
# ! C EPSI = 0, we'll have E_BEAM = 0.0, with no changes.
# ! C
# IF (F_WIGGLER.EQ.3) ANGLE=0 ! Elliptical Wiggler.
# ANGLEX = ANGLE + E_BEAM(1)
# DIREC(1) = TAN(ANGLEX)
# IF (R_ALADDIN.LT.0.0D0) DIREC(1) = - DIREC(1)
# DIREC(2) = 1.0D0
# ARG_ANG = GRID(6,ITIK)
ANGLEX = ANGLE + E_BEAM1
DIREC1 = numpy.tan(ANGLEX)
DIREC2 = 1.0
# ! C
# ! C In the case of SR, we take into account the fact that the electron
# ! C trajectory is not orthogonal to the field. This will give a correction
# ! C to the photon energy. We can write it as a correction to the
# ! C magnetic field strength; this will linearly shift the critical energy
# ! C and, with it, the energy of the emitted photon.
# ! C
# E_TEMP(3) = TAN(E_BEAM(3))/COS(E_BEAM(1))
# E_TEMP(2) = 1.0D0
# E_TEMP(1) = TAN(E_BEAM(1))
# CALL NORM (E_TEMP,E_TEMP)
# CORREC = SQRT(1.0D0-E_TEMP(3)**2)
# 4400 CONTINUE
E_TEMP3 = numpy.tan(E_BEAM3)/numpy.cos(E_BEAM1)
E_TEMP2 = 1.0
E_TEMP1 = numpy.tan(E_BEAM1)
e_temp_norm = numpy.sqrt( E_TEMP1**2 + E_TEMP2**2 + E_TEMP3**2)
E_TEMP3 /= e_temp_norm
E_TEMP2 /= e_temp_norm
E_TEMP1 /= e_temp_norm
CORREC = numpy.sqrt(1.0 - E_TEMP3**2)
# IF (FDISTR.EQ.6) THEN
# CALL ALADDIN1 (ARG_ANG,ANGLEV,F_POL,IER)
# Q_WAVE = TWOPI*PHOTON(1)/TOCM*CORREC
# POL_DEG = ARG_ANG
# ELSE IF (FDISTR.EQ.4) THEN
# ARG_ENER = WRAN (ISTAR1)
# RAD_MIN = ABS(R_MAGNET)
#
# i1 = 1
# CALL WHITE &
# (RAD_MIN,CORREC,ARG_ENER,ARG_ANG,Q_WAVE,ANGLEV,POL_DEG,i1)
# END IF
RAD_MIN = numpy.abs(R_MAGNET)
# CALL WHITE (RAD_MIN,CORREC,ARG_ENER,ARG_ANG,Q_WAVE,ANGLEV,POL_DEG,i1)
ARG_ANG = numpy.random.random()
ARG_ENER = numpy.random.random()
# print(" >> R_MAGNET, DIREC",R_MAGNET,DIREC1,DIREC2)
# print(" >> RAD_MIN,CORREC,ARG_ENER,ARG_ANG,",RAD_MIN,CORREC,ARG_ENER,ARG_ANG)
#######################################################################
# gamma = self.syned_electron_beam.gamma()
# m2ev = codata.c * codata.h / codata.e
# TOANGS = m2ev * 1e10
# critical_energy = TOANGS*3.0*numpy.power(gamma,3)/4.0/numpy.pi/1.0e10*(1.0/RAD_MIN)
# sampled_photon_energy = sampled_energies[itik]
# wavelength = codata.h * codata.c / codata.e /sampled_photon_energy
# Q_WAVE = 2 * numpy.pi / (wavelength*1e2)
# print(" >> PHOTON ENERGY, Ec, lambda, Q: ",sampled_photon_energy,critical_energy,wavelength*1e10,Q_WAVE)
###################################################################################
sampled_photon_energy = sampled_energies[itik]
# wavelength = codata.h * codata.c / codata.e /sampled_photon_energy
critical_energy = TOANGS * 3.0 * numpy.power(gamma, 3) / 4.0 / numpy.pi / 1.0e10 * (1.0 / RAD_MIN)
eene = sampled_photon_energy / critical_energy
# TODO: remove old after testing...
method = "new"
if method == "old":
# fm = sync_f(a*1e-3*self.syned_electron_beam.gamma(),eene,polarization=0) * \
# numpy.power(eene,2)*a8*self.syned_electron_beam._current*hdiv_mrad * \
# numpy.power(self.syned_electron_beam._energy_in_GeV,2)
fm_s = sync_f(a*1e-3*self.syned_electron_beam.gamma(),eene,polarization=1) * \
numpy.power(eene,2)*a8*self.syned_electron_beam._current*hdiv_mrad * \
numpy.power(self.syned_electron_beam._energy_in_GeV,2)
fm_p = sync_f(a*1e-3*self.syned_electron_beam.gamma(),eene,polarization=2) * \
numpy.power(eene,2)*a8*self.syned_electron_beam._current*hdiv_mrad * \
numpy.power(self.syned_electron_beam._energy_in_GeV,2)
else:
fm_s , fm_p = sync_f_sigma_and_pi(a*1e-3*syned_electron_beam.gamma(),eene)
cte = eene ** 2 * a8 * syned_electron_beam._current * hdiv_mrad * syned_electron_beam._energy_in_GeV ** 2
fm_s *= cte
fm_p *= cte
fm = fm_s + fm_p
fm_pol = numpy.zeros_like(fm)
for i in range(fm_pol.size):
if fm[i] == 0.0:
fm_pol[i] = 0
else:
fm_pol[i] = fm_s[i] / fm[i]
fm.shape = -1
fm_s.shape = -1
fm_pol.shape = -1
pol_deg_interpolator = interp1d(a*1e-3,fm_pol)
samplerAng = Sampler1D(fm,a*1e-3)
# samplerPol = Sampler1D(fm_s/fm,a*1e-3)
# plot(a*1e-3,fm_s/fm)
if fm.min() == fm.max():
print("Warning: cannot compute divergence for ray index %d"%itik)
sampled_theta = 0.0
else:
sampled_theta = samplerAng.get_sampled(ARG_ENER)
sampled_pol_deg = pol_deg_interpolator(sampled_theta)
# print("sampled_theta: ",sampled_theta, "sampled_energy: ",sampled_photon_energy, "sampled pol ",sampled_pol_deg)
ANGLEV = sampled_theta
ANGLEV += E_BEAM3
# IF (ANGLEV.LT.0.0) I_CHANGE = -1
# ANGLEV = ANGLEV + E_BEAM(3)
# ! C
# ! C Test if the ray is within the specified limits
# ! C
# IF (FGRID.EQ.0.OR.FGRID.EQ.2) THEN
# IF (ANGLEV.GT.VDIV1.OR.ANGLEV.LT.-VDIV2) THEN
# ARG_ANG = WRAN(ISTAR1)
# ! C
# ! C If it is outside the range, then generate another ray.
# ! C
# GO TO 4400
# END IF
# END IF
# DIREC(3) = TAN(ANGLEV)/COS(ANGLEX)
DIREC3 = numpy.tan(ANGLEV) / | numpy.cos(ANGLEX) | numpy.cos |
# Importação das bibliotecas
import rasterio as rst
import matplotlib.pyplot as plt
import numpy as np
import os
# As bibliotecas importadas abaixo são funções dos outros módulos presentes no pacote contraste
from contraste.RaizQuadrada import RQ
from contraste.Negativo import neg
from contraste.Linear import lin
from contraste.MinMax import mm
from contraste.Quadratico import Qd
from contraste.Equalizacao import cdf, df, equalize_image
#Definindo a variável CURR_DIR que receberá o path do diretório atual, com o objetivo de listar os arquivos .TIF no display
CURR_DIR = os.getcwd()
#################################################################################
#################################################################################
#BLOCO DE CÓDIGO RESPONSÁVEL PELA APLICAÇÃO DAS FUNÇÕES DE CONTRASTE OTIMIZADO POR CLASSE E PERSONALIZADO POR CLASSE
# Definindo a função PorClasse
def PORCLASSE():
### Bloco de código responsável por listar os arquivos .TIF (imagens) do diretório atual e exibi-los para o usuário escolher qual
### imagem ele deseja aplicar o contraste
lista_arqs = [arq for arq in os.listdir(CURR_DIR)] # armazena em variável os arquivos presentes no diretório atual
arquivos_tif = [a for a in lista_arqs if a[-4:] == '.tif'] # armazena em variável os arquivos .TIF do diretório atual
tam = len(arquivos_tif) #Obtem o tamanho da lista de arquivos .TIF
lista_pos_arquivos = [] #cria uma lista em branco para receber posteriormente a posição do arquivo na lista
print('Arquivos .TIF listados no diretório raiz:') #printa para o usuário o cabeçalho da mensagem de arquivos .TIF
for pos, arq in zip(range(1, tam + 1), arquivos_tif): #laço for que adiciona na lista criada acima a posição a partir de 1 do arquivo .TIF a lista
lista_pos_arquivos.append(str(pos))
print(pos, '-', arq) #printa na tela após a msg de cabeçalho os arquivos .TIF com um valor numérico sequencial
image_pos = input('Entre com o número associado à imagem de satélite, de acordo com a lista acima: ') #input para o usuário escolher através do número sequencial qual arquivo ele deseja para entrada da imagem de satélite
while image_pos not in lista_pos_arquivos: #laço criado para valores numéricos diferentes do armazenado na lista de posições
image_pos = input('Valor não encontrado. Entre com o número associado à imagem de satélite: ') #msg para nova entrada de valores
for pos, arq in zip(range(1, tam + 1), arquivos_tif): #novo laço for que armazena na variável image o nome do arquivo de imagem associada a posição na lista de arquivos
if image_pos == str(pos):
image = arq
classe_pos = input('Entre com o número associado à imagem classificada - Mapbiomas, de acordo com a lista acima: ') #input para o usuário escolher através do número sequencial qual arquivo ele deseja para entrada da imagem do Mapbiomas
while classe_pos not in lista_pos_arquivos: #laço criado para valores numéricos diferentes do armazenado na lista de posições
classe_pos = input('Valor não encontrado. Entre com o número associado à imagem classificada - Mapbiomas: ') #msg para nova entrada de valores
for pos, arq in zip(range(1, tam + 1), arquivos_tif): #novo laço for que armazena na variável image o nome do arquivo de imagem associada a posição na lista de arquivos
if classe_pos == str(pos):
classe = arq
#Abertura das imagens L8 e Mapbiomas e posterior leitura de cada uma das bandas através da biblioteca rasterio
mapbiomas = rst.open(classe) #abertura da imagem Mapbiomas
L8 = rst.open(image) #abertura da imagem L8
banda_classificada_array = mapbiomas.read(1) #leitura da banda da imagem Mapbiomas
# leitura das bandas da imagem L8
red = L8.read(1)
nir = L8.read(2)
swir = L8.read(3)
Ored = L8.read(1)
Onir = L8.read(2)
Oswir = L8.read(3)
## obter os mínimos e os máximos de cada banda do L8
min_red = red.min()
max_red = red.max()
min_nir = nir.min()
max_nir = nir.max()
min_swir = swir.min()
max_swir = swir.max()
#Armazena em variáveis o shape da dimensão 0 e 1 do array da imagem (essa informação será usada no laço que percorrerá a imagem, modificando os valores do pixel após aplicação do contraste)
linhas = red.shape[0]
colunas = red.shape[1]
## array para visualização de falsa-cor sem contraste
array_rgb = np.zeros((linhas, colunas, 3))
## valores entre 0-1
array_rgb[:, :, 0] = swir / 65535
array_rgb[:, :, 1] = nir / 65535
array_rgb[:, :, 2] = red / 65535
# criando variáveis para aplicação do contraste de Equalização
fered = equalize_image(red)
fenir = equalize_image(nir)
feswir = equalize_image(swir)
# Entrada de teclado do usuário para escolher entre o contraste otimizado ou personalizado
escolha = input('Você deseja aplicar um contraste otimizado por classe ou personalizado? Digite 1 para otimizado e 2 para personalizado: ')
while escolha != '1' and escolha != '2': #laço criado para valores numéricos diferentes do armazenado entrada de teclado da escolha do contraste
escolha = input('Valor incorreto. Entre com 1 para otimizado e 2 para personalizado: ')
###########################################################################################
# BLOCO DE CÓDIGO DA APLICAÇÃO DO CONTRASTE OTIMIZADO
if escolha == '1':
# printa a msg de executando, para o usuário entender que o programa está sendo executado
print('EXECUTANDO...')
# laço for que aplica a função de contraste otimizado para todas as classes percorrendo o array
for i in range(banda_classificada_array.shape[0]):
for j in range(banda_classificada_array.shape[1]):
if banda_classificada_array[i][j] == 3:
# aplica o contraste Linear para a classe 3 (Formação Florestal)
red[i][j] = lin(red[i][j], max_red, min_red)
nir[i][j] = lin(nir[i][j], max_nir, min_nir)
swir[i][j] = lin(swir[i][j], max_swir, min_swir)
elif banda_classificada_array[i][j] == 12:
# aplica o contraste MinMax para a classe 12 (Formação Natural não Florestal)
red[i][j] = mm(red[i][j], max_red, min_red)
nir[i][j] = mm(nir[i][j], max_nir, min_nir)
swir[i][j] = mm(swir[i][j], max_swir, min_swir)
elif banda_classificada_array[i][j] == 15 or 33:
# aplica o contraste equalização para as classes 15 ou 33 (classe 15: Agropecuária; classe 33: Corpos dágua)
red[i][j] = fered[i][j]
nir[i][j] = fenir[i][j]
swir[i][j] = feswir[i][j]
elif banda_classificada_array[i][j] == 25:
# aplica o contraste MinMax para a classe 25 (Área não Vegetada)
red[i][j] = mm(red[i][j], max_red, min_red)
nir[i][j] = mm(nir[i][j], max_nir, min_nir)
swir[i][j] = mm(swir[i][j], max_swir, min_swir)
# printa a msg de finalização da aplicação do contraste no array
print('FINALIZADO!!!')
# Usa a matplotlib para plotar as duas imagens (a sem contraste e a com contraste otimizado)
# montando a composição colorida falsa-cor 543
# array para visualização de falsa-cor com contraste
array_rgb_contraste = np.zeros((linhas, colunas, 3))
array_rgb_contraste[:, :, 0] = swir / 65535
array_rgb_contraste[:, :, 1] = nir / 65535
array_rgb_contraste[:, :, 2] = red / 65535
# Computa os histogramas para as 3 bandas original e com contraste
red_ori, x = np.histogram(Ored, bins=np.arange(65535))
nir_ori, x = np.histogram(Onir, bins=np.arange(65535))
swir_ori, x = np.histogram(Oswir, bins=np.arange(65535))
red_cont, x = np.histogram(red, bins=np.arange(65535))
nir_cont, x = np.histogram(nir, bins= | np.arange(65535) | numpy.arange |
from sklearn.model_selection import KFold, cross_val_score
from sklearn.metrics import mean_squared_error
from scipy.stats.stats import pearsonr
import numpy as np
from sklearn.svm import SVR
import datasetUtils as dsu
import embeddings
import sys
import os
def pccMean(arr):
pcc_only = np.array(list(scor[0] for scor in arr))
pcc_only = pcc_only[np.where(~np.isnan(pcc_only))]
if len(pcc_only) != 0:
mean_score = np.mean(pcc_only)
else: #all elements are nan
mean_score = "nan"
return mean_score
#configs
post_threshold = 3
#parse cmd arguments
if len(sys.argv) != 5 or sys.argv[1] not in ['O','C','E','A','N','o','c','e','a','n'] or sys.argv[2] not in ['fasttext', 'dataset9'] or not os.path.exists(sys.argv[3]) or sys.argv[4] not in ['True', 'False', 'yes', 'no']:
print("Usage:", sys.argv[0], "<BIG5_trait> <embeddings_dataset> <dataset_path> <shuffle_data>")
print("\tBIG5_trait: [O, C, E, A, N, o, c, e, a, n]")
print("\tembeddings_dataset: [fasttext, dataset9]")
print("\tdataset_path: [path/to/the/file]")
print("\tshuffle_data: [yes, no], [True, False]")
sys.exit(1)
else:
big5 = sys.argv[1].upper()
dataset = sys.argv[2]
dataset_path = sys.argv[3]
shuffle = sys.argv[4]
posts = []
yO = []
yC = []
yE = []
yA = []
yN = []
print("Loading myPersonality...")
[posts, yO, yC, yE, yA, yN] = dsu.readMyPersonality()
print("Loading embeddings dataset...")
if dataset == 'fasttext':
transform = True
wordDictionary = dsu.parseFastText(dataset_path)
else:
transform = False
wordDictionary = dsu.loadEmbeddingsDataset(dataset_path)
print("Data successfully loaded.")
filename = "tuning_SVM_"+big5+"_"+dataset
if shuffle == 'True' or shuffle == 'yes' or shuffle == 'true':
s = np.arange(posts.shape[0])
np.random.shuffle(s)
posts = posts[s]
yO = yO[s]
yC = yC[s]
yE = yE[s]
yA = yA[s]
yN = yN[s]
filename = filename + "_shuffle"
print("Data shuffled.")
else:
filename = filename + "_noShuffle"
pcc_filename = filename + "_pcc.txt"
filename = filename + ".csv"
#only for test
#subsetSize = len(sumE)
subsetSize = 100
posts = posts[0:subsetSize]
yO = yO[0:subsetSize]
yC = yC[0:subsetSize]
yE = yE[0:subsetSize]
yA = yA[0:subsetSize]
yN = yN[0:subsetSize]
#save lists because transformTextForTraining() changes them
old_yO = yO
old_yC = yC
old_yE = yE
old_yA = yA
old_yN = yN
[sumE, yO, yC, yE, yA, yN] = embeddings.transformTextForTraining(wordDictionary, post_threshold, posts, old_yO, old_yC, old_yE, old_yA, old_yN, "sum", transform)
maxE = embeddings.transformTextForTraining(wordDictionary, post_threshold, posts, old_yO, old_yC, old_yE, old_yA, old_yN, "max", transform)[0]
minE = embeddings.transformTextForTraining(wordDictionary, post_threshold, posts, old_yO, old_yC, old_yE, old_yA, old_yN, "min", transform)[0]
avgE = embeddings.transformTextForTraining(wordDictionary, post_threshold, posts, old_yO, old_yC, old_yE, old_yA, old_yN, "avg", transform)[0]
conE = embeddings.transformTextForTraining(wordDictionary, post_threshold, posts, old_yO, old_yC, old_yE, old_yA, old_yN, "conc", transform)[0]
if big5 == 'O':
labels = yO
elif big5 == 'C':
labels = yC
elif big5 == 'E':
labels = yE
elif big5 == 'A':
labels = yA
elif big5 == 'N':
labels = yN
if not os.path.exists("Results"):
os.makedirs("Results")
try:
os.remove("Results/"+filename)
except FileNotFoundError:
pass
try:
os.remove("Results/"+pcc_filename)
except FileNotFoundError:
pass
j = 1
k_fold = KFold(n_splits=10)
for data in [sumE, maxE, minE, avgE, conE]:
if j==1:
method = "sum"
print("computing results for sum...")
elif j==2:
method = "max"
print("computing results for max...")
elif j==3:
method = "min"
print("computing results for min...")
elif j==4:
method = "avg"
print("computing results for avg...")
elif j==5:
method = "conc"
print("computing results for concat...")
j += 1
linear = np.zeros([3,10,2], dtype=np.float)
poly_c1_d2 = np.zeros([3,10,2], dtype=np.float)
poly_c10_d2 = np.zeros([3,10,2], dtype=np.float)
poly_c100_d2 = np.zeros([3,10,2], dtype=np.float)
poly_c1_d3 = np.zeros([3,10,2], dtype=np.float)
poly_c10_d3 = np.zeros([3,10,2], dtype=np.float)
poly_c100_d3 = np.zeros([3,10,2], dtype=np.float)
rbf_g001_c1 = np.zeros([3,10,2], dtype=np.float)
rbf_g001_c10 = np.zeros([3,10,2], dtype=np.float)
rbf_g001_c100 = np.zeros([3,10,2], dtype=np.float)
rbf_g01_c1 = np.zeros([3,10,2], dtype=np.float)
rbf_g01_c10 = np.zeros([3,10,2], dtype=np.float)
rbf_g01_c100 = np.zeros([3,10,2], dtype=np.float)
rbf_g1_c1 = np.zeros([3,10,2], dtype=np.float)
rbf_g1_c10 = np.zeros([3,10,2], dtype=np.float)
rbf_g1_c100 = | np.zeros([3,10,2], dtype=np.float) | numpy.zeros |
import pytest
import mxnet as mx
from mxnet import nd
import numpy as np
from rl_coach.architectures.mxnet_components.utils import *
@pytest.mark.unit_test
def test_to_mx_ndarray():
# scalar
assert to_mx_ndarray(1.2) == nd.array([1.2])
# list of one scalar
assert to_mx_ndarray([1.2]) == [nd.array([1.2])]
# list of multiple scalars
assert to_mx_ndarray([1.2, 3.4]) == [nd.array([1.2]), nd.array([3.4])]
# list of lists of scalars
assert to_mx_ndarray([[1.2], [3.4]]) == [[nd.array([1.2])], [nd.array([3.4])]]
# numpy
assert np.array_equal(to_mx_ndarray(np.array([[1.2], [3.4]])).asnumpy(), nd.array([[1.2], [3.4]]).asnumpy())
# tuple
assert to_mx_ndarray(((1.2,), (3.4,))) == ((nd.array([1.2]),), (nd.array([3.4]),))
@pytest.mark.unit_test
def test_asnumpy_or_asscalar():
# scalar float32
assert asnumpy_or_asscalar(nd.array([1.2])) == np.float32(1.2)
# scalar int32
assert asnumpy_or_asscalar(nd.array([2], dtype=np.int32)) == np.int32(2)
# list of one scalar
assert asnumpy_or_asscalar([nd.array([1.2])]) == [np.float32(1.2)]
# list of multiple scalars
assert asnumpy_or_asscalar([nd.array([1.2]), nd.array([3.4])]) == [np.float32([1.2]), np.float32([3.4])]
# list of lists of scalars
assert asnumpy_or_asscalar([[nd.array([1.2])], [nd.array([3.4])]]) == [[np.float32([1.2])], [np.float32([3.4])]]
# tensor
assert np.array_equal(asnumpy_or_asscalar(nd.array([[1.2], [3.4]])), np.array([[1.2], [3.4]], dtype=np.float32))
# tuple
assert (asnumpy_or_asscalar(((nd.array([1.2]),), (nd.array([3.4]),))) ==
(( | np.array([1.2], dtype=np.float32) | numpy.array |
import os
import time
import torch
import numpy as np
from torch.autograd import Variable
import scipy
import cv2
import glob
import random
import math
def visual_img(img, folder = 'temp',name="0.png"):
scipy.misc.imsave(os.path.join(folder,name),img)
def visual_kp_in_img(img, kp, size = 4, folder = 'temp', name = "kp_in_img_0.png"):
# kp shape: objXnum_kpX2
for obj_id, obj in enumerate(kp):
b, g, r = get_class_colors(obj_id)
for xy in obj:
temp_x = int(xy[0]*img.shape[1])
temp_y = int(xy[1]*img.shape[0])
for i in range(temp_x-size, temp_x+size):
if i<0 or i > img.shape[1] -1 :continue
for j in range(temp_y-size, temp_y+size):
if j<0 or j> img.shape[0] -1 :continue
img[j][i][0] = r
img[j][i][1] = g
img[j][i][2] = b
scipy.misc.imsave(os.path.join(folder, name), img)
def get_class_colors(class_id):
colordict = {'gray': [128, 128, 128], 'silver': [192, 192, 192], 'black': [0, 0, 0],
'maroon': [128, 0, 0], 'red': [255, 0, 0], 'purple': [128, 0, 128], 'fuchsia': [255, 0, 255],
'green': [0, 128, 0],
'lime': [0, 255, 0], 'olive': [128, 128, 0], 'yellow': [255, 255, 0], 'navy': [0, 0, 128],
'blue': [0, 0, 255],
'teal': [0, 128, 128], 'aqua': [0, 255, 255], 'orange': [255, 165, 0], 'indianred': [205, 92, 92],
'lightcoral': [240, 128, 128], 'salmon': [250, 128, 114], 'darksalmon': [233, 150, 122],
'lightsalmon': [255, 160, 122], 'crimson': [220, 20, 60], 'firebrick': [178, 34, 34],
'darkred': [139, 0, 0],
'pink': [255, 192, 203], 'lightpink': [255, 182, 193], 'hotpink': [255, 105, 180],
'deeppink': [255, 20, 147],
'mediumvioletred': [199, 21, 133], 'palevioletred': [219, 112, 147], 'coral': [255, 127, 80],
'tomato': [255, 99, 71], 'orangered': [255, 69, 0], 'darkorange': [255, 140, 0], 'gold': [255, 215, 0],
'lightyellow': [255, 255, 224], 'lemonchiffon': [255, 250, 205],
'lightgoldenrodyellow': [250, 250, 210],
'papayawhip': [255, 239, 213], 'moccasin': [255, 228, 181], 'peachpuff': [255, 218, 185],
'palegoldenrod': [238, 232, 170], 'khaki': [240, 230, 140], 'darkkhaki': [189, 183, 107],
'lavender': [230, 230, 250], 'thistle': [216, 191, 216], 'plum': [221, 160, 221],
'violet': [238, 130, 238],
'orchid': [218, 112, 214], 'magenta': [255, 0, 255], 'mediumorchid': [186, 85, 211],
'mediumpurple': [147, 112, 219], 'blueviolet': [138, 43, 226], 'darkviolet': [148, 0, 211],
'darkorchid': [153, 50, 204], 'darkmagenta': [139, 0, 139], 'indigo': [75, 0, 130],
'slateblue': [106, 90, 205],
'darkslateblue': [72, 61, 139], 'mediumslateblue': [123, 104, 238], 'greenyellow': [173, 255, 47],
'chartreuse': [127, 255, 0], 'lawngreen': [124, 252, 0], 'limegreen': [50, 205, 50],
'palegreen': [152, 251, 152],
'lightgreen': [144, 238, 144], 'mediumspringgreen': [0, 250, 154], 'springgreen': [0, 255, 127],
'mediumseagreen': [60, 179, 113], 'seagreen': [46, 139, 87], 'forestgreen': [34, 139, 34],
'darkgreen': [0, 100, 0], 'yellowgreen': [154, 205, 50], 'olivedrab': [107, 142, 35],
'darkolivegreen': [85, 107, 47], 'mediumaquamarine': [102, 205, 170], 'darkseagreen': [143, 188, 143],
'lightseagreen': [32, 178, 170], 'darkcyan': [0, 139, 139], 'cyan': [0, 255, 255],
'lightcyan': [224, 255, 255],
'paleturquoise': [175, 238, 238], 'aquamarine': [127, 255, 212], 'turquoise': [64, 224, 208],
'mediumturquoise': [72, 209, 204], 'darkturquoise': [0, 206, 209], 'cadetblue': [95, 158, 160],
'steelblue': [70, 130, 180], 'lightsteelblue': [176, 196, 222], 'powderblue': [176, 224, 230],
'lightblue': [173, 216, 230], 'skyblue': [135, 206, 235], 'lightskyblue': [135, 206, 250],
'deepskyblue': [0, 191, 255], 'dodgerblue': [30, 144, 255], 'cornflowerblue': [100, 149, 237],
'royalblue': [65, 105, 225], 'mediumblue': [0, 0, 205], 'darkblue': [0, 0, 139],
'midnightblue': [25, 25, 112],
'cornsilk': [255, 248, 220], 'blanchedalmond': [255, 235, 205], 'bisque': [255, 228, 196],
'navajowhite': [255, 222, 173], 'wheat': [245, 222, 179], 'burlywood': [222, 184, 135],
'tan': [210, 180, 140],
'rosybrown': [188, 143, 143], 'sandybrown': [244, 164, 96], 'goldenrod': [218, 165, 32],
'darkgoldenrod': [184, 134, 11], 'peru': [205, 133, 63], 'chocolate': [210, 105, 30],
'saddlebrown': [139, 69, 19],
'sienna': [160, 82, 45], 'brown': [165, 42, 42], 'snow': [255, 250, 250], 'honeydew': [240, 255, 240],
'mintcream': [245, 255, 250], 'azure': [240, 255, 255], 'aliceblue': [240, 248, 255],
'ghostwhite': [248, 248, 255], 'whitesmoke': [245, 245, 245], 'seashell': [255, 245, 238],
'beige': [245, 245, 220], 'oldlace': [253, 245, 230], 'floralwhite': [255, 250, 240],
'ivory': [255, 255, 240],
'antiquewhite': [250, 235, 215], 'linen': [250, 240, 230], 'lavenderblush': [255, 240, 245],
'mistyrose': [255, 228, 225], 'gainsboro': [220, 220, 220], 'lightgrey': [211, 211, 211],
'darkgray': [169, 169, 169], 'dimgray': [105, 105, 105], 'lightslategray': [119, 136, 153],
'slategray': [112, 128, 144], 'darkslategray': [47, 79, 79], 'white': [255, 255, 255]}
colornames = list(colordict.keys())
assert (class_id < len(colornames))
r, g, b = colordict[colornames[class_id]]
return b, g, r # for OpenCV
def vertices_reprojection(vertices, rt, k):
p = np.matmul(k, | np.matmul(rt[:3,0:3], vertices.T) | numpy.matmul |
#!/usr/bin/env python
"""
Interpolation of scattered data using ordinary kriging/collocation
The program uses nearest neighbors interpolation and selects data from eight
quadrants around the prediction point and uses a third-order Gauss-Markov
covariance model, with a correlation length defined by the user.
Provides the possibility of pre-cleaning of the data using a spatial n-sigma
filter before interpolation.
Observations with provided noise/error estimates (for each observation) are
added to the diagonal of the covariance matrix if provided. User can also
provide a constant rms-noise added to the diagonal.
Takes as input a h5df file with needed data in geographical coordinates
and a-priori error if needed. The user provides the wanted projection
using the EPSG projection format.
Output consists of an hdf5 file containing the predictions, rmse and the
number of points used in the prediction, and the epsg number for the
projection.
Notes:
If both the a-priori errors are provided and constant rms all values
smaller then provided rms is set to this value providing a minimum
error for the observations.
To reduce the impact of highly correlated along-track measurements
(seen as streaks in the interpolated raster) the 'rand' option
can be used. This randomly samples N-observations in each quadrant
instead of using the closest data points.
Example:
python interpkrig.py ifile.h5 ofile.h5 -d 10 10 -n 25 -r 50 -a 25 -p 3031 \
-c 50 10 -v lon lat dhdt dummy -e 0.1 -m dist
python interpkrig.py ifile.h5 ofile.h5 -d 10 10 -n 25 -r 50 -a 25 -p 3031 \
-c 50 10 -v lon lat dhdt rmse -e 0.1 -m rand
Credits:
captoolkit - JPL Cryosphere Altimetry Processing Toolkit
<NAME> (<EMAIL>)
<NAME> (<EMAIL>)
<NAME> (<EMAIL>)
Jet Propulsion Laboratory, California Institute of Technology
"""
import h5py
import pyproj
import argparse
import numpy as np
from scipy import stats
from scipy.spatial import cKDTree
from scipy.spatial.distance import cdist
def rand(x, n):
"""Draws random samples from array"""
# Determine data density
if len(x) > n:
# Draw random samples from array
I = np.random.choice(np.arange(len(x)), n, replace=False)
else:
# Output boolean vector - true
I = np.ones(len(x), dtype=bool)
return I
def sort_dist(d, n):
""" Sort array by distance"""
# Determine if sorting needed
if len(d) >= n:
# Sort according to distance
I = np.argsort(d)
else:
# Output boolean vector - true
I = np.ones(len(x), dtype=bool)
return I
def transform_coord(proj1, proj2, x, y):
"""Transform coordinates from proj1 to proj2 (EPSG num)."""
# Set full EPSG projection strings
proj1 = pyproj.Proj("+init=EPSG:" + proj1)
proj2 = pyproj.Proj("+init=EPSG:" + proj2)
# Convert coordinates
return pyproj.transform(proj1, proj2, x, y)
def make_grid(xmin, xmax, ymin, ymax, dx, dy):
""" Construct output grid-coordinates. """
Nn = int((np.abs(ymax - ymin)) / dy) + 1 # ny
Ne = int(( | np.abs(xmax - xmin) | numpy.abs |
# pylint: disable=not-callable, no-member, arguments-differ, missing-docstring, invalid-name, line-too-long
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.utils.data
from scipy.ndimage import zoom
from cath.util import lr_schedulers
from se3cnn.image.filter import low_pass_filter
from se3cnn.image.gated_block import GatedBlock
from se3cnn.image.utils import rotate_scalar
from se3cnn.SO3 import rot
class AvgSpacial(nn.Module):
def forward(self, inp):
return inp.view(inp.size(0), inp.size(1), -1).mean(-1)
class LowPass(nn.Module):
def __init__(self, scale, stride):
super().__init__()
self.scale = scale
self.stride = stride
def forward(self, inp):
return low_pass_filter(inp, self.scale, self.stride)
def get_volumes(size=20, pad=8, rotate=False, rotate90=False):
assert size >= 4
tetris_tensorfields = [
[(0, 0, 0), (0, 0, 1), (1, 0, 0), (1, 1, 0)], # chiral_shape_1
[(0, 1, 0), (0, 1, 1), (1, 1, 0), (1, 0, 0)], # chiral_shape_2
[(0, 0, 0), (1, 0, 0), (0, 1, 0), (1, 1, 0)], # square
[(0, 0, 0), (0, 0, 1), (0, 0, 2), (0, 0, 3)], # line
[(0, 0, 0), (0, 0, 1), (0, 1, 0), (1, 0, 0)], # corner
[(0, 0, 0), (0, 0, 1), (0, 0, 2), (0, 1, 0)], # L
[(0, 0, 0), (0, 0, 1), (0, 0, 2), (0, 1, 1)], # T
[(0, 0, 0), (1, 0, 0), (1, 1, 0), (2, 1, 0)], # zigzag
]
labels = np.arange(len(tetris_tensorfields))
tetris_vox = []
for shape in tetris_tensorfields:
volume = | np.zeros((4, 4, 4)) | numpy.zeros |
# @Author: <NAME>
# @Email: <EMAIL>
# @Filename: artificial_datasets.py
# @Last modified by: <NAME>
# @Last modified time: 19-Jul-2018
import argparse
import bisect
import collections
import itertools
import json
import os
import random
import numpy
import plotly
import sklearn.neighbors
import download_png
INCREMENT = dict(
# -x, -y, angle/, random-angle, +n for uniform
corner=(0, 0, 2, 0, 1),
side=(),
centre=(0.5, 0.5, 1, 0.5, 0)
)
class PlotGraph(object):
@classmethod
def __call__(cls, *args, **kwargs):
return cls.run(*args, **kwargs)
@classmethod
def run(cls, path, _data, _layout):
print("Plotting graph of: {}".format(path), flush=True)
data = cls.plot_data_generation(_data)
layout = cls.layout(
"2-D Artificial Dataset",
**_layout)
cls.plot(
path,
data,
layout)
print("Graph Plotted: {}".format(path), flush=True)
@classmethod
def title_generation(cls, title, **kwargs):
return "{}{}".format(
title,
"".join(
["<br>{}: {}".format(key, value)
for key, value in kwargs.items()]))
@classmethod
def plot_data_generation(cls, _data):
return [
plotly.graph_objs.Scatter(
x=_data[0]['x'],
y=_data[0]['y'],
mode='markers',
name='category 0'
),
plotly.graph_objs.Scatter(
x=_data[1]['x'],
y=_data[1]['y'],
mode='markers',
name='category 1'
)
]
@classmethod
def plot_offline(cls, fig, path):
filename = "{}.html".format(path[:-len('.png')])
url = plotly.offline.plot(
fig,
image="png",
image_filename=path[path.rfind('/') + 1:-len('.png')],
filename=filename,
auto_open=False)
destination = path[:path.rfind('/')]
try:
download_png.download(destination, url)
except RuntimeError:
print("RuntimeError occurs when downloading {}".format(url),
flush=True)
return
print("Offline Graph Plotted: {}".format(path), flush=True)
@classmethod
def layout(cls, title, **kwargs):
layout = dict(
title=cls.title_generation(title, **kwargs))
return layout
@classmethod
def plot(cls, path, data, layout):
fig = plotly.graph_objs.Figure(data=data, layout=layout)
cls.plot_offline(fig, path)
def label(point, separators):
count = 0
for separator in separators:
matrix = numpy.matrix([
numpy.array(point) - numpy.array(separator[0]),
numpy.array(separator[1]) - | numpy.array(separator[0]) | numpy.array |
import numpy as np
import gym
from gym import spaces
from numpy.random import default_rng
import pickle
import os
import math
import matplotlib.pyplot as plt
from PIL import Image
from gym_flp import rewards
from IPython.display import display, clear_output
import anytree
from anytree import Node, RenderTree, PreOrderIter, LevelOrderIter, LevelOrderGroupIter
'''
v0.0.3
Significant changes:
08.09.2020:
- Dicrete option removed from spaces; only Box allowed
- Classes for quadtratic set covering and mixed integer programming (-ish) added
- Episodic tasks: no more terminal states (exception: max. no. of trials reached)
12.10.2020:
- mip added
- fbs added
'''
class qapEnv(gym.Env):
metadata = {'render.modes': ['rgb_array', 'human']}
def __init__(self, mode=None, instance=None):
__location__ = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__)))
self.DistanceMatrices, self.FlowMatrices = pickle.load(open(os.path.join(__location__,'discrete', 'qap_matrices.pkl'), 'rb'))
self.transport_intensity = None
self.instance = instance
self.mode = mode
while not (self.instance in self.DistanceMatrices.keys() or self.instance in self.FlowMatrices.keys() or self.instance in ['Neos-n6', 'Neos-n7', 'Brewery']):
print('Available Problem Sets:', self.DistanceMatrices.keys())
self.instance = input('Pick a problem:').strip()
self.D = self.DistanceMatrices[self.instance]
self.F = self.FlowMatrices[self.instance]
# Determine problem size relevant for much stuff in here:
self.n = len(self.D[0])
# Action space has two option:
# 1) Define as Box with shape (1, 2) and allow values to range from 1 through self.n
# 2) Define as Discrete with x = 1+((n^2-n)/2) actions (one half of matrix + 1 value from diagonal) --> Omit "+1" to obtain range from 0 to x!
# self.action_space = spaces.Box(low=-1, high=6, shape=(1,2), dtype=np.int) # Doubles complexity of the problem as it allows the identical action (1,2) and (2,1)
self.action_space = spaces.Discrete(int((self.n**2-self.n)*0.5)+1)
# If you are using images as input, the input values must be in [0, 255] as the observation is normalized (dividing by 255 to have values in [0, 1]) when using CNN policies.
if self.mode == "rgb_array":
self.observation_space = spaces.Box(low = 0, high = 255, shape=(1, self.n, 3), dtype = np.uint8) # Image representation
elif self.mode == 'human':
self.observation_space = spaces.Box(low=1, high = self.n, shape=(self.n,), dtype=np.float32)
self.states = {} # Create an empty dictonary where states and their respective reward will be stored for future reference
self.actions = self.pairwiseExchange(self.n)
# Initialize Environment with empty state and action
self.action = None
self.state = None
self.internal_state = None
#Initialize moving target to incredibly high value. To be updated if reward obtained is smaller.
self.movingTargetReward = np.inf
self.MHC = rewards.mhc.MHC() # Create an instance of class MHC in module mhc.py from package rewards
def reset(self):
state = default_rng().choice(range(1,self.n+1), size=self.n, replace=False)
#MHC, self.TM = self.MHC.compute(self.D, self.F, state)
self.internal_state = state.copy()
return state
def step(self, action):
# Create new State based on action
fromState = self.internal_state.copy()
swap = self.actions[action]
fromState[swap[0]-1], fromState[swap[1]-1] = fromState[swap[1]-1], fromState[swap[0]-1]
newState = fromState.copy()
#MHC, self.TM = self.MHC.compute(self.D, self.F, current_permutation)
MHC, self.TM = self.MHC.compute(self.D, self.F, newState)
if self.mode == 'human':
self.states[tuple(fromState)] = MHC
if self.movingTargetReward == np.inf:
self.movingTargetReward = MHC
#reward = self.movingTargetReward - MHC
reward = -1 if MHC > self.movingTargetReward else 10
self.movingTargetReward = MHC if MHC < self.movingTargetReward else self.movingTargetReward
if self.mode == "rgb_array":
rgb = np.zeros((1,self.n,3), dtype=np.uint8)
sources = np.sum(self.TM, axis = 1)
sinks = np.sum(self.TM, axis = 0)
R = np.array((fromState-np.min(fromState))/(np.max(fromState)-np.min(fromState))*255).astype(int)
G = np.array((sources-np.min(sources))/(np.max(sources)-np.min(sources))*255).astype(int)
B = np.array((sinks-np.min(sinks))/(np.max(sinks)-np.min(sinks))*255).astype(int)
for i, s in enumerate(fromState):
rgb[0:1, i] = [R[s-1], G[s-1], B[s-1]]
newState = np.array(rgb)
self.state = newState.copy()
self.internal_state = fromState.copy()
return newState, reward, False, {}
def render(self, mode=None):
if self.mode == "human":
SCALE = 1 # Scale size of pixels for displayability
img_h, img_w = SCALE, (len(self.internal_state))*SCALE
data = np.zeros((img_h, img_w, 3), dtype=np.uint8)
sources = np.sum(self.TM, axis = 1)
sinks = np.sum(self.TM, axis = 0)
R = np.array((self.internal_state-np.min(self.internal_state))/(np.max(self.internal_state)-np.min(self.internal_state))*255).astype(int)
G = np.array((sources-np.min(sources))/(np.max(sources)-np.min(sources))*255).astype(int)
B = np.array((sinks-np.min(sinks))/(np.max(sinks)-np.min(sinks))*255).astype(int)
for i, s in enumerate(self.internal_state):
data[0*SCALE:1*SCALE, i*SCALE:(i+1)*SCALE] = [R[s-1], G[s-1], B[s-1]]
img = Image.fromarray(data, 'RGB')
if self.mode == 'rgb_array':
img = Image.fromarray(self.state, 'RGB')
plt.imshow(img)
plt.axis('off')
plt.show()
return img
def close(self):
pass
def pairwiseExchange(self, x):
actions = [(i,j) for i in range(1,x) for j in range(i+1,x+1) if not i==j]
actions.append((1,1))
return actions
class fbsEnv(gym.Env):
metadata = {'render.modes': ['rgb_array', 'human']}
def __init__(self, mode=None, instance = None):
__location__ = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__)))
self.problems, self.FlowMatrices, self.sizes, self.LayoutWidths, self.LayoutLengths = pickle.load(open(os.path.join(__location__,'continual', 'cont_instances.pkl'), 'rb'))
self.mode = mode
self.instance = instance
while not (self.instance in self.FlowMatrices.keys() or self.instance in ['Brewery']):
print('Available Problem Sets:', self.FlowMatrices.keys())
self.instance = input('Pick a problem:').strip()
self.F = self.FlowMatrices[self.instance]
self.n = self.problems[self.instance]
self.AreaData = self.sizes[self.instance]
# Obtain size data: FBS needs a length and area
self.beta, self.l, self.w, self.a, self.min_side_length = getAreaData(self.AreaData) #Investigate available area data and compute missing values if needed
'''
Nomenclature:
W --> Width of Plant (y coordinate)
L --> Length of Plant (x coordinate)
w --> Width of facility/bay (x coordinate)
l --> Length of facility/bay (y coordinate)
A --> Area of Plant
a --> Area of facility
Point of origin analoguous to numpy indexing (top left corner of plant)
beta --> aspect ratios (as alpha is reserved for learning rate)
'''
#if self.l is None or self.w is None:
# self.l = np.random.randint(max(self.min_side_length, np.min(self.a)/self.min_side_length), max(self.min_side_length, np.min(self.a)/self.min_side_length), size=(self.n,))
# self.l = np.sqrt(self.A/self.aspect_ratio)
# self.w = np.round(self.a/self.l)
# Check if there are Layout Dimensions available, if not provide enough (sqrt(a)*1.5)
if self.instance in self.LayoutWidths.keys() and self.instance in self.LayoutLengths.keys():
self.L = int(self.LayoutLengths[self.instance]) # We need both values to be integers for converting into image
self.W = int(self.LayoutWidths[self.instance])
else:
self.A = np.sum(self.a)
# Design a squared plant layout
self.L = int(round(math.sqrt(self.A),0)) # We want the plant dimensions to be integers to fit them into an image
self.W = self.L
# Design a layout with l = 1,5 * w
#self.L = divisor(int(self.A))
#self.W = self.A/self.L
# These values need to be set manually, e.g. acc. to data from literature. Following Eq. 1 in Ulutas & Kulturel-Konak (2012), the minimum side length can be determined by assuming the smallest facility will occupy alone.
self.aspect_ratio = int(max(self.beta)) if not self.beta is None else 1
self.min_length = np.min(self.a) / self.L
self.min_width = np.min(self.a) / self.W
# We define minimum side lengths to be 1 in order to be displayable in array
self.min_length = 1
self.min_width = 1
self.action_space = spaces.Discrete(5) #Taken from doi:10.1016/j.engappai.2020.103697
self.actions = {0: 'Randomize', 1: 'Bit Swap', 2: 'Bay Exchange', 3: 'Inverse', 4: 'Idle'}
#self.state_space = spaces.Box(low=1, high = self.n, shape=(self.n,), dtype=np.int)
self.bay_space = spaces.Box(low=0, high = 1, shape=(self.n,), dtype=np.int) # binary vector indicating bay breaks (i = 1 means last facility in bay)
self.state = None
self.permutation = None # Permutation of all n facilities, read from top to bottom
self.bay = None
self.done = False
self.MHC = rewards.mhc.MHC()
if self.mode == "rgb_array":
self.observation_space = spaces.Box(low = 0, high = 255, shape= (self.W, self.L,3), dtype = np.uint8) # Image representation
elif self.mode == "human":
observation_low = np.tile(np.array([0,0,self.min_length,self.min_width],dtype=int), self.n)
observation_high = np.tile(np.array([self.W, self.L, self.W, self.L], dtype=int), self.n)
self.observation_space = spaces.Box(low=observation_low, high=observation_high, dtype = int) # Vector representation of coordinates
else:
print("Nothing correct selected")
def reset(self):
# 1. Get a random permutation and bays
self.permutation, self.bay = self.sampler()
# 2. Last position in bay break vector has to be 1 by default.
self.bay[-1] = 1
self.fac_x, self.fac_y, self.fac_b, self.fac_h = self.getCoordinates()
self.D = getDistances(self.fac_x, self.fac_y)
reward, self.TM = self.MHC.compute(self.D, self.F, self.permutation[:])
self.state = self.constructState(self.fac_x, self.fac_y, self.fac_b, self.fac_h, self.n)
return self.state
def constructState(self, x, y, l, w, n):
# Construct state
state_prelim = np.zeros((4*n,), dtype=float)
state_prelim[0::4] = y
state_prelim[1::4] = x
state_prelim[2::4] = w
state_prelim[3::4] = l
if self.mode == "human":
self.state = np.array(state_prelim)
elif self.mode == "rgb_array":
self.state = self.ConvertCoordinatesToState(state_prelim)
return self.state[:]
def ConvertCoordinatesToState(self, state_prelim):
data = np.zeros((self.observation_space.shape)) if self.mode == 'rgb_array' else np.zeros((self.W, self.L, 3),dtype=np.uint8)
sources = np.sum(self.TM, axis = 1)
sinks = np.sum(self.TM, axis = 0)
R = np.array((self.permutation-np.min(self.permutation))/(np.max(self.permutation)-np.min(self.permutation))*255).astype(int)
G = np.array((sources-np.min(sources))/(np.max(sources)-np.min(sources))*255).astype(int)
B = np.array((sinks-np.min(sinks))/(np.max(sinks)-np.min(sinks))*255).astype(int)
for x, p in enumerate(self.permutation):
x_from = state_prelim[4*x+1] -0.5 * state_prelim[4*x+3]
y_from = state_prelim[4*x+0] -0.5 * state_prelim[4*x+2]
x_to = state_prelim[4*x+1] + 0.5 * state_prelim[4*x+3]
y_to = state_prelim[4*x+0] + 0.5 * state_prelim[4*x+2]
data[int(y_from):int(y_to), int(x_from):int(x_to)] = [R[p-1], G[p-1], B[p-1]]
return np.array(data, dtype=np.uint8)
def sampler(self):
return default_rng().choice(range(1,self.n+1), size=self.n, replace=False), self.bay_space.sample()
def getCoordinates(self):
facilities = np.where(self.bay==1)[0] #Read all positions with a bay break
bays = np.split(self.permutation, facilities[:-1]+1)
lengths = np.zeros((len(self.permutation,)))
widths = np.zeros((len(self.permutation,)))
fac_x = np.zeros((len(self.permutation,)))
fac_y = np.zeros((len(self.permutation,)))
x = 0
start = 0
for b in bays: #Get the facilities that are located in the bay
areas = self.a[b-1] #Get the area associated with the facilities
end = start + len(areas)
lengths[start:end] = np.sum(areas)/self.W #Calculate all facility widhts in bay acc. to Eq. (1) in https://doi.org/10.1016/j.eswa.2011.11.046
widths[start:end] = areas/lengths[start:end]
fac_x[start:end] = lengths[start:end] * 0.5 + x
x += np.sum(areas)/self.W
y = np.ones(len(b))
ll = 0
for idx, l in enumerate(widths[start:end]):
y[idx] = ll + 0.5*l
ll += l
fac_y[start:end] = y
start = end
return fac_x, fac_y, lengths, widths
def step(self, action):
a = self.actions[action]
#k = np.count_nonzero(self.bay)
fromState = np.array(self.permutation)
# Get lists with a bay positions and facilities in each bay
facilities = np.where(self.bay==1)[0]
bay_breaks = np.split(self.bay, facilities[:-1]+1)
# Load indiv. facilities into bay acc. to breaks; omit break on last position to avoid empty array in list.
bays = np.split(self.permutation, facilities[:-1]+1)
if a == 'Randomize':
# Two vector elements randomly chosen are exchanged. Bay vector remains untouched.
k = default_rng().choice(range(len(self.permutation-1)), size=1, replace=False)
l = default_rng().choice(range(len(self.permutation-1)), size=1, replace=False)
fromState[k], fromState[l] = fromState[l], fromState[k]
self.permutation = np.array(fromState)
elif a == 'Bit Swap':
#One element randomly selected flips its value (1 to 0 or 0 to 1)
j = default_rng().choice(range(len(self.bay-1)), size=1, replace=False)
temp_bay = np.array(self.bay) # Make a copy of bay
temp_bay[j] = 1 if temp_bay[j] == 0 else 0
self.bay = np.array(temp_bay)
elif a == 'Bay Exchange':
#Two bays are randomly selected and exchange facilities contained in them
o = int(default_rng().choice(range(len(bays)), size=1, replace=False))
p = int(default_rng().choice(range(len(bays)), size=1, replace=False))
while p==o: # Make sure bays are not the same
p = int(default_rng().choice(range(len(bays)), size=1, replace=False))
# Swap bays and break points accordingly:
bays[o], bays[p] = bays[p], bays[o]
bay_breaks[o], bay_breaks[p] = bay_breaks[p], bay_breaks[o]
new_bay = np.concatenate(bay_breaks)
new_state = np.concatenate(bays)
# Make sure state is saved as copy
self.permutation = np.array(new_state)
self.bay = np.array(new_bay)
elif a == 'Inverse':
#Facilities present in a certain bay randomly chosen are inverted.
q = default_rng().choice(range(len(bays)))
bays[q] = np.flip(bays[q])
new_bay = np.concatenate(bay_breaks)
new_state = np.concatenate(bays)
# Make sure state is saved as copy
self.permutation = np.array(new_state)
self.bay = np.array(new_bay)
elif a == 'Idle':
pass # Keep old state
self.fac_x, self.fac_y, self.fac_b, self.fac_h = self.getCoordinates()
self.D = getDistances(self.fac_x, self.fac_y)
reward, self.TM = self.MHC.compute(self.D, self.F, fromState)
self.state = self.constructState(self.fac_x, self.fac_y, self.fac_b, self.fac_h, self.n)
self.done = False #Always false for continuous task
return self.state[:], reward, self.done, {}
def render(self, mode= None):
if self.mode== "human":
# Mode 'human' needs intermediate step to convert state vector into image array
data = self.ConvertCoordinatesToState(self.state[:])
img = Image.fromarray(data, 'RGB')
if self.mode == "rgb_array":
data = self.state[:]
img = Image.fromarray(self.state, 'RGB')
plt.imshow(img)
plt.axis('off')
plt.show()
#23.02.21: Switched to data instead of img for testing video
return img
def close(self):
pass
#self.close()
class ofpEnv(gym.Env):
metadata = {'render.modes': ['rgb_array', 'human']}
def __init__(self, mode = None, instance = None, distance = None, aspect_ratio = None, step_size = None, greenfield = None):
__location__ = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__)))
self.problems, self.FlowMatrices, self.sizes, self.LayoutWidths, self.LayoutLengths = pickle.load(open(os.path.join(__location__,'continual', 'cont_instances.pkl'), 'rb'))
self.mode = mode
self.aspect_ratio = 2 if aspect_ratio is None else aspect_ratio
self.step_size = 2 if step_size is None else step_size
self.greenfield = greenfield
self.instance = instance
while not (self.instance in self.FlowMatrices.keys() or self.instance in ['Brewery']):
print('Available Problem Sets:', self.FlowMatrices.keys())
self.instance = input('Pick a problem:').strip()
self.F = self.FlowMatrices[self.instance]
self.n = self.problems[self.instance]
self.AreaData = self.sizes[self.instance]
self.counter = 0
self.done = False
self.pseudo_stability = 0 #If the reward has not improved in the last 200 steps, terminate the episode
self.best_reward = None
# Obtain size data: FBS needs a length and area
self.beta, self.l, self.w, self.a, self.min_side_length = getAreaData(self.AreaData) #Investigate available area data and compute missing values if needed
'''
Nomenclature:
W --> Width of Plant (x coordinate)
L --> Length of Plant (y coordinate)
w --> Width of facility/bay (x coordinate)
l --> Length of facility/bay (y coordinate)
A --> Area of Plant
a --> Area of facility
Point of origin analoguous to numpy indexing (top left corner of plant)
beta --> aspect ratios (as alpha is reserved for learning rate)
'''
#if self.l is None or self.w is None:
# self.l = np.random.randint(max(self.min_side_length, np.min(self.a)/self.min_side_length), max(self.min_side_length, np.min(self.a)/self.min_side_length), size=(self.n,))
# self.l = np.sqrt(self.A/self.aspect_ratio)
# self.w = np.round(self.a/self.l)
# Check if there are Layout Dimensions available, if not provide enough (sqrt(a)*1.5)
if self.instance in self.LayoutWidths.keys() and self.instance in self.LayoutLengths.keys():
self.L = int(self.LayoutLengths[self.instance]) # We need both values to be integers for converting into image
self.W = int(self.LayoutWidths[self.instance])
else:
self.A = np.sum(self.a)
# Design a squared plant layout
self.L = int(round(math.sqrt(self.A),0)) # We want the plant dimensions to be integers to fit them into an image
self.W = self.L
if self.greenfield:
self.L = 2*self.L
self.W = 2*self.W
# Design a layout with l = 1,5 * w
#self.L = divisor(int(self.A))
#self.W = self.A/self.L
# These values need to be set manually, e.g. acc. to data from literature. Following Eq. 1 in Ulutas & Kulturel-Konak (2012), the minimum side length can be determined by assuming the smallest facility will occupy alone.
self.aspect_ratio = int(max(self.beta)) if not self.beta is None else self.aspect_ratio
self.min_length = 1
self.min_width = 1
# 3. Define the possible actions: 5 for each box [toDo: plus 2 to manipulate sizes] + 1 idle action for all
self.actions = {}
for i in range(self.n):
self.actions[0+(i)*5] = "up"
self.actions[1+(i)*5] = "down"
self.actions[2+(i)*5] = "right"
self.actions[3+(i)*5] = "left"
self.actions[4+(i)*5] = "rotate"
self.actions[len(self.actions)] = "keep"
# 4. Define actions space as Discrete Space
self.action_space = spaces.Discrete(1+5*self.n) #5 actions for each facility: left, up, down, right, rotate + idle action across all
# 5. Set some starting points
self.reward = 0
self.state = None
self.internal_state = None #Placeholder for state variable for internal manipulation in rgb_array mode
if self.w is None or self.l is None:
self.l = np.random.randint(self.min_side_length*self.aspect_ratio, np.min(self.a), size=(self.n, ))
self.w = np.round(self.a/self.l)
# 6. Set upper and lower bound for observation space
# min x position can be point of origin (0,0) [coordinates map to upper left corner]
# min y position can be point of origin (0,0) [coordinates map to upper left corner]
# min width can be smallest area divided by its length
# min lenght can be smallest width (above) multiplied by aspect ratio
# max x pos can be bottom right edge of grid
# max y pos can be bottpm right edge of grid
if self.mode == "rgb_array":
self.observation_space = spaces.Box(low = 0, high = 255, shape= (self.W, self.L,3), dtype = np.uint8) # Image representation
elif self.mode == "human":
#observation_low = np.tile(np.array([0,0,self.min_side_length, self.min_side_length],dtype=float), self.n)
#observation_high = np.tile(np.array([self.L, self.W, max(self.l), max(self.w)], dtype=float), self.n)
observation_low = np.zeros(4* self.n)
observation_high = np.zeros(4* self.n)
observation_low[0::4] = max(self.w)
observation_low[1::4] = max(self.l)
observation_low[2::4] = max(self.w)
observation_low[3::4] = max(self.l)
observation_high[0::4] = self.W - max(self.w)
observation_high[1::4] = self.L - max(self.l)
observation_high[2::4] = self.W - max(self.w)
observation_high[3::4] = self.L - max(self.l)
self.observation_space = spaces.Box(low=observation_low, high=observation_high, dtype = np.uint8) # Vector representation of coordinates
else:
print("Nothing correct selected")
self.MHC = rewards.mhc.MHC()
# Set Boundaries
self.upper_bound = self.L- max(self.l)/2
self.lower_bound = 0 + max(self.l)/2
self.left_bound = 0 + max(self.w)/2
self.right_bound = self.W- max(self.w)/2
def reset(self):
# Start with random x and y positions
if self.mode == 'human':
state_prelim = self.observation_space.sample()
# Override length (l) and width (w) or facilities with data from instances
state_prelim[2::4] = self.w
state_prelim[3::4] = self.l
self.D = getDistances(state_prelim[0::4], state_prelim[1::4])
self.internal_state = np.array(state_prelim)
self.state = np.array(state_prelim)
reward, self.TM = self.MHC.compute(self.D, self.F, np.array(range(1,self.n+1)))
self.counter = 0
self.best_reward = reward
self.reward = 0
elif self.mode == 'rgb_array':
state_prelim = np.zeros((self.W, self.L, 3),dtype=np.uint8)
x = np.random.uniform(0, self.L, size=(self.n,))
y = np.random.uniform(0, self.W, size=(self.n,))
#s = self.constructState(y, x, self.w, self.l, self.n)
s = np.zeros(4*self.n)
s[0::4] = y
s[1::4] = x
s[2::4] = self.w
s[3::4] = self.l
self.internal_state = np.array(s).copy()
#self.state = self.constructState(y, x, self.w, self.l, self.n)
self.D = getDistances(s[0::4], s[1::4])
reward, self.TM = self.MHC.compute(self.D, self.F, np.array(range(1,self.n+1)))
self.state = self.ConvertCoordinatesToState(self.internal_state)
self.counter = 0
self.best_reward = reward
return self.state.copy()
# def offGrid(self, s):
# if np.any(s[0::4]-s[2::4] < 0):
# #print("Bottom bound breached")
# og = True
# elif np.any(s[0::4]+s[2::4] > self.W):
# #print("Top bound breached")
# og = True
# elif np.any(s[1::4]-s[3::4] < 0):
# #print("left bound breached")
# og = True
# elif np.any(s[1::4]+s[3::4] > self.L):
# #print("right bound breached")
# og = True
# else:
# og = False
# return og
# def collision_test(self, y, x, w, l):
# # collision test
# collision = False #initialize collision for each collision test
# for i in range (0, self.n-1):
# for j in range (i+1,self.n):
# if not(x[i]+0.5*l[i] < x[j]-0.5*l[j] or x[i]-0.5*l[i] > x[j]+0.5*l[j] or y[i]-0.5*w[i] > y[j]+0.5*w[j] or y[i]+0.5*w[i] < y[j]-0.5*w[j]):
# collision = True
# break
# return collision
def collision(self,x,y,w,l):
collision = False
for i in range(0,self.n-1):
for j in range(i+1,self.n):
if (abs(int(x[i]) - int(x[j])) < 0.5*self.w[i]+0.5*self.w[j]):
if(abs(int(y[i]) - int(y[j])) < 0.5*self.l[i]+0.5*self.l[j]):
#print(x[i],y[i],x[j],y[j])
collision = True
if (abs(int(y[i]) - int(y[j])) < 0.5*self.l[i]+0.5*self.l[j]):
if(abs(int(x[i]) - int(x[j])) < 0.5*self.w[i]+0.5*self.w[j]):
#print(x[i],y[i],x[j],y[j])
collision = True
return collision
def step(self, action):
self.reward = 0
m = np.int(np.ceil((action+1)/5)) # Facility on which the action is
# Get copy of state to manipulate:
temp_state = self.internal_state[:]
step_size = self.step_size
# Do the action
if self.actions[action] == "up":
if temp_state[4*(m-1)+1] + temp_state[4*(m-1)+3]*0.5 + step_size < self.upper_bound:
temp_state[4*(m-1)+1] += step_size
else:
temp_state[4*(m-1)+1] += 0
#print('Forbidden action: machine', m, 'left grid on upper bound')
elif self.actions[action] == "down":
if temp_state[4*(m-1)+1] - temp_state[4*(m-1)+3]*0.5 + step_size > self.lower_bound:
temp_state[4*(m-1)+1] -= step_size
else:
temp_state[4*(m-1)+1] += 0
#print('Forbidden action: machine', m, 'left grid on lower bound')
elif self.actions[action] == "right":
if temp_state[4*(m-1)]+temp_state[4*(m-1)+2]*0.5 + step_size < self.right_bound:
temp_state[4*(m-1)] += step_size
else:
temp_state[4*(m-1)] += 0
#print('Forbidden action: machine', m, 'left grid on right bound')
elif self.actions[action] == "left":
if temp_state[4*(m-1)]-temp_state[4*(m-1)+2]*0.5 + step_size > self.left_bound:
temp_state[4*(m-1)] -= step_size
else:
temp_state[4*(m-1)] += 0
#print('Forbidden action: machine', m, 'left grid on left bound')
elif self.actions[action] == "keep":
None #Leave everything as is
elif self.actions[action] == "rotate":
temp_state[4*(m-1)+2], temp_state[4*(m-1)+3] = temp_state[4*(m-1)+3], temp_state[4*(m-1)+2]
else:
raise ValueError("Received invalid action={} which is not part of the action space".format(action))
self.fac_x, self.fac_y, self.fac_b, self.fac_h = temp_state[0::4], temp_state[1::4], temp_state[2::4], temp_state[3::4] # ToDo: Read this from self.state
self.D = getDistances(self.fac_x, self.fac_y)
fromState = np.array(range(1,self.n+1)) # Need to create permutation matrix
MHC, self.TM = self.MHC.compute(self.D, self.F, fromState)
self.internal_state = np.array(temp_state) # Keep a copy of the vector representation for future steps
self.state = self.internal_state[:]
# Test if initial state causing a collision. If yes than initialize a new state until there is no collision
collision = self.collision(temp_state[0::4],temp_state[1::4], temp_state[2::4], temp_state[3::4]) # Pass every 4th item starting at 0 (x pos) and 1 (y pos) for checking
if (MHC < self.best_reward) and (collision == False) :
self.best_reward = MHC
self.reward = 50
if collision == True:
self.reward = -2
if self.mode == 'rgb_array':
self.state = self.ConvertCoordinatesToState(self.internal_state) #Retain state for internal use
self.pseudo_stability = self.counter
self.done = True if self.pseudo_stability == 200 else False
self.counter += 1
#print(self.reward)
return self.state,self.reward,self.done,{}
def ConvertCoordinatesToState(self, state_prelim):
data = np.zeros((self.observation_space.shape)) if self.mode == 'rgb_array' else np.zeros((self.W, self.L, 3),dtype=np.uint8)
sources = np.sum(self.TM, axis = 1)
sinks = np.sum(self.TM, axis = 0)
p = np.arange(self.n)
R = np.array((p-np.min(p))/(np.max(p)-np.min(p))*255).astype(int)
R[R<=20] = 255
G = np.array((sources-np.min(sources))/(np.max(sources)-np.min(sources))*255).astype(int)
G[G<=20] = 255
B = np.array((sinks-np.min(sinks))/(np.max(sinks)-np.min(sinks))*255).astype(int)
B[B<=20] = 255
for x, p in enumerate(p):
x_from = state_prelim[4*x+0] -0.5 * state_prelim[4*x+2]
y_from = state_prelim[4*x+1] -0.5 * state_prelim[4*x+3]
x_to = state_prelim[4*x+0] + 0.5 * state_prelim[4*x+2]
y_to = state_prelim[4*x+1] + 0.5 * state_prelim[4*x+3]
data[int(y_from):int(y_to), int(x_from):int(x_to)] = [R[p-1], G[p-1], B[p-1]]
return np.array(data, dtype=np.uint8)
def constructState(self, x, y, b, h, n):
# Construct state
state_prelim = np.zeros((4*n,), dtype=float)
state_prelim[0::4] = x
state_prelim[1::4] = y
state_prelim[2::4] = b
state_prelim[3::4] = h
if self.mode == "human":
self.state = np.array(state_prelim)
elif self.mode == "rgb_array":
self.state = self.ConvertCoordinatesToState(state_prelim)
return self.state[:]
def render(self):
if self.mode == "human":
data = self.ConvertCoordinatesToState(self.state[:])
img = Image.fromarray(data, 'RGB')
if self.mode == "rgb_array":
img = Image.fromarray(self.state, 'RGB')
plt.imshow(img)
plt.axis('off')
plt.show()
return img
def close(self):
pass #Nothing here yet
class stsEnv(gym.Env):
metadata = {'render.modes': ['rgb_array', 'human']}
def __init__(self, mode = None, instance = None):
__location__ = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__)))
self.problems, self.FlowMatrices, self.sizes, self.LayoutWidths, self.LayoutLengths = pickle.load(open(os.path.join(__location__,'continual', 'cont_instances.pkl'), 'rb'))
self.instance = instance
self.mode = mode
self.MHC = rewards.mhc.MHC()
while not (self.instance in self.FlowMatrices.keys() or self.instance in ['Brewery']):
print('Available Problem Sets:', self.FlowMatrices.keys())
self.instance = input('Pick a problem:').strip()
self.F = self.FlowMatrices[self.instance]
self.n = self.problems[self.instance]
self.AreaData = self.sizes[self.instance]
# Obtain size data: FBS needs a length and area
self.beta, self.l, self.w, self.a, self.min_side_length = getAreaData(self.AreaData) #Investigate available area data and compute missing values if needed
# Check if there are Layout Dimensions available, if not provide enough (sqrt(a)*1.5)
if self.instance in self.LayoutWidths.keys() and self.instance in self.LayoutLengths.keys():
self.L = int(self.LayoutLengths[self.instance]) # We need both values to be integers for converting into image
self.W = int(self.LayoutWidths[self.instance])
else:
self.A = np.sum(self.a)
# Design a squared plant layout
self.L = int(round(math.sqrt(self.A),0)) # We want the plant dimensions to be integers to fit them into an image
self.W = self.L
'''
Nomenclature:
W --> Width of Plant (y coordinate)
L --> Length of Plant (x coordinate)
w --> Width of facility/bay (x coordinate)
l --> Length of facility/bay (y coordinate)
A --> Area of Plant
a --> Area of facility
Point of origin analoguous to numpy indexing (top left corner of plant)
beta --> aspect ratios (as alpha is reserved for learning rate)
'''
# Provide variables for layout encoding (epsilon in doi:10.1016/j.ejor.2018.01.001)
self.permutation = None
self.slicing = None
self.orientation_space = spaces.Box(low=0, high = 1, shape=(self.n-1,), dtype=np.int) # binary vector indicating bay breaks (i = 1 means last facility in bay)
self.state = None
if self.mode == "rgb_array":
self.observation_space = spaces.Box(low = 0, high = 255, shape= (self.W, self.L,3), dtype = np.uint8) # Image representation
elif self.mode == "human":
#observation_low = np.tile(np.array([0,0,self.min_side_length, self.min_side_length],dtype=float), self.n)
#observation_high = np.tile(np.array([self.L, self.W, max(self.l), max(self.w)], dtype=float), self.n)
observation_low = np.zeros(4* self.n)
observation_high = np.zeros(4* self.n)
observation_low[0::4] = 0.0 #Top-left corner y
observation_low[1::4] = 0.0 #Top-left corner x
observation_low[2::4] = 1.0 #Width
observation_low[3::4] = 1.0 #Length
observation_high[0::4] = self.W
observation_high[1::4] = self.L
observation_high[2::4] = self.W
observation_high[3::4] = self.L
self.observation_space = spaces.Box(low=observation_low, high=observation_high, dtype = float) # Vector representation of coordinates
else:
print("Nothing correct selected")
self.action_space = spaces.Discrete(5)
self.actions = {0: 'Permute', 1: 'Slice_Swap', 2: 'Shuffle', 3: 'Bit_Swap', 4: 'Idle'}
def reset(self):
# 1. Get a random permutation, slicing order and orientation
self.permutation, self.slicing, self.orientation = self.sampler()
# 2. Build the tree incl. size information
s = self.TreeBuilder(self.permutation, self.slicing, self.orientation)
centers = np.array([s[0::4] + 0.5*s[2::4], s[1::4] + 0.5* s[3::4]])
self.D = getDistances(centers[0], centers[1])
reward, self.TM = self.MHC.compute(self.D, self.F, np.array(range(1,self.n+1)))
if self.mode == "human":
self.state = np.array(s)
elif self.mode == "rgb_array":
self.state = self.ConvertCoordinatesToState(s)
return self.state
def ConvertCoordinatesToState(self, s):
data = np.zeros((self.observation_space.shape)) if self.mode == 'rgb_array' else np.zeros((self.W, self.L, 3),dtype=np.uint8)
sources = np.sum(self.TM, axis = 1)
sinks = np.sum(self.TM, axis = 0)
p = self.permutation[:]
R = np.array((p-np.min(p))/(np.max(p)-np.min(p))*255).astype(int)
G = np.array((sources-np.min(sources))/(np.max(sources)-np.min(sources))*255).astype(int)
B = np.array((sinks-np.min(sinks))/(np.max(sinks)-np.min(sinks))*255).astype(int)
for x in range(self.n):
y_from = s[4*x+0]
x_from = s[4*x+1]
y_to = y_from + s[4*x+2]
x_to = x_from + s[4*x+3]
data[int(y_from):int(y_to), int(x_from):int(x_to)] = [R[x], G[x], B[x]]
return np.array(data, dtype=np.uint8)
def TreeBuilder(self,p,s,o):
names = {0: 'V', 1: 'H'}
contains = np.array(p)
W = self.W
L = self.L
area = W * L
self.STS = Node(name = None, contains = contains, parent = None, area = area, width = W, length = L, upper_left = np.zeros((2,)), lower_right = np.array([W,L]), dtype = float)
for i,r in enumerate(o):
name = names[r]
cut_after_pos = s[i]
whats_in_pos = p[cut_after_pos-1]
parent = anytree.search.find(self.STS, lambda node: np.any(node.contains==whats_in_pos))
parent.name = name
starting_point = parent.upper_left
cuts = np.split(parent.contains, [np.where(parent.contains == whats_in_pos)[0][0]+1])
for c in cuts:
area = float(np.sum(self.a[c-1]))
length = area/parent.width if name == 'V' else parent.length
width = area/parent.length if name == 'H' else parent.width
starting_point = starting_point
contains = c
new_name = None if not len(c)==1 else c[0]
Node(name = new_name, \
contains = contains, \
parent = parent, \
area = area, \
width = width, \
length = length, \
upper_left = starting_point, \
lower_right = starting_point + np.array([width, length]), \
dtype = float)
starting_point = starting_point + np.array([0, length]) if parent.name == 'V' else starting_point + np.array([width, 0])
parent.contains = None
self.STS.root.area = np.sum([i.area for i in self.STS.root.children])
s = np.zeros((4*self.n,))
for l in self.STS.leaves:
trg = int(l.name)-1
s[4*trg] = l.upper_left[0]
s[4*trg+1] = l.upper_left[1]
s[4*trg+2] = l.width
s[4*trg+3] = l.length
return s
def step(self, a):
action = self.actions[a]
'''
Available actions in STS:
- Random permutation change
- Random slicing order change at two positions
- Shuffle slicing order (new random array)
- Bitswap in Orientation vector
- Do Nothing
'''
if action == 'Permute':
i = np.random.randint(0, len(self.permutation)-1)
j = np.random.randint(0, len(self.permutation)-1)
temp_perm = np.array(self.permutation)
temp_perm[i], temp_perm[j] = temp_perm[j], temp_perm[i]
self.permutation = np.array(temp_perm)
elif action == 'Slice_Swap':
i = np.random.randint(0, len(self.slicing)-1)
j = np.random.randint(0, len(self.slicing)-1)
temp_sli = np.array(self.slicing)
temp_sli[i], temp_sli[j] = temp_sli[j], temp_sli[i]
self.slicing = np.array(temp_sli)
elif action == 'Shuffle':
self.slicing = default_rng().choice(range(1,self.n), size=self.n-1, replace=False)
elif action == 'Bit_Swap':
i = np.random.randint(0, len(self.orientation)-1)
if self.orientation[i] == 1:
self.orientation[i] = 0
elif self.orientation[i] == 0:
self.orientation[i] = 1
elif action == 'Idle':
self.permutation = np.array(self.permutation)
self.slicing = np.array(self.slicing)
self.orientation = np.array(self.orientation)
new_state = self.TreeBuilder(self.permutation, self.slicing, self.orientation)
if self.mode == "human":
self.state = np.array(new_state)
elif self.mode == "rgb_array":
self.state = self.ConvertCoordinatesToState(new_state)
return self.state[:], 0, False, {}
def render(self, mode=None):
if self.mode == "human":
data = self.ConvertCoordinatesToState(self.state[:])
img = Image.fromarray(data, 'RGB')
elif self.mode == "rgb_array":
img = Image.fromarray(self.state, 'RGB')
plt.imshow(img)
plt.axis('off')
plt.show()
return img
def sampler(self):
return default_rng().choice(range(1,self.n+1),size=self.n, replace=False), \
default_rng().choice(range(1,self.n), size=self.n-1, replace=False), \
self.orientation_space.sample()
def close(self):
None
def getAreaData(df):
import re
# First check for area data
if np.any(df.columns.str.contains('Area', na=False, case = False)):
a = df.filter(regex = re.compile("Area", re.IGNORECASE)).to_numpy()
#a = np.reshape(a, (a.shape[0],))
else:
a = None
if np.any(df.columns.str.contains('Length', na=False, case = False)):
l = df.filter(regex = re.compile("Length", re.IGNORECASE)).to_numpy()
l = np.reshape(l, (l.shape[0],))
else:
l = None
if np.any(df.columns.str.contains('Width', na=False, case = False)):
w = df.filter(regex = re.compile("Width", re.IGNORECASE)).to_numpy()
w = np.reshape(w, (w.shape[0],))
else:
w = None
if np.any(df.columns.str.contains('Aspect', na=False, case = False)):
ar = df.filter(regex = re.compile("Aspect", re.IGNORECASE)).to_numpy()
#ar = np.reshape(a, (a.shape[0],))
else:
ar = None
'''
The following cases can apply in the implemented problem sets (as of 23.12.2020):
1. Area data --> use as is
2. Length and width data --> compute area as l * w
3. Only length data --> check for minimum length or aspect ratio
4. Several area columns (i.e. min/max) --> pick max
5. Lower and Upper Bounds for _machine-wise_ aspect ratio --> pick random between bounds
'''
l_min = 1
if a is None:
if not l is None and not w is None:
a = l * w
elif not l is None:
a = l * max(l_min, max(l))
else:
a = w * max(l_min, max(w))
if not ar is None and ar.ndim > 1:
ar = np.array([np.random.default_rng().uniform(min(ar[i]), max(ar[i])) for i in range(len(ar))])
if not a is None and a.ndim > 1:
#a = a[np.where(np.max(np.sum(a, axis = 0))),:]
a = a[:, 0] # We choose the maximum value here. Can be changed if something else is needed
a = | np.reshape(a, (a.shape[0],)) | numpy.reshape |
import itertools
import textwrap
import warnings
from datetime import datetime
from inspect import getfullargspec
from typing import Any, Iterable, Mapping, Tuple, Union
import numpy as np
import pandas as pd
from ..core.options import OPTIONS
from ..core.utils import is_scalar
try:
import nc_time_axis # noqa: F401
nc_time_axis_available = True
except ImportError:
nc_time_axis_available = False
ROBUST_PERCENTILE = 2.0
_registered = False
def register_pandas_datetime_converter_if_needed():
# based on https://github.com/pandas-dev/pandas/pull/17710
global _registered
if not _registered:
pd.plotting.register_matplotlib_converters()
_registered = True
def import_matplotlib_pyplot():
"""Import pyplot as register appropriate converters."""
register_pandas_datetime_converter_if_needed()
import matplotlib.pyplot as plt
return plt
def _determine_extend(calc_data, vmin, vmax):
extend_min = calc_data.min() < vmin
extend_max = calc_data.max() > vmax
if extend_min and extend_max:
extend = "both"
elif extend_min:
extend = "min"
elif extend_max:
extend = "max"
else:
extend = "neither"
return extend
def _build_discrete_cmap(cmap, levels, extend, filled):
"""
Build a discrete colormap and normalization of the data.
"""
import matplotlib as mpl
if not filled:
# non-filled contour plots
extend = "max"
if extend == "both":
ext_n = 2
elif extend in ["min", "max"]:
ext_n = 1
else:
ext_n = 0
n_colors = len(levels) + ext_n - 1
pal = _color_palette(cmap, n_colors)
new_cmap, cnorm = mpl.colors.from_levels_and_colors(levels, pal, extend=extend)
# copy the old cmap name, for easier testing
new_cmap.name = getattr(cmap, "name", cmap)
# copy colors to use for bad, under, and over values in case they have been
# set to non-default values
try:
# matplotlib<3.2 only uses bad color for masked values
bad = cmap(np.ma.masked_invalid([np.nan]))[0]
except TypeError:
# cmap was a str or list rather than a color-map object, so there are
# no bad, under or over values to check or copy
pass
else:
under = cmap(-np.inf)
over = cmap(np.inf)
new_cmap.set_bad(bad)
# Only update under and over if they were explicitly changed by the user
# (i.e. are different from the lowest or highest values in cmap). Otherwise
# leave unchanged so new_cmap uses its default values (its own lowest and
# highest values).
if under != cmap(0):
new_cmap.set_under(under)
if over != cmap(cmap.N - 1):
new_cmap.set_over(over)
return new_cmap, cnorm
def _color_palette(cmap, n_colors):
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
colors_i = | np.linspace(0, 1.0, n_colors) | numpy.linspace |
"""
Materials for the objects in a scene.
"""
import random
import math
import numpy
from PIL import Image
RNG = numpy.random.default_rng()
AXIS_COLOUR_PAIRS = [
# +X : Red
(numpy.array([1.0, 0.0, 0.0], dtype=numpy.single), numpy.array([1.0, 0.0, 0.0], dtype=numpy.single)),
# +Y : Green
(numpy.array([0.0, 1.0, 0.0], dtype=numpy.single), numpy.array([0.0, 1.0, 0.0], dtype=numpy.single)),
# +Z : Blue
(numpy.array([0.0, 0.0, 1.0]), numpy.array([0.0, 0.0, 1.0], dtype=numpy.single)),
# -X : Pink
(numpy.array([-1.0, 0.0, 0.0], dtype=numpy.single), numpy.array([1.0, 0.0, 1.0], dtype=numpy.single)),
# -Y : Yellow
(numpy.array([0.0, -1.0, 0.0], dtype=numpy.single), numpy.array([1.0, 1.0, 0.0], dtype=numpy.single)),
# -Z : Cyan
(numpy.array([0.0, 0.0, -1.0], dtype=numpy.single), numpy.array([0.0, 1.0, 1.0], dtype=numpy.single)),
]
class Diffuse():
"""
Scatter rays towards points on a hemisphere at the hit point.
This provides a good approximation to the lambert shading model.
This comes from https://raytracing.github.io/books/RayTracingInOneWeekend.html#diffusematerials/analternativediffuseformulation.
A scattered ray bounces off the hitpoint, aiming toward a
random point on the surface of a hemisphere with the centre of it's
flat side at the hit point, and the centre/top of the dome pointing
in the direction of the normal at that point of the surface.
"""
def __init__(self, colour):
"""
Initialise the object.
Args:
colour (numpy.array): An RGB 0-1 array representing the
colour of the material.
"""
self.colour = colour
def scatter(self, hit_raydirs, hit_points, hit_normals, hit_uvs, hit_backfaces):
# Generate points in unit hemispheres pointing in the normal direction
ray_dirs = numpy_random_unit_vecs(hit_points.shape[0])
# Reverse any points in the wrong hemisphere
cosine_angles = numpy.einsum("ij,ij->i", ray_dirs, hit_normals)
facing_wrong_way = cosine_angles < 0.0
ray_dirs[facing_wrong_way] *= -1.0
# Bounce ray origins are the hit points we fed in
# Bounce ray directions are the random points in the hemisphere.
hit_cols = numpy.full((hit_points.shape[0], 3), self.colour, dtype=numpy.single)
absorbtions = numpy.full((hit_points.shape[0]), False)
return hit_points, ray_dirs, hit_cols, absorbtions
class TexturedDiffuse():
def __init__(self, texture_path):
"""
Initialise the object.
Args:
texture_path (str): Path to texture
"""
texture = Image.open(texture_path)
width = texture.width
height = texture.height
self.smallest_side = float(min((width, height)))
tex_mode = texture.mode
tex_mode_map = {
"RGB": 3,
"RGBA": 4
}
if tex_mode not in tex_mode_map:
raise Exception(f"Unsupported texture image mode: {tex_mode}")
self.texture_pixels = numpy.array(texture.getdata(), dtype=numpy.single)
self.texture_pixels /= 255.0
self.texture_pixels = self.texture_pixels.reshape(
(height, width, tex_mode_map[tex_mode])
)
self.texture_pixels = self.texture_pixels[:, :, 0:3]
self.texture_pixels = numpy.flipud(self.texture_pixels)
# self.texture_pixels = numpy.fliplr(self.texture_pixels)
def scatter(self, hit_raydirs, hit_points, hit_normals, hit_uvs, hit_backfaces):
# Generate points in unit hemispheres pointing in the normal direction
ray_dirs = numpy_random_unit_vecs(hit_points.shape[0])
# Reverse any points in the wrong hemisphere
cosine_angles = numpy.einsum("ij,ij->i", ray_dirs, hit_normals)
facing_wrong_way = cosine_angles < 0.0
ray_dirs[facing_wrong_way] *= -1.0
# Bounce ray origins are the hit points we fed in
# Bounce ray directions are the random points in the hemisphere.
clipped_uvs = numpy.clip(hit_uvs, 0.0, 1.0)
mapped_uvs = clipped_uvs * (self.smallest_side - 1.0)
discretised_uvs = mapped_uvs.astype(numpy.intc)
hit_cols = self.texture_pixels[
discretised_uvs[:, 1],
discretised_uvs[:, 0],
]
# col_choice = hit_uvs[:, 0] > 0.5
# col_choice = hit_uvs[:, 1] > 0.5
# hit_cols = numpy.where(
# col_choice[:, numpy.newaxis],
# numpy.array([0.1, 0.8, 0.2]),
# numpy.array([0.2, 0.1, 0.1])
# )
absorbtions = numpy.full((hit_points.shape[0]), False)
return hit_points, ray_dirs, hit_cols, absorbtions
class CheckerboardDiffuse():
def __init__(self, scale, offset, colour_a, colour_b):
"""
Initialise the object.
Args:
"""
self.scale = scale
self.offset = offset
self.colour_a = colour_a
self.colour_b = colour_b
def scatter(self, hit_raydirs, hit_points, hit_normals, hit_uvs, hit_backfaces):
# Generate points in unit hemispheres pointing in the normal direction
ray_dirs = numpy_random_unit_vecs(hit_points.shape[0])
# Reverse any points in the wrong hemisphere
cosine_angles = numpy.einsum("ij,ij->i", ray_dirs, hit_normals)
facing_wrong_way = cosine_angles < 0.0
ray_dirs[facing_wrong_way] *= -1.0
# Bounce ray origins are the hit points we fed in
# Bounce ray directions are the random points in the hemisphere.
Xs = numpy.remainder(numpy.fabs(numpy.floor(hit_points[:, 0] * self.scale[0] + self.offset[0])), 2)
Ys = numpy.remainder(numpy.fabs(numpy.floor(hit_points[:, 1] * self.scale[1] + self.offset[1])), 2)
Zs = numpy.remainder(numpy.fabs(numpy.floor(hit_points[:, 2] * self.scale[2] + self.offset[2])), 2)
col_choice = numpy.logical_xor(Xs, numpy.logical_xor(Ys, Zs))
hit_cols = numpy.where(
col_choice[:, numpy.newaxis],
self.colour_a,
self.colour_b
)
absorbtions = numpy.full((hit_points.shape[0]), False)
return hit_points, ray_dirs, hit_cols, absorbtions
class NormalToRGBDiffuse():
"""
Colour the surface based on the world normal at that
point.
"""
def scatter(self, hit_raydirs, hit_points, hit_normals, hit_uvs, hit_backfaces):
# Generate points in unit hemispheres pointing in the normal direction
ray_dirs = numpy_random_unit_vecs(hit_points.shape[0])
# Reverse any points in the wrong hemisphere
cosine_angles = | numpy.einsum("ij,ij->i", ray_dirs, hit_normals) | numpy.einsum |
"""Random Forest (RandomForest) model from sklearn"""
import datatable as dt
import numpy as np
from h2oaicore.models import CustomModel
from sklearn.ensemble import RandomForestClassifier, RandomForestRegressor
from sklearn.preprocessing import LabelEncoder
from h2oaicore.systemutils import physical_cores_count, config
class RandomForestModel(CustomModel):
_regression = True
_binary = True
_multiclass = True
_display_name = "RandomForest"
_description = "Random Forest Model based on sklearn"
_testing_can_skip_failure = False # ensure tested as if shouldn't fail
@staticmethod
def can_use(accuracy, interpretability, train_shape=None, test_shape=None, valid_shape=None, n_gpus=0, num_classes=None, **kwargs):
if config.hard_asserts:
# for bigger data, too slow to test even with 1 iteration
use = train_shape is not None and train_shape[0] * train_shape[1] < 1024 * 1024 or \
valid_shape is not None and valid_shape[0] * valid_shape[1] < 1024 * 1024
# too slow for walmart with only 421k x 15
use &= train_shape is not None and train_shape[1] < 10
return use
else:
return True
def set_default_params(self, accuracy=None, time_tolerance=None,
interpretability=None, **kwargs):
# Fill up parameters we care about
n_estimators = min(kwargs.get("n_estimators", 100), 1000)
if config.hard_asserts:
# for testing avoid too many trees
n_estimators = 10
self.params = dict(random_state=kwargs.get("random_state", 1234),
n_estimators=n_estimators,
criterion="gini" if self.num_classes >= 2 else "mse",
n_jobs=self.params_base.get('n_jobs', max(1, physical_cores_count)),
max_depth=14,
min_samples_split=2,
min_samples_leaf=1,
oob_score=False,
)
def mutate_params(self, accuracy=10, **kwargs):
if accuracy > 8:
estimators_list = [100, 200, 300, 500, 1000, 2000]
elif accuracy >= 5:
estimators_list = [50, 100, 200, 300, 400, 500]
elif accuracy >= 3:
estimators_list = [10, 50, 100]
elif accuracy >= 2:
estimators_list = [10, 50]
else:
estimators_list = [10]
if config.hard_asserts:
# for testing avoid too many trees
estimators_list = [10]
# Modify certain parameters for tuning
self.params["n_estimators"] = int( | np.random.choice(estimators_list) | numpy.random.choice |
# This program was ported from the YAD2K project.
# https://github.com/allanzelener/YAD2K
#
# copyright
# https://github.com/allanzelener/YAD2K/blob/master/LICENSE
#
import numpy as np
region_biases = (1.080000, 1.190000, 3.420000, 4.410000, 6.630000, 11.380000, 9.420000, 5.110000, 16.620001, 10.520000)
voc_anchors = np.array(
[[1.08, 1.19], [3.42, 4.41], [6.63, 11.38], [9.42, 5.11], [16.62, 10.52]])
voc_label = ['aeroplane', 'bicycle', 'bird', 'boat', 'bottle', 'bus', 'car', 'cat',
'chair', 'cow', 'diningtable', 'dog', 'horse', 'motorbike', 'person',
'pottedplant', 'sheep', 'sofa', 'train', 'tvmonitor']
def sigmoid(x):
return 1.0 / (1.0 + np.exp(-x))
def softmax(x):
"""Compute softmax values for each sets of scores in x."""
# shape (1, 13 , 13, 5, 20)
dim = x.shape
arr = | np.copy(x) | numpy.copy |
'''
Comparing single layer MLP with deep MLP (using TensorFlow)
'''
import numpy as np
import pickle
import timeit
start = timeit.default_timer()
# Do not change this
def initializeWeights(n_in,n_out):
"""
# initializeWeights return the random weights for Neural Network given the
# number of node in the input layer and output layer
# Input:
# n_in: number of nodes of the input layer
# n_out: number of nodes of the output layer
# Output:
# W: matrix of random initial weights with size (n_out x (n_in + 1))"""
epsilon = sqrt(6) / sqrt(n_in + n_out + 1);
W = (np.random.rand(n_out, n_in + 1)*2* epsilon) - epsilon;
return W
# Replace this with your sigmoid implementation
def sigmoid(z):
"""# Notice that z can be a scalar, a vector or a matrix
# return the sigmoid of input z"""
Z = np.array(z)
if (np.shape(Z) == ()):
sigmoid = 1/(1+math.exp(-Z))
return sigmoid
else:
sigmoid = 1/(1+np.exp(-Z))
return sigmoid
# Replace this with your nnObjFunction implementation
def nnObjFunction(params, *args):
"""% nnObjFunction computes the value of objective function (negative log
% likelihood error function with regularization) given the parameters
% of Neural Networks, thetraining data, their corresponding training
% labels and lambda - regularization hyper-parameter.
% Input:
% params: vector of weights of 2 matrices w1 (weights of connections from
% input layer to hidden layer) and w2 (weights of connections from
% hidden layer to output layer) where all of the weights are contained
% in a single vector.
% n_input: number of node in input layer (not include the bias node)
% n_hidden: number of node in hidden layer (not include the bias node)
% n_class: number of node in output layer (number of classes in
% classification problem
% training_data: matrix of training data. Each row of this matrix
% represents the feature vector of a particular image
% training_label: the vector of truth label of training images. Each entry
% in the vector represents the truth label of its corresponding image.
% lambda: regularization hyper-parameter. This value is used for fixing the
% overfitting problem.
% Output:
% obj_val: a scalar value representing value of error function
% obj_grad: a SINGLE vector of gradient value of error function
% NOTE: how to compute obj_grad
% Use backpropagation algorithm to compute the gradient of error function
% for each weights in weight matrices.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% reshape 'params' vector into 2 matrices of weight w1 and w2
% w1: matrix of weights of connections from input layer to hidden layers.
% w1(i, j) represents the weight of connection from unit j in input
% layer to unit i in hidden layer.
% w2: matrix of weights of connections from hidden layer to output layers.
% w2(i, j) represents the weight of connection from unit j in hidden
% layer to unit i in output layer."""
# Your code here
#
#
#
#
#
# Make sure you reshape the gradient matrices to a 1D array. for instance if your gradient matrices are grad_w1 and grad_w2
# you would use code similar to the one below to create a flat array
# obj_grad = np.concatenate((grad_w1.flatten(), grad_w2.flatten()),0)
n_input, n_hidden, n_class, training_data, training_label, lambdaval = args
w1 = params[0:n_hidden * (n_input + 1)].reshape((n_hidden, (n_input + 1)))
w2 = params[(n_hidden * (n_input + 1)):].reshape((n_class, (n_hidden + 1)))
obj_val = 0
## Creating bias term in training data
training_data = np.concatenate((training_data,np.reshape(np.ones(len(training_data)),[len(training_data), 1])),axis = 1)
## Feed Forward network
output_HL = np.dot(w1,np.transpose(training_data))
output_HL_Sigmoid = sigmoid(output_HL)
bias_hidden = np.ones([1,output_HL_Sigmoid.shape[1]])
output_HL_Sigmoid = np.concatenate((output_HL_Sigmoid,bias_hidden),axis = 0)
output_OL = np.dot(w2,output_HL_Sigmoid)
output_OL_Sigmoid = sigmoid(output_OL)
## Creating boolean labels with size k * n
training_label_n = np.zeros([n_class, training_label.shape[0]])
for i in range(0,len(training_label)):
training_label_n[int(training_label[i]), i ] = 1
## Calculating error_function
leftTerm = training_label_n * np.log(output_OL_Sigmoid)
rightTerm = (1-training_label_n) * | np.log(1-output_OL_Sigmoid) | numpy.log |
import os
import numpy as np
from urllib import request
import errno
import struct
import tarfile
import glob
import scipy.io as sio
from sklearn.utils.extmath import cartesian
from scipy.stats import laplace
import joblib
from spriteworld import factor_distributions as distribs
from spriteworld import renderers as spriteworld_renderers
from spriteworld import sprite
import csv
from collections import defaultdict
import ast
from scripts.data_analysis_utils import load_csv
import pandas as pd
from sklearn import preprocessing
from sklearn import utils
import torch
from torch.utils.data import Dataset, DataLoader
from torchvision.datasets import ImageFolder
from torchvision.datasets.utils import download_url, check_integrity
from torchvision import transforms
from PIL import Image
import pickle
import h5py
from matplotlib import pyplot as plt
class TupleLoader(Dataset):
def __init__(self, k=-1, rate=1, prior='uniform', transform=None,
target_transform=None):
# k=-1 gives random number of changing factors as in Locatello k=rand
# rate=-1 gives random rate for each sample in Uniform(1,10)
self.index_manager = None # set in child class
self.factor_sizes = None # set in child class
self.categorical = None # set in child class
self.data = None # set in child class
self.prior = prior
self.transform = transform
self.target_transform = target_transform
self.rate = rate
self.k = k
if prior == 'laplace' and k != -1:
print('warning setting k has no effect on prior=laplace. '
'Set k=-1 or leave to default to get rid of this warning.')
if prior == 'uniform' and rate != -1:
print('warning setting rate has no effect on prior=uniform. '
'Set rate=-1 or leave to default to get rid of this warning.')
def __len__(self):
return len(self.data)
def sample_factors(self, num, random_state):
"""Sample a batch of observations X. Needed in dis. lib."""
assert not(num % 2)
batch_size = int(num / 2)
indices = random_state.choice(self.__len__(), 2 * batch_size, replace=False)
batch, latents = [], []
for ind in indices:
_, _, l1, _ = self.__getitem__(ind)
latents.append(l1)
return np.stack(latents)
def sample_observations_from_factors(self, factors, random_state):
batch = []
for factor in factors:
sample_ind = self.index_manager.features_to_index(factor)
sample = self.data[sample_ind]
if self.transform:
sample = self.transform(sample)
if len(sample.shape) == 2: # set channel dim to 1
sample = sample[None]
if np.issubdtype(sample.dtype, np.uint8):
sample = sample.astype(np.float32) / 255.
batch.append(sample)
return np.stack(batch)
def sample(self, num, random_state):
#Sample a batch of factors Y and observations X
factors = self.sample_factors(num, random_state)
return factors, self.sample_observations_from_factors(factors, random_state)
def sample_observations(self, num, random_state):
#Sample a batch of observations X
return self.sample(num, random_state)[1]
def __getitem__(self, idx):
n_factors = len(self.factor_sizes)
first_sample = self.data[idx]
first_sample_feat = self.index_manager.index_to_features(idx)
if self.prior == 'uniform':
# only change up to k factors
if self.k == -1:
k = np.random.randint(1, n_factors) # number of factors which can change
else:
k = self.k
second_sample_feat = first_sample_feat.copy()
indices = np.random.choice(n_factors, k, replace=False)
for ind in indices:
x = np.arange(self.factor_sizes[ind])
p = np.ones_like(x) / (x.shape[0] - 1)
p[x == first_sample_feat[ind]] = 0 # dont pick same
second_sample_feat[ind] = np.random.choice(x, 1, p=p)
assert np.equal(first_sample_feat - second_sample_feat, 0).sum() == n_factors - k
elif self.prior == 'laplace':
second_sample_feat = self.truncated_laplace(first_sample_feat)
else:
raise NotImplementedError
second_sample_ind = self.index_manager.features_to_index(second_sample_feat)
second_sample = self.data[second_sample_ind]
if self.transform:
first_sample = self.transform(first_sample)
second_sample = self.transform(second_sample)
if len(first_sample.shape) == 2: # set channel dim to 1
first_sample = first_sample[None]
second_sample = second_sample[None]
if np.issubdtype(first_sample.dtype, np.uint8) or np.issubdtype(second_sample.dtype, np.uint8):
first_sample = first_sample.astype(np.float32) / 255.
second_sample = second_sample.astype(np.float32) / 255.
if self.target_transform:
first_sample_feat = self.target_transform(first_sample_feat)
second_sample_feat = self.target_transform(second_sample_feat)
return first_sample, second_sample, first_sample_feat, second_sample_feat
def truncated_laplace(self, start):
if self.rate == -1:
rate = np.random.uniform(1, 10, 1)[0]
else:
rate = self.rate
end = []
n_factors = len(self.factor_sizes)
for mean, upper in zip(start, np.array(self.factor_sizes)): # sample each feature individually
x = np.arange(upper)
p = laplace.pdf(x, loc=mean, scale=np.log(upper) / rate)
p /= np.sum(p)
end.append(np.random.choice(x, 1, p=p)[0])
end = np.array(end).astype(np.int)
end[self.categorical] = start[self.categorical] # don't change categorical factors s.a. shape
# make sure there is at least one change
if np.sum(abs(start - end)) == 0:
ind = np.random.choice(np.arange(n_factors)[~self.categorical], 1)[0] # don't change categorical factors
x = np.arange(self.factor_sizes[ind])
p = laplace.pdf(x, loc=start[ind],
scale=np.log(self.factor_sizes[ind]) / rate)
p[x == start[ind]] = 0
p /= np.sum(p)
end[ind] = np.random.choice(x, 1, p=p)
assert np.sum(abs(start - end)) > 0
return end
class IndexManger(object):
"""Index mapping from features to positions of state space atoms."""
def __init__(self, factor_sizes):
"""Index to latent (= features) space and vice versa.
Args:
factor_sizes: List of integers with the number of distinct values for each
of the factors.
"""
self.factor_sizes = np.array(factor_sizes)
self.num_total = np.prod(self.factor_sizes)
self.factor_bases = self.num_total / np.cumprod(self.factor_sizes)
self.index_to_feat = cartesian([np.array(list(range(i))) for i in self.factor_sizes])
def features_to_index(self, features):
"""Returns the indices in the input space for given factor configurations.
Args:
features: Numpy matrix where each row contains a different factor
configuration for which the indices in the input space should be
returned.
"""
assert np.all((0 <= features) & (features <= self.factor_sizes))
index = np.array(np.dot(features, self.factor_bases), dtype=np.int64)
assert np.all((0 <= index) & (index < self.num_total))
return index
def index_to_features(self, index):
assert np.all((0 <= index) & (index < self.num_total))
features = self.index_to_feat[index]
assert np.all((0 <= features) & (features <= self.factor_sizes))
return features
class Cars3D(TupleLoader):
fname = 'nips2015-analogy-data.tar.gz'
url = 'http://www.scottreed.info/files/nips2015-analogy-data.tar.gz'
"""
[4, 24, 183]
0. phi altitude viewpoint
1. theta azimuth viewpoint
2. car type
"""
def __init__(self, path='./data/cars/', data=None, **tupel_loader_kwargs):
super().__init__(**tupel_loader_kwargs)
self.factor_sizes = [4, 24, 183]
self.num_factors = len(self.factor_sizes)
self.categorical = np.array([False, False, True])
self.data_shape = [64, 64, 3]
self.index_manager = IndexManger(self.factor_sizes)
# download automatically if not exists
if not os.path.exists(path):
self.download_data(path)
if data is None:
all_files = glob.glob(path + '/*.mat')
self.data = np.moveaxis(self._load_data(all_files).astype(np.float32), 3, 1)
else: # speedup for debugging
self.data = data
def _load_data(self, all_files):
def _load_mesh(filename):
"""Parses a single source file and rescales contained images."""
with open(os.path.join(filename), "rb") as f:
mesh = np.einsum("abcde->deabc", sio.loadmat(f)["im"])
flattened_mesh = mesh.reshape((-1,) + mesh.shape[2:])
rescaled_mesh = np.zeros((flattened_mesh.shape[0], 64, 64, 3))
for i in range(flattened_mesh.shape[0]):
pic = Image.fromarray(flattened_mesh[i, :, :, :])
pic.thumbnail((64, 64), Image.ANTIALIAS)
rescaled_mesh[i, :, :, :] = np.array(pic)
return rescaled_mesh * 1. / 255
dataset = np.zeros((24 * 4 * 183, 64, 64, 3))
for i, filename in enumerate(all_files):
data_mesh = _load_mesh(filename)
factor1 = np.array(list(range(4)))
factor2 = np.array(list(range(24)))
all_factors = np.transpose([np.tile(factor1, len(factor2)),
np.repeat(factor2, len(factor1)),
np.tile(i, len(factor1) * len(factor2))])
indexes = self.index_manager.features_to_index(all_factors)
dataset[indexes] = data_mesh
return dataset
def download_data(self, load_path='./data/cars/'):
os.makedirs(load_path, exist_ok=True)
print('downlading data may take a couple of seconds, total ~ 300MB')
request.urlretrieve(self.url, os.path.join(load_path, self.fname))
print('extracting data, do NOT interrupt')
tar = tarfile.open(os.path.join(load_path, self.fname), "r:gz")
tar.extractall()
tar.close()
print('saved data at', load_path)
class SmallNORB(TupleLoader):
"""`MNIST <https://cs.nyu.edu/~ylclab/data/norb-v1.0-small//>`_ Dataset.
factors:
[5, 10, 9, 18, 6]
- 0. (0 to 4) 0 for animal, 1 for human, 2 for plane, 3 for truck, 4 for car).
- 1. the instance in the category (0 to 9)
- 2. the elevation (0 to 8, which mean cameras are 30, 35,40,45,50,55,60,65,70 degrees from the horizontal respectively)
- 3. the azimuth (0,2,4,...,34, multiply by 10 to get the azimuth in degrees)
- 4. the lighting condition (0 to 5)
"""
dataset_root = "https://cs.nyu.edu/~ylclab/data/norb-v1.0-small/"
data_files = {
'train': {
'dat': {
"name": 'smallnorb-5x46789x9x18x6x2x96x96-training-dat.mat',
"md5_gz": "66054832f9accfe74a0f4c36a75bc0a2",
"md5": "8138a0902307b32dfa0025a36dfa45ec"
},
'info': {
"name": 'smallnorb-5x46789x9x18x6x2x96x96-training-info.mat',
"md5_gz": "51dee1210a742582ff607dfd94e332e3",
"md5": "19faee774120001fc7e17980d6960451"
},
'cat': {
"name": 'smallnorb-5x46789x9x18x6x2x96x96-training-cat.mat',
"md5_gz": "23c8b86101fbf0904a000b43d3ed2fd9",
"md5": "fd5120d3f770ad57ebe620eb61a0b633"
},
},
'test': {
'dat': {
"name": 'smallnorb-5x01235x9x18x6x2x96x96-testing-dat.mat',
"md5_gz": "e4ad715691ed5a3a5f138751a4ceb071",
"md5": "e9920b7f7b2869a8f1a12e945b2c166c"
},
'info': {
"name": 'smallnorb-5x01235x9x18x6x2x96x96-testing-info.mat',
"md5_gz": "a9454f3864d7fd4bb3ea7fc3eb84924e",
"md5": "7c5b871cc69dcadec1bf6a18141f5edc"
},
'cat': {
"name": 'smallnorb-5x01235x9x18x6x2x96x96-testing-cat.mat',
"md5_gz": "5aa791cd7e6016cf957ce9bdb93b8603",
"md5": "fd5120d3f770ad57ebe620eb61a0b633"
},
},
}
raw_folder = 'raw'
processed_folder = 'processed'
train_image_file = 'train_img'
train_label_file = 'train_label'
train_info_file = 'train_info'
test_image_file = 'test_img'
test_label_file = 'test_label'
test_info_file = 'test_info'
extension = '.pt'
def __init__(self, path='./data/smallNORB/', download=True,
mode="all",
transform=None,
evaluate=False,
**tupel_loader_kwargs):
super().__init__(**tupel_loader_kwargs)
self.root = os.path.expanduser(path)
self.mode = mode
self.evaluate = evaluate
self.factor_sizes = [5, 10, 9, 18, 6]
self.latent_factor_indices = [0, 2, 3, 4]
self.num_factors = len(self.latent_factor_indices)
self.categorical = np.array([True, True, False, False, False])
self.index_manager = IndexManger(self.factor_sizes)
if transform:
self.transform = transform
else:
self.transform = transforms.Compose([
transforms.ToPILImage(),
transforms.Resize((64, 64), interpolation=2),
transforms.ToTensor(),
lambda x: x.numpy()])
if download:
self.download()
if not self._check_exists():
raise RuntimeError('Dataset not found or corrupted.' +
' You can use download=True to download it')
# load labels
labels_train = self._load(self.train_label_file)
labels_test = self._load(self.test_label_file)
# load info files
infos_train = self._load(self.train_info_file)
infos_test = self._load(self.test_info_file)
# load right set
data_train = self._load("{}_left".format(self.train_image_file))
data_test = self._load("{}_left".format(self.test_image_file))
info_train = torch.cat([labels_train[:, None], infos_train], dim=1)
info_test = torch.cat([labels_test[:, None], infos_test], dim=1)
infos = torch.cat([info_train, info_test])
data = torch.cat([data_train, data_test])
sorted_inds = np.lexsort([infos[:, i] for i in range(4, -1, -1)])
self.infos = infos[sorted_inds]
self.data = data[sorted_inds].numpy() # is uint8
def sample_factors(self, num, random_state):
# override super to ignore instance (see https://github.com/google-research/disentanglement_lib/blob/86a644d4ed35c771560dc3360756363d35477357/disentanglement_lib/data/ground_truth/norb.py#L52)
factors = super().sample_factors(num, random_state)
if self.evaluate:
factors = np.concatenate([factors[:, :1], factors[:, 2:]], 1)
return factors
def sample_observations_from_factors(self, factors, random_state):
# override super to ignore instance (see https://github.com/google-research/disentanglement_lib/blob/86a644d4ed35c771560dc3360756363d35477357/disentanglement_lib/data/ground_truth/norb.py#L52)
if self.evaluate:
instances = random_state.randint(0, self.factor_sizes[1], factors[:, :1].shape)
factors = np.concatenate([factors[:, :1], instances, factors[:, 1:]], 1)
return super().sample_observations_from_factors(factors, random_state)
def __len__(self):
return len(self.data)
def _transform(self, img):
# doing this so that it is consistent with all other data sets
# to return a PIL Image
img = Image.fromarray(img.numpy(), mode='L')
if self.transform is not None:
img = self.transform(img)
return img
def _load(self, file_name):
return torch.load(os.path.join(self.root, self.processed_folder, file_name + self.extension))
def _save(self, file, file_name):
with open(os.path.join(self.root, self.processed_folder, file_name + self.extension), 'wb') as f:
torch.save(file, f)
def _check_exists(self):
""" Check if processed files exists."""
files = (
"{}_left".format(self.train_image_file),
"{}_right".format(self.train_image_file),
"{}_left".format(self.test_image_file),
"{}_right".format(self.test_image_file),
self.test_label_file,
self.train_label_file
)
fpaths = [os.path.exists(os.path.join(self.root, self.processed_folder, f + self.extension)) for f in files]
return False not in fpaths
def _flat_data_files(self):
return [j for i in self.data_files.values() for j in list(i.values())]
def _check_integrity(self):
"""Check if unpacked files have correct md5 sum."""
root = self.root
for file_dict in self._flat_data_files():
filename = file_dict["name"]
md5 = file_dict["md5"]
fpath = os.path.join(root, self.raw_folder, filename)
if not check_integrity(fpath, md5):
return False
return True
def download(self):
"""Download the SmallNORB data if it doesn't exist in processed_folder already."""
import gzip
if self._check_exists():
return
# check if already extracted and verified
if self._check_integrity():
print('Files already downloaded and verified')
else:
# download and extract
for file_dict in self._flat_data_files():
url = self.dataset_root + file_dict["name"] + '.gz'
filename = file_dict["name"]
gz_filename = filename + '.gz'
md5 = file_dict["md5_gz"]
fpath = os.path.join(self.root, self.raw_folder, filename)
gz_fpath = fpath + '.gz'
# download if compressed file not exists and verified
download_url(url, os.path.join(self.root, self.raw_folder), gz_filename, md5)
print('# Extracting data {}\n'.format(filename))
with open(fpath, 'wb') as out_f, \
gzip.GzipFile(gz_fpath) as zip_f:
out_f.write(zip_f.read())
os.unlink(gz_fpath)
# process and save as torch files
print('Processing...')
# create processed folder
try:
os.makedirs(os.path.join(self.root, self.processed_folder))
except OSError as e:
if e.errno == errno.EEXIST:
pass
else:
raise
# read train files
left_train_img, right_train_img = self._read_image_file(self.data_files["train"]["dat"]["name"])
train_info = self._read_info_file(self.data_files["train"]["info"]["name"])
train_label = self._read_label_file(self.data_files["train"]["cat"]["name"])
# read test files
left_test_img, right_test_img = self._read_image_file(self.data_files["test"]["dat"]["name"])
test_info = self._read_info_file(self.data_files["test"]["info"]["name"])
test_label = self._read_label_file(self.data_files["test"]["cat"]["name"])
# save training files
self._save(left_train_img, "{}_left".format(self.train_image_file))
self._save(right_train_img, "{}_right".format(self.train_image_file))
self._save(train_label, self.train_label_file)
self._save(train_info, self.train_info_file)
# save test files
self._save(left_test_img, "{}_left".format(self.test_image_file))
self._save(right_test_img, "{}_right".format(self.test_image_file))
self._save(test_label, self.test_label_file)
self._save(test_info, self.test_info_file)
print('Done!')
@staticmethod
def _parse_header(file_pointer):
# Read magic number and ignore
struct.unpack('<BBBB', file_pointer.read(4)) # '<' is little endian)
# Read dimensions
dimensions = []
num_dims, = struct.unpack('<i', file_pointer.read(4)) # '<' is little endian)
for _ in range(num_dims):
dimensions.extend(struct.unpack('<i', file_pointer.read(4)))
return dimensions
def _read_image_file(self, file_name):
fpath = os.path.join(self.root, self.raw_folder, file_name)
with open(fpath, mode='rb') as f:
dimensions = self._parse_header(f)
assert dimensions == [24300, 2, 96, 96]
num_samples, _, height, width = dimensions
left_samples = np.zeros(shape=(num_samples, height, width), dtype=np.uint8)
right_samples = np.zeros(shape=(num_samples, height, width), dtype=np.uint8)
for i in range(num_samples):
# left and right images stored in pairs, left first
left_samples[i, :, :] = self._read_image(f, height, width)
right_samples[i, :, :] = self._read_image(f, height, width)
return torch.ByteTensor(left_samples), torch.ByteTensor(right_samples)
@staticmethod
def _read_image(file_pointer, height, width):
"""Read raw image data and restore shape as appropriate. """
image = struct.unpack('<' + height * width * 'B', file_pointer.read(height * width))
image = np.uint8(np.reshape(image, newshape=(height, width)))
return image
def _read_label_file(self, file_name):
fpath = os.path.join(self.root, self.raw_folder, file_name)
with open(fpath, mode='rb') as f:
dimensions = self._parse_header(f)
assert dimensions == [24300]
num_samples = dimensions[0]
struct.unpack('<BBBB', f.read(4)) # ignore this integer
struct.unpack('<BBBB', f.read(4)) # ignore this integer
labels = np.zeros(shape=num_samples, dtype=np.int32)
for i in range(num_samples):
category, = struct.unpack('<i', f.read(4))
labels[i] = category
return torch.LongTensor(labels)
def _read_info_file(self, file_name):
fpath = os.path.join(self.root, self.raw_folder, file_name)
with open(fpath, mode='rb') as f:
dimensions = self._parse_header(f)
assert dimensions == [24300, 4]
num_samples, num_info = dimensions
struct.unpack('<BBBB', f.read(4)) # ignore this integer
infos = np.zeros(shape=(num_samples, num_info), dtype=np.int32)
for r in range(num_samples):
for c in range(num_info):
info, = struct.unpack('<i', f.read(4))
infos[r, c] = info
return torch.LongTensor(infos)
class Shapes3D(TupleLoader):
"""Shapes3D dataset.
self.factor_sizes = [10, 10, 10, 8, 4, 15]
The data set was originally introduced in "Disentangling by Factorising".
The ground-truth factors of variation are:
0 - floor color (10 different values)
1 - wall color (10 different values)
2 - object color (10 different values)
3 - object size (8 different values)
4 - object type (4 different values)
5 - azimuth (15 different values)
"""
#url = 'https://liquidtelecom.dl.sourceforge.net/project/shapes3d/Shapes3D.zip'
#fname = 'shapes3d.pkl'
url = 'https://storage.googleapis.com/3d-shapes/3dshapes.h5'
fname = '3dshapes.h5'
def __init__(self, path='./data/shapes3d/', data=None, **tupel_loader_kwargs):
super().__init__(**tupel_loader_kwargs)
self.factor_sizes = [10, 10, 10, 8, 4, 15]
self.num_factors = len(self.factor_sizes)
self.categorical = np.array([False, False, False, False, True, False])
self.index_manager = IndexManger(self.factor_sizes)
self.path = path
if not os.path.exists(self.path):
self.download()
# read dataset
print('init of shapes dataset (takes a couple of seconds) (large data array)')
if data is None:
with h5py.File(os.path.join(self.path, self.fname), 'r') as dataset:
images = dataset['images'][()]
self.data = np.transpose(images, (0, 3, 1, 2)) # np.uint8
else:
self.data = data
def download(self):
print('downloading shapes3d')
os.makedirs(self.path, exist_ok=True)
request.urlretrieve(self.url, os.path.join(self.path, self.fname))
class SpriteDataset(TupleLoader):
"""
A PyTorch wrapper for the dSprites dataset by
Matthey et al. 2017. The dataset provides a 2D scene
with a sprite under different transformations:
# dim, type, #values avail.-range
* 0, color | 1 | 1-1
* 1, shape | 3 | 1-3
* 2, scale | 6 | 0.5-1.
* 3, orientation | 40 | 0-2pi
* 4, x-position | 32 | 0-1
* 5, y-position | 32 | 0-1
for details see https://github.com/deepmind/dsprites-dataset
"""
def __init__(self, path='./data/dsprites/', **tupel_loader_kwargs):
super().__init__(**tupel_loader_kwargs)
url = "https://github.com/deepmind/dsprites-dataset/raw/master/dsprites_ndarray_co1sh3sc6or40x32y32_64x64.npz"
self.path = path
self.factor_sizes = [3, 6, 40, 32, 32]
self.num_factors = len(self.factor_sizes)
self.categorical = np.array([True, False, False, False, False])
self.index_manager = IndexManger(self.factor_sizes)
try:
self.data = self.load_data()
except FileNotFoundError:
if not os.path.exists(path):
os.makedirs(path, exist_ok=True)
print(
f'downloading dataset ... saving to {os.path.join(path, "dsprites.npz")}')
request.urlretrieve(url, os.path.join(path, 'dsprites.npz'))
self.data = self.load_data()
def __len__(self):
return len(self.data)
def load_data(self):
dataset_zip = np.load(os.path.join(self.path, 'dsprites.npz'),
encoding="latin1", allow_pickle=True)
return dataset_zip["imgs"].squeeze().astype(np.float32)
class MPI3DReal(TupleLoader):
"""
object_color white=0, green=1, red=2, blue=3, brown=4, olive=5
object_shape cone=0, cube=1, cylinder=2, hexagonal=3, pyramid=4, sphere=5
object_size small=0, large=1
camera_height top=0, center=1, bottom=2
background_color purple=0, sea green=1, salmon=2
horizontal_axis 0,...,39
vertical_axis 0,...,39
"""
url = 'https://storage.googleapis.com/disentanglement_dataset/Final_Dataset/mpi3d_real.npz'
fname = 'mpi3d_real.npz'
def __init__(self, path='./data/mpi3d_real/', **tupel_loader_kwargs):
super().__init__(**tupel_loader_kwargs)
self.factor_sizes = [6, 6, 2, 3, 3, 40, 40]
self.num_factors = len(self.factor_sizes)
self.categorical = np.array([False, True, False, False, False, False, False])
self.index_manager = IndexManger(self.factor_sizes)
if not os.path.exists(path):
self.download(path)
load_path = os.path.join(path, self.fname)
data = np.load(load_path)['images']
self.data = np.transpose(data.reshape([-1, 64, 64, 3]), (0, 3, 1, 2)) # np.uint8
def download(self, path):
os.makedirs(path, exist_ok=True)
print('downloading')
request.urlretrieve(self.url, os.path.join(path, self.fname))
print('download complete')
def value_to_key(x, val):
for k in x.keys():
if x[k] == val:
return k
def rgb(c):
return tuple((255 * np.array(c)).astype(np.uint8))
class NaturalSprites(Dataset):
def __init__(self, natural_discrete=False, path='./data/natural_sprites/'):
self.natural_discrete = natural_discrete
self.sequence_len = 2 #only consider pairs
self.area_filter = 0.1 #filter out 10% of outliers
self.path = path
self.fname = 'downscale_keepaspect.csv'
self.url = 'https://zenodo.org/record/3948069/files/downscale_keepaspect.csv?download=1'
self.load_data()
def load_data(self):
# download if not avaiable
file_path = os.path.join(self.path, self.fname)
if not os.path.exists(file_path):
os.makedirs(self.path, exist_ok=True)
print(f'file not found, downloading from {self.url} ...')
from urllib import request
url = self.url
request.urlretrieve(url, file_path)
with open(file_path) as data:
self.csv_dict = load_csv(data, sequence=self.sequence_len)
self.orig_num = [32, 32, 6, 40, 4, 1, 1, 1]
self.dsprites = {'x': np.linspace(0.2,0.8,self.orig_num[0]),
'y': np.linspace(0.2,0.8,self.orig_num[1]),
'scale': np.linspace(0,0.5,self.orig_num[2]+1)[1:],
'angle': np.linspace(0,360,self.orig_num[3],dtype=np.int,endpoint=False),
'shape': ['square', 'triangle', 'star_4', 'spoke_4'],
'c0': [1.], 'c1': [1.], 'c2': [1.]}
distributions = []
for key in self.dsprites.keys():
distributions.append(distribs.Discrete(key, self.dsprites[key]))
self.factor_dist = distribs.Product(distributions)
self.renderer = spriteworld_renderers.PILRenderer(image_size=(64, 64), anti_aliasing=5,
color_to_rgb=rgb)
if self.area_filter:
keep_idxes = []
print(len(self.csv_dict['x']))
for i in range(self.sequence_len):
x = pd.Series(np.array(self.csv_dict['area'])[:,i])
keep_idxes.append(x.between(x.quantile(self.area_filter/2), x.quantile(1-(self.area_filter/2))))
for k in self.csv_dict.keys():
y = pd.Series(self.csv_dict[k])
self.csv_dict[k] = np.array([x for x in y[np.logical_and(*keep_idxes)]])
print(len(self.csv_dict['x']))
if self.natural_discrete:
num_bins = self.orig_num[:3]
self.lab_encs = {}
print('num_bins', num_bins)
for i,key in enumerate(['x','y','area']):
count, bin_edges = np.histogram(np.array(self.csv_dict[key]).flatten().tolist(), bins=num_bins[i])
bin_left, bin_right = bin_edges[:-1], bin_edges[1:]
bin_centers = bin_left + (bin_right - bin_left)/2
new_data = []
old_shape = np.array(self.csv_dict[key]).shape
lab_enc = preprocessing.LabelEncoder()
if key == 'area':
self.lab_encs['scale'] = lab_enc.fit(np.sqrt(bin_centers/(64**2)))
else:
self.lab_encs[key] = lab_enc.fit(bin_centers/64)
for j in range(self.sequence_len):
differences = (np.array(self.csv_dict[key])[:,j].reshape(1,-1) - bin_centers.reshape(-1,1))
new_data.append([bin_centers[x] for x in np.abs(differences).argmin(axis=0)])
self.csv_dict[key] = np.swapaxes(new_data, 0, 1)
assert old_shape == np.array(self.csv_dict[key]).shape
assert len(np.unique(np.array(self.csv_dict[key]).flatten())) == num_bins[i]
for i,key in enumerate(['angle', 'shape', 'c0', 'c1', 'c2']):
lab_enc = preprocessing.LabelEncoder()
self.lab_encs[key] = lab_enc.fit(self.dsprites[key])
assert self.lab_encs.keys() == self.dsprites.keys()
self.factor_sizes = [len(np.unique(np.array(self.csv_dict['x']).flatten())),
len(np.unique(np.array(self.csv_dict['y']).flatten())),
len(np.unique(np.array(self.csv_dict['area']).flatten())),
40,4,1,1,1]
print(self.factor_sizes)
self.latent_factor_indices = list(range(5))
self.num_factors = len(self.latent_factor_indices)
self.observation_factor_indices = [i for i in range(self.num_factors) if i not in self.latent_factor_indices]
self.mapping = {'square': 0,
'triangle': 1,
'star_4': 2,
'spoke_4': 3}
def __getitem__(self, index):
sampled_latents = self.factor_dist.sample()
idx = np.random.choice(len(self.csv_dict['id']), p=None)
sprites = []
latents = []
for i in range(self.sequence_len):
curr_latents = sampled_latents.copy()
csv_vals = [self.csv_dict['x'][idx][i], self.csv_dict['y'][idx][i], self.csv_dict['area'][idx][i]]
curr_latents['x'] = csv_vals[0]/64
curr_latents['y'] = csv_vals[1]/64
curr_latents['scale'] = np.sqrt(csv_vals[2]/(64**2))
sprites.append(sprite.Sprite(**curr_latents))
latents.append(curr_latents)
first_sample = np.transpose(self.renderer.render(sprites=[sprites[0]]).astype(np.float32) / 255., (2,0,1))
second_sample = np.transpose(self.renderer.render(sprites=[sprites[1]]).astype(np.float32) / 255., (2,0,1))
latents1 = np.array([self.convert_cat(item) for item in latents[0].values()])
latents2 = np.array([self.convert_cat(item) for item in latents[1].values()])
return first_sample, second_sample, latents1, latents2
def __len__(self):
return len(self.csv_dict['id'])
def sample_factors(self, num, random_state):
#Sample a batch of factors Y
if self.natural_discrete:
factors = np.zeros(shape=(num, len(self.latent_factor_indices)), dtype=np.int64)
for pos, i in enumerate(self.latent_factor_indices):
factors[:, pos] = random_state.randint(self.factor_sizes[i], size=num)
return factors
else:
factors = []
for n in range(num):
sampled_latents = self.factor_dist.sample()
idx = random_state.choice(len(self.csv_dict['id']), p=None)
sampled_latents['x'] = self.csv_dict['x'][idx][0]/64
sampled_latents['y'] = self.csv_dict['y'][idx][0]/64
sampled_latents['scale'] = np.sqrt(self.csv_dict['area'][idx][0]/(64**2))
factors.append(np.array([self.convert_cat(item) for item in sampled_latents.values()]))
return | np.array(factors) | numpy.array |
import sys
import numpy as np
import pandas as pd
import openmdao.api as om
from wisdem.commonse import gravity
eps = 1e-3
# Convenience functions for computing McDonald's C and F parameters
def chsMshc(x):
return np.cosh(x) * np.sin(x) - np.sinh(x) * np.cos(x)
def chsPshc(x):
return np.cosh(x) * np.sin(x) + np.sinh(x) * np.cos(x)
def carterFactor(airGap, slotOpening, slotPitch):
"""Return Carter factor
(based on Langsdorff's empirical expression)
See page 3-13 Boldea Induction machines Chapter 3
"""
gma = (2 * slotOpening / airGap) ** 2 / (5 + 2 * slotOpening / airGap)
return slotPitch / (slotPitch - airGap * gma * 0.5)
# ---------------
def carterFactorMcDonald(airGap, h_m, slotOpening, slotPitch):
"""Return Carter factor using Carter's equation
(based on Schwartz-Christoffel's conformal mapping on simplified slot geometry)
This code is based on Eq. B.3-5 in Appendix B of McDonald's thesis.
It is used by PMSG_arms and PMSG_disc.
h_m : magnet height (m)
b_so : stator slot opening (m)
tau_s : Stator slot pitch (m)
"""
mu_r = 1.06 # relative permeability (probably for neodymium magnets, often given as 1.05 - GNS)
g_1 = airGap + h_m / mu_r # g
b_over_a = slotOpening / (2 * g_1)
gamma = 4 / np.pi * (b_over_a * np.arctan(b_over_a) - np.log(np.sqrt(1 + b_over_a ** 2)))
return slotPitch / (slotPitch - gamma * g_1)
# ---------------
def carterFactorEmpirical(airGap, slotOpening, slotPitch):
"""Return Carter factor using Langsdorff's empirical expression"""
sigma = (slotOpening / airGap) / (5 + slotOpening / airGap)
return slotPitch / (slotPitch - sigma * slotOpening)
# ---------------
def carterFactorSalientPole(airGap, slotWidth, slotPitch):
"""Return Carter factor for salient pole rotor
Where does this equation come from? It's different from other approximations above.
Original code:
tau_s = np.pi * dia / S # slot pitch
b_s = tau_s * b_s_tau_s # slot width
b_t = tau_s - b_s # tooth width
K_C1 = (tau_s + 10 * g_a) / (tau_s - b_s + 10 * g_a) # salient pole rotor
slotPitch - slotWidth == toothWidth
"""
return (slotPitch + 10 * airGap) / (slotPitch - slotWidth + 10 * airGap) # salient pole rotor
# ---------------------------------
def array_seq(q1, b, c, Total_number):
Seq = np.array([1, 0, 0, 1, 0])
diff = Total_number * 5 / 6
G = np.prod(Seq.shape)
return Seq, diff, G
# ---------------------------------
def winding_factor(Sin, b, c, p, m):
S = int(Sin)
# Step 1 Writing q1 as a fraction
q1 = b / c
# Step 2: Writing a binary sequence of b-c zeros and b ones
Total_number = int(S / b)
L = array_seq(q1, b, c, Total_number)
# STep 3 : Repeat binary sequence Q_s/b times
New_seq = np.tile(L[0], Total_number)
Actual_seq1 = pd.DataFrame(New_seq[:, None].T)
Winding_sequence = ["A", "C1", "B", "A1", "C", "B1"]
New_seq2 = np.tile(Winding_sequence, int(L[1]))
Actual_seq2 = pd.DataFrame(New_seq2[:, None].T)
Seq_f = pd.concat([Actual_seq1, Actual_seq2], ignore_index=True)
Seq_f.reset_index(drop=True)
Slots = S
R = S if S % 2 == 0 else S + 1
Windings_arrange = (pd.DataFrame(index=Seq_f.index, columns=Seq_f.columns[1:R])).fillna(0)
counter = 1
# Step #4 Arranging winding in Slots
for i in range(0, len(New_seq)):
if Seq_f.loc[0, i] == 1:
Windings_arrange.loc[0, counter] = Seq_f.loc[1, i]
counter = counter + 1
Windings_arrange.loc[1, 1] = "C1"
for k in range(1, R):
if Windings_arrange.loc[0, k] == "A":
Windings_arrange.loc[1, k + 1] = "A1"
elif Windings_arrange.loc[0, k] == "B":
Windings_arrange.loc[1, k + 1] = "B1"
elif Windings_arrange.loc[0, k] == "C":
Windings_arrange.loc[1, k + 1] = "C1"
elif Windings_arrange.loc[0, k] == "A1":
Windings_arrange.loc[1, k + 1] = "A"
elif Windings_arrange.loc[0, k] == "B1":
Windings_arrange.loc[1, k + 1] = "B"
elif Windings_arrange.loc[0, k] == "C1":
Windings_arrange.loc[1, k + 1] = "C"
Phase_A = np.zeros((1000, 1), dtype=float)
counter_A = 0
# Windings_arrange.to_excel('test.xlsx')
# Winding vector, W_A for Phase A
for l in range(1, R):
if Windings_arrange.loc[0, l] == "A" and Windings_arrange.loc[1, l] == "A":
Phase_A[counter_A, 0] = l
Phase_A[counter_A + 1, 0] = l
counter_A = counter_A + 2
elif Windings_arrange.loc[0, l] == "A1" and Windings_arrange.loc[1, l] == "A1":
Phase_A[counter_A, 0] = -1 * l
Phase_A[counter_A + 1, 0] = -1 * l
counter_A = counter_A + 2
elif Windings_arrange.loc[0, l] == "A" or Windings_arrange.loc[1, l] == "A":
Phase_A[counter_A, 0] = l
counter_A = counter_A + 1
elif Windings_arrange.loc[0, l] == "A1" or Windings_arrange.loc[1, l] == "A1":
Phase_A[counter_A, 0] = -1 * l
counter_A = counter_A + 1
W_A = (np.trim_zeros(Phase_A)).T
# Calculate winding factor
K_w = 0
for r in range(0, int(2 * (S) / 3)):
Gamma = 2 * np.pi * p * np.abs(W_A[0, r]) / S
K_w += np.sign(W_A[0, r]) * (np.exp(Gamma * 1j))
K_w = np.abs(K_w) / (2 * S / 3)
CPMR = np.lcm(S, int(2 * p))
N_cog_s = CPMR / S
N_cog_p = CPMR / p
N_cog_t = CPMR * 0.5 / p
A = np.lcm(S, int(2 * p))
b_p_tau_p = 2 * 1 * p / S - 0
b_t_tau_s = (2) * S * 0.5 / p - 2
return K_w
# ---------------------------------
def shell_constant(R, t, l, x, E, v):
Lambda = (3 * (1 - v ** 2) / (R ** 2 * t ** 2)) ** 0.25
D = E * t ** 3 / (12 * (1 - v ** 2))
C_14 = (np.sinh(Lambda * l)) ** 2 + (np.sin(Lambda * l)) ** 2
C_11 = (np.sinh(Lambda * l)) ** 2 - (np.sin(Lambda * l)) ** 2
F_2 = np.cosh(Lambda * x) * np.sin(Lambda * x) + np.sinh(Lambda * x) * np.cos(Lambda * x)
C_13 = np.cosh(Lambda * l) * np.sinh(Lambda * l) - np.cos(Lambda * l) * np.sin(Lambda * l)
F_1 = np.cosh(Lambda * x) * np.cos(Lambda * x)
F_4 = np.cosh(Lambda * x) * np.sin(Lambda * x) - np.sinh(Lambda * x) * np.cos(Lambda * x)
return D, Lambda, C_14, C_11, F_2, C_13, F_1, F_4
# ---------------------------------
def plate_constant(a, b, E, v, r_o, t):
D = E * t ** 3 / (12 * (1 - v ** 2))
C_2 = 0.25 * (1 - (b / a) ** 2 * (1 + 2 * | np.log(a / b) | numpy.log |
"""MHD rotor test script
"""
import numpy as np
from scipy.constants import pi as PI
from gawain.main import run_gawain
run_name = "mhd_rotor"
output_dir = "."
cfl = 0.25
with_mhd = True
t_max = 0.15
integrator = "euler"
# "base", "lax-wendroff", "lax-friedrichs", "vanleer", "hll"
fluxer = "hll"
################ MESH #####################
nx, ny, nz = 128, 128, 1
mesh_shape = (nx, ny, nz)
n_outputs = 100
lx, ly, lz = 1, 1, 0.001
mesh_size = (lx, ly, lz)
x = np.linspace(0.0, lx, num=nx)
y = np.linspace(0.0, ly, num=ny)
z = np.linspace(0.0, lz, num=nz)
X, Y, Z = np.meshgrid(x, y, z, indexing="ij")
############ INITIAL CONDITION #################
adiabatic_idx = 1.4
R = np.sqrt((X - 0.5) ** 2 + (Y - 0.5) ** 2)
R0 = 0.1
R1 = 0.115
FR = (R1 - R) / (R - R0)
U0 = 2
rho_mid_vals = 1 + 9 * FR
vx_in_vals = -FR * U0 * (Y - 0.5) / R0
vx_mid_vals = -FR * U0 * (Y - 0.5) / R
vy_in_vals = FR * U0 * (X - 0.5) / R0
vy_mid_vals = FR * U0 * (X - 0.5) / R
inner_mask = np.where(R <= R0)
middle_mask = np.where( | np.logical_and(R > R0, R < R1) | numpy.logical_and |
from gzip import GzipFile
import logging
import numpy as np
from struct import unpack
from sys import argv
def get_size(format_string):
return sum(
size_lookup[_t]
for _t in list(format_string))
# define constants
size_lookup = {
"I": 4, # uint32
"Q": 8, # uint64
"i": 4, # int32
"B": 1, # byte
}
BG_ONLY = 0
FG_ONLY = 1
MIXED = 2
# compute header info for reading
body_header_t = "IIIQ"
body_header_n = get_size(body_header_t)
block_header_t = "iiiB"
block_header_n = get_size(block_header_t)
subblock_header_t = "B"
subblock_header_n = get_size(subblock_header_t)
subblock_t = 64*"B"
subblock_n = get_size(subblock_t)
def assemble_array(mask_list):
x_list = list()
y_list = list()
z_list = list()
for x, y, z, _ in mask_list:
x_list.append(x)
y_list.append(y)
z_list.append(z)
x_unique = np.unique(x_list)
y_unique = np.unique(y_list)
z_unique = np.unique(z_list)
min_x = x_unique[0]
min_y = y_unique[0]
min_z = z_unique[0]
max_x = x_unique[-1]
max_y = y_unique[-1]
max_z = z_unique[-1]
dx = x_unique[1] - x_unique[0]
dy = y_unique[1] - y_unique[0]
dz = z_unique[1] - z_unique[0]
block_shape = mask_list[0][-1].shape
x_space = int(dx/block_shape[0])
y_space = int(dy/block_shape[1])
z_space = int(dz/block_shape[2])
mask_x = max_x - min_x
mask_x = int(mask_x/x_space) + block_shape[0]
mask_y = max_y - min_y
mask_y = int(mask_y/y_space) + block_shape[1]
mask_z = max_z - min_z
mask_z = int(mask_z/z_space) + block_shape[2]
mask_array = np.zeros(
(
mask_x,
mask_y,
mask_z),
dtype=np.uint8)
for x, y, z, block in mask_list:
x_low = x-min_x
x_low = int(x_low/x_space)
x_high = x-min_x
x_high = int(x_high/x_space)+block_shape[0]
y_low = y-min_y
y_low = int(y_low/y_space)
y_high = y-min_y
y_high = int(y_high/y_space)+block_shape[1]
z_low = z-min_z
z_low = int(z_low/z_space)
z_high = z-min_z
z_high = int(z_high/z_space)+block_shape[2]
mask_array[
x_low:x_high,
y_low:y_high,
z_low:z_high] = block
return mask_array
def assemble_list(
body_handle,
granularity="bit"):
# read body header
gx, gy, gz, fg_label = unpack(
"=" + body_header_t,
body_handle.read(body_header_n))
# read body and process blocks
blocks = list()
while True:
_bytes = body_handle.read(block_header_n)
if len(_bytes) == 0:
break
x_block, y_block, z_block, content_flag = unpack(
"=" + block_header_t,
_bytes)
if granularity == "bit":
block_shape = (8*gx, 8*gy, 8*gz)
elif granularity == "subblock":
block_shape = (gx, gy, gz)
elif granularity == "block":
block_shape = (1, 1, 1)
if content_flag == BG_ONLY:
mask = np.zeros(
block_shape,
dtype=np.uint8)
elif content_flag == FG_ONLY:
mask = np.ones(
block_shape,
dtype=np.uint8)
elif content_flag == MIXED:
mask = assemble_block(
gx,
gy,
gz,
body_handle,
granularity=granularity)
else:
logging.error("invalid content_flag")
blocks.append((
x_block,
y_block,
z_block,
mask))
mask_array = blocks
return mask_array
def assemble_block(
gx,
gy,
gz,
body_handle,
granularity="bit"):
mask = np.empty(
(8*gx, 8*gy, 8*gz),
dtype=np.uint8)
for s_ix in range(gx*gy*gz):
x_index = s_ix // (gy*gz)
y_index = (s_ix // gz) % gy
z_index = s_ix % gz
content_flag = unpack(
"=" + subblock_header_t,
body_handle.read(subblock_header_n))[0]
if content_flag == BG_ONLY:
submask = np.zeros(
(8, 8, 8),
dtype=np.uint8)
elif content_flag == FG_ONLY:
submask = np.ones(
(8, 8, 8),
dtype=np.uint8)
elif content_flag == MIXED:
byte_raw = unpack(
"=" + subblock_t,
body_handle.read(subblock_n))
byte_list = list(byte_raw)
byte_flat = np.array(
byte_list,
dtype=np.uint8)
byte_structured = byte_flat.reshape((
8,
8,
1))
submask = np.flip(
np.unpackbits(
byte_structured,
axis=-1),
axis=-1)
else:
logging.error("invalid content_flag")
mask[
(8*x_index):(8*x_index+8),
(8*y_index):(8*y_index+8),
(8*z_index):(8*z_index+8)] = submask
if granularity == "subblock":
temp = np.empty(
(gx, gy, gz),
dtype=np.uint8)
for x_index in range(gx):
for y_index in range(gy):
for z_index in range(gz):
x_low = 8*x_index
x_high = x_low+8
y_low = 8*y_index
y_high = y_low+8
z_low = 8*z_index
z_high = z_low+8
temp[
x_index,
y_index,
z_index] = mask[
x_low:x_high,
y_low:y_high,
z_low:z_high].max()
mask = temp
elif granularity == "block":
mask = np.full(
(1, 1, 1),
mask.max(),
dtype=np.uint8)
return | np.transpose(mask, (2, 1, 0)) | numpy.transpose |
# -*- coding: utf-8 -*-
'''
Survival (toxico-dynamics) models, forward simulation and model fitting.
References
----------
[1] <NAME> al. (2011). General unified threshold model of survival -
a toxicokinetic-toxicodynamic framework for ecotoxicology.
Environmental Science & Technology, 45(7), 2529-2540.
'''
import sys
import numpy as np
import pandas as pd
import scipy.integrate as sid
from scipy.special import erf
import lmfit
import matplotlib.pyplot as plt
import seaborn as sns
from tqdm import tqdm
import corner
#ODE solver settings
ATOL = 1e-9
MXSTEP = 1000
def mortality_lognormal(r, s):
'''Calculate mortality from cumulative log-normal distribution
Keyword arguments:
:param r: ratio of body burdens to cbr, summed (dimensionless)
:param s: dose-response slope (dimensionless)
:returns: mortality fraction (fraction)
'''
if r>0:
mean = 0.0
x = (np.log10(r) - mean) / (s * np.sqrt(2))
return 0.5 * (1 + erf(x))
else:
return 0.0
def guts_sic(y, t, ke, cd):
'''One-compartment scaled internal concentration ODE (rhs)'''
# One-compartment kinetics model for body residues
dy = ke*(cd(t) - y)
return dy
def guts_sic_sd(y, t, params, cd, dy):
'''GUTS-SIC-SD: Scaled internal concentration + hazard rate survival ODE (rhs)'''
v = params
n = y.size - 1
# One-compartment kinetics model for body residues
dcv = guts_sic(y[:n], t, v['ke'], cd)
#Dose metric
cstot = np.sum(y[:n])
#Hazard rate
hc = v['b'] * max(0, cstot - v['c0s'])
h = hc + v['hb']
ds = -h * y[n]
dy[:n] = dcv
dy[n] = ds
return dy
def solve_guts_sic_sd(params, y0, times, cd):
'''Solve the GUTS-SIC-SD ODE.'''
v = params.valuesdict()
dy = y0.copy()
rhs = guts_sic_sd
y = sid.odeint(rhs, y0, times, args=(v, cd, dy), atol=ATOL, mxstep=MXSTEP)
return y
def solve_guts_sic_it(params, y0, times, cd):
'''Solve the GUTS-SIC-IT ODE.
Scaled internal concentration, individual tolerance
'''
v = params.valuesdict()
#Solve uptake kinetics for internal concentrations
y = sid.odeint(guts_sic, y0, times, args=(v['ke'], cd), atol=ATOL,
mxstep=MXSTEP)
#Number of body residues
n = ystep.shape[1] - 1
for i, ystep in enumerate(y):
if i == 0:
continue
#Total internal concentration
cstot = np.sum(ystep[:n])
#Calculate survival from ratio of internal concentration to
#tolerance threshold.
surv = y[0, n] * (1.0 - mortality_lognormal(cstot/v['cbr'], v['s']))
#Survival cannot increase with time
y[i, n] = min(y[i-1, n], surv)
return y
def get_model_prediction(times, params, exposure, s0=1,
solver=solve_guts_sic_sd):
v = params.valuesdict()
n = exposure.shape[0]
#Evaluate model for each exposure concentration
model_pred = []
for col in exposure.columns:
cd = lambda t: exposure[col].values
# Initial conditions: zero internal concentration, 100% survival
y0 = | np.array([0.0]*n + [s0]) | numpy.array |
import tensorflow as tf
import numpy as np
import cv2
import argparse
from sklearn.utils import shuffle
def Dataset_preprocessing(dataset = 'MNIST', image_type = True):
if dataset == 'mnist':
nch = 1
r = 32
(train_images, _), (test_images, _) = tf.keras.datasets.mnist.load_data()
elif dataset == 'fmnist':
(train_images, _), (test_images, _) = tf.keras.datasets.fashion_mnist.load_data()
r = 32
nch = 1
elif dataset == 'cifar10':
(train_images, _), (test_images, _) = tf.keras.datasets.cifar10.load_data()
r = 32
nch = 3
elif dataset == 'celeba':
celeba = np.load('/raid/konik/data/celeba_64_100k.npy')
celeba = shuffle(celeba)
train_images, test_images = np.split(celeba, [80000], axis=0)
print(type(train_images[0,0,0,0]))
nch = 3
r = 64
elif dataset == 'imagenet':
imagenet = np.load('/raid/Amir/Projects/datasets/Tiny_imagenet.npy')
imagenet = shuffle(imagenet)
train_images, test_images = np.split(imagenet, [80000], axis=0)
nch = 3
r = 64
elif dataset == 'rheo':
rheo = np.load('/raid/Amir/Projects/datasets/rheology.npy')
rheo = shuffle(rheo)
train_images, test_images = np.split(rheo, [1500], axis=0)
nch = 3
r = 64
elif dataset == 'chest':
chest = np.load('/raid/Amir/Projects/datasets/X_ray_dataset_128.npy')[:100000,:,:,0:1]
chest = shuffle(chest)
print(np.shape(chest))
train_images, test_images = np.split(chest, [80000], axis=0)
# print(type(train_images[0,0,0,0]))
nch = 1
r = 128
elif dataset == 'church':
church = np.load('/raid/Amir/Projects/datasets/church_outdoor_train_lmdb_color_64.npy')[:100000,:,:,:]
church = shuffle(church)
print(np.shape(church))
train_images, test_images = np.split(church, [80000], axis=0)
# print(type(train_images[0,0,0,0]))
nch = 3
r = 64
training_images = np.zeros(( | np.shape(train_images) | numpy.shape |
import os
import gc
from tqdm import tqdm
import numpy as np
import scipy.sparse as smat
from sklearn.svm import LinearSVR, LinearSVC
from sklearn.linear_model import Ridge, LogisticRegression
from pathlib import Path
import json
from multiprocessing import cpu_count, Pool
_FUNC = None # place holder to Pool functions.
def _worker_init(func):
"""Init method to invoke Pool."""
global _FUNC
_FUNC = func
def _worker(x):
"""Init function to invoke Pool."""
return _FUNC(x)
class MultiLabelInstance(object):
"""Class for input data type of model for one level."""
def __init__(self, X, Y, C, M=None):
self.X = smat.csr_matrix(X, dtype=np.float32)
self.Y = smat.csc_matrix(Y, dtype=np.float32)
self.C = smat.csc_matrix(C, dtype=np.float32)
if M is None:
self.M = self.Y.dot(self.C).tocsc()
else:
self.M = smat.csc_matrix(M, dtype=np.float32)
self.X.eliminate_zeros()
self.Y.eliminate_zeros()
self.C.eliminate_zeros()
self.M.eliminate_zeros()
self.C_csr = self.C.tocsr()
@property
def nr_labels(self):
return self.Y.shape[1]
class MultiLabelSolve(object):
"""Object to hold solution to a multilabel instance."""
def __init__(self, W, C):
self.W = smat.csc_matrix(W, dtype=np.float32)
self.C = smat.csc_matrix(C, dtype=np.float32)
@property
def nr_labels(self):
return self.W.shape[1]
@property
def nr_codes(self):
return self.C.shape[1]
@property
def nr_features(self):
return self.W.shape[0] - 1
def save(self, model_folder):
"""Save model."""
smat.save_npz(Path(model_folder, "W.npz"), self.W)
smat.save_npz(Path(model_folder, "C.npz"), self.C)
@classmethod
def load(cls, model_folder):
"""Load model."""
W = smat.load_npz(Path(model_folder, "W.npz"))
C = smat.load_npz(Path(model_folder, "C.npz"))
return cls(W, C)
@classmethod
def train(
cls,
mli,
learner="SVC",
linear_config={"tol": 0.1, "max_iter": 40},
threshold=0.1,
threads=cpu_count(),
):
"""Train code for mli.
Parameters:
---------
mli: object
ml instance
regression: bool
if true then regression training is used
linear_config: dict
config for liblinear
threshold: float
values below this are deleted
Returns:
instance of type MultiLabelSolve
"""
chunks = np.array_split(np.arange(mli.nr_labels), threads)
results = []
with Pool(
processes=threads,
initializer=_worker_init,
initargs=(lambda i: cls._train_label(mli, i, learner, linear_config, threshold),),
) as pool:
results = pool.map(_worker, np.arange(mli.nr_labels))
gc.collect()
W = smat.hstack(results).tocsc()
return cls(W, mli.C)
@classmethod
def _train_label(self, mli, label, learner, linear_config, threshold):
positives = set(list(mli.Y[:, label].indices))
negatives = set(list(mli.M[:, mli.C_csr[label, :].indices[0]].indices)).difference(
positives
)
if len(negatives) == 0:
negatives = [np.random.choice(mli.X.shape[0])]
if len(positives) == 0:
positives = [ | np.random.choice(mli.X.shape[0]) | numpy.random.choice |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.