prompt
stringlengths 19
879k
| completion
stringlengths 3
53.8k
| api
stringlengths 8
59
|
---|---|---|
import PyDAQmx
import ctypes
from enum import IntEnum
import numpy as np
from pymodaq.daq_utils.daq_utils import set_logger, get_module_name
logger = set_logger(get_module_name(__file__))
class DAQ_NIDAQ_source(IntEnum):
"""
Enum class of NIDAQ_source
=============== ==========
**Attributes** **Type**
*Analog_Input* int
*Counter* int
=============== ==========
"""
Analog_Input = 0
Counter = 1
Analog_Output = 2
Digital_Output = 3
Digital_Input = 4
Terminals = 5
@classmethod
def names(cls):
return [name for name, member in cls.__members__.items()]
class DAQ_analog_types(IntEnum):
"""
Enum class of Ai types
=============== ==========
**Attributes** **Type**
=============== ==========
"""
Voltage = PyDAQmx.DAQmx_Val_Voltage
Current = PyDAQmx.DAQmx_Val_Current
Thermocouple = PyDAQmx.DAQmx_Val_Temp_TC
@classmethod
def names(cls):
return [name for name, member in cls.__members__.items()]
@classmethod
def values(cls):
return [cls[name].value for name, member in cls.__members__.items()]
class DAQ_thermocouples(IntEnum):
"""
Enum class of thermocouples type
=============== ==========
**Attributes** **Type**
=============== ==========
"""
J = PyDAQmx.DAQmx_Val_J_Type_TC
K = PyDAQmx.DAQmx_Val_K_Type_TC
N = PyDAQmx.DAQmx_Val_N_Type_TC
R = PyDAQmx.DAQmx_Val_R_Type_TC
S = PyDAQmx.DAQmx_Val_S_Type_TC
T = PyDAQmx.DAQmx_Val_T_Type_TC
B = PyDAQmx.DAQmx_Val_B_Type_TC
E = PyDAQmx.DAQmx_Val_E_Type_TC
@classmethod
def names(cls):
return [name for name, member in cls.__members__.items()]
class DAQ_termination(IntEnum):
"""
Enum class of thermocouples type
=============== ==========
**Attributes** **Type**
=============== ==========
"""
Auto = PyDAQmx.DAQmx_Val_Cfg_Default
RSE = PyDAQmx.DAQmx_Val_RSE
NRSE = PyDAQmx.DAQmx_Val_NRSE
Diff = PyDAQmx.DAQmx_Val_Diff
Pseudodiff = PyDAQmx.DAQmx_Val_PseudoDiff
@classmethod
def names(cls):
return [name for name, member in cls.__members__.items()]
class Edge(IntEnum):
"""
"""
Rising = PyDAQmx.DAQmx_Val_Rising
Falling = PyDAQmx.DAQmx_Val_Falling
@classmethod
def names(cls):
return [name for name, member in cls.__members__.items()]
class ClockMode(IntEnum):
"""
"""
Finite = PyDAQmx.DAQmx_Val_Rising
Continuous = PyDAQmx.DAQmx_Val_Falling
@classmethod
def names(cls):
return [name for name, member in cls.__members__.items()]
class ClockSettingsBase:
def __init__(self, Nsamples=1000, repetition=False):
self.Nsamples = Nsamples
self.repetition = repetition
class ClockSettings(ClockSettingsBase):
def __init__(self, source=None, frequency=1000, Nsamples=1000, edge=Edge.names()[0], repetition=False):
super().__init__(Nsamples, repetition)
self.source = source
assert edge in Edge.names()
self.frequency = frequency
self.edge = edge
class ChangeDetectionSettings(ClockSettingsBase):
def __init__(self, Nsamples=1000, rising_channel='', falling_channel='',
repetition=False):
super().__init__(Nsamples, repetition)
self.rising_channel = rising_channel
self.falling_channel = falling_channel
class TriggerSettings:
def __init__(self, trig_source='', enable=False, edge=Edge.names()[0], level=0.1):
assert edge in Edge.names()
self.trig_source = trig_source
self.enable = enable
self.edge = edge
self.level = level
class Channel:
def __init__(self, name='', source=DAQ_NIDAQ_source.names()[0]):
"""
Parameters
----------
"""
self.name = name
assert source in DAQ_NIDAQ_source.names()
self.source = source
class AChannel(Channel):
def __init__(self, analog_type=DAQ_analog_types.names()[0], value_min=-10., value_max=+10., **kwargs):
"""
Parameters
----------
min: (float) minimum value for the configured input channel (could be voltage, amps, temperature...)
max: (float) maximum value for the configured input channel
"""
super().__init__(**kwargs)
self.value_min = value_min
self.value_max = value_max
self.analog_type = analog_type
class AIChannel(AChannel):
def __init__(self, termination=DAQ_termination.names()[0], **kwargs):
super().__init__(**kwargs)
assert termination in DAQ_termination.names()
self.termination = termination
class AIThermoChannel(AIChannel):
def __init__(self, thermo_type=DAQ_thermocouples.names()[0], **kwargs):
super().__init__(**kwargs)
assert thermo_type in DAQ_thermocouples.names()
self.thermo_type = thermo_type
class AOChannel(AChannel):
def __init__(self, **kwargs):
super().__init__(**kwargs)
class Counter(Channel):
def __init__(self, edge=Edge.names()[0], **kwargs):
assert edge in Edge.names()
super().__init__(**kwargs)
self.edge = edge
class DigitalChannel(Channel):
def __init__(self, **kwargs):
super().__init__(**kwargs)
class DOChannel(DigitalChannel):
def __init__(self, **kwargs):
super().__init__(**kwargs)
class DIChannel(DigitalChannel):
def __init__(self, **kwargs):
super().__init__(**kwargs)
def try_string_buffer(fun, *args):
"""
generic function to read string from a PyDAQmx function making sure the chosen buffer is large enough
Parameters
----------
fun: (PyDAQmx function pointer) e.g. PyDAQmx.DAQmxGetSysDevNames
kwargs
Returns
-------
"""
buff_size = 1024
while True:
buff = PyDAQmx.create_string_buffer(buff_size)
try:
if not not len(args):
fun(args[0], buff, buff_size)
else:
fun(buff, buff_size)
break
except Exception as e:
if isinstance(e, PyDAQmx.DAQmxFunctions.DAQException):
if e.error == -200228: # BufferTooSmallForStringError
buff_size = 2 * buff_size
else:
raise e
else:
raise e
return buff.value.decode()
class DAQmx:
def __init__(self):
super().__init__()
self.devices = []
self.channels = []
self._device = None
self._task = None
self.update_NIDAQ_devices()
self.update_NIDAQ_channels()
self.c_callback = None
self.callback_data = None
self.is_scalar = True
self.write_buffer = np.array([0.])
@property
def task(self):
return self._task
@property
def device(self):
return self._device
@device.setter
def device(self, device):
if device not in self.devices:
raise IOError(f'your device: {device} is not known or connected')
self._device = device
def update_NIDAQ_devices(self):
self.devices = self.get_NIDAQ_devices()
@classmethod
def get_NIDAQ_devices(cls):
"""Get list of NI connected devices
Returns
-------
list
list of devices as strings to be used in subsequent commands
"""
try:
string = try_string_buffer(PyDAQmx.DAQmxGetSysDevNames)
devices = string.split(', ')
if devices == ['']:
devices = []
return devices
except:
return []
def update_NIDAQ_channels(self, source_type=None):
self.channels = self.get_NIDAQ_channels(self.devices, source_type=source_type)
@classmethod
def get_NIDAQ_channels(cls, devices=None, source_type=None):
"""Get the list of available channels for all NiDAq connected devices
Parameters
----------
devices: list
list of strings, each one being a connected device
source_type: str
One of the entries of DAQ_NIDAQ_source enum
Returns
-------
List of str containing device and channel names
"""
if devices is None:
devices = cls.get_NIDAQ_devices()
if source_type is None:
source_type = DAQ_NIDAQ_source.names()
if not isinstance(source_type, list):
source_type = [source_type]
channels_tot = []
if not not devices:
for device in devices:
for source in source_type:
if source == DAQ_NIDAQ_source['Analog_Input'].name: # analog input
string = try_string_buffer(PyDAQmx.DAQmxGetDevAIPhysicalChans, device)
elif source == DAQ_NIDAQ_source['Counter'].name: # counter
string = try_string_buffer(PyDAQmx.DAQmxGetDevCIPhysicalChans, device)
elif source == DAQ_NIDAQ_source['Analog_Output'].name: # analog output
string = try_string_buffer(PyDAQmx.DAQmxGetDevAOPhysicalChans, device)
elif source == DAQ_NIDAQ_source['Digital_Output'].name: # digital output
string = try_string_buffer(PyDAQmx.DAQmxGetDevDOLines, device)
elif source == DAQ_NIDAQ_source['Digital_Input'].name: # digital output
string = try_string_buffer(PyDAQmx.DAQmxGetDevDILines, device)
elif source == DAQ_NIDAQ_source['Terminals'].name: # digital output
string = try_string_buffer(PyDAQmx.DAQmxGetDevTerminals, device)
channels = string.split(', ')
if channels != ['']:
channels_tot.extend(channels)
return channels_tot
@classmethod
def getAOMaxRate(cls, device):
data = PyDAQmx.c_double()
PyDAQmx.DAQmxGetDevAOMaxRate(device, PyDAQmx.byref(data))
return data.value
@classmethod
def getAIMaxRate(cls, device):
data = PyDAQmx.c_double()
PyDAQmx.DAQmxGetDevAIMaxSingleChanRate(device, PyDAQmx.byref(data))
return data.value
@classmethod
def isAnalogTriggeringSupported(cls, device):
data = PyDAQmx.c_uint32()
PyDAQmx.DAQmxGetDevAnlgTrigSupported(device, PyDAQmx.byref(data))
return bool(data.value)
@classmethod
def isDigitalTriggeringSupported(cls, device):
data = PyDAQmx.c_uint32()
PyDAQmx.DAQmxGetDevDigTrigSupported(device, PyDAQmx.byref(data))
return bool(data.value)
@classmethod
def getTriggeringSources(cls, devices=None):
sources = []
if devices is None:
devices = cls.get_NIDAQ_devices()
for device in devices:
if cls.isDigitalTriggeringSupported(device):
string = try_string_buffer(PyDAQmx.DAQmxGetDevTerminals, device)
channels = [chan for chan in string.split(', ') if 'PFI' in chan]
if channels != ['']:
sources.extend(channels)
if cls.isAnalogTriggeringSupported(device):
channels = cls.get_NIDAQ_channels(devices=[device], source_type='Analog_Input')
if channels != ['']:
sources.extend(channels)
return sources
def update_task(self, channels=[], clock_settings=ClockSettings(), trigger_settings=TriggerSettings()):
"""
"""
try:
if self._task is not None:
if isinstance(self._task, PyDAQmx.Task):
self._task.ClearTask()
self._task = None
self.c_callback = None
self._task = PyDAQmx.Task()
## create all channels one task for one type of channels
for channel in channels:
if channel.source == 'Analog_Input': #analog input
if channel.analog_type == "Voltage":
err_code = self._task.CreateAIVoltageChan(channel.name, "",
DAQ_termination[channel.termination].value,
channel.value_min,
channel.value_max,
PyDAQmx.DAQmx_Val_Volts, None)
elif channel.analog_type == "Current":
err_code = self._task.CreateAICurrentChan(channel.name, "",
DAQ_termination[channel.termination].value,
channel.value_min,
channel.value_max,
PyDAQmx.DAQmx_Val_Amps, PyDAQmx.DAQmx_Val_Internal,
0., None)
elif channel.analog_type == "Thermocouple":
err_code = self._task.CreateAIThrmcplChan(channel.name, "",
channel.value_min,
channel.value_max,
PyDAQmx.DAQmx_Val_DegC,
DAQ_termination[channel.thermo_type].value,
PyDAQmx.DAQmx_Val_BuiltIn, 0., "")
elif channel.source == 'Counter': #counter
err_code = self._task.CreateCICountEdgesChan(channel.name, "",
Edge[channel.edge].value, 0,
PyDAQmx.DAQmx_Val_CountUp)
if not not err_code:
status = self.DAQmxGetErrorString(err_code)
raise IOError(status)
elif channel.source == 'Analog_Output': # Analog_Output
if channel.analog_type == "Voltage":
err_code = self._task.CreateAOVoltageChan(channel.name, "",
channel.value_min,
channel.value_max,
PyDAQmx.DAQmx_Val_Volts, None)
if channel.analog_type == "Current":
err_code = self._task.CreateAOCurrentChan(channel.name, "",
channel.value_min,
channel.value_max,
PyDAQmx.DAQmx_Val_Amps, None)
elif channel.source == 'Digital_Output': #Digital_Output
err_code = self._task.CreateDOChan(channel.name, "", PyDAQmx.DAQmx_Val_ChanPerLine)
if not not err_code:
status = self.DAQmxGetErrorString(err_code)
raise IOError(status)
elif channel.source == 'Digital_Input': #Digital_Input
err_code = self._task.CreateDIChan(channel.name, "", PyDAQmx.DAQmx_Val_ChanPerLine)
if not not err_code:
status = self.DAQmxGetErrorString(err_code)
raise IOError(status)
## configure the timing
if clock_settings.repetition:
mode = PyDAQmx.DAQmx_Val_ContSamps
else:
mode = PyDAQmx.DAQmx_Val_FiniteSamps
if clock_settings.Nsamples > 1 and err_code == 0:
if isinstance(clock_settings, ClockSettings):
err_code =\
self._task.CfgSampClkTiming(clock_settings.source, clock_settings.frequency,
Edge[clock_settings.edge].value,
mode,
clock_settings.Nsamples)
elif isinstance(clock_settings, ChangeDetectionSettings):
err_code =\
self._task.CfgChangeDetectionTiming(clock_settings.rising_channel,
clock_settings.falling_channel,
mode,
clock_settings.Nsamples)
if not not err_code:
status = self.DAQmxGetErrorString(err_code)
raise IOError(status)
# if channel.source == 'Analog_Input': # analog input
# if isinstance(clock_settings, ClockSettings):
# err_code =\
# self._task.CfgSampClkTiming(clock_settings.source, clock_settings.frequency,
# Edge[clock_settings.edge].value,
# mode,
# clock_settings.Nsamples)
# elif isinstance(clock_settings, ChangeDetectionSettings):
# err_code =\
# self._task.CfgChangeDetectionTiming(clock_settings.source,
# clock_settings.rising_channel,
# clock_settings.falling_channel,
# mode,
# clock_settings.Nsamples)
#
# if not not err_code:
# status = self.DAQmxGetErrorString(err_code)
# raise IOError(status)
#
# elif channel.source == 'Counter': # counter
# pass
#
# elif channel.source == 'Analog_Output': # Analog_Output
# if clock_settings.Nsamples > 1 and err_code == 0:
#
# if isinstance(clock_settings, ClockSettings):
# err_code = self._task.CfgSampClkTiming(clock_settings.source,
# clock_settings.frequency,
# Edge[clock_settings.edge].value,
# mode,
# clock_settings.Nsamples)
# elif isinstance(clock_settings, ChangeDetectionSettings):
# err_code = \
# self._task.CfgChangeDetectionTiming(clock_settings.source,
# clock_settings.rising_channel,
# clock_settings.falling_channel,
# mode,
# clock_settings.Nsamples)
#
# if not not err_code:
# status = self.DAQmxGetErrorString(err_code)
# raise IOError(status)
#
# else:
# pass
##configure the triggering
if not trigger_settings.enable:
err = self._task.DisableStartTrig()
if err != 0:
raise IOError(self.DAQmxGetErrorString(err))
else:
if 'PF' in trigger_settings.trig_source:
self._task.CfgDigEdgeStartTrig(trigger_settings.trig_source, Edge[trigger_settings.edge].value)
elif 'ai' in trigger_settings.trig_source:
self._task.CfgAnlgEdgeStartTrig(trigger_settings.trig_source,
Edge[trigger_settings.edge].value,
PyDAQmx.c_double(trigger_settings.level))
else:
raise IOError('Unsupported Trigger source')
except Exception as e:
print(e)
def register_callback(self, callback, event='done', nsamples=1):
if event == 'done':
self.c_callback = PyDAQmx.DAQmxDoneEventCallbackPtr(callback)
self._task.RegisterDoneEvent(0, self.c_callback, None)
elif event == 'sample':
self.c_callback = PyDAQmx.DAQmxSignalEventCallbackPtr(callback)
self._task.RegisterSignalEvent(PyDAQmx.DAQmx_Val_SampleCompleteEvent, 0, self.c_callback, None)
elif event == 'Nsamples':
self.c_callback = PyDAQmx.DAQmxEveryNSamplesEventCallbackPtr(callback)
self._task.RegisterEveryNSamplesEvent(PyDAQmx.DAQmx_Val_Acquired_Into_Buffer, nsamples,
0, self.c_callback, None)
def get_last_write_index(self):
if self.task is not None:
index_buffer = PyDAQmx.c_uint64()
ret = self._task.GetWriteCurrWritePos(PyDAQmx.byref(index_buffer))
if not not ret:
raise IOError(self.DAQmxGetErrorString(ret))
else:
return index_buffer.value
else:
return -1
def get_last_write(self):
if self.is_scalar:
return self.write_buffer[-1]
else:
index = self.get_last_write_index()
if index != -1:
return self.write_buffer[index % len(self.write_buffer)]
else:
return 0.
def writeAnalog(self, Nsamples, Nchannels, values, autostart=False):
"""
Write Nsamples on N analog output channels
Parameters
----------
Nsamples: (int) numver of samples to write on each channel
Nchannels: (int) number of AO channels defined in the task
values: (ndarray) 2D array (or flattened array) of size Nsamples * Nchannels
Returns
-------
"""
if np.prod(values.shape) != Nsamples * Nchannels:
raise ValueError(f'The shape of analog outputs values is incorrect, should be {Nsamples} x {Nchannels}')
if len(values.shape) != 1:
values = values.reshape((Nchannels * Nsamples))
self.write_buffer = values
timeout = -1
if values.size == 1:
self._task.WriteAnalogScalarF64(autostart, timeout, values[0], None)
self.is_scalar = True
else:
self.is_scalar = False
read = PyDAQmx.int32()
self._task.WriteAnalogF64(Nsamples, autostart, timeout, PyDAQmx.DAQmx_Val_GroupByChannel, values,
PyDAQmx.byref(read), None)
if read.value != Nsamples:
raise IOError(f'Insufficient number of samples have been written:{read.value}/{Nsamples}')
def readAnalog(self, Nchannels, clock_settings):
read = PyDAQmx.int32()
N = clock_settings.Nsamples
data = np.zeros(N * Nchannels, dtype=np.float64)
timeout = N * Nchannels * 1 / clock_settings.frequency * 2 # set to twice the time it should take to acquire the data
self._task.ReadAnalogF64(N, timeout, PyDAQmx.DAQmx_Val_GroupByChannel, data, len(data),
PyDAQmx.byref(read), None)
if read.value == N:
return data
else:
raise IOError(f'Insufficient number of samples have been read:{read.value}/{N}')
def readCounter(self, Nchannels, counting_time=10.):
data_counter = np.zeros(Nchannels, dtype='uint32')
read = PyDAQmx.int32()
self._task.ReadCounterU32Ex(PyDAQmx.DAQmx_Val_Auto, 2*counting_time, PyDAQmx.DAQmx_Val_GroupByChannel,
data_counter,
Nchannels, PyDAQmx.byref(read), None)
self._task.StopTask()
if read.value == Nchannels:
return data_counter
else:
raise IOError(f'Insufficient number of samples have been read:{read}/{Nchannels}')
def readDigital(self, Nchannels):
read = PyDAQmx.int32()
bytes_sample = PyDAQmx.int32()
data = np.zeros(Nchannels, dtype='uint8')
self._task.ReadDigitalLines(Nchannels, 0, PyDAQmx.DAQmx_Val_GroupByChannel,
data, Nchannels, PyDAQmx.byref(read), PyDAQmx.byref(bytes_sample), None);
if read.value == Nchannels:
return data
else:
raise IOError(f'Insufficient number of samples have been read:{read}/{Nchannels}')
def writeDigital(self, Nchannels, values, autostart=False):
if np.prod(values.shape) != Nchannels:
raise ValueError(f'The shape of digital outputs values is incorrect, should be {Nchannels}')
values.astype(np.uint8)
written = PyDAQmx.int32()
self._task.WriteDigitalLines(Nchannels, autostart, 0, PyDAQmx.DAQmx_Val_GroupByChannel,
values, PyDAQmx.byref(written), None)
if written.value != Nchannels:
raise IOError(f'Insufficient number of samples have been written:{written}/{Nchannels}')
def getAIVoltageRange(self, device='Dev1'):
buff_size = 100
ranges = ctypes.pointer((buff_size*ctypes.c_double)())
ret = PyDAQmx.DAQmxGetDevAIVoltageRngs(device, ranges[0], buff_size)
if ret == 0:
return [tuple(ranges.contents[2*ind:2*(ind+1)]) for ind in range(int(buff_size/2-2))
if np.abs(ranges.contents[2*ind]) > 1e-12]
return [(-10., 10.)]
def getAOVoltageRange(self, device='Dev1'):
buff_size = 100
ranges = ctypes.pointer((buff_size*ctypes.c_double)())
ret = PyDAQmx.DAQmxGetDevAOVoltageRngs(device, ranges[0], buff_size)
if ret == 0:
return [tuple(ranges.contents[2*ind:2*(ind+1)]) for ind in range(int(buff_size/2-2))
if | np.abs(ranges.contents[2*ind]) | numpy.abs |
import numpy as np
import IPython
from .module import Module
from .parameter import Parameter
from .activation import Sigmoid, Tanh, ReLU
class RNN(Module):
"""Vanilla recurrent neural network layer.
The single time step forward transformation is
h[:,t+1] = tanh(Whh * h[:,t] + Whx * X[:,t] + bh)
with the following dimensions
X: (T, N, D)
h: (N, H)
Whx: (H, D)
Whh: (H, H)
b: (H)
where
D: input dimension
T: input sequence length
H: hidden dimension
Parameters
----------
input_size : [type]
[description]
hidden_size : [type]
[description]
bias : [type]
[description]
nonlinearity : [type]
[description]
Returns
-------
[type]
[description]
"""
def __init__(self, input_size, hidden_size, output_size, bias=True, nonlinearity=Tanh(), time_first=True, bptt_truncate=0):
super(RNN, self).__init__()
self.input_size = input_size
self.hidden_size = hidden_size
self.nonlinearity = nonlinearity
self.time_first = time_first
self.bptt_truncate = bptt_truncate
self.Wxh = Parameter(np.zeros((hidden_size, input_size)))
self.Whh = Parameter(np.zeros((hidden_size, hidden_size)))
self.Why = Parameter(np.zeros((output_size, hidden_size)))
if bias:
self.b = Parameter(np.zeros(hidden_size))
else:
self.b = None
if time_first:
self.t_dim = 0
self.n_dim = 1
self.d_dim = 2
else:
self.t_dim = 1
self.n_dim = 0
self.d_dim = 2
self.reset_parameters()
def reset_parameters(self):
stdhh = np.sqrt(1. / self.hidden_size)
stdhx = np.sqrt(1. / self.input_size)
self.Wxh.data = np.random.uniform(-stdhx, stdhx, size=(self.hidden_size, self.input_size))
self.Whh.data = np.random.uniform(-stdhh, stdhh, size=(self.hidden_size, self.hidden_size))
if self.b is not None:
self.b.data = np.zeros(self.hidden_size)
def forward_step(self, x, h):
"""Compute state k from the previous state (sk) and current input (xk),
by use of the input weights (wx) and recursive weights (wRec).
"""
return self.nonlinearity.forward(h @ self.Whh.data.T + x @ self.Wxh.data.T + self.b.data)
def forward(self, X, h0=None):
"""Unfold the network and compute all state activations given the input X,
and input weights (wx) and recursive weights (wRec).
Return the state activations in a matrix, the last column S[:,-1] contains the
final activations.
"""
# Initialise the matrix that holds all states for all input sequences.
# The initial state s0 is set to 0.
if not self.time_first:
X = X.transpose(self.n_dim, self.t_dim, self.n_dim) # [N, T, D] --> [T, N, D]
h = np.zeros((X.shape[self.t_dim] + 1, X.shape[self.n_dim], self.hidden_size)) # (T, N, H)
if h0:
h[0] = h0
# Use the recurrence relation defined by forward_step to update the states trough time.
for t in range(0, X.shape[self.t_dim]):
h[t + 1] = self.nonlinearity.forward(np.dot(X[t], self.Wxh.data.T) + np.dot(h[t], self.Whh.data.T) + self.b.data)
# h[t + 1] = self.forward_step(X[t, :], h[t])
# np.dot(self.Wxh.data, X[t][5])
# np.dot(X[t], self.Wxh.data.T)
# Cache
self.X = X
self.h = h
return h
def backward_step_old_broken(self, dh, x_cache, h_cache):
"""Compute a single backwards time step.
"""
# https://gist.github.com/karpathy/d4dee566867f8291f086
# Activation
dh = self.nonlinearity.backward(dh, h_cache)
# Gradient of the linear layer parameters (accumulate)
self.Whh.grad += dh.T @ h_cache # np.outer(dh, h_cache)
self.Wxh.grad += dh.T @ x_cache # np.outer(dh, x_cache)
if self.b is not None:
self.b.grad += dh.sum(axis=0)
# Gradient at the output of the previous layer
dh_prev = dh @ self.Whh.data.T # self.Whh.data @ dh.T
return dh_prev
def backward_old_broken(self, delta):
"""Backpropagate the gradient computed at the output (delta) through the network.
Accumulate the parameter gradients for `Whx` and `Whh` by for each layer by addition.
Return the parameter gradients as a tuple, and the gradients at the output of each layer.
"""
# Initialise the array that stores the gradients of the cost with respect to the states.
dh = np.zeros((self.X.shape[self.t_dim] + 1, self.X.shape[self.n_dim], self.hidden_size))
dh[-1] = delta
for t in range(self.X.shape[self.t_dim], 0, -1):
dh[t - 1, :] = self.backward_step_old_broken(dh[t, :], self.X[t - 1, :], self.h[t - 1, :])
return dh
def backward(self, delta):
"""Backpropagate the gradient computed at the output (delta) through the network.
Accumulate the parameter gradients for `Whx` and `Whh` by for each layer by addition.
Return the parameter gradients as a tuple, and the gradients at the output of each layer.
delta can be
(N, H)
(N, H, T)
"""
# http://www.wildml.com/2015/10/recurrent-neural-networks-tutorial-part-3-backpropagation-through-time-and-vanishing-gradients/
# Initialise the array that stores the gradients of the cost with respect to the states.
# dh = np.zeros((self.X.shape[self.t_dim] + 1, self.X.shape[self.n_dim], self.hidden_size))
# dh[-1] = delta
dh_t = delta
for t in range(self.X.shape[self.t_dim], 0, -1):
# IPython.embed()
# Initial delta calculation: dL/dz (TODO Don't really care about this)
# dLdz = self.V.T.dot(delta_o[t]) * (1 - (self.h[t] ** 2)) # (1 - (self.h[t] ** 2)) is Tanh()
dh_t = self.nonlinearity.backward(dh_t, self.h[t])
# Backpropagation through time (for at most self.bptt_truncate steps)
for bptt_step in np.arange(max(0, t - self.bptt_truncate), t + 1)[::-1]:
# print "Backpropagation step t=%d bptt step=%d " % (t, bptt_step)
# Add to gradients at each previous step
self.Whh.grad += np.einsum('NH,iNH->NH', dh_t, self.h[bptt_step - 1])
# self.Whh.grad += np.outer(dh_t, self.h[bptt_step - 1])
self.Wxh.grad[:, self.X[bptt_step]] += dh_t
# self.Wxh.grad[:, self.X[bptt_step]] += dLdz # TODO Really want dh/dU
# Update delta for next step dL/dz at t-1
dh_t = self.nonlinearity.backward(self.Whh.data.T.dot(dh_t), self.h[bptt_step-1]) # (1 - self.h[bptt_step-1] ** 2)
# dh[t - 1, :] = self.backward_step(dh[t, :], self.X[t - 1, :], self.h[t - 1, :])
return dh_t
def backward_step(self, dh, x_cache, h_cache):
pass
# return [dLdU, dLdV, dLdW]
def bptt(self, x, y):
T = len(y)
# Perform forward propagation
o, s = self.forward_propagation(x)
# We accumulate the gradients in these variables
dLdU = np.zeros(self.Wxh.shape)
dLdV = np.zeros(self.V.shape)
dLdW = np.zeros(self.Whh.shape)
delta_o = o
delta_o[np.arange(len(y)), y] -= 1.
# For each output backwards...
for t in np.arange(T)[::-1]:
dLdV += np.outer(delta_o[t], s[t].T)
# Initial delta calculation: dL/dz
delta_t = self.V.T.dot(delta_o[t]) * (1 - (s[t] ** 2)) # (1 - (s[t] ** 2)) is Tanh()
# Backpropagation through time (for at most self.bptt_truncate steps)
for bptt_step in np.arange(max(0, t - self.bptt_truncate), t + 1)[::-1]:
# print "Backpropagation step t=%d bptt step=%d " % (t, bptt_step)
# Add to gradients at each previous step
dLdW += np.outer(delta_t, s[bptt_step - 1])
dLdU[:, x[bptt_step]] += delta_t
# Update delta for next step dL/dz at t-1
delta_t = self.Whh.data.T.dot(delta_t) * (1 - s[bptt_step-1] ** 2)
return [dLdU, dLdV, dLdW]
# http://willwolf.io/2016/10/18/recurrent-neural-network-gradients-and-lessons-learned-therein/
# https://github.com/go2carter/nn-learn/blob/master/grad-deriv-tex/rnn-grad-deriv.pdf
# https://peterroelants.github.io/posts/rnn-implementation-part01/
# http://www.wildml.com/2015/10/recurrent-neural-networks-tutorial-part-3-backpropagation-through-time-and-vanishing-gradients/
class GRU(Module):
def __init__(self):
pass
class LSTM(Module):
def __init__(self, input_size, hidden_size=128, bias=True, time_first=True):
super(LSTM, self).__init__()
self.input_size = input_size
self.hidden_size = hidden_size
self.time_first = time_first
if time_first:
self.t_dim = 0
self.n_dim = 1
self.d_dim = 2
else:
self.t_dim = 1
self.n_dim = 0
self.d_dim = 2
D = self.input_size
H = self.hidden_size
Z = D + H # Concatenation
self.Wf = Parameter(np.zeros((Z, H)))
self.Wi = Parameter(np.zeros((Z, H)))
self.Wc = Parameter(np.zeros((Z, H)))
self.Wo = Parameter(np.zeros((Z, H)))
self.Wy = Parameter(np.zeros((H, D)))
if bias:
self.bf = Parameter(np.zeros((1, H)))
self.bi = Parameter(np.zeros((1, H)))
self.bc = Parameter(np.zeros((1, H)))
self.bo = Parameter(np.zeros((1, H)))
self.by = Parameter(np.zeros((1, D)))
else:
self.bf = None
self.bi = None
self.bc = None
self.bo = None
self.by = None
self.reset_parameters()
def reset_parameters(self):
# TODO Add orthogonal initialization
D = self.input_size
H = self.hidden_size
Z = D + H # Concatenation
self.Wf.data = np.random.randn(Z, H) / np.sqrt(Z / 2.)
self.Wi.data = np.random.randn(Z, H) / np.sqrt(Z / 2.)
self.Wc.data = np.random.randn(Z, H) / np.sqrt(Z / 2.)
self.Wo.data = np.random.randn(Z, H) / np.sqrt(Z / 2.)
self.Wy.data = np.random.randn(H, D) / np.sqrt(D / 2.)
if self.bf is not None:
self.bf.data = np.zeros((1, H))
self.bi.data = np.zeros((1, H))
self.bc.data = np.zeros((1, H))
self.bo.data = np.zeros((1, H))
self.by.data = np.zeros((1, D))
else:
self.bf = None
self.bi = None
self.bc = None
self.bo = None
self.by = None
self.sigmoidf = Sigmoid()
self.sigmoidi = Sigmoid()
self.sigmoido = Sigmoid()
self.tanhc = Tanh()
self.tanh = Tanh()
def forward_step(self, x, state):
h_old, c_old = state
# # One-hot encode
# X_one_hot = np.zeros(D)
# X_one_hot[X] = 1.
# X_one_hot = X_one_hot.reshape(1, -1)
# Concatenate old state with current input
hx = np.column_stack((h_old, x))
hf = self.sigmoidf.forward(hx @ self.Wf.data + self.bf.data)
hi = self.sigmoidi.forward(hx @ self.Wi.data + self.bi.data)
ho = self.sigmoido.forward(hx @ self.Wo.data + self.bo.data)
hc = self.tanhc.forward(hx @ self.Wc.data + self.bc.data)
c = hf * c_old + hi * hc
h = ho * self.tanh.forward(c)
# y = h @ Wy + by
# prob = softmax(y)
self.cache = dict(hx=[*self.cache['hx'], hx],
hf=[*self.cache['hf'], hf],
hi=[*self.cache['hi'], hi],
ho=[*self.cache['ho'], ho],
hc=[*self.cache['hc'], hc],
c=[*self.cache['c'], c],
c_old=[*self.cache['c_old'], c_old])
return (h, c)
def forward(self, X):
self.cache = dict(hx=[],
hf=[],
hi=[],
ho=[],
hc=[],
c=[],
c_old=[])
if not self.time_first:
X = X.transpose(self.n_dim, self.t_dim, self.n_dim) # [N, T, D] --> [T, N, D]
h = np.zeros((X.shape[self.t_dim] + 1, X.shape[self.n_dim], self.hidden_size)) # (T, N, H)
c = np.zeros((X.shape[self.t_dim] + 1, X.shape[self.n_dim], self.hidden_size)) # (T, N, H)
# Use the recurrence relation defined by forward_step to update the states trough time.
for t in range(0, X.shape[self.t_dim]):
h[t + 1], c[t + 1] = self.forward_step(X[t, :], (h[t], c[t]))
return h[-1]
def backward_step(self, dh_next, dc_next, t):
# Unpack the cache variable to get the intermediate variables used in forward step
hx = self.cache['hx'][t]
hf = self.cache['hf'][t]
hi = self.cache['hi'][t]
ho = self.cache['ho'][t]
hc = self.cache['hc'][t]
c = self.cache['c'][t]
c_old = self.cache['c_old'][t]
IPython.embed()
# # Softmax loss gradient
# dy = prob.copy()
# dy[1, y_train] -= 1.
# # Hidden to output gradient
# dWy = h.T @ dy
# dby = dy
# # Note we're adding dh_next here
# dh = dy @ Wy.T + dh_next
# Gradient for ho in h = ho * tanh(c)
dho = self.tanh.forward(c) * dh_next
dho = self.sigmoido.backward(ho) * dho
# Gradient for c in h = ho * tanh(c), note we're adding dc_next here
dc = ho * dh_next * self.tanh.backward(c)
dc = dc + dc_next
# Gradient for hf in c = hf * c_old + hi * hc
dhf = c_old * dc
dhf = self.sigmoidf.backward(hf) * dhf
# Gradient for hi in c = hf * c_old + hi * hc
dhi = hc * dc
dhi = self.sigmoidi.backward(hi) * dhi
# Gradient for hc in c = hf * c_old + hi * hc
dhc = hi * dc
dhc = self.tanhc.backward(hc) * dhc
# Gate gradients, just a normal fully connected layer gradient
self.Wf.grad += hx.T @ dhf
self.bf.grad += dhf.sum(axis=0)
dxf = dhf @ self.Wf.data.T
self.Wi.grad += hx.T @ dhi
self.bi.grad += dhi.sum(axis=0)
dxi = dhi @ self.Wi.data.T
self.Wo.grad += hx.T @ dho
self.bo.grad += dho.sum(axis=0)
dxo = dho @ self.Wo.data.T
self.Wc.grad += hx.T @ dhc
self.bc.grad += dhc.sum(axis=0)
dxc = dhc @ self.Wc.data.T
# As x was used in multiple gates, the gradient must be accumulated here
dx = dxo + dxc + dxi + dxf
# Split the concatenated X, so that we get our gradient of h_old
dh_next = dx[:, :self.hidden_size]
# Gradient for c_old in c = hf * c_old + hi * hc
dc_next = hf * dc
return dh_next, dc_next
def backward(self, delta):
# https://wiseodd.github.io/techblog/2016/08/12/lstm-backprop/
# https://gist.github.com/karpathy/d4dee566867f8291f086
dh_next = delta
dc_next = np.zeros_like(dh_next)
for t in range(len(self.cache['hx']) - 1, 0, -1):
dh_next, dc_next = self.backward_step(dh_next, dc_next, t)
def lstm_backward(prob, y_train, d_next, cache):
# Unpack the cache variable to get the intermediate variables used in forward step
# ... = cache
dh_next, dc_next = d_next
# Softmax loss gradient
dy = prob.copy()
dy[1, y_train] -= 1.
# Hidden to output gradient
dWy = h.T @ dy
dby = dy
# Note we're adding dh_next here
dh = dy @ Wy.T + dh_next
# Gradient for ho in h = ho * tanh(c)
dho = tanh(c) * dh
dho = dsigmoid(ho) * dho
# Gradient for c in h = ho * tanh(c), note we're adding dc_next here
dc = ho * dh * dtanh(c)
dc = dc + dc_next
# Gradient for hf in c = hf * c_old + hi * hc
dhf = c_old * dc
dhf = dsigmoid(hf) * dhf
# Gradient for hi in c = hf * c_old + hi * hc
dhi = hc * dc
dhi = dsigmoid(hi) * dhi
# Gradient for hc in c = hf * c_old + hi * hc
dhc = hi * dc
dhc = dtanh(hc) * dhc
# Gate gradients, just a normal fully connected layer gradient
dWf = X.T @ dhf
dbf = dhf
dXf = dhf @ Wf.T
dWi = X.T @ dhi
dbi = dhi
dXi = dhi @ Wi.T
dWo = X.T @ dho
dbo = dho
dXo = dho @ Wo.T
dWc = X.T @ dhc
dbc = dhc
dXc = dhc @ Wc.T
# As X was used in multiple gates, the gradient must be accumulated here
dX = dXo + dXc + dXi + dXf
# Split the concatenated X, so that we get our gradient of h_old
dh_next = dX[:, :H]
# Gradient for c_old in c = hf * c_old + hi * hc
dc_next = hf * dc
grad = dict(Wf=dWf, Wi=dWi, Wc=dWc, Wo=dWo, Wy=dWy, bf=dbf, bi=dbi, bc=dbc, bo=dbo, by=dby)
state = (dh_next, dc_next)
return grad, state
import numpy as np
import code
class LSTM:
# https://gist.github.com/karpathy/587454dc0146a6ae21fc
@staticmethod
def init(input_size, hidden_size, fancy_forget_bias_init = 3):
"""
Initialize parameters of the LSTM (both weights and biases in one matrix)
One might way to have a positive fancy_forget_bias_init number (e.g. maybe even up to 5, in some papers)
"""
# +1 for the biases, which will be the first row of WLSTM
WLSTM = np.random.randn(input_size + hidden_size + 1, 4 * hidden_size) / np.sqrt(input_size + hidden_size)
WLSTM[0,:] = 0 # initialize biases to zero
if fancy_forget_bias_init != 0:
# forget gates get little bit negative bias initially to encourage them to be turned off
# remember that due to Xavier initialization above, the raw output activations from gates before
# nonlinearity are zero mean and on order of standard deviation ~1
WLSTM[0,hidden_size:2*hidden_size] = fancy_forget_bias_init
return WLSTM
@staticmethod
def forward(X, WLSTM, c0 = None, h0 = None):
"""
X should be of shape (n,b,input_size), where n = length of sequence, b = batch size
"""
n,b,input_size = X.shape
d = WLSTM.shape[1]/4 # hidden size
if c0 is None: c0 = np.zeros((b,d))
if h0 is None: h0 = np.zeros((b,d))
# Perform the LSTM forward pass with X as the input
xphpb = WLSTM.shape[0] # x plus h plus bias, lol
Hin = np.zeros((n, b, xphpb)) # input [1, xt, ht-1] to each tick of the LSTM
Hout = np.zeros((n, b, d)) # hidden representation of the LSTM (gated cell content)
IFOG = np.zeros((n, b, d * 4)) # input, forget, output, gate (IFOG)
IFOGf = np.zeros((n, b, d * 4)) # after nonlinearity
C = np.zeros((n, b, d)) # cell content
Ct = np.zeros((n, b, d)) # tanh of cell content
for t in xrange(n):
# concat [x,h] as input to the LSTM
prevh = Hout[t-1] if t > 0 else h0
Hin[t,:,0] = 1 # bias
Hin[t,:,1:input_size+1] = X[t]
Hin[t,:,input_size+1:] = prevh
# compute all gate activations. dots: (most work is this line)
IFOG[t] = Hin[t].dot(WLSTM)
# non-linearities
IFOGf[t,:,:3*d] = 1.0/(1.0+np.exp(-IFOG[t,:,:3*d])) # sigmoids; these are the gates
IFOGf[t,:,3*d:] = np.tanh(IFOG[t,:,3*d:]) # tanh
# compute the cell activation
prevc = C[t-1] if t > 0 else c0
C[t] = IFOGf[t,:,:d] * IFOGf[t,:,3*d:] + IFOGf[t,:,d:2*d] * prevc
Ct[t] = np.tanh(C[t])
Hout[t] = IFOGf[t,:,2*d:3*d] * Ct[t]
cache = {}
cache['WLSTM'] = WLSTM
cache['Hout'] = Hout
cache['IFOGf'] = IFOGf
cache['IFOG'] = IFOG
cache['C'] = C
cache['Ct'] = Ct
cache['Hin'] = Hin
cache['c0'] = c0
cache['h0'] = h0
# return C[t], as well so we can continue LSTM with prev state init if needed
return Hout, C[t], Hout[t], cache
@staticmethod
def backward(dHout_in, cache, dcn = None, dhn = None):
WLSTM = cache['WLSTM']
Hout = cache['Hout']
IFOGf = cache['IFOGf']
IFOG = cache['IFOG']
C = cache['C']
Ct = cache['Ct']
Hin = cache['Hin']
c0 = cache['c0']
h0 = cache['h0']
n,b,d = Hout.shape
input_size = WLSTM.shape[0] - d - 1 # -1 due to bias
# backprop the LSTM
dIFOG = np.zeros(IFOG.shape)
dIFOGf = np.zeros(IFOGf.shape)
dWLSTM = np.zeros(WLSTM.shape)
dHin = np.zeros(Hin.shape)
dC = np.zeros(C.shape)
dX = np.zeros((n,b,input_size))
dh0 = np.zeros((b, d))
dc0 = np.zeros((b, d))
dHout = dHout_in.copy() # make a copy so we don't have any funny side effects
if dcn is not None: dC[n-1] += dcn.copy() # carry over gradients from later
if dhn is not None: dHout[n-1] += dhn.copy()
for t in reversed(xrange(n)):
tanhCt = Ct[t]
dIFOGf[t,:,2*d:3*d] = tanhCt * dHout[t]
# backprop tanh non-linearity first then continue backprop
dC[t] += (1-tanhCt**2) * (IFOGf[t,:,2*d:3*d] * dHout[t])
if t > 0:
dIFOGf[t,:,d:2*d] = C[t-1] * dC[t]
dC[t-1] += IFOGf[t,:,d:2*d] * dC[t]
else:
dIFOGf[t,:,d:2*d] = c0 * dC[t]
dc0 = IFOGf[t,:,d:2*d] * dC[t]
dIFOGf[t,:,:d] = IFOGf[t,:,3*d:] * dC[t]
dIFOGf[t,:,3*d:] = IFOGf[t,:,:d] * dC[t]
# backprop activation functions
dIFOG[t,:,3*d:] = (1 - IFOGf[t,:,3*d:] ** 2) * dIFOGf[t,:,3*d:]
y = IFOGf[t,:,:3*d]
dIFOG[t,:,:3*d] = (y*(1.0-y)) * dIFOGf[t,:,:3*d]
# backprop matrix multiply
dWLSTM += np.dot(Hin[t].transpose(), dIFOG[t])
dHin[t] = dIFOG[t].dot(WLSTM.transpose())
# backprop the identity transforms into Hin
dX[t] = dHin[t,:,1:input_size+1]
if t > 0:
dHout[t-1,:] += dHin[t,:,input_size+1:]
else:
dh0 += dHin[t,:,input_size+1:]
return dX, dWLSTM, dc0, dh0
# -------------------
# TEST CASES
# -------------------
def checkSequentialMatchesBatch():
""" check LSTM I/O forward/backward interactions """
n,b,d = (5, 3, 4) # sequence length, batch size, hidden size
input_size = 10
WLSTM = LSTM.init(input_size, d) # input size, hidden size
X = np.random.randn(n,b,input_size)
h0 = np.random.randn(b,d)
c0 = np.random.randn(b,d)
# sequential forward
cprev = c0
hprev = h0
caches = [{} for t in xrange(n)]
Hcat = np.zeros((n,b,d))
for t in xrange(n):
xt = X[t:t+1]
_, cprev, hprev, cache = LSTM.forward(xt, WLSTM, cprev, hprev)
caches[t] = cache
Hcat[t] = hprev
# sanity check: perform batch forward to check that we get the same thing
H, _, _, batch_cache = LSTM.forward(X, WLSTM, c0, h0)
assert np.allclose(H, Hcat), 'Sequential and Batch forward don''t match!'
# eval loss
wrand = np.random.randn(*Hcat.shape)
loss = np.sum(Hcat * wrand)
dH = wrand
# get the batched version gradients
BdX, BdWLSTM, Bdc0, Bdh0 = LSTM.backward(dH, batch_cache)
# now perform sequential backward
dX = np.zeros_like(X)
dWLSTM = np.zeros_like(WLSTM)
dc0 = np.zeros_like(c0)
dh0 = np.zeros_like(h0)
dcnext = None
dhnext = None
for t in reversed(xrange(n)):
dht = dH[t].reshape(1, b, d)
dx, dWLSTMt, dcprev, dhprev = LSTM.backward(dht, caches[t], dcnext, dhnext)
dhnext = dhprev
dcnext = dcprev
dWLSTM += dWLSTMt # accumulate LSTM gradient
dX[t] = dx[0]
if t == 0:
dc0 = dcprev
dh0 = dhprev
# and make sure the gradients match
print('Making sure batched version agrees with sequential version: (should all be True)')
print(np.allclose(BdX, dX))
print(np.allclose(BdWLSTM, dWLSTM))
print(np.allclose(Bdc0, dc0))
print(np.allclose(Bdh0, dh0))
def checkBatchGradient():
""" check that the batch gradient is correct """
# lets gradient check this beast
n,b,d = (5, 3, 4) # sequence length, batch size, hidden size
input_size = 10
WLSTM = LSTM.init(input_size, d) # input size, hidden size
X = np.random.randn(n,b,input_size)
h0 = np.random.randn(b,d)
c0 = np.random.randn(b,d)
# batch forward backward
H, Ct, Ht, cache = LSTM.forward(X, WLSTM, c0, h0)
wrand = | np.random.randn(*H.shape) | numpy.random.randn |
# coding=utf-8
from __future__ import (division, print_function, absolute_import,
unicode_literals)
'''
GCE OMEGA (One-zone Model for the Evolution of Galaxies) module
Functionality
=============
This tool allows one to simulate the chemical evolution of single-zone galaxies.
Having the star formation history as one of the input parameters, OMEGA can
target local galaxies by using observational data found in the literature.
Made by
=======
FEB2015: <NAME>, <NAME>
MAY2015: B. Cote
The code inherits the chem_evol class, which contains common functions shared by
SYGMA and OMEGA. The code in chem_evol has been developed by :
v0.1 NOV2013: <NAME>, <NAME>
v0.2 JAN2014: <NAME>
v0.3 APR2014: <NAME>, <NAME>, <NAME>, <NAME>, <NAME>,
<NAME>, <NAME>, <NAME>, <NAME> &
the NuGrid collaboration
v0.4 FEB2015: <NAME>, B. Cote
v0.5 MAR2015: B. Cote
v0.6 OCT2016: B. Cote
Stop keeking track of version from now on.
MARCH2018: B. Cote
- Switched to Python 3
- Capability to include radioactive isotopes
FEB2019: A. Yagüe, B. Cote
- Optimized to code to run faster
Note
====
Please do not use "tabs" when introducing new lines of code.
Usage
=====
Import the module:
>>> import omega as o
Get help:
>>> help o
Get more information:
>>> o.omega?
Create a custom galaxy (closed box):
>>> o1 = o.omega(cte_sfr=1.0, mgal=1.5e10)
Simulate a known galaxy (open box):
>>> o2 = o.omega(galaxy='sculptor', in_out_control=True, mgal=1e6, mass_loading=8, in_out_ratio=1.5)
Analysis functions: See the Sphinx documentation
'''
# Standard packages
import copy
import math
import random
import os
# Define where is the working directory
# This is where the NuPyCEE code will be extracted
nupy_path = os.path.dirname(os.path.realpath(__file__))
# Import NuPyCEE codes
import NuPyCEE.sygma as sygma
from NuPyCEE.chem_evol import *
class omega( chem_evol ):
'''
Input parameters (OMEGA)
================
Important : By default, a closed box model is always assumed.
galaxy : string
Name of the target galaxy. By using a known galaxy, the code
automatically selects the corresponding star formation history, stellar
mass, and total mass (when available). By using 'none', the user has
perfect control of these three last parameters.
Choices : 'milky_way', 'milky_way_cte', 'sculptor', 'carina', 'fornax',
'none'
Default value : 'none'
Special note : The 'milky_way_cte' option uses the Milky Way's
characteristics, but with a constant star formation history.
cte_sfr : float
Constant star formation history in [Mo/yr].
Default value : 1.0
rand_sfh : float
Maximum possible ratio between the maximum and the minimum values of a star
formation history that is randomly generated.
Default value : 0.0 (deactivated)
Special note : A value greater than zero automatically generates a random
star formation history, which pypasses the use of the cte_sfr parameter.
sfh_file : string
Path to a file containing an input star formation history. The first and
second columns must be the age of the galaxy in [yr] and the star
formation rate in [Mo/yr].
Default value : 'none' (deactivated)
Special note : When a path is specified, it by passes the cte_sfr and the
and_sfh parameters.
stellar_mass_0 : float
Current stellar mass of the galaxy, in [Mo], at the end of the simulation.
Default value : -1.0 (you need to specify a value with unknown galaxies)
in_out_control : boolean
The in_out_control implementation enables control of the outflow and
the inflow rates independently by using constant values (see outflow_rate
and inflow_rate) or by using a mass-loading factor that connects the
rates to the star formation history (see mass_loading and in_out_ratio).
Default value : False (deactivated)
mass_loading : float
Ratio between the outflow rate and the star formation rate.
Default value : 1.0
outflow_rate : float
Constant outflow rate in [Mo/yr].
Default value : -1.0 (deactivated)
Special note : A value greater or equal to zero activates the constant
utflow mode, which bypasses the use of the mass_loading parameter.
in_out_ratio : float
Used in : in_out_control mode
Ratio between the inflow rate and the outflow rate. This parameter is
used to calculate the inflow rate, not the outflow rate.
Default value : 1.0
inflow_rate : float
Used in : in_out_control mode
Constant inflow rate in [Mo/yr].
Default value : -1.0 (deactivated)
Special note : A value greater or equal to zero activates the constant
inflow mode, which bypasses the use of the in_out_ratio parameter.
SF_law : boolean
The SF_law inplementation assumes a Kennicutt-Schmidt star formation law
and combines it to the known input star formation history in order to
derive the mass of the gas reservoir at every timestep.
Default value : False (deactivated)
sfe : float
Used in : SF_law and DM_evolution modes
Star formation efficiency present in the Kennicutt-Schmidt law.
Default value : 0.1
f_dyn : float
Used in : SF_law and DM_evolution modes
Scaling factor used to calculate the star formation timescale present in
the Kennicutt-Schmidt law. We assume that this timescale is equal to a
fraction of the dynamical timescale of the virialized system (dark and
baryonic matter), t_star = f_dyn * t_dyn.
Default value : 0.1
m_DM_0 : float
Used in : SF_law and DM_evolution modes
Current dark matter halo mass of the galaxy, in [Mo], at the end of the
simulations.
Default value : 1.0e+11
t_star : float
Used in : SF_law and DM_evolution modes
Star formation timescale, in [yr], used in the Kennicutt-Schmidt law.
Default value = -1.0 (deactivated)
Special note : A positive value activates the use of this parameter,
which bypasses the f_dyn parameter.
DM_evolution : boolean
The DM_evolution implementation is an extension of the SF_law option.
In addition to using a Kennicutt-Schmidt star formation law, it assumes
an evolution in the total mass of the galaxy as function of time. With
this prescription, the mass-loading factor has a mass dependency. The
mass_loading parameter then only represents the final value at the end
of the simulation.
Default value : False (deactivated)
exp_ml : float
Used in : DM_evolution mode
Exponent of the mass dependency of the mass-loading factor. This last
factor is proportional to M_vir**(-exp_ml/3), where M_vir is the sum of
dark and baryonic matter.
Default value : 2.0
================
'''
#Combine docstrings from chem_evol with sygma docstring
__doc__ = __doc__+chem_evol.__doc__
##############################################
## Constructor ##
##############################################
def __init__(self, galaxy='none', in_out_control=False, SF_law=False, \
DM_evolution=False, Z_trans=1e-20, f_dyn=0.1, sfe=0.1, \
outflow_rate=-1.0, inflow_rate=-1.0, rand_sfh=0.0, cte_sfr=1.0, \
m_DM_0=1.0e11, mass_loading=1.0, t_star=-1.0, sfh_file='none', \
in_out_ratio=1.0, stellar_mass_0=-1.0, \
z_dependent=True, exp_ml=2.0,nsmerger_bdys=[8, 100], \
imf_type='kroupa', alphaimf=2.35, imf_bdys=[0.1,100], \
sn1a_rate='power_law', iniZ=0.0, dt=1e6, special_timesteps=30, \
tend=13e9, mgal=1.0e10, transitionmass=8.0, iolevel=0, \
ini_alpha=True, nb_nsm_per_m=-1.0, t_nsm_coal=30.0e6,\
high_mass_extrapolation='copy',\
table='yield_tables/agb_and_massive_stars_nugrid_MESAonly_fryer12delay.txt', \
use_decay_module=False, yield_tables_dir='',\
f_network='isotopes_modified.prn', f_format=1,\
table_radio='', decay_file='', sn1a_table_radio='',\
bhnsmerger_table_radio='', nsmerger_table_radio='',\
hardsetZ=-1, sn1a_on=True, nsm_dtd_power=[],\
sn1a_table='yield_tables/sn1a_i99_W7.txt',\
ns_merger_on=False, f_binary=1.0, f_merger=0.0008,\
t_merger_max=1.3e10, m_ej_nsm = 2.5e-02, \
nsmerger_table = 'yield_tables/r_process_arnould_2007.txt', \
bhns_merger_on=False, m_ej_bhnsm=2.5e-02, \
bhnsmerger_table = 'yield_tables/r_process_arnould_2007.txt', \
iniabu_table='', extra_source_on=False, \
extra_source_table=['yield_tables/extra_source.txt'], \
f_extra_source=[1.0], pre_calculate_SSPs=False, \
extra_source_mass_range=[[8,30]], \
total_ejecta_interp=True, radio_refinement=100, \
extra_source_exclude_Z=[[]], beta_crit=1.0, \
pop3_table='yield_tables/popIII_heger10.txt', \
imf_bdys_pop3=[0.1,100], imf_yields_range_pop3=[10,30], \
imf_pop3_char_mass=40.0, \
starbursts=[], beta_pow=-1.0, gauss_dtd=[1e9,6.6e8],exp_dtd=2e9,\
nb_1a_per_m=1.0e-3, f_arfo=1, t_merge=-1.0,\
imf_yields_range=[1,30],exclude_masses=[], \
netyields_on=False,wiersmamod=False,skip_zero=False,\
redshift_f=0.0,print_off=False,long_range_ref=False,\
f_s_enhance=1.0,m_gas_f=-1.0, cl_SF_law=False,\
external_control=False, use_external_integration=False,\
calc_SSP_ej=False, tau_ferrini=False,\
input_yields=False, popIII_info_fast=True, t_sf_z_dep = 1.0,\
m_crit_on=False, norm_crit_m=8.0e+09, mass_frac_SSP=0.5,\
sfh_array_norm=-1.0, imf_rnd_sampling=False,\
out_follows_E_rate=False, yield_interp='lin',\
r_gas_star=-1.0, cte_m_gas = -1.0, t_dtd_poly_split=-1.0,\
stellar_param_on=False, delayed_extra_log=False,\
delayed_extra_yields_log_int=False,\
bhnsmerger_dtd_array=np.array([]), dt_in_SSPs=np.array([]), \
DM_array=np.array([]), nsmerger_dtd_array=np.array([]),\
sfh_array=np.array([]),ism_ini=np.array([]),\
ism_ini_radio=np.array([]),\
m_inflow_array=np.array([]), m_gas_array=np.array([]),\
mdot_ini=np.array([]), mdot_ini_t=np.array([]),\
ytables_in=np.array([]), zm_lifetime_grid_nugrid_in=np.array([]),\
isotopes_in=np.array([]), ytables_pop3_in=np.array([]),\
zm_lifetime_grid_pop3_in=np.array([]), ytables_1a_in=np.array([]),\
ytables_nsmerger_in=np.array([]), SSPs_in=np.array([]),\
dt_in=np.array([]), dt_split_info=np.array([]),\
ej_massive=np.array([]), ej_agb=np.array([]),\
ej_sn1a=np.array([]), ej_massive_coef=np.array([]),\
ej_agb_coef=np.array([]), ej_sn1a_coef=np.array([]),\
dt_ssp=np.array([]), r_vir_array=np.array([]),\
mass_sampled=np.array([]), scale_cor=np.array([]),\
mass_sampled_ssp=np.array([]), scale_cor_ssp=np.array([]),\
poly_fit_dtd_5th=np.array([]), poly_fit_range=np.array([]),\
m_tot_ISM_t_in=np.array([]), m_inflow_X_array=np.array([]),\
delayed_extra_dtd=np.array([]), delayed_extra_dtd_norm=np.array([]), \
delayed_extra_yields=np.array([]), delayed_extra_yields_norm=np.array([]),\
delayed_extra_yields_radio=np.array([]), \
delayed_extra_yields_norm_radio=np.array([]), \
ytables_radio_in=np.array([]), radio_iso_in=np.array([]), \
ytables_1a_radio_in=np.array([]), ytables_nsmerger_radio_in=np.array([]),\
omega_0=0.32, omega_b_0=0.05, lambda_0=0.68, H_0=67.11,\
test_clayton=np.array([]), inter_Z_points=np.array([]),\
nb_inter_Z_points=np.array([]), y_coef_M=np.array([]),\
y_coef_M_ej=np.array([]), y_coef_Z_aM=np.array([]),\
y_coef_Z_bM=np.array([]), y_coef_Z_bM_ej=np.array([]),\
tau_coef_M=np.array([]), tau_coef_M_inv=np.array([]),\
tau_coef_Z_aM=np.array([]), tau_coef_Z_bM=np.array([]),\
tau_coef_Z_aM_inv=np.array([]), tau_coef_Z_bM_inv=np.array([]),\
y_coef_M_pop3=np.array([]), y_coef_M_ej_pop3=np.array([]),\
tau_coef_M_pop3=np.array([]), tau_coef_M_pop3_inv=np.array([]),\
inter_lifetime_points_pop3=np.array([]),\
inter_lifetime_points_pop3_tree=np.array([]),\
nb_inter_lifetime_points_pop3=np.array([]),\
inter_lifetime_points=np.array([]), inter_lifetime_points_tree=np.array([]),\
nb_inter_lifetime_points=np.array([]), nb_inter_M_points_pop3=np.array([]),\
inter_M_points_pop3_tree=np.array([]), nb_inter_M_points=np.array([]),\
inter_M_points=np.array([]), y_coef_Z_aM_ej=np.array([])):
# Get the name of the instance
import traceback
(filename,line_number,function_name,text)=traceback.extract_stack()[-2]
self.inst_name = text[:text.find('=')].strip()
# Announce the beginning of the simulation
if not print_off:
print ('OMEGA run in progress..')
start_time = t_module.time()
self.start_time = start_time
# Call the init function of the class inherited by SYGMA
chem_evol.__init__(self, imf_type=imf_type, alphaimf=alphaimf, \
imf_bdys=imf_bdys, sn1a_rate=sn1a_rate, iniZ=iniZ, dt=dt, \
special_timesteps=special_timesteps, tend=tend, mgal=mgal, \
transitionmass=transitionmass, iolevel=iolevel, \
ini_alpha=ini_alpha, table=table, hardsetZ=hardsetZ, \
sn1a_on=sn1a_on, sn1a_table=sn1a_table, nsm_dtd_power=nsm_dtd_power,\
ns_merger_on=ns_merger_on, f_binary=f_binary, f_merger=f_merger,\
nsmerger_table=nsmerger_table, t_merger_max=t_merger_max,\
m_ej_nsm = m_ej_nsm, nb_nsm_per_m=nb_nsm_per_m, t_nsm_coal=t_nsm_coal, \
bhns_merger_on=bhns_merger_on, m_ej_bhnsm=m_ej_bhnsm, \
bhnsmerger_table=bhnsmerger_table, \
table_radio=table_radio, decay_file=decay_file,\
sn1a_table_radio=sn1a_table_radio, \
bhnsmerger_table_radio=bhnsmerger_table_radio,\
nsmerger_table_radio=nsmerger_table_radio,\
iniabu_table=iniabu_table, extra_source_on=extra_source_on, \
extra_source_table=extra_source_table,f_extra_source=f_extra_source, \
extra_source_mass_range=extra_source_mass_range, \
extra_source_exclude_Z=extra_source_exclude_Z,\
pop3_table=pop3_table, \
imf_bdys_pop3=imf_bdys_pop3, \
imf_pop3_char_mass=imf_pop3_char_mass, \
total_ejecta_interp=total_ejecta_interp, \
imf_yields_range_pop3=imf_yields_range_pop3, \
starbursts=starbursts, beta_pow=beta_pow, \
gauss_dtd = gauss_dtd, exp_dtd = exp_dtd, \
nb_1a_per_m=nb_1a_per_m, Z_trans=Z_trans, f_arfo=f_arfo, \
imf_yields_range=imf_yields_range,exclude_masses=exclude_masses, \
netyields_on=netyields_on,wiersmamod=wiersmamod, \
input_yields=input_yields, ism_ini_radio=ism_ini_radio,\
tau_ferrini=tau_ferrini, t_dtd_poly_split=t_dtd_poly_split, \
t_merge=t_merge,popIII_info_fast=popIII_info_fast,\
out_follows_E_rate=out_follows_E_rate,\
use_external_integration=use_external_integration,\
stellar_param_on=stellar_param_on, pre_calculate_SSPs=pre_calculate_SSPs,\
print_off=print_off, yield_tables_dir=yield_tables_dir, \
ism_ini=ism_ini,ytables_in=ytables_in,\
delayed_extra_yields_log_int=delayed_extra_yields_log_int,\
zm_lifetime_grid_nugrid_in=zm_lifetime_grid_nugrid_in,\
isotopes_in=isotopes_in,ytables_pop3_in=ytables_pop3_in,\
zm_lifetime_grid_pop3_in=zm_lifetime_grid_pop3_in,\
ytables_1a_in=ytables_1a_in, dt_in_SSPs=dt_in_SSPs, \
delayed_extra_log=delayed_extra_log, \
nsmerger_dtd_array=nsmerger_dtd_array,\
bhnsmerger_dtd_array=bhnsmerger_dtd_array, \
ytables_nsmerger_in=ytables_nsmerger_in, dt_in=dt_in,\
dt_split_info=dt_split_info,ej_massive=ej_massive,\
ej_agb=ej_agb,ej_sn1a=ej_sn1a,\
ej_massive_coef=ej_massive_coef,ej_agb_coef=ej_agb_coef,\
ej_sn1a_coef=ej_sn1a_coef,dt_ssp=dt_ssp,\
yield_interp=yield_interp, SSPs_in=SSPs_in,\
poly_fit_dtd_5th=poly_fit_dtd_5th,poly_fit_range=poly_fit_range,\
delayed_extra_dtd=delayed_extra_dtd,\
delayed_extra_dtd_norm=delayed_extra_dtd_norm,\
delayed_extra_yields=delayed_extra_yields,\
delayed_extra_yields_norm=delayed_extra_yields_norm,\
delayed_extra_yields_radio=delayed_extra_yields_radio,\
delayed_extra_yields_norm_radio=delayed_extra_yields_norm_radio,\
ytables_radio_in=ytables_radio_in, radio_iso_in=radio_iso_in,\
ytables_1a_radio_in=ytables_1a_radio_in,\
ytables_nsmerger_radio_in=ytables_nsmerger_radio_in,\
test_clayton=test_clayton, radio_refinement=radio_refinement,\
use_decay_module=use_decay_module,\
f_network=f_network, f_format=f_format,\
high_mass_extrapolation=high_mass_extrapolation,\
inter_Z_points=inter_Z_points,\
nb_inter_Z_points=nb_inter_Z_points, y_coef_M=y_coef_M,\
y_coef_M_ej=y_coef_M_ej, y_coef_Z_aM=y_coef_Z_aM,\
y_coef_Z_bM=y_coef_Z_bM, y_coef_Z_bM_ej=y_coef_Z_bM_ej,\
tau_coef_M=tau_coef_M, tau_coef_M_inv=tau_coef_M_inv,\
tau_coef_Z_aM=tau_coef_Z_aM, tau_coef_Z_bM=tau_coef_Z_bM,\
tau_coef_Z_aM_inv=tau_coef_Z_aM_inv, tau_coef_Z_bM_inv=tau_coef_Z_bM_inv,\
y_coef_M_pop3=y_coef_M_pop3, y_coef_M_ej_pop3=y_coef_M_ej_pop3,\
tau_coef_M_pop3=tau_coef_M_pop3, tau_coef_M_pop3_inv=tau_coef_M_pop3_inv,\
inter_lifetime_points_pop3=inter_lifetime_points_pop3,\
inter_lifetime_points_pop3_tree=inter_lifetime_points_pop3_tree,\
nb_inter_lifetime_points_pop3=nb_inter_lifetime_points_pop3,\
inter_lifetime_points=inter_lifetime_points,\
inter_lifetime_points_tree=inter_lifetime_points_tree,\
nb_inter_lifetime_points=nb_inter_lifetime_points,\
nb_inter_M_points_pop3=nb_inter_M_points_pop3,\
inter_M_points_pop3_tree=inter_M_points_pop3_tree,\
nb_inter_M_points=nb_inter_M_points, inter_M_points=inter_M_points,\
y_coef_Z_aM_ej=y_coef_Z_aM_ej)
# Quit if something bad happened in chem_evol ..
if self.need_to_quit:
return
# Calculate the number of CC SNe per Msun formed
if out_follows_E_rate:
A_pop3 = 1.0 / self._imf(imf_bdys_pop3[0],imf_bdys_pop3[1],2)
self.nb_ccsne_per_m_pop3 = \
A_pop3 * self._imf(imf_yields_range_pop3[0], \
imf_yields_range_pop3[1],1)
A = 1.0 / self._imf(imf_bdys[0],imf_bdys[1],2)
self.nb_ccsne_per_m = \
A * self._imf(transitionmass,imf_yields_range[1],1)
# Attribute the input parameters to the current OMEGA object
self.galaxy = galaxy
self.in_out_control = in_out_control
self.SF_law = SF_law
self.DM_evolution = DM_evolution
self.f_dyn = f_dyn
self.sfe = sfe
self.outflow_rate = outflow_rate
self.inflow_rate = inflow_rate
self.rand_sfh = rand_sfh
self.cte_sfr = cte_sfr
self.m_DM_0 = m_DM_0
self.mass_loading = mass_loading
self.t_star = t_star
self.sfh_file = sfh_file
self.in_out_ratio = in_out_ratio
self.stellar_mass_0 = stellar_mass_0
self.z_dependent = z_dependent
self.exp_ml = exp_ml
self.DM_too_low = False
self.skip_zero = skip_zero
self.redshift_f = redshift_f
self.print_off = print_off
self.long_range_ref = long_range_ref
self.m_crit_on = m_crit_on
self.norm_crit_m = norm_crit_m
self.sfh_array_norm = sfh_array_norm
self.DM_array = DM_array
self.sfh_array = sfh_array
self.mdot_ini = mdot_ini
self.mdot_ini_t = mdot_ini_t
self.r_gas_star = r_gas_star
self.m_gas_f = m_gas_f
self.cl_SF_law = cl_SF_law
self.external_control = external_control
self.mass_sampled = mass_sampled
self.scale_cor = scale_cor
self.imf_rnd_sampling = imf_rnd_sampling
self.cte_m_gas = cte_m_gas
self.t_sf_z_dep = t_sf_z_dep
self.out_follows_E_rate = out_follows_E_rate
self.m_tot_ISM_t_in = m_tot_ISM_t_in
self.m_inflow_array = m_inflow_array
self.len_m_inflow_array = len(m_inflow_array)
self.m_inflow_X_array = m_inflow_X_array
self.len_m_inflow_X_array = len(m_inflow_X_array)
self.m_gas_array = m_gas_array
self.len_m_gas_array = len(m_gas_array)
self.beta_crit = beta_crit
self.r_vir_array = r_vir_array
self.pre_calculate_SSPs = pre_calculate_SSPs
# If SSPs needs to be pre-calculated ..
if self.pre_calculate_SSPs:
# Calculate all SSPs
self.__run_all_ssps()
# Create the arrays that will contain the interpolated isotopes
self.ej_SSP_int = np.zeros((self.nb_steps_table,self.nb_isotopes))
if self.len_decay_file > 0:
self.ej_SSP_int_radio = np.zeros((self.nb_steps_table,self.nb_radio_iso))
# If the IMF will randomly be sampled ...
if self.imf_rnd_sampling:
# Print info about the IMF samplint
self.m_pop_max = 1.0e4
print ('IMF random sampling for SSP with M < ',self.m_pop_max)
# Calculate the stellar mass associated with the
# highest IMF value (needed for Monte Carlo)
# ONLY SAMPLING MASSIVE STARS
self.A_rdm = 1.0 / self.transitionmass**(-2.3)
self.m_frac_massive_rdm = self.A_rdm * \
self._imf(self.transitionmass, self.imf_bdys[1], 2)
# Calculate the stellar mass associated with the
# highest IMF value (needed for Monte Carlo)
# SAMPLING ALL STARS (warning! --> Need to modify the code for this)
#self.imf_norm_sampled = 10.0
#self.imfnorm = self.imf_norm_sampled
#imf_temp = []
#m_temp = self.imf_bdys[0]
#dm = 0.02
#while m_temp <= (self.imf_bdys[1]):
# imf_temp.append(self._imf(1.0,2.0,0,mass=m_temp))
# m_temp += dm
#self.imf_max = max(imf_temp)
# Set cosmological parameters - Dunkley et al. (2009)
#self.omega_0 = 0.257 # Current mass density parameter
#self.omega_b_0 = 0.044 # Current baryonic mass density parameter
#self.lambda_0 = 0.742 # Current dark energy density parameter
#self.H_0 = 71.9 # Hubble constant [km s^-1 Mpc^-1]
# Set cosmological parameters - as in Wise et al. 2012
#self.omega_0 = 0.266 # Current mass density parameter
#self.omega_b_0 = 0.0449 # Current baryonic mass density parameter
#self.lambda_0 = 0.734 # Current dark energy density parameter
#self.H_0 = 71.0 # Hubble constant [km s^-1 Mpc^-1]
# Set cosmological parameters - default is Planck 2013 (used in Caterpillar)
self.omega_0 = omega_0 # Current mass density parameter
self.omega_b_0 = omega_b_0 # Current baryonic mass density parameter
self.lambda_0 = lambda_0 # Current dark energy density parameter
self.H_0 = H_0 # Hubble constant [km s^-1 Mpc^-1]
# Look for errors in the input parameters
self.__check_inputs_omega()
# Define whether the open box scenario is used or not
if self.in_out_control or self.SF_law or self.DM_evolution:
self.open_box = True
else:
self.open_box = False
# Check if the timesteps need to be refined
if self.SF_law or self.DM_evolution:
self.t_SF_t = []
self.redshift_t = []
for k in range(self.nb_timesteps):
self.t_SF_t.append(0.0)
self.redshift_t.append(0.0)
self.t_SF_t.append(0.0)
self.redshift_t.append(0.0)
self.calculate_redshift_t()
self.__calculate_t_SF_t()
need_t_raf = False
for i_raf in range(self.nb_timesteps):
if self.history.timesteps[i_raf] > self.t_SF_t[i_raf] / self.sfe:
need_t_raf = True
break
if need_t_raf:
if self.long_range_ref:
self.__rafine_steps_lr()
else:
self.__rafine_steps()
# Re-Create entries for the mass-loss rate of massive stars
self.massive_ej_rate = []
self.sn1a_ej_rate = []
for k in range(self.nb_timesteps + 1):
self.massive_ej_rate.append(0.0)
self.sn1a_ej_rate.append(0.0)
# Declare arrays used to follow the evolution of the galaxy
self.__declare_evol_arrays()
# If the mass fraction ejected by SSPs needs to be calculated ...
# Need to be before self.__initialize_gal_prop()!!
self.mass_frac_SSP = -1.0
if calc_SSP_ej:
# Run SYGMA with five different metallicities
Z = [0.02, 0.01, 0.006, 0.001, 0.0001]
s_inst = []
self.mass_frac_SSP = 0.0
for i_Z_SSP in range(0,len(Z)):
s_inst = sygma.sygma(imf_type=imf_type, alphaimf=alphaimf,\
imf_bdys=imf_bdys, sn1a_rate=sn1a_rate, iniZ=Z[i_Z_SSP], dt=dt, \
special_timesteps=special_timesteps, tend=tend, mgal=1.0, \
transitionmass=transitionmass, iolevel=iolevel, \
ini_alpha=ini_alpha, table=table, hardsetZ=hardsetZ, \
sn1a_on=sn1a_on, sn1a_table=sn1a_table, \
iniabu_table=iniabu_table, extra_source_on=extra_source_on, \
extra_source_table=extra_source_table, pop3_table=pop3_table, \
imf_bdys_pop3=imf_bdys_pop3, \
imf_yields_range_pop3=imf_yields_range_pop3, \
starbursts=starbursts, beta_pow=beta_pow, \
gauss_dtd = gauss_dtd, exp_dtd = exp_dtd, \
nb_1a_per_m=nb_1a_per_m, Z_trans=Z_trans, f_arfo=f_arfo, \
imf_yields_range=imf_yields_range,exclude_masses=exclude_masses,\
netyields_on=netyields_on,wiersmamod=wiersmamod)
self.mass_frac_SSP += np.sum(s_inst.ymgal[-1])
# Calculate the average mass fraction returned
self.mass_frac_SSP = self.mass_frac_SSP / len(Z)
print ('Average SSP mass fraction returned = ',self.mass_frac_SSP)
else:
self.mass_frac_SSP = mass_frac_SSP
# Set the general properties of the selected galaxy
self.__initialize_gal_prop()
# Fill arrays used to follow the evolution
self.__fill_evol_arrays()
# Read the primordial composition of the inflow gas
if self.in_out_control or self.SF_law or self.DM_evolution:
prim_comp_table = os.path.join('yield_tables', 'iniabu',\
'iniab_bb_walker91.txt')
self.prim_comp = ry.read_yield_sn1a_tables(os.path.join(nupy_path,\
prim_comp_table), self.history.isotopes)
# In construction .. need to avoid altering default setups ..
# Assume the baryonic ratio for the initial gas reservoir, if needed
# if len(self.ism_ini) == 0 and not self.SF_law and not self.DM_evolution:
# if self.bar_ratio and not self.cl_SF_law:
# scale_m_tot = self.m_DM_0 * self.omega_b_0 / \
# (self.omega_0*np.sum(self.ymgal[0]))
# for k_cm in range(len(self.ymgal[0])):
# self.ymgal[0][k_cm] = self.ymgal[0][k_cm] * scale_m_tot
# Add the stellar ejecta coming from external galaxies that just merged
if len(self.mdot_ini) > 0:
self.__add_ext_mdot()
# Initialisation of the composition of the gas reservoir
if len(self.ism_ini) > 0:
for i_ini in range(0,self.len_ymgal):
self.ymgal[0][i_ini] = self.ism_ini[i_ini]
# Copy the outflow-vs-SFR array and re-initialize for delayed outflow
if out_follows_E_rate:
self.outflow_test = np.sum(self.m_outflow_t)
self.m_outflow_t_vs_SFR = copy.copy(self.m_outflow_t)
for i_ofer in range(0,self.nb_timesteps):
self.m_outflow_t[i_ofer] = 0.0
# If the timestep are not control by an external program ...
if not self.external_control:
# Run the simulation
self.__run_simulation(mass_sampled, scale_cor)
##############################################
# Check Inputs OMEGA #
##############################################
def __check_inputs_omega(self):
'''
This function checks for incompatible input entries, and stops
the simulation if needed.
'''
# Input galaxy
if not self.galaxy in ['none', 'milky_way', 'milky_way_cte', \
'sculptor', 'fornax', 'carina']:
print ('Error - Selected galaxy not available.')
return
# Random SFH
if self.rand_sfh > 0.0 and self.stellar_mass_0 < 0.0:
print ('Error - You need to choose a current stellar mass.')
return
# Inflow control when non-available
if self.in_out_control and (self.SF_law or self.DM_evolution):
print ('Error - Cannot control inflows and outflows when SF_law or'\
'DM_evolution is equal to True.')
return
# Defined initial dark matter halo mass when non-available
#if self.m_DM_ini > 0.0 and not self.DM_evolution:
# print ('Warning - Can\'t control m_DM_ini when the mass of', \
# 'the dark matter halo is not evolving.')
# Inflow and outflow control when the dark matter mass if evolving
if (self.outflow_rate >= 0.0 or self.inflow_rate >= 0.0) and \
self.DM_evolution:
print ('Error - Cannot fix inflow and outflow rates when the mass'\
'of the dark matter halo is evolving.')
return
# Inflow array when input
if self.len_m_inflow_array > 0:
if not self.len_m_inflow_array == self.nb_timesteps:
print ('Error - len(m_inflow_array) needs to equal nb_timesteps.')
return
# Inflow X array when input
if self.len_m_inflow_X_array > 0:
if not self.len_m_inflow_X_array == self.nb_timesteps:
print ('Error - len(m_inflow_X_array) needs to equal nb_timesteps.')
return
if not len(self.m_inflow_X_array[0]) == self.nb_isotopes:
print ('Error - len(m_inflow_X_array[i]) needs to equal nb_isotopes.')
return
# Mgas array when input
if self.len_m_gas_array > 0:
if not self.len_m_gas_array == (self.nb_timesteps+1):
print ('Error - len(m_gas_array) needs to equal nb_timesteps+1.')
return
##############################################
# Refine Steps #
##############################################
def __rafine_steps(self):
'''
This function increases the number of timesteps if the star formation
will eventually consume all the gas, which occurs when dt > (t_star/sfe).
'''
# Declaration of the new timestep array
if not self.print_off:
print ('..Time refinement..')
new_dt = []
# For every timestep ...
for i_rs in range(0,len(self.history.timesteps)):
# Calculate the critical time delay
t_raf = self.t_SF_t[i_rs] / self.sfe
# If the step needs to be refined ...
if self.history.timesteps[i_rs] > t_raf:
# Calculate the split factor
nb_split = int(self.history.timesteps[i_rs] / t_raf) + 1
# Split the step
for i_sp_st in range(0,nb_split):
new_dt.append(self.history.timesteps[i_rs]/nb_split)
# If ok, don't change anything
else:
new_dt.append(self.history.timesteps[i_rs])
# Update the timestep information
self.nb_timesteps = len(new_dt)
self.history.timesteps = new_dt
# Update self.history.age
self.history.age = [0]
for ii in range(self.nb_timesteps):
self.history.age.append(self.history.age[-1] + new_dt[ii])
self.history.age = np.array(self.history.age)
# If a timestep needs to be added to be synchronized with
# the external program managing merger trees ...
if self.t_merge > 0.0:
# Find the interval where the step needs to be added
i_temp = 0
t_temp = new_dt[0]
while t_temp / self.t_merge < 0.9999999:
i_temp += 1
t_temp += new_dt[i_temp]
# Keep the t_merger index in memory
self.i_t_merger = i_temp
# Update/redeclare all the arrays (stable isotopes)
ymgal = self._get_iniabu()
self.len_ymgal = len(ymgal)
self.mdot, self.ymgal, self.ymgal_massive, self.ymgal_agb, \
self.ymgal_1a, self.ymgal_nsm, self.ymgal_bhnsm, \
self.ymgal_delayed_extra, self.mdot_massive, \
self.mdot_agb, self.mdot_1a, self.mdot_nsm, self.mdot_bhnsm, \
self.mdot_delayed_extra, \
self.sn1a_numbers, self.sn2_numbers, self.nsm_numbers, self.bhnsm_numbers,\
self.delayed_extra_numbers, self.imf_mass_ranges, \
self.imf_mass_ranges_contribution, self.imf_mass_ranges_mtot = \
self._get_storing_arrays(ymgal, len(self.history.isotopes))
# Update/redeclare all the arrays (unstable isotopes)
if self.len_decay_file > 0:
ymgal_radio = np.zeros(self.nb_radio_iso)
# Initialisation of the storing arrays for radioactive isotopes
self.mdot_radio, self.ymgal_radio, self.ymgal_massive_radio, \
self.ymgal_agb_radio, self.ymgal_1a_radio, self.ymgal_nsm_radio, \
self.ymgal_bhnsm_radio, self.ymgal_delayed_extra_radio, \
self.mdot_massive_radio, self.mdot_agb_radio, self.mdot_1a_radio, \
self.mdot_nsm_radio, self.mdot_bhnsm_radio,\
self.mdot_delayed_extra_radio, dummy, dummy, dummy, dummy, dummy, \
dummy, dummy, dummy = \
self._get_storing_arrays(ymgal_radio, self.nb_radio_iso)
# Recalculate the simulation time (used in chem_evol)
self.t_ce = []
self.t_ce.append(self.history.timesteps[0])
for i_init in range(1,self.nb_timesteps):
self.t_ce.append(self.t_ce[i_init-1] + self.history.timesteps[i_init])
##############################################
# Rafine Steps LR #
##############################################
def __rafine_steps_lr(self):
'''
This function increases the number of timesteps if the star formation
will eventually consume all the gas, which occurs when dt > (t_star/sfe).
'''
# Declaration of the new timestep array
if not self.print_off:
print ('..Time refinement (long range)..')
new_dt = []
# For every timestep ...
for i_rs in range(0,len(self.history.timesteps)):
# Calculate the critical time delay
t_raf = self.t_SF_t[i_rs] / self.sfe
# If the step needs to be refined ...
if self.history.timesteps[i_rs] > t_raf:
# Calculate the number of remaining steps
nb_step_rem = len(self.history.timesteps) - i_rs
t_rem = 0.0
for i_rs in range(0,len(self.history.timesteps)):
t_rem += self.history.timesteps[i_rs]
# Calculate the split factor
nb_split = int(t_rem / t_raf) + 1
# Split the step
for i_sp_st in range(0,nb_split):
new_dt.append(t_rem/nb_split)
# Quit the for loop
break
# If ok, don't change anything
else:
new_dt.append(self.history.timesteps[i_rs])
# Update the timestep information
self.nb_timesteps = len(new_dt)
self.history.timesteps = new_dt
# Update self.history.age
self.history.age = [0]
for ii in range(self.nb_timesteps):
self.history.age.append(self.history.age[-1] + new_dt[ii])
self.history.age = np.array(self.history.age)
# If a timestep needs to be added to be synchronized with
# the external program managing merger trees ...
if self.t_merge > 0.0:
# Find the interval where the step needs to be added
i_temp = 0
t_temp = new_dt[0]
while t_temp / self.t_merge < 0.9999999:
i_temp += 1
t_temp += new_dt[i_temp]
# Keep the t_merger index in memory
self.i_t_merger = i_temp
# Update/redeclare all the arrays (stable isotopes)
ymgal = self._get_iniabu()
self.len_ymgal = len(ymgal)
self.mdot, self.ymgal, self.ymgal_massive, self.ymgal_agb, \
self.ymgal_1a, self.ymgal_nsm, self.ymgal_bhnsm, \
self.ymgal_delayed_extra, self.mdot_massive, \
self.mdot_agb, self.mdot_1a, self.mdot_nsm, self.mdot_bhnsm, \
self.mdot_delayed_extra, \
self.sn1a_numbers, self.sn2_numbers, self.nsm_numbers, self.bhnsm_numbers,\
self.delayed_extra_numbers, self.imf_mass_ranges, \
self.imf_mass_ranges_contribution, self.imf_mass_ranges_mtot = \
self._get_storing_arrays(ymgal, len(self.history.isotopes))
# Update/redeclare all the arrays (unstable isotopes)
if self.len_decay_file > 0:
ymgal_radio = np.zeros(self.nb_radio_iso)
# Initialisation of the storing arrays for radioactive isotopes
self.mdot_radio, self.ymgal_radio, self.ymgal_massive_radio, \
self.ymgal_agb_radio, self.ymgal_1a_radio, self.ymgal_nsm_radio, \
self.ymgal_bhnsm_radio, self.ymgal_delayed_extra_radio, \
self.mdot_massive_radio, self.mdot_agb_radio, self.mdot_1a_radio, \
self.mdot_nsm_radio, self.mdot_bhnsm_radio,\
self.mdot_delayed_extra_radio, dummy, dummy, dummy, dummy, dummy, \
dummy, dummy, dummy = \
self._get_storing_arrays(ymgal_radio, self.nb_radio_iso)
# Recalculate the simulation time (used in chem_evol)
self.t_ce = []
self.t_ce.append(self.history.timesteps[0])
for i_init in range(1,self.nb_timesteps):
self.t_ce.append(self.t_ce[i_init-1] + self.history.timesteps[i_init])
##############################################
# Declare Evol Arrays #
##############################################
def __declare_evol_arrays(self):
'''
This function declares the arrays used to follow the evolution of the
galaxy regarding its growth and the exchange of gas with its surrounding.
'''
# Arrays with specific values at every timestep
self.sfr_input = np.zeros(self.nb_timesteps+1) # Star formation rate [Mo yr^-1]
self.m_DM_t = np.zeros(self.nb_timesteps+1) # Mass of the dark matter halo
self.r_vir_DM_t= np.zeros(self.nb_timesteps+1) # Virial radius of the dark matter halo
self.v_vir_DM_t= np.zeros(self.nb_timesteps+1) # Virial velocity of the halo
self.m_tot_ISM_t = np.zeros(self.nb_timesteps+1) # Mass of the ISM in gas
self.m_outflow_t = np.zeros(self.nb_timesteps) # Mass of the outflow at every timestep
self.eta_outflow_t = np.zeros(self.nb_timesteps) # Mass-loading factor == M_outflow / SFR
self.t_SF_t = np.zeros(self.nb_timesteps+1) # Star formation timescale at every timestep
self.m_crit_t = np.zeros(self.nb_timesteps+1) # Critital ISM mass below which no SFR
self.redshift_t = np.zeros(self.nb_timesteps+1) # Redshift associated to every timestep
self.m_inflow_t = np.zeros(self.nb_timesteps) # Mass of the inflow at every timestep
##############################################
# Initialize Gal Prop #
##############################################
def __initialize_gal_prop(self):
'''
This function sets the properties of the selected galaxy, such as its
SFH, its total mass, and its stellar mass.
'''
# No specific galaxy - Use input parameters
if self.galaxy == 'none':
#If an array is used for the SFH ..
if len(self.sfh_array) > 0:
self.__copy_sfr_array()
# If an input file is used for the SFH ...
elif not self.sfh_file == 'none':
self.__copy_sfr_input(self.sfh_file)
# If a star formation law is used in a closed box ...
elif self.cl_SF_law and not self.open_box:
self.__calculate_sfe_cl()
# If a random SFH is chosen ...
elif self.rand_sfh > 0.0:
self.__generate_rand_sfh()
# If the SFH is constant ...
else:
for i_cte_sfr in range(0, self.nb_timesteps+1):
self.sfr_input[i_cte_sfr] = self.cte_sfr
# Milky Way galaxy ...
elif self.galaxy == 'milky_way' or self.galaxy == 'milky_way_cte':
# Set the current dark and stellar masses (corrected for mass loss)
self.m_DM_0 = 1.0e12
self.stellar_mass_0 = 5.0e10
# Read Chiappini et al. (2001) SFH
if self.galaxy == 'milky_way':
self.__copy_sfr_input('stellab_data/milky_way_data/sfh_mw_cmr01.txt')
# Read constant SFH
else:
self.__copy_sfr_input('stellab_data/milky_way_data/sfh_cte.txt')
# Sculptor dwarf galaxy ...
elif self.galaxy == 'sculptor':
# Set the current dark and stellar masses (corrected for mass loss)
self.m_DM_0 = 1.5e9
self.stellar_mass_0 = 7.8e6
self.stellar_mass_0 = self.stellar_mass_0 * (1-self.mass_frac_SSP)
# Read deBoer et al. (2012) SFH
self.__copy_sfr_input('stellab_data/sculptor_data/sfh_deBoer12.txt')
# Fornax dwarf galaxy ...
elif self.galaxy == 'fornax':
# Set the current dark and stellar masses (corrected for mass loss)
self.m_DM_0 = 7.08e8
self.stellar_mass_0 = 4.3e7
self.stellar_mass_0 = self.stellar_mass_0 * (1-self.mass_frac_SSP)
# Read deBoer et al. (2012) SFH
self.__copy_sfr_input('stellab_data/fornax_data/sfh_fornax_deboer_et_al_2012.txt')
# Carina dwarf galaxy ...
elif self.galaxy == 'carina':
# Set the current dark and stellar masses (corrected for mass loss)
self.m_DM_0 = 3.4e6
self.stellar_mass_0 = 1.07e6
self.stellar_mass_0 = self.stellar_mass_0 * (1-self.mass_frac_SSP)
# Read deBoer et al. (2014) SFH
self.__copy_sfr_input('stellab_data/carina_data/sfh_deBoer14.txt')
# Interpolate the last timestep
if len(self.sfr_input) > 3:
aa = (self.sfr_input[-2] - self.sfr_input[-3])/\
self.history.timesteps[-2]
bb = self.sfr_input[-2]- (self.history.tend-self.history.timesteps[-1])*aa
self.sfr_input[-1] = aa*self.history.tend + bb
# Keep the SFH in memory
self.history.sfr_abs = self.sfr_input
##############################################
## Copy SFR Array ##
##############################################
def __copy_sfr_array(self):
'''
See copy_sfr_input() for more info.
'''
# Variable to keep track of the OMEGA's timestep
i_dt_csa = 0
t_csa = 0.0
nb_dt_csa = self.nb_timesteps + 1
# Variable to keep track of the total stellar mass from the input SFH
m_stel_sfr_in = 0.0
# For every timestep given in the array (starting at the second step)
for i_csa in range(1,len(self.sfh_array)):
# Calculate the SFR interpolation coefficient
a_sfr = (self.sfh_array[i_csa][1] - self.sfh_array[i_csa-1][1]) / \
(self.sfh_array[i_csa][0] - self.sfh_array[i_csa-1][0])
b_sfr = self.sfh_array[i_csa][1] - a_sfr * self.sfh_array[i_csa][0]
# While we stay in the same time bin ...
while t_csa <= self.sfh_array[i_csa][0]:
# Interpolate the SFR
self.sfr_input[i_dt_csa] = a_sfr * t_csa + b_sfr
# Cumulate the stellar mass formed
m_stel_sfr_in += self.sfr_input[i_dt_csa] * \
self.history.timesteps[i_dt_csa]
# Exit the loop if the array is full
if i_dt_csa >= nb_dt_csa:
break
# Calculate the new time
t_csa += self.history.timesteps[i_dt_csa]
i_dt_csa += 1
# Exit the loop if the array is full
if (i_dt_csa + 1) >= nb_dt_csa:
break
# If the array has been read completely, but the sfr_input array is
# not full, fil the rest of the array with the last read value
if self.sfh_array[-1][1] == 0.0:
sfr_temp = 0.0
else:
sfr_temp = self.sfr_input[i_dt_csa-1]
while i_dt_csa < nb_dt_csa - 1:
self.sfr_input[i_dt_csa] = sfr_temp
m_stel_sfr_in += self.sfr_input[i_dt_csa] * \
self.history.timesteps[i_dt_csa]
t_csa += self.history.timesteps[i_dt_csa]
i_dt_csa += 1
# Normalise the SFR in order to be consistent with the integrated
# input star formation array (no mass loss considered!)
if self.sfh_array_norm > 0.0:
norm_sfr_in = self.sfh_array_norm / m_stel_sfr_in
for i_csa in range(0, nb_dt_csa):
self.sfr_input[i_csa] = self.sfr_input[i_csa] * norm_sfr_in
# Fill the missing last entry (extention of the last timestep, for tend)
# Since we don't know dt starting at tend, it is not part of m_stel_sfr_in
self.sfr_input[-1] = self.sfr_input[-2]
##############################################
## Calculate SFE Cl. ##
##############################################
def __calculate_sfe_cl(self):
'''
Calculate the star formation efficiency and the initial mass of gas
for a closed box model, given the final gas mass and the current
stellar mass.
'''
# Get the average return gas fraction of SSPs
if self.mass_frac_SSP == -1.0:
f_ej = 0.35
else:
f_ej = self.mass_frac_SSP
# If the gas-to-stellar mass ratio is the selected input ...
if self.r_gas_star > 0.0:
# Calculate the final mass of gas
self.m_gas_f = self.r_gas_star * self.stellar_mass_0
# Calculate the initial mass of gas
m_gas_ini = self.m_gas_f + self.stellar_mass_0
# If the final mass of gas is the selected input ...
elif self.m_gas_f > 0.0:
# Calculate the initial mass of gas
m_gas_ini = self.m_gas_f + self.stellar_mass_0
# If the initial mass of gas is the selected input ...
else:
# Use the input value for the initial mass of gas
m_gas_ini = self.mgal
# Calculate the final mass of gas
self.m_gas_f = m_gas_ini - self.stellar_mass_0
# Verify if the final mass of gas is negative
if self.m_gas_f < 0.0:
self.not_enough_gas = True
sfe_gcs = 1.0e-10
print ('!!Error - Try to have a negative final gas mass!!')
if not self.not_enough_gas:
# Scale the initial mass of all isotopes
scale_m_tot = m_gas_ini / np.sum(self.ymgal[0])
for k_cm in range(len(self.ymgal[0])):
self.ymgal[0][k_cm] = self.ymgal[0][k_cm] * scale_m_tot
# Initialization for finding the right SFE
sfe_gcs = 1.8e-10
sfe_max = 1.0
sfe_min = 0.0
m_gas_f_try = self.__get_m_gas_f(m_gas_ini, sfe_gcs, f_ej)
# While the SFE is not the right one ...
while abs(m_gas_f_try - self.m_gas_f) > 0.01:
# If the SFE needs to be increased ...
if (m_gas_f_try / self.m_gas_f) > 1.0:
# Set the lower limit of the SFE interval
sfe_min = sfe_gcs
# If an upper limit is already defined ...
if sfe_max < 1.0:
# Set the SFE to the middle point of the interval
sfe_gcs = (sfe_max + sfe_gcs) * 0.5
# If an upper limit is not already defined ...
else:
# Try a factor of 2
sfe_gcs = sfe_gcs * 2.0
# If the SFE needs to be decreased ...
else:
# Set the upper limit of the SFE interval
sfe_max = sfe_gcs
# If a lower limit is already defined ...
if sfe_min > 0.0:
# Set the SFE to the middle point of the interval
sfe_gcs = (sfe_min + sfe_gcs) * 0.5
# If a lower limit is not already defined ...
else:
# Try a factor of 2
sfe_gcs = sfe_gcs * 0.5
# Get the approximated final mass of gas
m_gas_f_try = self.__get_m_gas_f(m_gas_ini, sfe_gcs, f_ej)
# Keep the SFE in memory
self.sfe_gcs = sfe_gcs
##############################################
## Get M_gas_f ##
##############################################
def __get_m_gas_f(self, m_gas_ini, sfe_gcs, f_ej):
'''
Return the final mass of gas, given the initial mass of the gas
reservoir and the star formation efficiency. The function uses
a simple star formation law in the form of SFR(t) = sfe * M_gas(t)
'''
# Initialisation of the integration
m_gas_loop = m_gas_ini
t_gmgf = 0.0
# For every timestep ...
for i_gmgf in range(0,self.nb_timesteps):
# Calculate the new mass of gass
t_gmgf += self.history.timesteps[i_gmgf]
#self.sfr_input[i_gmgf] = sfe_gcs * m_gas_loop
m_gas_loop -= sfe_gcs * (1-f_ej) * m_gas_loop * \
self.history.timesteps[i_gmgf]
# Return the final mass of gas
return m_gas_loop
##############################################
# Copy SFR Input #
##############################################
def __copy_sfr_input(self, path_sfh_in):
'''
This function reads a SFH input file and interpolates its values so it
can be inserted in the array "sfr_input", which contains the SFR for each
OMEGA timestep.
Note
====
The input file does not need to have constant time step lengths, and
does not need to have the same number of timesteps as the number of
OMEGA timesteps.
Important
=========
In OMEGA and SYGMA, t += timestep[i] is the first thing done in the main
loop. The loop calculates what happened between the previous t and the
new t. This means the mass of stars formed must be SFR(previous t) *
timestep[i]. Therefore, sfr_input[i] IS NOT the SFR at time t +=
timestep[i], but rather the SFR at previous time which is used for the
current step i.
Argument
========
path_sfh_in : Path of the input SFH file.
'''
# Variable to keep track of the OMEGA timestep
nb_dt_csi = self.nb_timesteps + 1
i_dt_csi = 0
t_csi = 0.0 # Not timesteps[0] because sfr_input[0] must be
# used from t = 0 to t = timesteps[0]
# Variable to keep track of the total stellar mass from the input SFH
m_stel_sfr_in = 0.0
# Open the file containing the SFR vs time
with open(os.path.join(nupy_path, path_sfh_in), 'r') as sfr_file:
# Read the first line (col 0 : t, col 1 : SFR)
line_1_str = sfr_file.readline()
parts_1 = [float(x) for x in line_1_str.split()]
# For every remaining line ...
for line_2_str in sfr_file:
# Extract data
parts_2 = [float(x) for x in line_2_str.split()]
# Calculate the interpolation coefficients (SFR = a*t + b)
a_csi = (parts_2[1] - parts_1[1]) / (parts_2[0] - parts_1[0])
b_csi = parts_1[1] - a_csi * parts_1[0]
# While we stay in the same time bin ...
while t_csi <= parts_2[0]:
# Calculate the right SFR for the specific OMEGA timestep
#self.sfr_input[i_dt_csi] = a_csi * t_csi + b_csi
# Calculate the average SFR for the specific OMEGA timestep
if i_dt_csi < self.nb_timesteps:
self.sfr_input[i_dt_csi] = a_csi * (t_csi + \
self.history.timesteps[i_dt_csi] * 0.5) + b_csi
else:
self.sfr_input[i_dt_csi] = a_csi * t_csi + b_csi
# Cumulate the mass of stars formed
if i_dt_csi < nb_dt_csi - 1:
m_stel_sfr_in += self.sfr_input[i_dt_csi] * \
self.history.timesteps[i_dt_csi]
# Calculate the new time
t_csi += self.history.timesteps[i_dt_csi]
# Go to the next time step
i_dt_csi += 1
# Exit the loop if the array is full
if i_dt_csi >= nb_dt_csi:
break
# Exit the loop if the array is full
if i_dt_csi >= nb_dt_csi:
break
# Copie the last read line
parts_1 = copy.copy(parts_2)
# Close the file
sfr_file.close()
# If the file has been read completely, but the sfr_input array is
# not full, fill the rest of the array with the last read value
while i_dt_csi < nb_dt_csi:
self.sfr_input[i_dt_csi] = self.sfr_input[i_dt_csi-1]
if i_dt_csi < nb_dt_csi - 1:
m_stel_sfr_in += self.sfr_input[i_dt_csi] * \
self.history.timesteps[i_dt_csi]
i_dt_csi += 1
# Normalise the SFR in order to be consistent with the input current
# stellar mass (if the stellar mass is known)
if self.stellar_mass_0 > 0.0:
norm_sfr_in = self.stellar_mass_0 / ((1-self.mass_frac_SSP) * m_stel_sfr_in)
for i_csi in range(0, nb_dt_csi):
self.sfr_input[i_csi] = self.sfr_input[i_csi] * norm_sfr_in
##############################################
# Generate Rand SFH #
##############################################
def __generate_rand_sfh(self):
'''
This function generates a random SFH. This should only be used for
testing purpose in order to look at how the uncertainty associated to the
SFH can affects the results.
The self.rand_sfh sets the maximum ratio between the maximum and the
minimum values for the SFR. This parameter sets how "bursty" or constant
a SFH is. self.rand_sfh = 1 means a constant SFH.
'''
# Variable to keep track of the total stellar mass from the random SFH
m_stel_sfr_in = 0.0
# For each timestep
for i_csi in range(0,self.nb_timesteps+1):
self.sfr_input[i_csi] = random.randrange(1,self.rand_sfh+1)
# Cumulate the total mass of stars formed
if i_csi < self.nb_timesteps:
m_stel_sfr_in += self.sfr_input[i_csi] * \
self.history.timesteps[i_csi]
# Normalise the SFR in order to be consistent with the input
# current stellar mass
norm_sfr_in = self.stellar_mass_0 / ((1-self.mass_frac_SSP) * m_stel_sfr_in)
for i_csi in range(0,len(timesteps)+1):
self.sfr_input[i_csi] = self.sfr_input[i_csi] * norm_sfr_in
##############################################
# Fill Evol Arrays #
##############################################
def __fill_evol_arrays(self):
'''
This function fills the arrays used to follow the evolution of the
galaxy regarding its growth and the exchange of gas with its surrounding.
'''
# Execute this function only if needed
if self.in_out_control or self.SF_law or self.DM_evolution:
# Calculate the redshift for every timestep, if needed
self.calculate_redshift_t()
# Calculate the mass of the dark matter halo at every timestep
self.__calculate_m_DM_t()
# Calculate the virial radius and velocity at every timestep
self.calculate_virial()
# Calculate the critical, mass below which no SFR, at every dt
self.__calculate_m_crit_t()
# Calculate the star formation timescale at every timestep
self.__calculate_t_SF_t()
# Calculate the gas mass of the ISM at every timestep
self.__calculate_m_tot_ISM_t()
# Calculate the mass-loading factor and ouflow mass at every timestep
self.__calculate_outflow_t()
##############################################
# Get t From z #
##############################################
def __get_t_from_z(self, z_gttfz):
'''
This function returns the age of the Universe at a given redshift.
Argument
========
z_gttfz : Redshift that needs to be converted into age.
'''
# Return the age of the Universe
temp_var = math.sqrt((self.lambda_0/self.omega_0)/(1.0+z_gttfz)**3)
x_var = math.log( temp_var + math.sqrt( temp_var**2 + 1.0 ) )
return 2.0 / ( 3.0 * self.H_0 * math.sqrt(self.lambda_0)) * \
x_var * 9.77793067e11
##############################################
# Get z From t #
##############################################
def __get_z_from_t(self, t_gtzft):
'''
This function returns the redshift of a given Universe age.
Argument
========
t_gtzft : Age of the Universe that needs to be converted into redshift.
'''
# Return the redshift
temp_var = 1.5340669e-12 * self.lambda_0**0.5 * self.H_0 * t_gtzft
return (self.lambda_0 / self.omega_0)**0.3333333 / \
math.sinh(temp_var)**0.66666667 - 1.0
##############################################
# Calculate redshift(t) #
##############################################
def calculate_redshift_t(self):
'''
This function calculates the redshift associated to every timestep
assuming that 'tend' represents redshift zero.
'''
# Calculate the current age of the Universe (LambdaCDM - z = 0)
current_age_czt = self.__get_t_from_z(self.redshift_f)
# Calculate the age of the Universe when the galaxy forms
age_formation_czt = current_age_czt - self.history.tend
# Initiate the age of the galaxy
t_czt = 0.0
# Initialize the linear interpolation coefficients
self.redshift_t_coef = np.zeros((self.nb_timesteps,2))
#For each timestep
for i_czt in range(0, self.nb_timesteps+1):
#Calculate the age of the Universe at that time [yr]
age_universe_czt = age_formation_czt + t_czt
#Calculate the redshift at that time
self.redshift_t[i_czt] = self.__get_z_from_t(age_universe_czt)
# Calculate the interpolation coefficients
# z = self.redshift_t_coef[0] * t + self.redshift_t_coef[1]
if i_czt > 0:
self.redshift_t_coef[i_czt-1][0] = \
(self.redshift_t[i_czt]-self.redshift_t[i_czt-1]) / \
self.history.timesteps[i_czt-1]
self.redshift_t_coef[i_czt-1][1] = self.redshift_t[i_czt] - \
self.redshift_t_coef[i_czt-1][0] * t_czt
#Udpate the age of the galaxy [yr]
if i_czt < self.nb_timesteps:
t_czt += self.history.timesteps[i_czt]
#Correction for last digit error (e.g. z = -2.124325345e-8)
if self.redshift_t[-1] < 0.0:
self.redshift_t[-1] = 0.0
##############################################
# Run All SSPs #
##############################################
def __run_all_ssps(self):
'''
Create a SSP with SYGMA for each metallicity available in the yield tables.
Each SSP has a total mass of 1 Msun, is it can easily be re-normalized.
'''
# Copy the metallicities and put them in increasing order
self.Z_table_SSP = copy.copy(self.ytables.metallicities)
self.Z_table_first_nzero = min(self.Z_table_SSP)
if self.popIII_info_fast and self.iniZ <= 0.0 and self.Z_trans > 0.0:
self.Z_table_SSP.append(0.0)
self.Z_table_SSP = sorted(self.Z_table_SSP)
self.nb_Z_table_SSP = len(self.Z_table_SSP)
# If the SSPs are not given as an input ..
if len(self.SSPs_in) == 0:
# Define the SSP timesteps
len_dt_SSPs = len(self.dt_in_SSPs)
if len_dt_SSPs == 0:
dt_in_ras = self.history.timesteps
len_dt_SSPs = self.nb_timesteps
else:
dt_in_ras = self.dt_in_SSPs
# Declare the SSP ejecta arrays [Z][dt][iso]
self.ej_SSP = np.zeros((self.nb_Z_table_SSP,len_dt_SSPs,self.nb_isotopes))
if self.len_decay_file > 0:
self.ej_SSP_radio = \
np.zeros((self.nb_Z_table_SSP,len_dt_SSPs,self.nb_radio_iso))
# For each metallicity ...
for i_ras in range(0,self.nb_Z_table_SSP):
# Use a dummy iniabu file if the metallicity is not zero
if self.Z_table_SSP[i_ras] == 0:
iniabu_t = ''
hardsetZ2 = self.hardsetZ
else:
iniabu_t='yield_tables/iniabu/iniab2.0E-02GN93.ppn'
hardsetZ2 = self.Z_table_SSP[i_ras]
# Run a SYGMA simulation (1 Msun SSP)
sygma_inst = sygma.sygma(pre_calculate_SSPs=False, \
imf_type=self.imf_type, alphaimf=self.alphaimf, \
imf_bdys=self.history.imf_bdys, sn1a_rate=self.history.sn1a_rate, \
iniZ=self.Z_table_SSP[i_ras], dt=self.history.dt, \
special_timesteps=self.special_timesteps, \
nsmerger_bdys=self.nsmerger_bdys, tend=self.history.tend, \
mgal=1.0, transitionmass=self.transitionmass, \
table=self.table, hardsetZ=hardsetZ2, \
sn1a_on=self.sn1a_on, sn1a_table=self.sn1a_table, \
sn1a_energy=self.sn1a_energy, ns_merger_on=self.ns_merger_on, \
bhns_merger_on=self.bhns_merger_on, f_binary=self.f_binary, \
f_merger=self.f_merger, t_merger_max=self.t_merger_max, \
m_ej_nsm=self.m_ej_nsm, nsm_dtd_power=self.nsm_dtd_power,\
m_ej_bhnsm=self.m_ej_bhnsm, bhnsmerger_table=self.bhnsmerger_table, \
nsmerger_table=self.nsmerger_table, iniabu_table=iniabu_t, \
extra_source_on=self.extra_source_on, nb_nsm_per_m=self.nb_nsm_per_m, \
t_nsm_coal=self.t_nsm_coal, extra_source_table=self.extra_source_table, \
f_extra_source=self.f_extra_source, \
extra_source_mass_range=self.extra_source_mass_range, \
extra_source_exclude_Z=self.extra_source_exclude_Z, \
pop3_table=self.pop3_table, imf_bdys_pop3=self.imf_bdys_pop3, \
imf_yields_range_pop3=self.imf_yields_range_pop3, \
starbursts=self.starbursts, beta_pow=self.beta_pow, \
gauss_dtd=self.gauss_dtd, exp_dtd=self.exp_dtd, \
nb_1a_per_m=self.nb_1a_per_m, direct_norm_1a=self.direct_norm_1a, \
imf_yields_range=self.imf_yields_range, \
exclude_masses=self.exclude_masses, netyields_on=self.netyields_on, \
wiersmamod=self.wiersmamod, yield_interp=self.yield_interp, \
stellar_param_on=self.stellar_param_on, \
t_dtd_poly_split=self.t_dtd_poly_split, \
stellar_param_table=self.stellar_param_table, \
tau_ferrini=self.tau_ferrini, delayed_extra_log=self.delayed_extra_log, \
dt_in=dt_in_ras, nsmerger_dtd_array=self.nsmerger_dtd_array, \
bhnsmerger_dtd_array=self.bhnsmerger_dtd_array, \
poly_fit_dtd_5th=self.poly_fit_dtd_5th, \
poly_fit_range=self.poly_fit_range, \
delayed_extra_dtd=self.delayed_extra_dtd, \
delayed_extra_dtd_norm=self.delayed_extra_dtd_norm, \
delayed_extra_yields=self.delayed_extra_yields, \
delayed_extra_yields_norm=self.delayed_extra_yields_norm, \
table_radio=self.table_radio, decay_file=self.decay_file, \
sn1a_table_radio=self.sn1a_table_radio, \
bhnsmerger_table_radio=self.bhnsmerger_table_radio, \
nsmerger_table_radio=self.nsmerger_table_radio, \
ism_ini_radio=self.ism_ini_radio, \
delayed_extra_yields_radio=self.delayed_extra_yields_radio, \
delayed_extra_yields_norm_radio=self.delayed_extra_yields_norm_radio, \
ytables_radio_in=self.ytables_radio_in, radio_iso_in=self.radio_iso_in, \
ytables_1a_radio_in=self.ytables_1a_radio_in, \
ytables_nsmerger_radio_in=self.ytables_nsmerger_radio_in)
# Copy the ejecta arrays from the SYGMA simulation
self.ej_SSP[i_ras] = sygma_inst.mdot
if self.len_decay_file > 0:
self.ej_SSP_radio[i_ras] = sygma_inst.mdot_radio
# If this is the last Z entry ..
if i_ras == self.nb_Z_table_SSP - 1:
# Keep in memory the number of timesteps in SYGMA
self.nb_steps_table = len(sygma_inst.history.timesteps)
self.dt_ssp = sygma_inst.history.timesteps
# Keep the time of ssp in memory
self.t_ssp = np.zeros(self.nb_steps_table)
self.t_ssp[0] = self.dt_ssp[0]
for i_ras in range(1,self.nb_steps_table):
self.t_ssp[i_ras] = self.t_ssp[i_ras-1] + self.dt_ssp[i_ras]
# Clear the memory
del sygma_inst
# Calculate the interpolation coefficients (between metallicities)
self.__calculate_int_coef()
# If the SSPs are given as an input ..
else:
# Copy the SSPs
self.ej_SSP = self.SSPs_in[0]
self.nb_steps_table = len(self.ej_SSP[0])
self.ej_SSP_coef = self.SSPs_in[1]
self.dt_ssp = self.SSPs_in[2]
self.t_ssp = self.SSPs_in[3]
if len(self.SSPs_in) > 4:
self.ej_SSP_radio = self.SSPs_in[4]
self.ej_SSP_coef_radio = self.SSPs_in[5]
self.decay_info = self.SSPs_in[6]
self.len_decay_file = self.SSPs_in[7]
self.nb_radio_iso = len(self.decay_info)
self.nb_new_radio_iso = len(self.decay_info)
del self.SSPs_in
##############################################
# Calculate Int. Coef. #
##############################################
def __calculate_int_coef(self):
'''
Calculate the interpolation coefficients of each isotope between the
different metallicities for every timestep considered in the SYGMA
simulations. ejecta = a * log(Z) + b
self.ej_x[Z][step][isotope][0 -> a, 1 -> b], where the Z index refers
to the lower metallicity boundary of the interpolation.
'''
# Declare the interpolation coefficients arrays
self.ej_SSP_coef = \
np.zeros((2,self.nb_Z_table_SSP,self.nb_steps_table,self.nb_isotopes))
if self.len_decay_file > 0:
self.ej_SSP_coef_radio = \
np.zeros((2,self.nb_Z_table_SSP,self.nb_steps_table,self.nb_radio_iso))
# For each metallicity interval ...
for i_cic in range(0,self.nb_Z_table_SSP-1):
# If the metallicity is not zero ...
if not self.Z_table_SSP[i_cic] == 0.0:
# Calculate the log(Z) for the boundary metallicities
logZ_low = np.log10(self.Z_table_SSP[i_cic])
logZ_up = np.log10(self.Z_table_SSP[i_cic+1])
dif_logZ_inv = 1.0 / (logZ_up - logZ_low)
# For each step ...
for j_cic in range(0,self.nb_steps_table):
# For every stable isotope ..
for k_cic in range(0,self.nb_isotopes):
# Copy the isotope mass for the boundary metallicities
iso_low = self.ej_SSP[i_cic][j_cic][k_cic]
iso_up = self.ej_SSP[i_cic+1][j_cic][k_cic]
# Calculate the "a" and "b" coefficients
self.ej_SSP_coef[0][i_cic][j_cic][k_cic] = \
(iso_up - iso_low) * dif_logZ_inv
self.ej_SSP_coef[1][i_cic][j_cic][k_cic] = iso_up - \
self.ej_SSP_coef[0][i_cic][j_cic][k_cic] * logZ_up
# For every radioactive isotope ..
if self.len_decay_file > 0:
for k_cic in range(0,self.nb_radio_iso):
# Copy the isotope mass for the boundary metallicities
iso_low = self.ej_SSP_radio[i_cic][j_cic][k_cic]
iso_up = self.ej_SSP_radio[i_cic+1][j_cic][k_cic]
# Calculate the "a" and "b" coefficients
self.ej_SSP_coef_radio[0][i_cic][j_cic][k_cic] = \
(iso_up - iso_low) * dif_logZ_inv
self.ej_SSP_coef_radio[1][i_cic][j_cic][k_cic] = iso_up - \
self.ej_SSP_coef_radio[0][i_cic][j_cic][k_cic] * logZ_up
##############################################
# Calculate M_DM(t) #
##############################################
def __calculate_m_DM_t(self):
'''
This functions calculates the mass of the dark matter halo at each
timestep.
'''
# If the mass of the dark matter halo is kept at a constant value ...
if not self.DM_evolution:
# If the dark matter evolution is an input array ...
if len(self.DM_array) > 0:
# Copy the input values
self.copy_DM_input()
# Use the current value for every timestep
else:
for i_cmdt in range(0, self.nb_timesteps+1):
self.m_DM_t[i_cmdt] = self.m_DM_0
# If the mass of the dark matter halo evolves with time ...
else:
# If the dark matter evolution is an input array ...
if len(self.DM_array) > 0:
# Copy the input values
self.copy_DM_input()
# If the dark matter evolution is taken from Millenium simulations ...
else:
# Calculate the polynomial coefficient for the evolution of
# the dark matter mass
poly_up_dm, poly_low_dm = self.__get_DM_bdy()
# For each timestep ...
for i_cmdt in range(0, self.nb_timesteps+1):
# Calculate the lower and upper dark matter mass boundaries
log_m_dm_up = poly_up_dm[0] * self.redshift_t[i_cmdt]**3 + \
poly_up_dm[1] * self.redshift_t[i_cmdt]**2 + poly_up_dm[2] * \
self.redshift_t[i_cmdt] + poly_up_dm[3]
log_m_dm_low = poly_low_dm[0] * self.redshift_t[i_cmdt]**3 + \
poly_low_dm[1] * self.redshift_t[i_cmdt]**2 + poly_low_dm[2]*\
self.redshift_t[i_cmdt] + poly_low_dm[3]
# If the dark matter mass is too low for the available fit ...
if self.DM_too_low:
# Scale the fit using the current input mass
self.m_DM_t[i_cmdt] = 10**log_m_dm_low * \
self.m_DM_0 / 10**poly_low_dm[3]
# If the dark matter mass can be interpolated
else:
# Use a linear interpolation with the log of the mass
a = (log_m_dm_up - log_m_dm_low) / \
(poly_up_dm[3] - poly_low_dm[3])
b = log_m_dm_up - a * poly_up_dm[3]
self.m_DM_t[i_cmdt] = 10**( a * math.log10(self.m_DM_0) + b )
# If the simulation does not stop at redshift zero ...
if not self.redshift_f == 0.0:
# Scale the DM mass (because the fits look at M_DM_0 at z=0)
m_dm_scale = self.m_DM_0 / self.m_DM_t[-1]
for i_cmdt in range(0, self.nb_timesteps+1):
self.m_DM_t[i_cmdt] = self.m_DM_t[i_cmdt] * m_dm_scale
# Create the interpolation coefficients
# M_DM = self.m_DM_t_coef[0] * t + self.m_DM_t_coef[1]
self.m_DM_t_coef = np.zeros((self.nb_timesteps,2))
for i_cmdt in range(0, self.nb_timesteps):
self.m_DM_t_coef[i_cmdt][0] = (self.m_DM_t[i_cmdt+1] - \
self.m_DM_t[i_cmdt]) / self.history.timesteps[i_cmdt]
self.m_DM_t_coef[i_cmdt][1] = self.m_DM_t[i_cmdt] - \
self.m_DM_t_coef[i_cmdt][0] * self.history.age[i_cmdt]
##############################################
# Copy DM Input #
##############################################
def copy_DM_input(self):
'''
This function interpolates the DM masses from an input array
and add the masses to the corresponding OMEGA step
'''
# Variable to keep track of the OMEGA's timestep
i_dt_csa = 0
t_csa = 0.0
nb_dt_csa = self.nb_timesteps
# If just one entry ...
if len(self.DM_array) == 1:
self.m_DM_t[i_dt_csa] = self.DM_array[0][1]
i_dt_csa += 1
# If DM values need to be interpolated ...
else:
# For every timestep given in the array (starting at the second step)
for i_csa in range(1,len(self.DM_array)):
# Calculate the DM interpolation coefficient
a_DM = (self.DM_array[i_csa][1] - self.DM_array[i_csa-1][1]) / \
(self.DM_array[i_csa][0] - self.DM_array[i_csa-1][0])
b_DM = self.DM_array[i_csa][1] - a_DM * self.DM_array[i_csa][0]
# While we stay in the same time bin ...
while t_csa <= self.DM_array[i_csa][0]:
# Interpolate the SFR
self.m_DM_t[i_dt_csa] = a_DM * t_csa + b_DM
# Exit the loop if the array is full
if i_dt_csa >= nb_dt_csa:
break
# Calculate the new time
t_csa += self.history.timesteps[i_dt_csa]
i_dt_csa += 1
# Exit the loop if the array is full
if i_dt_csa >= nb_dt_csa:
break
# If the array has been read completely, but the DM array is
# not full, fil the rest of the array with the last input value
while i_dt_csa < nb_dt_csa+1:
self.m_DM_t[i_dt_csa] = self.DM_array[-1][1]
#self.m_DM_t[i_dt_csa] = self.m_DM_t[i_dt_csa-1]
i_dt_csa += 1
##############################################
# Copy R_vir Input #
##############################################
def copy_r_vir_input(self):
'''
This function interpolates the R_vir from an input array
and add the radius to the corresponding OMEGA step
'''
# Variable to keep track of the OMEGA's timestep
i_dt_csa = 0
t_csa = 0.0
nb_dt_csa = self.nb_timesteps
# If just one entry ...
if len(self.r_vir_array) == 1:
self.r_vir_DM_t[i_dt_csa] = self.r_vir_array[0][1]
i_dt_csa += 1
# If r_vir values need to be interpolated ...
else:
# For every timestep given in the array (starting at the second step)
for i_csa in range(1,len(self.r_vir_array)):
# Calculate the DM interpolation coefficient
a_r_vir = (self.r_vir_array[i_csa][1] - self.r_vir_array[i_csa-1][1]) / \
(self.r_vir_array[i_csa][0] - self.r_vir_array[i_csa-1][0])
b_r_vir = self.r_vir_array[i_csa][1] - a_r_vir * self.r_vir_array[i_csa][0]
# While we stay in the same time bin ...
while t_csa <= self.r_vir_array[i_csa][0]:
# Interpolate r_vir
self.r_vir_DM_t[i_dt_csa] = a_r_vir * t_csa + b_r_vir
# Exit the loop if the array is full
if i_dt_csa >= nb_dt_csa:
break
# Calculate the new time
t_csa += self.history.timesteps[i_dt_csa]
i_dt_csa += 1
# Exit the loop if the array is full
if i_dt_csa >= nb_dt_csa:
break
# If the array has been read completely, but the r_vir array is
# not full, fil the rest of the array with the last input value
while i_dt_csa < nb_dt_csa+1:
self.r_vir_DM_t[i_dt_csa] = self.r_vir_array[-1][1]
#self.r_vir_DM_t[i_dt_csa] = self.r_vir_DM_t[i_dt_csa-1]
i_dt_csa += 1
# Create the interpolation coefficients
# R_vir = self.r_vir_DM_t_coef[0] * t + self.r_vir_DM_t_coef[1]
self.r_vir_DM_t_coef = np.zeros((self.nb_timesteps,2))
for i_cmdt in range(0, self.nb_timesteps):
self.r_vir_DM_t_coef[i_cmdt][0] = (self.r_vir_DM_t[i_cmdt+1] - \
self.r_vir_DM_t[i_cmdt]) / self.history.timesteps[i_cmdt]
self.r_vir_DM_t_coef[i_cmdt][1] = self.r_vir_DM_t[i_cmdt] - \
self.r_vir_DM_t_coef[i_cmdt][0] * self.history.age[i_cmdt]
##############################################
# Get DM Bdy #
##############################################
# Return the fit coefficients for the interpolation of the dark matter mass
def __get_DM_bdy(self):
'''
This function calculates and returns the fit coefficients for the
interpolation of the evolution of the dark matter mass as a function
of time.
'''
# Open the file containing the coefficient of the 3rd order polynomial fit
with open(os.path.join(nupy_path, "m_dm_evolution", "poly3_fits.txt"),\
'r') as m_dm_file:
# Read the first line
line_str = m_dm_file.readline()
parts_1 = [float(x) for x in line_str.split()]
# If the input dark matter mass is higher than the ones provided
# by the fits ...
if math.log10(self.m_DM_0) > parts_1[3]:
# Use the highest dark matter mass available
parts_2 = copy.copy(parts_1)
print ('Warning - Current dark matter mass too high for' \
'the available fits.')
# If the input dark matter mass is in the available range ...
# Find the mass boundary for the interpolation.
else:
# For every remaining line ...
for line_str in m_dm_file:
# Extract data
parts_2 = [float(x) for x in line_str.split()]
# If the read mass is lower than the input dark matter mass
if math.log10(self.m_DM_0) > parts_2[3]:
# Exit the loop and use the current interpolation boundary
break
# Copy the current read line
parts_1 = copy.copy(parts_2)
# Keep track if the input dark matter mass is too low ...
if parts_1[3] == parts_2[3]:
self.DM_too_low = True
#Close the file
m_dm_file.close()
return parts_1, parts_2
##############################################
# Calculate Virial #
##############################################
def calculate_virial(self):
# If R_vir needs to be calculated ..
if len(self.r_vir_array) == 0:
# Average current mass density of the Universe [Mo Mpc^-3]
rho_0_uni = 3.7765e10
# For each timestep ...
for i_cv in range(0,len(self.history.timesteps)+1):
# Calculate the virial radius of the dark matter halo [kpc]
self.r_vir_DM_t[i_cv] = 1.0e3 * 0.106078 * \
(self.m_DM_t[i_cv] / rho_0_uni)**0.3333333 / \
(1 + self.redshift_t[i_cv])
# If R_vir is provided as an input ..
else:
# Use the input array and synchronize the timesteps
self.copy_r_vir_input()
# For each timestep ...
for i_cv in range(0,len(self.history.timesteps)+1):
#Calculate the virial velocity of the dark matter "particles" [km/s]
self.v_vir_DM_t[i_cv] = ( 4.302e-6 * self.m_DM_t[i_cv] / \
self.r_vir_DM_t[i_cv] )** 0.5
# Create the interpolation coefficients
# R_vir = self.r_vir_DM_t_coef[0] * t + self.r_vir_DM_t_coef[1]
self.r_vir_DM_t_coef = np.zeros((self.nb_timesteps,2))
for i_cmdt in range(0, self.nb_timesteps):
self.r_vir_DM_t_coef[i_cmdt][0] = (self.r_vir_DM_t[i_cmdt+1] - \
self.r_vir_DM_t[i_cmdt]) / self.history.timesteps[i_cmdt]
self.r_vir_DM_t_coef[i_cmdt][1] = self.r_vir_DM_t[i_cmdt] - \
self.r_vir_DM_t_coef[i_cmdt][0] * self.history.age[i_cmdt]
# Create the interpolation coefficients
# v_vir = self.v_vir_DM_t_coef[0] * t + self.v_vir_DM_t_coef[1]
self.v_vir_DM_t_coef = np.zeros((self.nb_timesteps,2))
for i_cmdt in range(0, self.nb_timesteps):
self.v_vir_DM_t_coef[i_cmdt][0] = (self.v_vir_DM_t[i_cmdt+1] - \
self.v_vir_DM_t[i_cmdt]) / self.history.timesteps[i_cmdt]
self.v_vir_DM_t_coef[i_cmdt][1] = self.v_vir_DM_t[i_cmdt] - \
self.v_vir_DM_t_coef[i_cmdt][0] * self.history.age[i_cmdt]
##############################################
# Calculate M_crit_t #
##############################################
def __calculate_m_crit_t(self):
# Calculate the real constant
# m_crit_final = self.norm_crit_m * (0.1/2000.0) * \
# (self.v_vir_DM_t[-1] * self.r_vir_DM_t[-1])
# the_constant = m_crit_final / ((0.1/2000.0) * \
# (self.v_vir_DM_t[-1] * self.r_vir_DM_t[-1])**self.beta_crit)
the_constant = self.norm_crit_m
#For each timestep ...
for i_ctst in range(0,len(self.history.timesteps)+1):
# If m_crit_t is wanted ...
if self.m_crit_on:
# Calculate the critical mass (Croton et al. 2006 .. modified)
self.m_crit_t[i_ctst] = the_constant * (0.1/2000.0) * \
(self.v_vir_DM_t[i_ctst] * self.r_vir_DM_t[i_ctst])**self.beta_crit
# If m_crit_t is not wanted ...
else:
# Set the critical mass to zero
self.m_crit_t[i_ctst] = 0.0
# Create the interpolation coefficients
# M_crit = self.m_crit_t_coef[0] * t + self.m_crit_t_coef[1]
self.m_crit_t_coef = np.zeros((self.nb_timesteps,2))
for i_cmdt in range(0, self.nb_timesteps):
self.m_crit_t_coef[i_cmdt][0] = (self.m_crit_t[i_cmdt+1] - \
self.m_crit_t[i_cmdt]) / self.history.timesteps[i_cmdt]
self.m_crit_t_coef[i_cmdt][1] = self.m_crit_t[i_cmdt] - \
self.m_crit_t_coef[i_cmdt][0] * self.history.age[i_cmdt]
##############################################
# Calculate t_SF(t) #
##############################################
def __calculate_t_SF_t(self):
'''
This function calculates the star formation timescale at every timestep.
'''
# Execute this function only if needed
if self.SF_law or self.DM_evolution:
# If the star formation timescale is kept constant ...
if self.t_star > 0:
# Use the same value for every timestep
for i_ctst in range(0, self.nb_timesteps+1):
self.t_SF_t[i_ctst] = self.t_star
# If the timescale follows the halo dynamical time ...
else:
# Set the timescale to a fraction of the halo dynamical time
# See White & Frenk (1991); Springel et al. (2001)
for i_ctst in range(0, self.nb_timesteps+1):
# If the dark matter mass is evolving ...
if self.DM_evolution:
self.t_SF_t[i_ctst] = self.f_dyn * 0.1 * (1 + \
self.redshift_t[i_ctst])**((-1.5)*self.t_sf_z_dep) \
/ self.H_0 * 9.7759839e11
# If the dark matter mass is not evolving ...
else:
self.t_SF_t[i_ctst] = self.f_dyn * 0.1 / self.H_0 * \
9.7759839e11
# Create the interpolation coefficients
# SF_t = self.t_SF_t_coef[0] * t + self.t_SF_t_coef[1]
self.t_SF_t_coef = np.zeros((self.nb_timesteps,2))
for i_cmdt in range(0, self.nb_timesteps):
self.t_SF_t_coef[i_cmdt][0] = (self.t_SF_t[i_cmdt+1] - \
self.t_SF_t[i_cmdt]) / self.history.timesteps[i_cmdt]
self.t_SF_t_coef[i_cmdt][1] = self.t_SF_t[i_cmdt] - \
self.t_SF_t_coef[i_cmdt][0] * self.history.age[i_cmdt]
##############################################
# Calculate M_tot ISM(t) #
##############################################
def __calculate_m_tot_ISM_t(self):
'''
This function calculates the mass of the gas reservoir at every
timestep using a classical star formation law.
'''
# If the evolution of the mass of the ISM is an input ...
if len(self.m_tot_ISM_t_in) > 0:
# Copy and adjust the input array for the OMEGA timesteps
self.__copy_m_tot_ISM_input()
# If the ISM has a constant mass ...
elif self.cte_m_gas > 0.0:
# For each timestep ...
for i_cm in range(0, self.nb_timesteps+1):
self.m_tot_ISM_t[i_cm] = self.cte_m_gas
# If the mass of gas is tighted to the SFH ...
elif self.SF_law or self.DM_evolution:
# For each timestep ...
for i_cm in range(0, self.nb_timesteps+1):
# If it's the last timestep ... use the previous sfr_input
if i_cm == self.nb_timesteps:
# Calculate the total mass of the ISM using the previous SFR
self.m_tot_ISM_t[i_cm] = self.sfr_input[i_cm-1] * \
self.t_SF_t[i_cm] / self.sfe + self.m_crit_t[i_cm]
# If it's not the last timestep ...
else:
# Calculate the total mass of the ISM using the current SFR
self.m_tot_ISM_t[i_cm] = self.sfr_input[i_cm] * \
self.t_SF_t[i_cm] / self.sfe + self.m_crit_t[i_cm]
# If the IO model ...
elif self.in_out_control:
self.m_tot_ISM_t[0] = self.mgal
# Scale the initial gas reservoir that was already set
scale_m_tot = self.m_tot_ISM_t[0] / np.sum(self.ymgal[0])
for k_cm in range(len(self.ymgal[0])):
self.ymgal[0][k_cm] = self.ymgal[0][k_cm] * scale_m_tot
##############################################
# Copy M_tot_ISM Input #
##############################################
def __copy_m_tot_ISM_input(self):
'''
This function interpolates the gas masses from an input array
and add the masses to the corresponding OMEGA step
'''
# Variable to keep track of the OMEGA's timestep
i_dt_csa = 0
t_csa = 0.0
nb_dt_csa = self.nb_timesteps + 1
# If just one entry ...
if len(self.m_tot_ISM_t_in) == 1:
self.m_tot_ISM_t[i_dt_csa] = self.m_tot_ISM_t_in[0][1]
i_dt_csa += 1
# If DM values need to be interpolated ...
else:
# For every timestep given in the array (starting at the second step)
for i_csa in range(1,len(self.m_tot_ISM_t_in)):
# Calculate the DM interpolation coefficient
a_gas = (self.m_tot_ISM_t_in[i_csa][1] - self.m_tot_ISM_t_in[i_csa-1][1]) / \
(self.m_tot_ISM_t_in[i_csa][0] - self.m_tot_ISM_t_in[i_csa-1][0])
b_gas = self.m_tot_ISM_t_in[i_csa][1] - a_gas * self.m_tot_ISM_t_in[i_csa][0]
# While we stay in the same time bin ...
while t_csa <= self.m_tot_ISM_t_in[i_csa][0]:
# Interpolate the SFR
self.m_tot_ISM_t[i_dt_csa] = a_gas * t_csa + b_gas
# Exit the loop if the array is full
if i_dt_csa >= nb_dt_csa:
break
# Calculate the new time
t_csa += self.history.timesteps[i_dt_csa]
i_dt_csa += 1
# Exit the loop if the array is full
if i_dt_csa >= nb_dt_csa:
break
# If the array has been read completely, but the DM array is
# not full, fil the rest of the array with the last read value
while i_dt_csa < nb_dt_csa:
self.m_tot_ISM_t[i_dt_csa] = self.m_tot_ISM_t_in[-1][1]
i_dt_csa += 1
##############################################
# Calculate Outflow #
##############################################
def __calculate_outflow_t(self):
'''
This function calculates the mass-loading factor and the mass of outflow
at every timestep.
'''
# If the outflow rate is kept constant ...
if self.outflow_rate >= 0.0:
# Use the input value for each timestep
for i_ceo in range(0, self.nb_timesteps):
self.eta_outflow_t[i_ceo] = self.outflow_rate / \
self.sfr_input[i_ceo]
self.m_outflow_t[i_ceo] = self.outflow_rate * \
self.history.timesteps[i_ceo]
# If the outflow rate is connected to the SFR ...
else:
# If the mass of the dark matter halo is not evolving
if not self.DM_evolution:
#For each timestep ...
for i_ceo in range(0, self.nb_timesteps):
# Use the input mass-loading factor
self.eta_outflow_t[i_ceo] = self.mass_loading
self.m_outflow_t[i_ceo] = self.eta_outflow_t[i_ceo] * \
self.sfr_input[i_ceo] * self.history.timesteps[i_ceo]
# If the mass of the dark matter halo is evolving
else:
# Use the input mass-loading factor to normalize the evolution
# of this factor as a function of time
eta_norm = self.mass_loading * \
self.m_DM_0**(self.exp_ml*0.33333)* \
(1+self.redshift_f)**(0.5*self.exp_ml)
# For each timestep ...
for i_ceo in range(0, self.nb_timesteps):
# Calculate the mass-loading factor with redshift dependence
if self.z_dependent:
self.eta_outflow_t[i_ceo] = eta_norm * \
self.m_DM_t[i_ceo]**((-0.3333)*self.exp_ml) * \
(1+self.redshift_t[i_ceo])**(-(0.5)*self.exp_ml)
# Calculate the mass-loading factor without redshift dependence
else:
self.eta_outflow_t[i_ceo] = eta_norm * \
self.m_DM_t[i_ceo]**((-0.3333)*self.exp_ml)
# Calculate the outflow mass during the current timestep
self.m_outflow_t[i_ceo] = self.eta_outflow_t[i_ceo] * \
self.sfr_input[i_ceo] * self.history.timesteps[i_ceo]
# Create the interpolation coefficients
# eta = self.eta_outflow_t_coef[0] * t + self.eta_outflow_t_coef[1]
self.eta_outflow_t_coef = np.zeros((self.nb_timesteps,2))
for i_cmdt in range(self.nb_timesteps-1):
self.eta_outflow_t_coef[i_cmdt][0] = (self.eta_outflow_t[i_cmdt+1] - \
self.eta_outflow_t[i_cmdt]) / self.history.timesteps[i_cmdt]
self.eta_outflow_t_coef[i_cmdt][1] = self.eta_outflow_t[i_cmdt] - \
self.eta_outflow_t_coef[i_cmdt][0] * self.history.age[i_cmdt]
self.eta_outflow_t_coef[-1][0] = self.eta_outflow_t_coef[-2][0]
self.eta_outflow_t_coef[-1][1] = self.eta_outflow_t_coef[-2][1]
##############################################
# Add Ext. M_dot #
##############################################
def __add_ext_mdot(self):
'''
This function adds the stellar ejecta of external galaxies that
just merged in the mdot array of the current galaxy. This function
assumes that the times and the number of timesteps of the merging
galaxies are different from the current galaxy.
Notes
=====
i_ext : Step index in the "external" merging mdot array
i_cur : Step index in the "current" galaxy mdot array
t_cur_prev : Lower time limit in the current i_cur bin
t_cur : Upper time limit in the current i_cur bin
M_dot_ini has an extra slot in the isotopes for the time,
which is t = 0.0 for i_ext = 0.
'''
# For every merging galaxy (every branch of a merger tree)
for i_merg in range(0,len(self.mdot_ini)):
# Initialisation of the local variables
i_ext = 0
i_cur = 0
t_cur_prev = 0.0
t_cur = self.history.timesteps[0]
t_ext_prev = 0.0
t_ext = self.mdot_ini_t[i_merg][i_ext+1]
# While the external ejecta has not been fully transfered...
len_mdot_ini_i_merg = len(self.mdot_ini[i_merg])
while i_ext < len_mdot_ini_i_merg and i_cur < self.nb_timesteps:
# While we need to change the external time bin ...
while t_ext <= t_cur:
# Calculate the overlap time between ext. and cur. bins
dt_trans = t_ext - max([t_ext_prev, t_cur_prev])
# Calculate the mass fraction that needs to be transfered
f_dt = dt_trans / (t_ext - t_ext_prev)
# Transfer all isotopes in the current mdot array
self.mdot[i_cur] += self.mdot_ini[i_merg][i_ext] * f_dt
# Move to the next external bin
i_ext += 1
if i_ext == (len_mdot_ini_i_merg):
break
t_ext_prev = t_ext
t_ext = self.mdot_ini_t[i_merg][i_ext+1]
# Quit the loop if all external bins have been considered
if i_ext == (len_mdot_ini_i_merg):
break
# While we need to change the current time bin ...
while t_cur < t_ext:
# Calculate the overlap time between ext. and cur. bins
dt_trans = t_cur - max([t_ext_prev, t_cur_prev])
# Calculate the mass fraction that needs to be transfered
f_dt = dt_trans / (t_ext - t_ext_prev)
# Transfer all isotopes in the current mdot array
self.mdot[i_cur] += self.mdot_ini[i_merg][i_ext] * f_dt
# Move to the next current bin
i_cur += 1
if i_cur == self.nb_timesteps:
break
t_cur_prev = t_cur
t_cur += self.history.timesteps[i_cur]
##############################################
# Run Simulation #
##############################################
def __run_simulation(self, mass_sampled=np.array([]), \
scale_cor=np.array([])):
'''
This function calculates the evolution of the chemical abundances of a
galaxy as a function of time.
Argument
========
mass_sampled : Stars sampled in the IMF by an external program.
scale_cor : Envelope correction for the IMF.
'''
# if self.len_decay_file > 0:
# print ('Warning, radioactive isotopes are missing in the outflows')
# For every timestep i considered in the simulation ...
for i in range(1, self.nb_timesteps+1):
# If the IMF must be sampled ...
if self.imf_rnd_sampling and self.m_pop_max >= \
(self.sfr_input[i-1] * self.history.timesteps[i-1]):
# Get the sampled masses
mass_sampled = self._get_mass_sampled(\
self.sfr_input[i-1] * self.history.timesteps[i-1])
# No mass sampled if using the full IMF ...
else:
mass_sampled = np.array([])
# Run a timestep using the input SFR
self.run_step(i, self.sfr_input[i-1], \
mass_sampled=mass_sampled, scale_cor=scale_cor)
# Calculate the last SFR at the end point of the simulation
if self.cl_SF_law and not self.open_box:
self.history.sfr_abs[-1] = self.sfe_gcs * np.sum(self.ymgal[i])
##############################################
# Run Step #
##############################################
def run_step(self, i, sfr_rs, m_added = np.array([]), m_lost = 0.0, \
no_in_out = False, f_esc_yields=0.0, mass_sampled=np.array([]),
scale_cor=np.array([])):
'''
This function calculates the evolution of one single step in the
chemical evolution.
Argument
========
i : Index of the timestep.
sfr_rs : Input star formation rate [Mo/yr] for the step i.
m_added : Mass (and composition) added for the step i.
m_lost : Mass lost for the step i.
no_in_out : Cancel the open box "if" statement if True
f_esc_yields: Fraction of non-contributing stellar ejecta
mass_sampled : Stars sampled in the IMF by an external program.
scale_cor : Envelope correction for the IMF.
'''
# Make sure that the the number of timestep is not exceeded
if not i == (self.nb_timesteps+1):
# For testing ..
if i == 1:
self.sfr_test = sfr_rs
# Calculate the current mass fraction of gas converted into stars,
# but only if the star formation rate is not followed
# within a self-consistent integration scheme.
if not self.use_external_integration:
self.__cal_m_frac_stars(i, sfr_rs)
else:
self.sfrin = sfr_rs # [Msun/yr]
self.m_locked = self.sfrin * self.history.timesteps[i-1]
# Run the timestep i (!need to be right after __cal_m_frac_stars!)
self._evol_stars(i, f_esc_yields, mass_sampled, scale_cor)
# Decay radioactive isotopes
if self.len_decay_file > 0 and not self.use_external_integration:
if self.use_decay_module:
self._decay_radio_with_module(i)
else:
self._decay_radio(i)
# Delay outflow is needed (following SNe rather than SFR) ...
if self.out_follows_E_rate:
self.__delay_outflow(i)
# Add the incoming gas (if any)
if not self.use_external_integration:
len_m_added = len(m_added)
for k_op in range(0, len_m_added):
self.ymgal[i][k_op] += m_added[k_op]
# If no integration scheme is used to advance the system ..
if not self.use_external_integration:
# If gas needs to be removed ...
if m_lost > 0.0:
# Calculate the gas fraction lost
f_lost = m_lost / sum(self.ymgal[i])
if f_lost > 1.0:
f_lost = 1.0
if not self.print_off:
print ('!!Warning -- Remove more mass than available!!')
# Remove the mass for each isotope
f_lost_2 = (1.0 - f_lost)
self.ymgal[i] = f_lost_2 * self.ymgal[i]
# Radioactive isotopes lost
if self.len_decay_file > 0:
self.ymgal_radio[i] = f_lost_2 * self.ymgal_radio[i]
if not self.pre_calculate_SSPs:
self.ymgal_agb[i] = f_lost_2 * self.ymgal_agb[i]
self.ymgal_1a[i] = f_lost_2 * self.ymgal_1a[i]
self.ymgal_nsm[i] = f_lost_2 * self.ymgal_nsm[i]
self.ymgal_bhnsm[i] = f_lost_2 * self.ymgal_bhnsm[i]
self.ymgal_massive[i] = f_lost_2 * self.ymgal_massive[i]
for iiii in range(0,self.nb_delayed_extra):
self.ymgal_delayed_extra[iiii][i] = \
f_lost_2 * self.ymgal_delayed_extra[iiii][i]
# Radioactive isotopes lost
if self.len_decay_file > 0:
if self.radio_massive_agb_on:
self.ymgal_massive_radio[i] = f_lost_2 * self.ymgal_massive_radio[i]
self.ymgal_agb_radio[i] = f_lost_2 * self.ymgal_agb_radio[i]
if self.radio_sn1a_on:
self.ymgal_1a_radio[i] = f_lost_2 * self.ymgal_1a_radio[i]
if self.radio_nsmerger_on:
self.ymgal_nsm_radio[i] = f_lost_2 * self.ymgal_nsm_radio[i]
if self.radio_bhnsmerger_on:
self.ymgal_bhnsm_radio[i] = f_lost_2 * self.ymgal_bhnsm_radio[i]
for iiii in range(0,self.nb_delayed_extra_radio):
self.ymgal_delayed_extra_radio[iiii][i] = \
f_lost_2 * self.ymgal_delayed_extra_radio[iiii][i]
# If the open box scenario is used (and it is not skipped) ...
if self.open_box and (not no_in_out):
# Calculate the total mass of the gas reservoir at timstep i
# after the star formation and the stellar ejecta
m_tot_current = sum(self.ymgal[i])
# Add inflows
if self.len_m_inflow_X_array > 0.0:
self.ymgal[i] += self.m_inflow_X_array[i-1]
m_inflow_current = self.m_inflow_array[i-1]
self.m_inflow_t[i-1] = float(m_inflow_current)
else:
# Get the current mass of inflow
m_inflow_current = self.__get_m_inflow(i, m_tot_current)
# Add primordial gas coming with the inflow
if m_inflow_current > 0.0:
ym_inflow = self.prim_comp.get(quantity='Yields') * \
m_inflow_current
for k_op in range(0, self.nb_isotopes):
self.ymgal[i][k_op] += ym_inflow[k_op]
# Calculate the fraction of gas removed by the outflow
if not (m_tot_current + m_inflow_current) == 0.0:
if self.len_m_gas_array > 0:
self.m_outflow_t[i-1] = (m_tot_current + m_inflow_current) - self.m_gas_array[i]
frac_rem = self.m_outflow_t[i-1] / (m_tot_current + m_inflow_current)
if frac_rem < 0.0:
frac_rem = 0.0
# Add primordial gas coming with the inflow
self.m_outflow_t[i-1] = 0.0
ym_inflow = self.prim_comp.get(quantity='Yields') * \
(-1.0) * self.m_outflow_t[i-1]
for k_op in range(0, self.nb_isotopes):
self.ymgal[i][k_op] += ym_inflow[k_op]
else:
frac_rem = self.m_outflow_t[i-1] / \
(m_tot_current + m_inflow_current)
else:
frac_rem = 0.0
# Limit the outflow mass to the amount of available gas
if frac_rem > 1.0:
frac_rem = 1.0
self.m_outflow_t[i-1] = m_tot_current + m_inflow_current
if not self.print_off:
print ('Warning - '\
'Outflows eject more mass than available. ' \
'It has been reduced to the amount of available gas.')
# Remove mass from the ISM because of the outflow
self.ymgal[i] *= (1.0 - frac_rem)
if self.len_decay_file > 0:
self.ymgal_radio[i] *= (1.0 - frac_rem)
if not self.pre_calculate_SSPs:
self.ymgal_agb[i] *= (1.0 - frac_rem)
self.ymgal_1a[i] *= (1.0 - frac_rem)
self.ymgal_nsm[i] *= (1.0 - frac_rem)
self.ymgal_bhnsm[i] *= (1.0 - frac_rem)
self.ymgal_massive[i] *= (1.0 - frac_rem)
for iiii in range(0,self.nb_delayed_extra):
self.ymgal_delayed_extra[iiii][i] *= (1.0 - frac_rem)
# Radioactive isotopes lost
if self.len_decay_file > 0:
if self.radio_massive_agb_on:
self.ymgal_massive_radio[i] *= (1.0 - frac_rem)
self.ymgal_agb_radio[i] *= (1.0 - frac_rem)
if self.radio_sn1a_on:
self.ymgal_1a_radio[i] *= (1.0 - frac_rem)
if self.radio_nsmerger_on:
self.ymgal_nsm_radio[i] *= (1.0 - frac_rem)
if self.radio_bhnsmerger_on:
self.ymgal_bhnsm_radio[i] *= (1.0 - frac_rem)
for iiii in range(0,self.nb_delayed_extra_radio):
self.ymgal_delayed_extra_radio[iiii][i] *= (1.0 - frac_rem)
# Get the new metallicity of the gas and update history class
self.zmetal = self._getmetallicity(i)
self._update_history(i)
# If this is the last step ...
if i == self.nb_timesteps:
# Do the final update of the history class
self._update_history_final()
# Add the evolution arrays to the history class
self.history.m_tot_ISM_t = self.m_tot_ISM_t
self.history.eta_outflow_t = self.eta_outflow_t
# If external control ...
if self.external_control:
self.history.sfr_abs[i] = self.history.sfr_abs[i-1]
# Calculate the total mass of gas
self.m_stel_tot = 0.0
for i_tot in range(0,len(self.history.timesteps)):
self.m_stel_tot += self.history.sfr_abs[i_tot] * \
self.history.timesteps[i_tot]
if self.m_stel_tot > 0.0:
self.m_stel_tot = 1.0 / self.m_stel_tot
self.f_m_stel_tot = []
m_temp = 0.0
for i_tot in range(0,len(self.history.timesteps)):
m_temp += self.history.sfr_abs[i_tot] * \
self.history.timesteps[i_tot]
self.f_m_stel_tot.append(m_temp*self.m_stel_tot)
self.f_m_stel_tot.append(self.f_m_stel_tot[-1])
# Announce the end of the simulation
print (' OMEGA run completed -',self._gettime())
# Error message
else:
print ('The simulation is already over.')
##############################################
# Get Mass Sampled #
##############################################
def _get_mass_sampled(self, m_pop):
'''
This function samples randomly the IMF using a Monte Carlo
approach and returns an array with all masses sampled (not
in increasing or decreasing orders).
Argument
========
m_pop : Mass of the considered stellar population
'''
# Initialization of the sampling arrays
mass_sampled_gms = []
m_tot_temp = 0.0
# Define the sampling precision in Msun
precision = 0.01 * m_pop * self.m_frac_massive_rdm
# Copy the lower and upper mass limit of the IMF
m_low_imf = self.transitionmass
m_up_imf = self.imf_bdys[1]
dm_temp = m_up_imf - m_low_imf
# While the total stellar mass is not formed ...
while abs(m_tot_temp - m_pop) > precision:
# Choose randomly a (m,nb) coordinate
rand_m = m_low_imf + np.random.random_sample()*dm_temp
rand_y = np.random.random_sample()
# If the coordinate is below the IMF curve
if rand_y <= (self.A_rdm * rand_m**(-2.3)):
# Add the stellar mass only if it doesn't
# form to much mass compared to m_pop
if (m_tot_temp + rand_m) - m_pop <= precision:
mass_sampled_gms.append(rand_m)
m_tot_temp += rand_m
# Stop if cannot fit a massive star
if abs(m_tot_temp - m_pop) < self.transitionmass:
break
# Return the stellar masses sampled using Monte Carlo
return mass_sampled_gms
##############################################
# Cal M Frac Stars #
##############################################
def __cal_m_frac_stars(self, i, sfr_rs):
'''
This function calculates the mass fraction of the gas reservoir that
is converted into stars at a given timestep.
Argument
========
i : Index of the timestep.
sfr_rs : Star formation rate [Mo/yr] for the timestep i
'''
# If the SFR is calculated from a star formation law (closed box)
if self.cl_SF_law and not self.open_box:
self.history.sfr_abs[i-1] = self.sfe_gcs * np.sum(self.ymgal[i-1])
self.sfrin = self.history.sfr_abs[i-1] * self.history.timesteps[i-1]
else:
# Calculate the total mass of stars formed during this timestep
self.sfrin = sfr_rs * self.history.timesteps[i-1]
self.history.sfr_abs[i-1] = sfr_rs
# Calculate the mass fraction of gas converted into stars
mgal_tot = 0.0
for k_ml in range(0, self.nb_isotopes):
mgal_tot += self.ymgal[i-1][k_ml]
if mgal_tot <= 0.0:
self.sfrin = 0.0
else:
self.sfrin = self.sfrin / mgal_tot
# Modify the history of SFR if there is not enough gas
if self.sfrin > 1.0:
self.history.sfr_abs[i-1] = mgal_tot / self.history.timesteps[i-1]
##############################################
# Delay Outflow #
##############################################
def __delay_outflow(self, i):
'''
This function convert the instantaneous outflow rate (vs SFR) into a delayed
rate where Mout follows the number of CC SNe.
Argument
========
i : Index of the timestep.
'''
# Calculate the 1 / (total number of CC SNe in the SSP)
if self.m_locked <= 0.0:
nb_cc_sne_inv = 1.0e+30
elif self.zmetal <= 0.0 and self.Z_trans > 0.0:
nb_cc_sne_inv = 1.0 / (self.nb_ccsne_per_m_pop3 * self.m_locked)
else:
nb_cc_sne_inv = 1.0 / (self.nb_ccsne_per_m * self.m_locked)
# Calculate the fraction of CC SNe in each future timesteps
len_ssp_nb_cc_sne = len(self.ssp_nb_cc_sne)
f_nb_cc = np.zeros(len_ssp_nb_cc_sne, np.float64)
for i_nb_cc in range(0,len_ssp_nb_cc_sne):
f_nb_cc[i_nb_cc] = self.ssp_nb_cc_sne[i_nb_cc] * nb_cc_sne_inv
# Copy the original instanteneous mass outflow [Msun]
m_out_inst = self.m_outflow_t_vs_SFR[i-1]
# For each future timesteps including the current one ...
for i_do in range(0,len_ssp_nb_cc_sne):
# Add the delayed mass outflow
#print (i, i_do, i+i_do, len(self.m_outflow_t))
self.m_outflow_t[i-1+i_do] += m_out_inst * f_nb_cc[i_do]
##############################################
# Get M Inflow #
##############################################
def __get_m_inflow(self, i, m_tot_current):
'''
This function calculates and returns the inflow mass at a given timestep
Argument
========
i : Index of the timestep.
m_tot_current : Total mass of the gas reservoir at step i
'''
# If an inflow mass in given at each timestep as an input ...
if self.len_m_inflow_array > 0:
m_inflow_current = self.m_inflow_array[i-1]
# If the constant inflow rate is kept constant ...
elif self.inflow_rate >= 0.0:
# Use the input rate to calculate the inflow mass
# Note : i-1 --> current timestep, see __copy_sfr_input()
m_inflow_current = self.inflow_rate * self.history.timesteps[i-1]
# If the inflow rate follows the outflow rate ...
elif self.in_out_control:
# Use the input scale factor to calculate the inflow mass
if self.out_follows_E_rate:
m_inflow_current = self.in_out_ratio * self.m_outflow_t_vs_SFR[i-1]
else:
m_inflow_current = self.in_out_ratio * self.m_outflow_t[i-1]
# If the inflow rate is calculated from the main equation ...
else:
# If SFR = 0 and we do not want to use the main equation ..
if self.sfr_input[i] == 0 and self.skip_zero:
m_inflow_current = 0.0
else:
# Calculate the mass of the inflow
m_inflow_current = self.m_tot_ISM_t[i] - \
m_tot_current + self.m_outflow_t[i-1]
# If the inflow mass is negative ...
if m_inflow_current < 0.0:
# Convert the negative inflow into positive outflow
if not self.skip_zero:
self.m_outflow_t[i-1] += (-1.0) * m_inflow_current
if not self.print_off:
print ('Warning - Negative inflow. ' \
'The outflow rate has been increased.', i)
# Assume no inflow
m_inflow_current = 0.0
# Keep the mass of inflow in memory
self.m_inflow_t[i-1] = float(m_inflow_current)
return m_inflow_current
###############################################################################################
######################## Here start the analysis methods ######################################
###############################################################################################
#### trueman edits
def mass_frac_plot(self,fig=0,species=['all'],sources=['agb','massive','1a'],\
cycle=-1, solar_ref='Asplund_et_al_2009',yscale='log'):
'''
fractional contribution from each stellar source towards the galactic total relative to solar
Parameters
----------
species : array of strings
isotope or element name,
e.g. ['H-1','He-4','Fe','Fe-56']
default = ['all']
sources : array of strings
specifies the stellar sources to plot,
e.g. ['agb','massive','1a']
cycle : float
specifies cycle number to plot,
e.g. 'cycle=-1' will plot last cycle
solar_ref : string
the solar abundances used as a reference
default is Asplund et al. 2009
'Asplund_et_al_2009'
'Anders_Grevesse_1989'
'Grevesse_Noels_1993'
'Grevesse_Sauval_1998'
'Lodders_et_al_2009'
yscale: string
choose y axis scale
'log' or 'linear'
Examples
---------
>>> s.plot(['all']['agb','massive','1a'],
cycle=-1, solar_ref='Lodders', yscale='log')
'''
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from matplotlib.patches import Patch
f = open(os.path.join(nupy_path, 'stellab_data',\
'solar_normalization', str(solar_ref) + '.txt'), 'r')
g = open(os.path.join(nupy_path, 'stellab_data',\
'solar_normalization', 'element_mass.txt'), 'r')
h = open(os.path.join(nupy_path, 'stellab_data',\
'solar_normalization', 'Asplund_et_al_2009_iso.txt'), 'r')
lines=f.readlines()
lines_g=g.readlines()
lines_h=h.readlines()
ele_mass = []
ele_nam = []
abu_sol = []
ele_sol = []
iso_nam =[]
iso_frac =[]
# items taken from Asplund
# keys = element symbol, values = logarithmic solar abundnace
for i in lines:
ele_sol.append(i.split()[1])
abu_sol.append(float(i.split()[2]))
f.close()
sol_dict = dict(zip(ele_sol, abu_sol))
# items taken from online data table
# keys = element symbol, values = element mass number
for j in lines_g:
ele_mass.append(float(j.split()[0]))
ele_nam.append(j.split()[2])
g.close()
ele_dict = dict(zip(ele_nam, ele_mass))
# items taken from Asplund
# keys = isotope symbol, values = relative number fraction of isotope
for k in lines_h:
iso_nam.append(k.split()[0])
iso_frac.append(float(k.split()[1])/100)
h.close()
iso_frac_dict = dict(zip(iso_nam, iso_frac))
# Create a dictionary with keys = element symbol
# and vals = solar mass fraction
ele_mass_frac = {}
for ele,mass in ele_dict.items():
for el,abu in sol_dict.items():
if ele == el:
ele_mass_frac.update([(ele,10**(abu-12)*mass*0.7381)])
# Normalise the above dictionary so that mass fractions
# sum to unity
tot_mass_frac = sum(ele_mass_frac.values())
for ele,frac in ele_mass_frac.items():
sol_dict.update([(ele,frac/tot_mass_frac)])
# Create a dictionary with keys = isotope
# vals = (mass fraction)/(isotope mass)
new = {}
for ele,mass in ele_dict.items():
for iso,frac in iso_frac_dict.items():
if ele == iso.split('-',1)[0]:
new.update([(iso,frac/mass)])
# Create a dictionary with keys = isotope
# vals = contribution towards total element mass fraction from each isotope
weighted_iso_frac={}
for ele,frac in sol_dict.items():
for iso,fracs in new.items():
if ele == iso.split('-',1)[0]:
weighted_iso_frac.update([
(iso,frac*fracs*float(iso.split('-',1)[-1]))])
species_mass_frac_sol_dict = weighted_iso_frac
species_mass_frac_sol_dict.update(sol_dict)
# Remove species which have no solar mass data
remove_keys = []
for key,val in species_mass_frac_sol_dict.items():
if val < 10e-30:
remove_keys.append(key)
for i in remove_keys:
if i in species_mass_frac_sol_dict:
del species_mass_frac_sol_dict[i]
iso_mass_gal = dict(zip(self.history.isotopes, self.ymgal[cycle]))
ele_dum=[]
for iso,mass in iso_mass_gal.items(): # create a list of the elements
ele = (iso.split('-',1)[0]) # from list of isotopes
ele_dum.append(ele)
elements = np.unique(ele_dum)
ele_mass_gal = np.zeros(len(elements))
i=0
# add the mass contribution from each isotope to
# make the total element mass
for el in elements:
for iso,mass in iso_mass_gal.items():
mass = float(mass)
if el == iso.split('-', 1)[0]:
ele_mass_gal[i] += mass
i+=1
# create a dictionary which has keys = element/isotope and
# vals = mass of species
ele_mass_gal_dict = dict(zip(elements, ele_mass_gal))
species_mass_gal = iso_mass_gal
species_mass_gal.update(ele_mass_gal_dict)
iso_mass_agb = dict(zip(self.history.isotopes, self.ymgal_agb[cycle]/sum(self.ymgal[cycle])))
ele_mass_agb = np.zeros(len(elements))
i=0
for el in elements:
for iso,mass in iso_mass_agb.items():
mass = float(mass)
if el == iso.split('-',1)[0]:
ele_mass_agb[i] += mass
i+=1
ele_mass_agb_dict = dict(zip(elements, ele_mass_agb))
species_mass_agb = iso_mass_agb
species_mass_agb.update(ele_mass_agb_dict)
# This dictionary contains the mass fraction contribution toward the total
# by AGB's for each species
species_frac_agb = {k: species_mass_agb[k] / species_mass_gal[k]
for k in species_mass_agb if k in species_mass_gal}
iso_mass_massive = dict(zip(self.history.isotopes, self.ymgal_massive[cycle]/sum(self.ymgal[cycle])))
ele_mass_massive = np.zeros(len(elements))
i=0
for el in elements:
for iso,mass in iso_mass_massive.items():
mass = float(mass)
if el == iso.split('-',1)[0]:
ele_mass_massive[i] += mass
i+=1
ele_mass_massive_dict = dict(zip(elements, ele_mass_massive))
species_mass_massive = iso_mass_massive
species_mass_massive.update(ele_mass_massive_dict)
# This dictionary contains the mass fraction contribution toward the total
# by SN1a's for each species
species_frac_massive = {k: species_mass_massive[k] / species_mass_gal[k]
for k in species_mass_massive if k in species_mass_gal}
iso_mass_1a = dict(zip(self.history.isotopes, self.ymgal_1a[cycle]/sum(self.ymgal[cycle])))
ele_mass_1a = np.zeros(len(elements))
i=0
for el in elements:
for iso,mass in iso_mass_1a.items():
mass = float(mass)
if el == iso.split('-',1)[0]:
ele_mass_1a[i] += mass
i+=1
ele_mass_1a_dict = dict(zip(elements, ele_mass_1a))
species_mass_1a = iso_mass_1a
species_mass_1a.update(ele_mass_1a_dict)
# This dictionary contains the mass fraction contribution toward the total
# by SN1a's for each species
species_frac_1a = {k: species_mass_1a[k] / species_mass_gal[k]
for k in species_mass_1a if k in species_mass_gal}
iso_mass_bhnsm = dict(zip(self.history.isotopes, self.ymgal_bhnsm[cycle]/sum(self.ymgal[cycle])))
ele_mass_bhnsm = np.zeros(len(elements))
i=0
for el in elements:
for iso,mass in iso_mass_bhnsm.items():
mass = float(mass)
if el == iso.split('-',1)[0]:
ele_mass_bhnsm[i] += mass
i+=1
ele_mass_bhnsm_dict = dict(zip(elements, ele_mass_bhnsm))
species_mass_bhnsm = iso_mass_bhnsm
species_mass_bhnsm.update(ele_mass_bhnsm_dict)
map_str_dic = {
"agb":species_mass_agb,
"1a":species_mass_1a,
"massive":species_mass_massive,
"bhnsm":species_mass_bhnsm
}
source_proper_name = {
"agb":'AGB',
"1a":'SN1a',
"massive":'Massive Stars',
"bhnsm":'Black hole-neutron star merger'
}
colors = ['blue', 'orange', 'grey','navy','green']
if species == ['all']:
species = species_mass_frac_sol_dict.keys()
bar_bottom=[]
for spec in species:
bar_bottom.append(0)
h=0
j=0
labels=[]
for source in sources:
labels.append(source_proper_name[source])
ii=0
for spe in species:
if spe in species_mass_agb:
source_frac = map_str_dic[source][spe]
val = source_frac/species_mass_frac_sol_dict[spe]
plt.bar(spe, val,bottom=bar_bottom[ii], color=colors[j])
bar_bottom[ii]+=val
ii+=1
j+=1
legend_elements = [Patch(facecolor='blue',
label='AGBs'),
Patch(facecolor='orange',
label='Massive Stars'),
Patch(facecolor='grey',
label='SN1a')]
plt.legend(handles=legend_elements)
plt.axhline(y=1, ls='--', color='k')
plt.title('Galaxy Age: '+str(round(self.history.age[cycle]/10**6, 1))+' Myr')
plt.xticks(rotation=90, fontsize=12)
plt.yscale(yscale)
plt.ylabel('$X/X_{\odot}$')
plt.tick_params(right=True)
def plot_mass(self,fig=0,specie='C',source='all',norm=False,label='',shape='',marker='',color='',markevery=20,multiplot=False,return_x_y=False,fsize=[10,4.5],fontsize=14,rspace=0.6,bspace=0.15,labelsize=15,legend_fontsize=14,show_legend=True):
'''
mass evolution (in Msun) of an element or isotope vs time.
Parameters
----------
specie : string
isotope or element name, in the form 'C' or 'C-12'
source : string
Specifies if yields come from
all sources ('all'), including
AGB+SN1a, massive stars. Or from
distinctive sources:
only agb stars ('agb'), only
SN1a ('SN1a'), or only massive stars
('massive')
norm : boolean
If True, normalize to current total ISM mass
label : string
figure label
marker : string
figure marker
shape : string
line style
color : string
color of line
fig : string,float
to name the plot figure
show_legend : boolean
Default True. Show or not the legend
Examples
----------
>>> s.plot('C-12')
'''
import matplotlib
import matplotlib.pyplot as plt
yaxis=specie
if len(label)<1:
label=yaxis
if source=='agb':
label=yaxis+', AGB'
if source=='massive':
label=yaxis+', Massive'
if source=='sn1a':
label=yaxis+', SNIa'
#Reserved for plotting
if not return_x_y:
shape,marker,color=self.__msc(source,shape,marker,color)
x=self.history.age
self.x=x
y=[]
yields_evol_all=self.history.ism_elem_yield
if yaxis in self.history.elements:
if source == 'all':
yields_evol=self.history.ism_elem_yield
elif source =='agb':
yields_evol=self.history.ism_elem_yield_agb
elif source == 'sn1a':
yields_evol=self.history.ism_elem_yield_1a
elif source == 'massive':
yields_evol=self.history.ism_elem_yield_massive
idx=self.history.elements.index(yaxis)
elif yaxis in self.history.isotopes:
if source == 'all':
yields_evol=self.history.ism_iso_yield
elif source =='agb':
yields_evol=self.history.ism_iso_yield_agb
elif source == 'sn1a':
yields_evol=self.history.ism_iso_yield_1a
elif source == 'massive':
yields_evol=self.history.ism_iso_yield_massive
idx=self.history.isotopes.index(yaxis)
else:
print ('Isotope or element not available')
return 0
for k in range(0,len(yields_evol)):
if norm == False:
y.append(yields_evol[k][idx])
else:
y.append( yields_evol[k][idx]/yields_evol_all[k][idx])
x=x[1:]
y=y[1:]
if multiplot==True:
return x,y
#Reserved for plotting
if not return_x_y:
plt.figure(fig, figsize=(fsize[0],fsize[1]))
plt.xscale('log')
plt.xlabel('log-scaled age [yrs]')
if norm == False:
plt.ylabel('yields [Msun]')
plt.yscale('log')
else:
plt.ylabel('(IMF-weighted) fraction of ejecta')
self.y=y
#If x and y need to be returned ...
if return_x_y:
return x, y
else:
if show_legend:
plt.plot(x,y,label=label,linestyle=shape,marker=marker,color=color,markevery=markevery)
plt.legend()
else:
plt.plot(x,y,linestyle=shape,marker=marker,color=color,markevery=markevery)
ax=plt.gca()
self.__fig_standard(ax=ax,fontsize=fontsize,labelsize=labelsize,rspace=rspace, bspace=bspace,legend_fontsize=legend_fontsize)
plt.xlim(self.history.dt,self.history.tend)
#return x,y
#self.save_data(header=['Age[yrs]',specie],data=[x,y])
def plot_massfrac(self,fig=2,xaxis='age',yaxis='O-16',source='all',norm='no',label='',shape='',marker='',color='',markevery=20,fsize=[10,4.5],fontsize=14,rspace=0.6,bspace=0.15,labelsize=15,legend_fontsize=14):
'''
Plots mass fraction of isotope or element
vs either time or other isotope or element.
Parameters
----------
xaxis : string
either 'age' for time
or isotope name, in the form e.g. 'C-12'
yaxis : string
isotope name, in the same form as for xaxis
source : string
Specifies if yields come from
all sources ('all'), including
AGB+SN1a, massive stars. Or from
distinctive sources:
only agb stars ('agb'), only
SN1a ('SN1a'), or only massive stars
('massive')
norm : string
if 'no', no normalization of mass fraction
if 'ini', normalization ot initial abundance
label : string
figure label
marker : string
figure marker
shape : string
line style
color : string
color of line
fig : string,float
to name the plot figure
Examples
----------
>>> s.plot_massfrac('age','C-12')
'''
import matplotlib
import matplotlib.pyplot as plt
if len(label)<1:
label=yaxis
shape,marker,color=self.__msc(source,shape,marker,color)
plt.figure(fig, figsize=(fsize[0],fsize[1]))
#Input X-axis
if '-' in xaxis:
#to test the different contributions
if source == 'all':
yields_evol=self.history.ism_iso_yield
elif source =='agb':
yields_evol=self.history.ism_iso_yield_agb
elif source == 'sn1a':
yields_evol=self.history.ism_iso_yield_1a
elif source == 'massive':
yields_evol=self.history.ism_iso_yield_massive
iso_idx=self.history.isotopes.index(xaxis)
x=[]
for k in range(1,len(yields_evol)):
if norm=='no':
x.append(yields_evol[k][iso_idx]/np.sum(yields_evol[k]))
if norm=='ini':
x.append(yields_evol[k][iso_idx]/np.sum(yields_evol[k])/yields_evol[0][iso_idx])
plt.xlabel('log-scaled X('+xaxis+')')
plt.xscale('log')
elif 'age' == xaxis:
x=self.history.age#[1:]
plt.xscale('log')
plt.xlabel('log-scaled Age [yrs]')
elif 'Z' == xaxis:
x=self.history.metallicity#[1:]
plt.xlabel('ISM metallicity')
plt.xscale('log')
elif xaxis in self.history.elements:
if source == 'all':
yields_evol=self.history.ism_elem_yield
elif source =='agb':
yields_evol=self.history.ism_elem_yield_agb
elif source == 'sn1a':
yields_evol=self.history.ism_elem_yield_1a
elif source == 'massive':
yields_evol=self.history.ism_elem_yield_massive
iso_idx=self.history.elements.index(xaxis)
x=[]
for k in range(1,len(yields_evol)):
if norm=='no':
x.append(yields_evol[k][iso_idx]/np.sum(yields_evol[k]))
if norm=='ini':
x.append(yields_evol[k][iso_idx]/np.sum(yields_evol[k])/yields_evol[0][iso_idx])
print (yields_evol[0][iso_idx])
plt.xlabel('log-scaled X('+xaxis+')')
plt.xscale('log')
#Input Y-axis
if '-' in yaxis:
#to test the different contributions
if source == 'all':
yields_evol=self.history.ism_iso_yield
elif source =='agb':
yields_evol=self.history.ism_iso_yield_agb
elif source == 'sn1a':
yields_evol=self.history.ism_iso_yield_1a
elif source == 'massive':
yields_evol=self.history.ism_iso_yield_massive
iso_idx=self.history.isotopes.index(yaxis)
y=[]
#change of xaxis array 'age 'due to continue statement below
if xaxis=='age':
x_age=x
x=[]
for k in range(1,len(yields_evol)):
if np.sum(yields_evol[k]) ==0:
continue
if norm=='no':
y.append(yields_evol[k][iso_idx]/np.sum(yields_evol[k]))
if norm=='ini':
y.append(yields_evol[k][iso_idx]/np.sum(yields_evol[k])/yields_evol[0][iso_idx])
x.append(x_age[k])
plt.ylabel('X('+yaxis+')')
self.y=y
plt.yscale('log')
elif 'Z' == yaxis:
y=self.history.metallicity
plt.ylabel('ISM metallicity')
plt.yscale('log')
elif yaxis in self.history.elements:
if source == 'all':
yields_evol=self.history.ism_elem_yield
elif source =='agb':
yields_evol=self.history.ism_elem_yield_agb
elif source == 'sn1a':
yields_evol=self.history.ism_elem_yield_1a
elif source == 'massive':
yields_evol=self.history.ism_elem_yield_massive
iso_idx=self.history.elements.index(yaxis)
y=[]
#change of xaxis array 'age 'due to continue statement below
if xaxis=='age':
x_age=x
x=[]
for k in range(1,len(yields_evol)):
if np.sum(yields_evol[k]) ==0:
continue
if norm=='no':
y.append(yields_evol[k][iso_idx]/np.sum(yields_evol[k]))
if norm=='ini':
y.append(yields_evol[k][iso_idx]/np.sum(yields_evol[k])/yields_evol[0][iso_idx])
x.append(x_age[k])
#plt.yscale('log')
plt.ylabel('X('+yaxis+')')
self.y=y
plt.yscale('log')
#To prevent 0 +log scale
if 'age' == xaxis:
x=x[1:]
y=y[1:]
plt.xlim(self.history.dt,self.history.tend)
plt.plot(x,y,label=label,linestyle=shape,marker=marker,color=color,markevery=markevery)
plt.legend()
ax=plt.gca()
self.__fig_standard(ax=ax,fontsize=fontsize,labelsize=labelsize,rspace=rspace, bspace=bspace,legend_fontsize=legend_fontsize)
self.save_data(header=[xaxis,yaxis],data=[x,y])
def plot_spectro(self,fig=3,xaxis='age',yaxis='[Fe/H]',source='all',label='',shape='-',marker='o',color='k',markevery=100,show_data=False,show_sculptor=False,show_legend=True,return_x_y=False,sub_plot=False,linewidth=3,sub=1,plot_data=False,fsize=[10,4.5],fontsize=14,rspace=0.6,bspace=0.15,labelsize=15,legend_fontsize=14,only_one_iso=False,solar_ab='',sfr_thresh=0.0,m_formed_thresh=1.0,solar_norm=''):
'''
Plots elements in spectroscopic notation:
Parameters
----------
xaxis : string
Elements spectroscopic notation e.g. [Fe/H]
if 'age': time evolution in years
yaxis : string
Elements in spectroscopic notation, e.g. [C/Fe]
source : string
If yields come from
all sources use 'all' (include
AGB+SN1a, massive stars.)
If yields come from distinctive source:
only agb stars use 'agb', only
SN1a ('SN1a'), or only massive stars
('massive')
label : string
figure label
marker : string
figure marker
shape : string
line style
color : string
color of line
fig : string,float
to name the plot figure
Examples
----------
>>> plt.plot_spectro('[Fe/H]','[C/Fe]')
'''
import matplotlib
import matplotlib.pyplot as plt
#Error message if there is the "subplot" has not been provided
if sub_plot and sub == 1:
print ('!! Error - You need to use the \'sub\' parameter and provide the frame for the plot !!')
return
#Operations associated with plot visual aspects
if not return_x_y and not sub_plot:
if len(label)<1:
label=yaxis
shape,marker,color=self.__msc(source,shape,marker,color)
#Set the figure output
if sub_plot:
plt_ps = sub
else:
plt_ps = plt
#Access solar abundance
if len(solar_ab) > 0:
iniabu=ry.iniabu(os.path.join(nupy_path, solar_ab))
else:
iniabu=ry.iniabu(os.path.join(nupy_path, 'yield_tables', 'iniabu',\
'iniab2.0E-02GN93.ppn'))
# If a solar normalization is used ..
if len(solar_norm) > 0:
# Mass number of the most abundant isotopes
el_norm = ['H', 'He', 'Li', 'Be', 'B', 'C', 'N', 'O', 'F', 'Ne', 'Na', 'Mg',\
'Al', 'Si', 'P', 'S', 'Cl', 'Ar', 'K', 'Ca', 'Sc', 'Ti', 'V', 'Cr',\
'Mn', 'Fe', 'Co', 'Ni', 'Cu', 'Zn', 'Ga', 'Ge', 'As', 'Se', 'Br',\
'Kr', 'Rb', 'Sr', 'Y', 'Zr', 'Nb', 'Mo', 'Ru', 'Rh', 'Pd', 'Ag',\
'Cd', 'In', 'Sn', 'Sb', 'Te', 'I', 'Xe', 'Cs', 'Ba', 'La', 'Ce',\
'Pr', 'Nd', 'Sm', 'Eu', 'Gd', 'Tb', 'Dy', 'Ho', 'Er', 'Tm', 'Yb',\
'Lu', 'Hf', 'Ta', 'W', 'Re', 'Os', 'Ir', 'Pt', 'Au', 'Hg', 'Tl',\
'Pb', 'Bi', 'Th', 'U']
mn_norm = [1.0000200000000001, 3.999834, 6.924099999999999, 9.0, 10.801,\
12.011061999999999, 14.00229, 16.004379000000004, 19.0, 20.13891,\
23.0, 24.3202, 27.0, 28.108575891424106, 31.0, 32.094199999999994,\
35.4844, 36.30859999999999, 39.13588999999999, 40.115629999999996,\
45.0, 47.9183, 50.9975, 52.05541, 55.0, 55.90993, 59.0, 58.759575,\
63.6166, 65.4682, 69.79784000000001, 72.69049999999999, 75.0, 79.0421,\
79.9862, 83.88084, 85.58312, 87.71136299999999, 89.0, 91.31840000000001,\
93.0, 96.05436999999998, 101.1598, 103.0, 106.5111, 107.96322,\
112.508, 114.9142, 118.8077, 121.85580000000002, 127.69839999999999,\
127.0, 131.28810000000001, 133.0, 137.42162, 138.99909000000002,\
140.20986, 141.0, 144.33351666483335, 150.4481, 152.0438, 157.3281,\
159.0, 162.57152999999997, 165.0, 167.32707000000002, 169.0,\
173.11618838116186, 175.02820514102572, 178.54163, 180.99988000000002,\
183.89069999999998, 186.28676, 190.28879711202887, 192.254,\
195.11347999999998, 197.0, 200.6297, 204.40952, 207.34285, 209.0,\
232.0, 237.27134]
# Solar values
sol_values_el = []
sol_values_ab = []
# Open the data file
with open(os.path.join(nupy_path, 'stellab_data',\
'solar_normalization', solar_norm + '.txt'), 'r') as data_file:
# For every line (for each element) ...
i_elem = 0
for line_1_str in data_file:
# Split the line
split = [str(x_split) for x_split in line_1_str.split()]
# Copy the element and the solar value
sol_values_el.append(str(split[1]))
sol_values_ab.append(float(split[2]))
# Go to the next element
i_elem += 1
# Close the file
data_file.close()
x_ini_iso=iniabu.iso_abundance(self.history.isotopes)
elements = self.history.elements
x_ini = self._iso_abu_to_elem(x_ini_iso)
#to test the different contributions
if source == 'all':
yields_evol=self.history.ism_elem_yield
elif source =='agb':
yields_evol=self.history.ism_elem_yield_agb
elif source == 'sn1a':
yields_evol=self.history.ism_elem_yield_1a
elif source == 'massive':
yields_evol=self.history.ism_elem_yield_massive
#Operations associated with plot visual aspects
if not return_x_y and not sub_plot:
plt.figure(fig, figsize=(fsize[0],fsize[1]))
if 'age' == xaxis:
x=self.history.age
#Operations associated with plot visual aspects
if not return_x_y and not sub_plot:
#plt.xscale('log')
plt.xlabel('Age [yr]')
self.x=x
else:
xaxis_elem1=xaxis.split('/')[0][1:]
xaxis_elem2=xaxis.split('/')[1][:-1]
#print (xaxis_elem1, xaxis_elem2)
#X-axis ini values
x_elem1_ini=x_ini[elements.index(xaxis_elem1)]
x_elem2_ini=x_ini[elements.index(xaxis_elem2)]
#X-axis gce values
elem_idx1=self.history.elements.index(xaxis_elem1)
elem_idx2=self.history.elements.index(xaxis_elem2)
# Take only 56-Fe is needed
if only_one_iso:
if yaxis_elem1 == 'Fe':
yields_evol = self.history.ism_iso_yield
elem_idx1 = self.history.isotopes.index('Fe-56')
x=[]
for k in range(0,len(yields_evol)):
if np.sum(yields_evol[k]) ==0:
continue
#in case no contribution during timestep
x1=yields_evol[k][elem_idx1]/np.sum(yields_evol[k])
x2=yields_evol[k][elem_idx2]/np.sum(yields_evol[k])
if x1 <= 0.0 or x2 <= 0.0:
spec = -30.0
else:
if len(solar_norm) > 0:
index_1 = el_norm.index(xaxis_elem1)
index_2 = el_norm.index(xaxis_elem2)
i_xx_sol_1 = sol_values_el.index(xaxis_elem1)
i_xx_sol_2 = sol_values_el.index(xaxis_elem2)
aaa = np.log10(yields_evol[k][elem_idx1]*mn_norm[index_2] /\
(yields_evol[k][elem_idx2]*mn_norm[index_1]))
bbb = sol_values_ab[i_xx_sol_1] - sol_values_ab[i_xx_sol_2]
spec= aaa - bbb
else:
spec=np.log10(x1/x2) - np.log10(x_elem1_ini/x_elem2_ini)
x.append(spec)
#Operations associated with plot visual aspects
if not return_x_y and not sub_plot:
plt.xlabel(xaxis)
self.x=x
yaxis_elem1=yaxis.split('/')[0][1:]
yaxis_elem2=yaxis.split('/')[1][:-1]
#y=axis ini values
x_elem1_ini=x_ini[elements.index(yaxis_elem1)]
x_elem2_ini=x_ini[elements.index(yaxis_elem2)]
#print ('Fe_sol = ',x_elem1_ini,' , H_sol = ',x_elem2_ini)
#Y-axis gce values
elem_idx1=self.history.elements.index(yaxis_elem1)
elem_idx2=self.history.elements.index(yaxis_elem2)
# Take only 56-Fe is needed
if only_one_iso:
if yaxis_elem1 == 'Fe':
yields_evol = self.history.ism_iso_yield
elem_idx1 = self.history.isotopes.index('Fe-56')
elif yaxis_elem2 == 'Fe':
yields_evol = self.history.ism_iso_yield
elem_idx2 = self.history.isotopes.index('Fe-56')
y=[]
if xaxis=='age':
x_age=x
x=[]
for k in range(0,len(yields_evol)):
if np.sum(yields_evol[k]) ==0:
continue
#in case no contribution during timestep
x1=yields_evol[k][elem_idx1]/np.sum(yields_evol[k])
x2=yields_evol[k][elem_idx2]/np.sum(yields_evol[k])
if x1 <= 0.0 or x2 <= 0.0:
spec = -30.0
else:
#print ('Fe_sim = ',x1, ' , H_sim = ',x2)
if len(solar_norm) > 0:
index_1 = el_norm.index(yaxis_elem1)
index_2 = el_norm.index(yaxis_elem2)
i_xx_sol_1 = sol_values_el.index(yaxis_elem1)
i_xx_sol_2 = sol_values_el.index(yaxis_elem2)
aaa = np.log10(yields_evol[k][elem_idx1]*mn_norm[index_2] /\
(yields_evol[k][elem_idx2]*mn_norm[index_1]))
bbb = sol_values_ab[i_xx_sol_1] - sol_values_ab[i_xx_sol_2]
spec= aaa - bbb
else:
spec=np.log10(x1/x2) - np.log10(x_elem1_ini/x_elem2_ini)
y.append(spec)
if xaxis=='age':
x.append(x_age[k])
if len(y)==0:
print ('Y values all zero')
#Operations associated with plot visual aspects
if not return_x_y and not sub_plot:
plt.ylabel(yaxis)
self.y=y
#To prevent 0 +log scale
if 'age' == xaxis:
x=x[1:]
y=y[1:]
#Operations associated with plot visual aspects
if not return_x_y and not sub_plot:
plt.xlim(self.history.dt,self.history.tend)
#Remove values when SFR is zero, that is when no element is locked into stars
i_rem = len(y) - 1
if m_formed_thresh < 1.0 or sfr_thresh > 0.0:
while self.history.sfr_abs[i_rem] <= sfr_thresh or \
self.f_m_stel_tot[i_rem] >= m_formed_thresh:
del y[-1]
del x[-1]
i_rem -= 1
else:
while self.history.sfr_abs[i_rem] == 0.0:
del y[-1]
del x[-1]
i_rem -= 1
if not plot_data:
# Filtrate bad value
x_temp = []
y_temp = []
for i_temp in range(0,len(x)):
if np.isfinite(x[i_temp]) and np.isfinite(y[i_temp])\
and x[i_temp] > -20.0 and y[i_temp] > -20.0:
x_temp.append(x[i_temp])
y_temp.append(y[i_temp])
x = x_temp
y = y_temp
#If this function is supposed to return the x, y arrays only ...
if return_x_y:
return x, y
#If this is a sub-figure managed by an external module
elif sub_plot:
if self.galaxy == 'none':
if show_legend:
sub.plot(x,y,linestyle=shape,label=label,marker=marker,color=color,markevery=markevery,linewidth=linewidth)
else:
sub.plot(x,y,linestyle=shape,marker=marker,color=color,markevery=markevery,linewidth=linewidth)
else:
if show_legend:
sub.plot(x,y,linestyle=shape,label=label,marker=marker,color=color,markevery=markevery,linewidth=linewidth)
else:
sub.plot(x,y,linestyle=shape,marker=marker,color=color,markevery=markevery,linewidth=linewidth)
#If this function is supposed to plot ...
else:
#Plot a thicker line for specific galaxies, since they must be visible with all the obs. data
if self.galaxy == 'none':
if show_legend:
plt.plot(x,y,linestyle=shape,label=label,marker=marker,color=color,markevery=markevery,linewidth=linewidth)
else:
plt.plot(x,y,linestyle=shape,marker=marker,color=color,markevery=markevery,linewidth=linewidth)
else:
if show_legend:
plt.plot(x,y,linestyle=shape,label=label,marker=marker,color=color,markevery=markevery,linewidth=linewidth)
else:
plt.plot(x,y,linestyle=shape,marker=marker,color=color,markevery=markevery,linewidth=linewidth)
#plt.plot([1.93,2.123123,3.23421321321],[4.123123132,5.214124142,6.11111],linestyle='--')
#plt.plot([1.93,2.123123,3.23421321321],[4.123123132,5.214124142,6.11111],linestyle='--')
if len(label)>0:
plt.legend()
ax=plt.gca()
self.__fig_standard(ax=ax,fontsize=fontsize,labelsize=labelsize,rspace=rspace, bspace=bspace,legend_fontsize=legend_fontsize)
#self.save_data(header=[xaxis,yaxis],data=[x,y])
def plot_totmasses(self,fig=4,mass='gas',source='all',norm='no',label='',shape='',marker='',color='',markevery=20,log=True,fsize=[10,4.5],fontsize=14,rspace=0.6,bspace=0.15,labelsize=15,legend_fontsize=14):
'''
Plots either gas or star mass in fraction of total mass
vs time.
Parameters
----------
mass : string
either 'gas' for ISM gas mass
or 'stars' for gas locked away in stars (totalgas - ISM gas)
norm : string
normalization, either 'no' for no normalization (total gass mass in solar masses),
for normalization to the initial gas mass (mgal) with 'ini',
for normalization to the current total gas mass 'current'.
The latter case makes sense when comparing different
sources (see below)
source : string
specificies if yields come from
all sources ('all'), including
AGB+SN1a, massive stars. Or from
distinctive sources:
only agb stars ('agb'), only
SN1a ('sn1a'), or only massive stars
('massive')
log : boolean
if true plot logarithmic y axis
label : string
figure label
marker : string
figure marker
shape : string
line style
color : string
color of line
fig : string,float
to name the plot figure
Examples
----------
>>> s.plot_totmasses()
'''
import matplotlib
import matplotlib.pyplot as plt
#if len(label)<1:
# label=mass+', '+source
plt.figure(fig, figsize=(fsize[0],fsize[1]))
#Assume isotope input
xaxis='age'
if source =='all':
if len(label)==0:
label='All'
if source == 'agb':
if len(label)==0:
label='AGB'
if source =='massive':
if len(label)==0:
label='Massive'
if source =='sn1a':
if len(label)==0:
label='SNIa'
shape,marker,color=self.__msc(source,shape,marker,color)
if 'age' == xaxis:
x_all=self.history.age#[1:]
plt.xscale('log')
plt.xlabel('log-scaled '+xaxis+' [yrs]')
#self.x=x
gas_mass=self.history.gas_mass
#to test the different contributions
if source == 'all':
gas_evol=self.history.gas_mass
else:
if source =='agb':
yields_evol=self.history.ism_elem_yield_agb
elif source == 'sn1a':
yields_evol=self.history.ism_elem_yield_1a
elif source == 'massive':
yields_evol=self.history.ism_elem_yield_massive
gas_evol=[]
for k in range(len(yields_evol)):
gas_evol.append(np.sum(yields_evol[k]))
ism_gasm=[]
star_m=[]
x=[]
#To prevent 0 +log scale
if 'age' == xaxis:
x_all=x_all[1:]
gas_evol=gas_evol[1:]
gas_mass=gas_mass[1:]
for k in range(0,len(gas_evol)):
if (gas_evol[k]==0) or (gas_mass[k]==0):
continue
x.append(x_all[k])
if norm=='ini':
ism_gasm.append(gas_evol[k]/self.history.mgal)
star_m.append((self.history.mgal-gas_evol[k])/self.history.mgal)
if norm == 'current':
if not self.history.gas_mass[k] ==0.:
ism_gasm.append(gas_evol[k]/gas_mass[k])
star_m.append((self.history.mgal-gas_evol[k])/gas_mass[k])
#else:
# ism_gasm.append(0.)
# star_m.append(0.)
elif norm == 'no':
ism_gasm.append(gas_evol[k])
star_m.append(self.history.mgal-gas_evol[k])
if mass == 'gas':
y=ism_gasm
if mass == 'stars':
y=star_m
plt.plot(x,y,linestyle=shape,marker=marker,markevery=markevery,color=color,label=label)
if len(label)>0:
plt.legend()
if norm=='current':
plt.ylim(0,1.2)
if not norm=='no':
if mass=='gas':
plt.ylabel('mass fraction')
plt.title('Gas mass as a fraction of total gas mass')
else:
plt.ylabel('mass fraction')
plt.title('Star mass as a fraction of total star mass')
else:
if mass=='gas':
plt.ylabel('ISM gas mass [Msun]')
else:
plt.ylabel('mass locked in stars [Msun]')
if mass=='gas':
plt.ylabel('ISM gas mass [Msun]')
else:
plt.ylabel('Mass locked in stars [Msun]')
if log==True:
plt.yscale('log')
if not norm=='no':
plt.ylim(1e-4,1.2)
ax=plt.gca()
self.__fig_standard(ax=ax,fontsize=fontsize,labelsize=labelsize,rspace=rspace, bspace=bspace,legend_fontsize=legend_fontsize)
plt.xlim(self.history.dt,self.history.tend)
#self.save_data(header=['age','mass'],data=[x,y])
def plot_sn_distr(self,fig=5,rate=True,rate_only='',xaxis='time',fraction=False,label1='SNIa',label2='SN2',shape1=':',shape2='--',marker1='o',marker2='s',color1='k',color2='b',markevery=20,fsize=[10,4.5],fontsize=14,rspace=0.6,bspace=0.15,labelsize=15,legend_fontsize=14):
'''
Plots the SN1a distribution:
The evolution of the number of SN1a and SN2
#Add numbers/dt numbers/year...
Parameters
----------
rate : boolean
if true, calculate rate [1/century]
else calculate numbers
fraction ; boolean
if true, ignorate rate and calculate number fraction of SNIa per WD
rate_only : string
if empty string, plot both rates (default)
if 'sn1a', plot only SN1a rate
if 'sn2', plot only SN2 rate
xaxis: string
if 'time' : time evolution
if 'redshift': experimental! use with caution; redshift evolution
label : string
figure label
marker : string
figure marker
shape : string
line style
color : string
color of line
fig : string,float
to name the plot figure
Examples
----------
>>> s.plot_sn_distr()
'''
import matplotlib
import matplotlib.pyplot as plt
#For Wiersma09
Hubble_0=73.
Omega_lambda=0.762
Omega_m=0.238
figure=plt.figure(fig, figsize=(fsize[0],fsize[1]))
age=self.history.age
sn1anumbers=self.history.sn1a_numbers#[:-1]
sn2numbers=self.history.sn2_numbers
if xaxis=='redshift':
print ('this features is not tested yet.')
return 0
age,idx=self.__time_to_z(age,Hubble_0,Omega_lambda,Omega_m)
age=[0]+age
plt.xlabel('Redshift z')
timesteps=self.history.timesteps[idx-1:]
sn2numbers=sn2numbers[idx:]
sn1anumbers=sn1anumbers[idx:]
else:
plt.xlabel('Log-scaled age [yrs]')
#plt.xscale('log')
if rate and not fraction:
if xaxis=='redshift':
sn1a_rate=np.array(sn1anumbers)/ (np.array(timesteps)/100.)
sn2_rate=np.array(sn2numbers)/ (np.array(timesteps)/100.)
else:
sn1a_rate=np.array(sn1anumbers[1:])/ (np.array(self.history.timesteps)/100.)
sn2_rate= | np.array(sn2numbers[1:]) | numpy.array |
'''
Module with a class to create a generator for low-frequency images.
'''
# System imports
import time
# Standard imports
import numpy as np
import matplotlib.pyplot as plt
import itertools
class LowFreqGenerator(object):
'''
A class to create a generator of low-frequency images.
'''
def __init__(self, batch_size=128, N=4, im_size=64, discounting=1, constant_components=False):
'''
Constructor
'''
self.N = N
self.im_size = im_size
self.batch_size = batch_size
# array with discretized Fourier eigenfunctions
self._base = np.zeros(shape=(im_size, im_size, 2 * N + 1, 2 * N + 1), dtype=np.complex64)
# Create Fourier coefficients
if constant_components:
self._fourier_components = get_constant_fourier_components(N)
else:
self._fourier_components = get_normal_fourier_components(N, discounting)
# array with discretized Fourier eigenfunctions premultiplied with Fourier coefficients
self._base_multiplied = | np.zeros(shape=(im_size, im_size, 2 * N + 1, 2 * N + 1), dtype=np.complex64) | numpy.zeros |
import os
import tempfile
import numpy as np
import scipy.ndimage.measurements as meas
from functools import reduce
import warnings
import sys
sys.path.append(os.path.abspath(r'../lib'))
import NumCppPy as NumCpp # noqa E402
####################################################################################
def factors(n):
return set(reduce(list.__add__,
([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0)))
####################################################################################
def test_seed():
np.random.seed(1)
####################################################################################
def test_abs():
randValue = np.random.randint(-100, -1, [1, ]).astype(np.double).item()
assert NumCpp.absScaler(randValue) == np.abs(randValue)
components = np.random.randint(-100, -1, [2, ]).astype(np.double)
value = complex(components[0], components[1])
assert np.round(NumCpp.absScaler(value), 9) == np.round(np.abs(value), 9)
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArray(shape)
data = np.random.randint(-100, 100, [shape.rows, shape.cols])
cArray.setArray(data)
assert np.array_equal(NumCpp.absArray(cArray), np.abs(data))
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArrayComplexDouble(shape)
data = np.random.randint(-100, 100, [shape.rows, shape.cols]) + \
1j * np.random.randint(-100, 100, [shape.rows, shape.cols])
cArray.setArray(data)
assert np.array_equal(np.round(NumCpp.absArray(cArray), 9), np.round(np.abs(data), 9))
####################################################################################
def test_add():
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray1 = NumCpp.NdArray(shape)
cArray2 = NumCpp.NdArray(shape)
data1 = np.random.randint(-100, 100, [shape.rows, shape.cols])
data2 = np.random.randint(-100, 100, [shape.rows, shape.cols])
cArray1.setArray(data1)
cArray2.setArray(data2)
assert np.array_equal(NumCpp.add(cArray1, cArray2), data1 + data2)
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArray(shape)
data = np.random.randint(-100, 100, [shape.rows, shape.cols])
cArray.setArray(data)
value = np.random.randint(-100, 100)
assert np.array_equal(NumCpp.add(cArray, value), data + value)
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArray(shape)
data = np.random.randint(-100, 100, [shape.rows, shape.cols])
cArray.setArray(data)
value = np.random.randint(-100, 100)
assert np.array_equal(NumCpp.add(value, cArray), data + value)
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray1 = NumCpp.NdArrayComplexDouble(shape)
cArray2 = NumCpp.NdArrayComplexDouble(shape)
real1 = np.random.randint(1, 100, [shape.rows, shape.cols])
imag1 = np.random.randint(1, 100, [shape.rows, shape.cols])
data1 = real1 + 1j * imag1
real2 = np.random.randint(1, 100, [shape.rows, shape.cols])
imag2 = np.random.randint(1, 100, [shape.rows, shape.cols])
data2 = real2 + 1j * imag2
cArray1.setArray(data1)
cArray2.setArray(data2)
assert np.array_equal(NumCpp.add(cArray1, cArray2), data1 + data2)
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArrayComplexDouble(shape)
real = np.random.randint(1, 100, [shape.rows, shape.cols])
imag = np.random.randint(1, 100, [shape.rows, shape.cols])
data = real + 1j * imag
cArray.setArray(data)
value = np.random.randint(-100, 100) + 1j * np.random.randint(-100, 100)
assert np.array_equal(NumCpp.add(cArray, value), data + value)
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArrayComplexDouble(shape)
real = np.random.randint(1, 100, [shape.rows, shape.cols])
imag = np.random.randint(1, 100, [shape.rows, shape.cols])
data = real + 1j * imag
cArray.setArray(data)
value = np.random.randint(-100, 100) + 1j * np.random.randint(-100, 100)
assert np.array_equal(NumCpp.add(value, cArray), data + value)
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray1 = NumCpp.NdArrayComplexDouble(shape)
cArray2 = NumCpp.NdArray(shape)
real1 = np.random.randint(1, 100, [shape.rows, shape.cols])
imag1 = np.random.randint(1, 100, [shape.rows, shape.cols])
data1 = real1 + 1j * imag1
data2 = np.random.randint(1, 100, [shape.rows, shape.cols])
cArray1.setArray(data1)
cArray2.setArray(data2)
assert np.array_equal(NumCpp.add(cArray1, cArray2), data1 + data2)
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray1 = NumCpp.NdArray(shape)
cArray2 = NumCpp.NdArrayComplexDouble(shape)
data1 = np.random.randint(1, 100, [shape.rows, shape.cols])
real2 = np.random.randint(1, 100, [shape.rows, shape.cols])
imag2 = np.random.randint(1, 100, [shape.rows, shape.cols])
data2 = real2 + 1j * imag2
cArray1.setArray(data1)
cArray2.setArray(data2)
assert np.array_equal(NumCpp.add(cArray1, cArray2), data1 + data2)
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArray(shape)
data = np.random.randint(-100, 100, [shape.rows, shape.cols])
cArray.setArray(data)
value = np.random.randint(-100, 100) + 1j * np.random.randint(-100, 100)
assert np.array_equal(NumCpp.add(cArray, value), data + value)
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArray(shape)
data = np.random.randint(-100, 100, [shape.rows, shape.cols])
cArray.setArray(data)
value = np.random.randint(-100, 100) + 1j * np.random.randint(-100, 100)
assert np.array_equal(NumCpp.add(value, cArray), data + value)
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArrayComplexDouble(shape)
real = np.random.randint(1, 100, [shape.rows, shape.cols])
imag = np.random.randint(1, 100, [shape.rows, shape.cols])
data = real + 1j * imag
cArray.setArray(data)
value = np.random.randint(-100, 100)
assert np.array_equal(NumCpp.add(cArray, value), data + value)
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArrayComplexDouble(shape)
real = np.random.randint(1, 100, [shape.rows, shape.cols])
imag = np.random.randint(1, 100, [shape.rows, shape.cols])
data = real + 1j * imag
cArray.setArray(data)
value = np.random.randint(-100, 100)
assert np.array_equal(NumCpp.add(value, cArray), data + value)
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray1 = NumCpp.NdArrayComplexDouble(shape)
cArray2 = NumCpp.NdArrayComplexDouble(shape)
real1 = np.random.randint(1, 100, [shape.rows, shape.cols])
imag1 = np.random.randint(1, 100, [shape.rows, shape.cols])
data1 = real1 + 1j * imag1
real2 = np.random.randint(1, 100, [shape.rows, shape.cols])
imag2 = np.random.randint(1, 100, [shape.rows, shape.cols])
data2 = real2 + 1j * imag2
cArray1.setArray(data1)
cArray2.setArray(data2)
assert np.array_equal(NumCpp.add(cArray1, cArray2), data1 + data2)
####################################################################################
def test_alen():
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArray(shape)
data = np.random.randint(-100, 100, [shape.rows, shape.cols])
cArray.setArray(data)
assert NumCpp.alen(cArray) == shape.rows
####################################################################################
def test_all():
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArray(shape)
data = np.random.randint(0, 100, [shape.rows, shape.cols])
cArray.setArray(data)
assert NumCpp.all(cArray, NumCpp.Axis.NONE).astype(bool).item() == np.all(data).item()
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArrayComplexDouble(shape)
real = np.random.randint(1, 100, [shape.rows, shape.cols])
imag = np.random.randint(1, 100, [shape.rows, shape.cols])
data = real + 1j * imag
cArray.setArray(data)
assert NumCpp.all(cArray, NumCpp.Axis.NONE).astype(bool).item() == np.all(data).item()
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArray(shape)
data = np.random.randint(0, 100, [shape.rows, shape.cols])
cArray.setArray(data)
assert np.array_equal(NumCpp.all(cArray, NumCpp.Axis.ROW).flatten().astype(bool), np.all(data, axis=0))
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArrayComplexDouble(shape)
real = np.random.randint(1, 100, [shape.rows, shape.cols])
imag = np.random.randint(1, 100, [shape.rows, shape.cols])
data = real + 1j * imag
cArray.setArray(data)
assert np.array_equal(NumCpp.all(cArray, NumCpp.Axis.ROW).flatten().astype(bool), np.all(data, axis=0))
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArray(shape)
data = np.random.randint(0, 100, [shape.rows, shape.cols])
cArray.setArray(data)
assert np.array_equal(NumCpp.all(cArray, NumCpp.Axis.COL).flatten().astype(bool), np.all(data, axis=1))
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArrayComplexDouble(shape)
real = np.random.randint(1, 100, [shape.rows, shape.cols])
imag = np.random.randint(1, 100, [shape.rows, shape.cols])
data = real + 1j * imag
cArray.setArray(data)
assert np.array_equal(NumCpp.all(cArray, NumCpp.Axis.COL).flatten().astype(bool), np.all(data, axis=1))
####################################################################################
def test_allclose():
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray1 = NumCpp.NdArray(shape)
cArray2 = NumCpp.NdArray(shape)
cArray3 = NumCpp.NdArray(shape)
tolerance = 1e-5
data1 = np.random.randn(shape.rows, shape.cols)
data2 = data1 + tolerance / 10
data3 = data1 + 1
cArray1.setArray(data1)
cArray2.setArray(data2)
cArray3.setArray(data3)
assert NumCpp.allclose(cArray1, cArray2, tolerance) and not NumCpp.allclose(cArray1, cArray3, tolerance)
####################################################################################
def test_amax():
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArray(shape)
data = np.random.randint(0, 100, [shape.rows, shape.cols])
cArray.setArray(data)
assert NumCpp.amax(cArray, NumCpp.Axis.NONE).item() == np.max(data)
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArrayComplexDouble(shape)
real = np.random.randint(1, 100, [shape.rows, shape.cols])
imag = np.random.randint(1, 100, [shape.rows, shape.cols])
data = real + 1j * imag
cArray.setArray(data)
assert NumCpp.amax(cArray, NumCpp.Axis.NONE).item() == np.max(data)
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArray(shape)
data = np.random.randint(0, 100, [shape.rows, shape.cols])
cArray.setArray(data)
assert np.array_equal(NumCpp.amax(cArray, NumCpp.Axis.ROW).flatten(), np.max(data, axis=0))
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArrayComplexDouble(shape)
real = np.random.randint(1, 100, [shape.rows, shape.cols])
imag = np.random.randint(1, 100, [shape.rows, shape.cols])
data = real + 1j * imag
cArray.setArray(data)
assert np.array_equal(NumCpp.amax(cArray, NumCpp.Axis.ROW).flatten(), np.max(data, axis=0))
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArray(shape)
data = np.random.randint(0, 100, [shape.rows, shape.cols])
cArray.setArray(data)
assert np.array_equal(NumCpp.amax(cArray, NumCpp.Axis.COL).flatten(), np.max(data, axis=1))
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArrayComplexDouble(shape)
real = np.random.randint(1, 100, [shape.rows, shape.cols])
imag = np.random.randint(1, 100, [shape.rows, shape.cols])
data = real + 1j * imag
cArray.setArray(data)
assert np.array_equal(NumCpp.amax(cArray, NumCpp.Axis.COL).flatten(), np.max(data, axis=1))
####################################################################################
def test_amin():
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArray(shape)
data = np.random.randint(0, 100, [shape.rows, shape.cols])
cArray.setArray(data)
assert NumCpp.amin(cArray, NumCpp.Axis.NONE).item() == np.min(data)
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArrayComplexDouble(shape)
real = np.random.randint(1, 100, [shape.rows, shape.cols])
imag = np.random.randint(1, 100, [shape.rows, shape.cols])
data = real + 1j * imag
cArray.setArray(data)
assert NumCpp.amin(cArray, NumCpp.Axis.NONE).item() == np.min(data)
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArray(shape)
data = np.random.randint(0, 100, [shape.rows, shape.cols])
cArray.setArray(data)
assert np.array_equal(NumCpp.amin(cArray, NumCpp.Axis.ROW).flatten(), np.min(data, axis=0))
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArrayComplexDouble(shape)
real = np.random.randint(1, 100, [shape.rows, shape.cols])
imag = np.random.randint(1, 100, [shape.rows, shape.cols])
data = real + 1j * imag
cArray.setArray(data)
assert np.array_equal(NumCpp.amin(cArray, NumCpp.Axis.ROW).flatten(), np.min(data, axis=0))
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArray(shape)
data = np.random.randint(0, 100, [shape.rows, shape.cols])
cArray.setArray(data)
assert np.array_equal(NumCpp.amin(cArray, NumCpp.Axis.COL).flatten(), np.min(data, axis=1))
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArrayComplexDouble(shape)
real = np.random.randint(1, 100, [shape.rows, shape.cols])
imag = np.random.randint(1, 100, [shape.rows, shape.cols])
data = real + 1j * imag
cArray.setArray(data)
assert np.array_equal(NumCpp.amin(cArray, NumCpp.Axis.COL).flatten(), np.min(data, axis=1))
####################################################################################
def test_angle():
components = np.random.randint(-100, -1, [2, ]).astype(np.double)
value = complex(components[0], components[1])
assert np.round(NumCpp.angleScaler(value), 9) == np.round(np.angle(value), 9) # noqa
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArrayComplexDouble(shape)
data = np.random.randint(-100, 100, [shape.rows, shape.cols]) + \
1j * np.random.randint(-100, 100, [shape.rows, shape.cols])
cArray.setArray(data)
assert np.array_equal(np.round(NumCpp.angleArray(cArray), 9), np.round(np.angle(data), 9))
####################################################################################
def test_any():
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArray(shape)
data = np.random.randint(0, 100, [shape.rows, shape.cols])
cArray.setArray(data)
assert NumCpp.any(cArray, NumCpp.Axis.NONE).astype(bool).item() == np.any(data).item()
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArrayComplexDouble(shape)
real = np.random.randint(1, 100, [shape.rows, shape.cols])
imag = np.random.randint(1, 100, [shape.rows, shape.cols])
data = real + 1j * imag
cArray.setArray(data)
assert NumCpp.any(cArray, NumCpp.Axis.NONE).astype(bool).item() == np.any(data).item()
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArray(shape)
data = np.random.randint(0, 100, [shape.rows, shape.cols])
cArray.setArray(data)
assert np.array_equal(NumCpp.any(cArray, NumCpp.Axis.ROW).flatten().astype(bool), np.any(data, axis=0))
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArrayComplexDouble(shape)
real = np.random.randint(1, 100, [shape.rows, shape.cols])
imag = np.random.randint(1, 100, [shape.rows, shape.cols])
data = real + 1j * imag
cArray.setArray(data)
assert np.array_equal(NumCpp.any(cArray, NumCpp.Axis.ROW).flatten().astype(bool), np.any(data, axis=0))
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArray(shape)
data = np.random.randint(0, 100, [shape.rows, shape.cols])
cArray.setArray(data)
assert np.array_equal(NumCpp.any(cArray, NumCpp.Axis.COL).flatten().astype(bool), np.any(data, axis=1))
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArrayComplexDouble(shape)
real = np.random.randint(1, 100, [shape.rows, shape.cols])
imag = np.random.randint(1, 100, [shape.rows, shape.cols])
data = real + 1j * imag
cArray.setArray(data)
assert np.array_equal(NumCpp.any(cArray, NumCpp.Axis.COL).flatten().astype(bool), np.any(data, axis=1))
####################################################################################
def test_append():
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray1 = NumCpp.NdArray(shape)
cArray2 = NumCpp.NdArray(shape)
data1 = np.random.randint(0, 100, [shape.rows, shape.cols])
data2 = np.random.randint(0, 100, [shape.rows, shape.cols])
cArray1.setArray(data1)
cArray2.setArray(data2)
assert np.array_equal(NumCpp.append(cArray1, cArray2, NumCpp.Axis.NONE).getNumpyArray().flatten(),
np.append(data1, data2))
shapeInput = np.random.randint(20, 100, [2, ])
numRows = np.random.randint(1, 100, [1, ]).item()
shape1 = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
shape2 = NumCpp.Shape(shapeInput[0].item() + numRows, shapeInput[1].item())
cArray1 = NumCpp.NdArray(shape1)
cArray2 = NumCpp.NdArray(shape2)
data1 = np.random.randint(0, 100, [shape1.rows, shape1.cols])
data2 = np.random.randint(0, 100, [shape2.rows, shape2.cols])
cArray1.setArray(data1)
cArray2.setArray(data2)
assert np.array_equal(NumCpp.append(cArray1, cArray2, NumCpp.Axis.ROW).getNumpyArray(),
np.append(data1, data2, axis=0))
shapeInput = np.random.randint(20, 100, [2, ])
NumCppols = np.random.randint(1, 100, [1, ]).item()
shape1 = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
shape2 = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item() + NumCppols)
cArray1 = NumCpp.NdArray(shape1)
cArray2 = NumCpp.NdArray(shape2)
data1 = np.random.randint(0, 100, [shape1.rows, shape1.cols])
data2 = np.random.randint(0, 100, [shape2.rows, shape2.cols])
cArray1.setArray(data1)
cArray2.setArray(data2)
assert np.array_equal(NumCpp.append(cArray1, cArray2, NumCpp.Axis.COL).getNumpyArray(),
np.append(data1, data2, axis=1))
####################################################################################
def test_arange():
start = np.random.randn(1).item()
stop = np.random.randn(1).item() * 100
step = np.abs(np.random.randn(1).item())
if stop < start:
step *= -1
data = np.arange(start, stop, step)
assert np.array_equal(np.round(NumCpp.arange(start, stop, step).flatten(), 9), np.round(data, 9))
####################################################################################
def test_arccos():
value = np.abs(np.random.rand(1).item())
assert np.round(NumCpp.arccosScaler(value), 9) == np.round(np.arccos(value), 9)
components = np.random.rand(2).astype(np.double)
value = complex(components[0], components[1])
assert np.round(NumCpp.arccosScaler(value), 9) == np.round(np.arccos(value), 9)
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArray(shape)
data = np.random.rand(shape.rows, shape.cols)
cArray.setArray(data)
assert np.array_equal(np.round(NumCpp.arccosArray(cArray), 9), np.round(np.arccos(data), 9))
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArrayComplexDouble(shape)
data = np.random.rand(shape.rows, shape.cols) + 1j * np.random.rand(shape.rows, shape.cols)
cArray.setArray(data)
assert np.array_equal(np.round(NumCpp.arccosArray(cArray), 9), np.round(np.arccos(data), 9))
####################################################################################
def test_arccosh():
value = np.abs(np.random.rand(1).item()) + 1
assert np.round(NumCpp.arccoshScaler(value), 9) == np.round(np.arccosh(value), 9)
components = np.random.rand(2).astype(np.double)
value = complex(components[0], components[1])
assert np.round(NumCpp.arccoshScaler(value), 9) == np.round(np.arccosh(value), 9)
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArray(shape)
data = np.random.rand(shape.rows, shape.cols) + 1
cArray.setArray(data)
assert np.array_equal(np.round(NumCpp.arccoshArray(cArray), 9), np.round(np.arccosh(data), 9))
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArrayComplexDouble(shape)
data = np.random.rand(shape.rows, shape.cols) + 1j * np.random.rand(shape.rows, shape.cols)
cArray.setArray(data)
assert np.array_equal(np.round(NumCpp.arccoshArray(cArray), 9), np.round(np.arccosh(data), 9))
####################################################################################
def test_arcsin():
value = np.abs(np.random.rand(1).item())
assert np.round(NumCpp.arcsinScaler(value), 9) == np.round(np.arcsin(value), 9)
components = np.random.rand(2).astype(np.double)
value = complex(components[0], components[1])
assert np.round(NumCpp.arcsinScaler(value), 9) == np.round(np.arcsin(value), 9)
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArray(shape)
data = np.random.rand(shape.rows, shape.cols)
cArray.setArray(data)
assert np.array_equal(np.round(NumCpp.arcsinArray(cArray), 9), np.round(np.arcsin(data), 9))
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArrayComplexDouble(shape)
data = np.random.rand(shape.rows, shape.cols) + 1j * np.random.rand(shape.rows, shape.cols)
cArray.setArray(data)
np.array_equal(np.round(NumCpp.arcsinArray(cArray), 9), np.round(np.arcsin(data), 9))
####################################################################################
def test_arcsinh():
value = np.abs(np.random.rand(1).item())
assert np.round(NumCpp.arcsinhScaler(value), 9) == np.round(np.arcsinh(value), 9)
components = np.random.rand(2).astype(np.double)
value = complex(components[0], components[1])
assert np.round(NumCpp.arcsinhScaler(value), 9) == np.round(np.arcsinh(value), 9)
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArray(shape)
data = np.random.rand(shape.rows, shape.cols)
cArray.setArray(data)
assert np.array_equal(np.round(NumCpp.arcsinhArray(cArray), 9), np.round(np.arcsinh(data), 9))
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArrayComplexDouble(shape)
data = np.random.rand(shape.rows, shape.cols) + 1j * np.random.rand(shape.rows, shape.cols)
cArray.setArray(data)
np.array_equal(np.round(NumCpp.arcsinhArray(cArray), 9), np.round(np.arcsinh(data), 9))
####################################################################################
def test_arctan():
value = np.abs(np.random.rand(1).item())
assert np.round(NumCpp.arctanScaler(value), 9) == np.round(np.arctan(value), 9)
components = np.random.rand(2).astype(np.double)
value = complex(components[0], components[1])
assert np.round(NumCpp.arctanScaler(value), 9) == np.round(np.arctan(value), 9)
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArray(shape)
data = np.random.rand(shape.rows, shape.cols)
cArray.setArray(data)
assert np.array_equal(np.round(NumCpp.arctanArray(cArray), 9), np.round(np.arctan(data), 9))
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArrayComplexDouble(shape)
data = np.random.rand(shape.rows, shape.cols) + 1j * np.random.rand(shape.rows, shape.cols)
cArray.setArray(data)
np.array_equal(np.round(NumCpp.arctanArray(cArray), 9), np.round(np.arctan(data), 9))
####################################################################################
def test_arctan2():
xy = np.random.rand(2) * 2 - 1
assert np.round(NumCpp.arctan2Scaler(xy[1], xy[0]), 9) == np.round(np.arctan2(xy[1], xy[0]), 9)
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArrayX = NumCpp.NdArray(shape)
cArrayY = NumCpp.NdArray(shape)
xy = np.random.rand(*shapeInput, 2) * 2 - 1
xData = xy[:, :, 0].reshape(shapeInput)
yData = xy[:, :, 1].reshape(shapeInput)
cArrayX.setArray(xData)
cArrayY.setArray(yData)
assert np.array_equal(np.round(NumCpp.arctan2Array(cArrayY, cArrayX), 9), np.round(np.arctan2(yData, xData), 9))
####################################################################################
def test_arctanh():
value = np.abs(np.random.rand(1).item())
assert np.round(NumCpp.arctanhScaler(value), 9) == np.round(np.arctanh(value), 9)
components = np.random.rand(2).astype(np.double)
value = complex(components[0], components[1])
assert np.round(NumCpp.arctanhScaler(value), 9) == np.round(np.arctanh(value), 9)
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArray(shape)
data = np.random.rand(shape.rows, shape.cols)
cArray.setArray(data)
assert np.array_equal(np.round(NumCpp.arctanhArray(cArray), 9), np.round(np.arctanh(data), 9))
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArrayComplexDouble(shape)
data = np.random.rand(shape.rows, shape.cols) + 1j * np.random.rand(shape.rows, shape.cols)
cArray.setArray(data)
np.array_equal(np.round(NumCpp.arctanhArray(cArray), 9), np.round(np.arctanh(data), 9))
####################################################################################
def test_argmax():
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArray(shape)
data = np.random.randint(0, 100, [shape.rows, shape.cols])
cArray.setArray(data)
assert np.array_equal(NumCpp.argmax(cArray, NumCpp.Axis.NONE).item(), np.argmax(data))
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArrayComplexDouble(shape)
real = np.random.randint(1, 100, [shape.rows, shape.cols])
imag = np.random.randint(1, 100, [shape.rows, shape.cols])
data = real + 1j * imag
cArray.setArray(data)
assert np.array_equal(NumCpp.argmax(cArray, NumCpp.Axis.NONE).item(), np.argmax(data))
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArray(shape)
data = np.random.randint(0, 100, [shape.rows, shape.cols])
cArray.setArray(data)
assert np.array_equal(NumCpp.argmax(cArray, NumCpp.Axis.ROW).flatten(), np.argmax(data, axis=0))
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArrayComplexDouble(shape)
real = np.random.randint(1, 100, [shape.rows, shape.cols])
imag = np.random.randint(1, 100, [shape.rows, shape.cols])
data = real + 1j * imag
cArray.setArray(data)
assert np.array_equal(NumCpp.argmax(cArray, NumCpp.Axis.ROW).flatten(), np.argmax(data, axis=0))
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArray(shape)
data = np.random.randint(0, 100, [shape.rows, shape.cols])
cArray.setArray(data)
assert np.array_equal(NumCpp.argmax(cArray, NumCpp.Axis.COL).flatten(), np.argmax(data, axis=1))
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArrayComplexDouble(shape)
real = np.random.randint(1, 100, [shape.rows, shape.cols])
imag = np.random.randint(1, 100, [shape.rows, shape.cols])
data = real + 1j * imag
cArray.setArray(data)
assert np.array_equal(NumCpp.argmax(cArray, NumCpp.Axis.COL).flatten(), np.argmax(data, axis=1))
####################################################################################
def test_argmin():
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArray(shape)
data = np.random.randint(0, 100, [shape.rows, shape.cols])
cArray.setArray(data)
assert np.array_equal(NumCpp.argmin(cArray, NumCpp.Axis.NONE).item(), np.argmin(data))
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArrayComplexDouble(shape)
real = np.random.randint(1, 100, [shape.rows, shape.cols])
imag = np.random.randint(1, 100, [shape.rows, shape.cols])
data = real + 1j * imag
cArray.setArray(data)
assert np.array_equal(NumCpp.argmin(cArray, NumCpp.Axis.NONE).item(), np.argmin(data))
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArray(shape)
data = np.random.randint(0, 100, [shape.rows, shape.cols])
cArray.setArray(data)
assert np.array_equal(NumCpp.argmin(cArray, NumCpp.Axis.ROW).flatten(), np.argmin(data, axis=0))
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArrayComplexDouble(shape)
real = np.random.randint(1, 100, [shape.rows, shape.cols])
imag = np.random.randint(1, 100, [shape.rows, shape.cols])
data = real + 1j * imag
cArray.setArray(data)
assert np.array_equal(NumCpp.argmin(cArray, NumCpp.Axis.ROW).flatten(), np.argmin(data, axis=0))
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArray(shape)
data = np.random.randint(0, 100, [shape.rows, shape.cols])
cArray.setArray(data)
assert np.array_equal(NumCpp.argmin(cArray, NumCpp.Axis.COL).flatten(), np.argmin(data, axis=1))
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArrayComplexDouble(shape)
real = np.random.randint(1, 100, [shape.rows, shape.cols])
imag = np.random.randint(1, 100, [shape.rows, shape.cols])
data = real + 1j * imag
cArray.setArray(data)
assert np.array_equal(NumCpp.argmin(cArray, NumCpp.Axis.COL).flatten(), np.argmin(data, axis=1))
####################################################################################
def test_argsort():
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArray(shape)
data = np.random.randint(0, 100, [shape.rows, shape.cols])
cArray.setArray(data)
dataFlat = data.flatten()
assert np.array_equal(dataFlat[NumCpp.argsort(cArray, NumCpp.Axis.NONE).flatten().astype(np.uint32)],
dataFlat[np.argsort(data, axis=None)])
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArrayComplexDouble(shape)
real = np.random.randint(1, 100, [shape.rows, shape.cols])
imag = np.random.randint(1, 100, [shape.rows, shape.cols])
data = real + 1j * imag
cArray.setArray(data)
dataFlat = data.flatten()
assert np.array_equal(dataFlat[NumCpp.argsort(cArray, NumCpp.Axis.NONE).flatten().astype(np.uint32)],
dataFlat[np.argsort(data, axis=None)])
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArray(shape)
data = np.random.randint(0, 100, [shape.rows, shape.cols])
cArray.setArray(data)
pIdx = np.argsort(data, axis=0)
cIdx = NumCpp.argsort(cArray, NumCpp.Axis.ROW).astype(np.uint16)
allPass = True
for idx, row in enumerate(data.T):
if not np.array_equal(row[cIdx[:, idx]], row[pIdx[:, idx]]):
allPass = False
break
assert allPass
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArrayComplexDouble(shape)
real = np.random.randint(1, 100, [shape.rows, shape.cols])
imag = np.random.randint(1, 100, [shape.rows, shape.cols])
data = real + 1j * imag
cArray.setArray(data)
pIdx = np.argsort(data, axis=0)
cIdx = NumCpp.argsort(cArray, NumCpp.Axis.ROW).astype(np.uint16)
allPass = True
for idx, row in enumerate(data.T):
if not np.array_equal(row[cIdx[:, idx]], row[pIdx[:, idx]]):
allPass = False
break
assert allPass
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArray(shape)
data = np.random.randint(0, 100, [shape.rows, shape.cols])
cArray.setArray(data)
pIdx = np.argsort(data, axis=1)
cIdx = NumCpp.argsort(cArray, NumCpp.Axis.COL).astype(np.uint16)
allPass = True
for idx, row in enumerate(data):
if not np.array_equal(row[cIdx[idx, :]], row[pIdx[idx, :]]): # noqa
allPass = False
break
assert allPass
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArrayComplexDouble(shape)
real = np.random.randint(1, 100, [shape.rows, shape.cols])
imag = np.random.randint(1, 100, [shape.rows, shape.cols])
data = real + 1j * imag
cArray.setArray(data)
pIdx = np.argsort(data, axis=1)
cIdx = NumCpp.argsort(cArray, NumCpp.Axis.COL).astype(np.uint16)
allPass = True
for idx, row in enumerate(data):
if not np.array_equal(row[cIdx[idx, :]], row[pIdx[idx, :]]):
allPass = False
break
assert allPass
####################################################################################
def test_argwhere():
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArray(shape)
data = np.random.randint(0, 100, [shape.rows, shape.cols])
randValue = np.random.randint(0, 100, [1, ]).item()
data2 = data > randValue
cArray.setArray(data2)
assert np.array_equal(NumCpp.argwhere(cArray).flatten(), np.argwhere(data.flatten() > randValue).flatten())
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArrayComplexDouble(shape)
real = np.random.randint(1, 100, [shape.rows, shape.cols])
imag = np.random.randint(1, 100, [shape.rows, shape.cols])
data = real + 1j * imag
randValue = np.random.randint(0, 100, [1, ]).item()
data2 = data > randValue
cArray.setArray(data2)
assert np.array_equal(NumCpp.argwhere(cArray).flatten(), np.argwhere(data.flatten() > randValue).flatten())
####################################################################################
def test_around():
value = np.abs(np.random.rand(1).item()) * np.random.randint(1, 10, [1, ]).item()
numDecimalsRound = np.random.randint(0, 10, [1, ]).astype(np.uint8).item()
assert NumCpp.aroundScaler(value, numDecimalsRound) == np.round(value, numDecimalsRound)
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArray(shape)
data = np.random.rand(shape.rows, shape.cols) * np.random.randint(1, 10, [1, ]).item()
cArray.setArray(data)
numDecimalsRound = np.random.randint(0, 10, [1, ]).astype(np.uint8).item()
assert np.array_equal(NumCpp.aroundArray(cArray, numDecimalsRound), np.round(data, numDecimalsRound))
####################################################################################
def test_array_equal():
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray1 = NumCpp.NdArray(shape)
cArray2 = NumCpp.NdArray(shape)
cArray3 = NumCpp.NdArray(shape)
data1 = np.random.randint(1, 100, shapeInput)
data2 = np.random.randint(1, 100, shapeInput)
cArray1.setArray(data1)
cArray2.setArray(data1)
cArray3.setArray(data2)
assert NumCpp.array_equal(cArray1, cArray2) and not NumCpp.array_equal(cArray1, cArray3)
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray1 = NumCpp.NdArrayComplexDouble(shape)
cArray2 = NumCpp.NdArrayComplexDouble(shape)
cArray3 = NumCpp.NdArrayComplexDouble(shape)
real1 = np.random.randint(1, 100, [shape.rows, shape.cols])
imag1 = np.random.randint(1, 100, [shape.rows, shape.cols])
data1 = real1 + 1j * imag1
real2 = np.random.randint(1, 100, [shape.rows, shape.cols])
imag2 = np.random.randint(1, 100, [shape.rows, shape.cols])
data2 = real2 + 1j * imag2
cArray1.setArray(data1)
cArray2.setArray(data1)
cArray3.setArray(data2)
assert NumCpp.array_equal(cArray1, cArray2) and not NumCpp.array_equal(cArray1, cArray3)
####################################################################################
def test_array_equiv():
shapeInput1 = np.random.randint(1, 100, [2, ])
shapeInput3 = np.random.randint(1, 100, [2, ])
shape1 = NumCpp.Shape(shapeInput1[0].item(), shapeInput1[1].item())
shape2 = NumCpp.Shape(shapeInput1[1].item(), shapeInput1[0].item())
shape3 = NumCpp.Shape(shapeInput3[0].item(), shapeInput3[1].item())
cArray1 = NumCpp.NdArray(shape1)
cArray2 = NumCpp.NdArray(shape2)
cArray3 = NumCpp.NdArray(shape3)
data1 = np.random.randint(1, 100, shapeInput1)
data3 = np.random.randint(1, 100, shapeInput3)
cArray1.setArray(data1)
cArray2.setArray(data1.reshape([shapeInput1[1].item(), shapeInput1[0].item()]))
cArray3.setArray(data3)
assert NumCpp.array_equiv(cArray1, cArray2) and not NumCpp.array_equiv(cArray1, cArray3)
shapeInput1 = np.random.randint(1, 100, [2, ])
shapeInput3 = np.random.randint(1, 100, [2, ])
shape1 = NumCpp.Shape(shapeInput1[0].item(), shapeInput1[1].item())
shape2 = NumCpp.Shape(shapeInput1[1].item(), shapeInput1[0].item())
shape3 = NumCpp.Shape(shapeInput3[0].item(), shapeInput3[1].item())
cArray1 = NumCpp.NdArrayComplexDouble(shape1)
cArray2 = NumCpp.NdArrayComplexDouble(shape2)
cArray3 = NumCpp.NdArrayComplexDouble(shape3)
real1 = np.random.randint(1, 100, [shape1.rows, shape1.cols])
imag1 = np.random.randint(1, 100, [shape1.rows, shape1.cols])
data1 = real1 + 1j * imag1
real3 = np.random.randint(1, 100, [shape3.rows, shape3.cols])
imag3 = np.random.randint(1, 100, [shape3.rows, shape3.cols])
data3 = real3 + 1j * imag3
cArray1.setArray(data1)
cArray2.setArray(data1.reshape([shapeInput1[1].item(), shapeInput1[0].item()]))
cArray3.setArray(data3)
assert NumCpp.array_equiv(cArray1, cArray2) and not NumCpp.array_equiv(cArray1, cArray3)
####################################################################################
def test_asarray():
values = np.random.randint(0, 100, [2, ]).astype(np.double)
assert np.array_equal(NumCpp.asarrayArray1D(*values).flatten(), values)
real = np.random.randint(0, 100, [2, ]).astype(np.double)
imag = np.random.randint(0, 100, [2, ]).astype(np.double)
values = real + 1j * imag
assert np.array_equal(NumCpp.asarrayArray1D(*values).flatten(), values)
values = np.random.randint(0, 100, [2, ]).astype(np.double)
assert np.array_equal(NumCpp.asarrayArray1DCopy(*values).flatten(), values)
real = np.random.randint(0, 100, [2, ]).astype(np.double)
imag = np.random.randint(0, 100, [2, ]).astype(np.double)
values = real + 1j * imag
assert np.array_equal(NumCpp.asarrayArray1DCopy(*values).flatten(), values)
values = np.random.randint(0, 100, [2, ]).astype(np.double)
data = np.vstack([values, values])
assert np.array_equal(NumCpp.asarrayArray2D(*values), data)
real = np.random.randint(0, 100, [2, ]).astype(np.double)
imag = np.random.randint(0, 100, [2, ]).astype(np.double)
values = real + 1j * imag
data = np.vstack([values, values])
assert np.array_equal(NumCpp.asarrayArray2D(*values), data)
values = np.random.randint(0, 100, [2, ]).astype(np.double)
data = np.vstack([values, values])
assert np.array_equal(NumCpp.asarrayArray2DCopy(*values), data)
real = np.random.randint(0, 100, [2, ]).astype(np.double)
imag = np.random.randint(0, 100, [2, ]).astype(np.double)
values = real + 1j * imag
data = np.vstack([values, values])
assert np.array_equal(NumCpp.asarrayArray2DCopy(*values), data)
values = np.random.randint(0, 100, [2, ]).astype(np.double)
assert np.array_equal(NumCpp.asarrayVector1D(*values).flatten(), values)
real = np.random.randint(0, 100, [2, ]).astype(np.double)
imag = np.random.randint(0, 100, [2, ]).astype(np.double)
values = real + 1j * imag
assert np.array_equal(NumCpp.asarrayVector1D(*values).flatten(), values)
values = np.random.randint(0, 100, [2, ]).astype(np.double)
assert np.array_equal(NumCpp.asarrayVector1DCopy(*values).flatten(), values)
real = np.random.randint(0, 100, [2, ]).astype(np.double)
imag = np.random.randint(0, 100, [2, ]).astype(np.double)
values = real + 1j * imag
assert np.array_equal(NumCpp.asarrayVector1DCopy(*values).flatten(), values)
values = np.random.randint(0, 100, [2, ]).astype(np.double)
data = np.vstack([values, values])
assert np.array_equal(NumCpp.asarrayVector2D(*values), data)
real = np.random.randint(0, 100, [2, ]).astype(np.double)
imag = np.random.randint(0, 100, [2, ]).astype(np.double)
values = real + 1j * imag
data = np.vstack([values, values])
assert np.array_equal(NumCpp.asarrayVector2D(*values), data)
values = np.random.randint(0, 100, [2, ]).astype(np.double)
data = np.vstack([values, values])
assert np.array_equal(NumCpp.asarrayVectorArray2D(*values), data)
real = np.random.randint(0, 100, [2, ]).astype(np.double)
imag = np.random.randint(0, 100, [2, ]).astype(np.double)
values = real + 1j * imag
data = np.vstack([values, values])
assert np.array_equal(NumCpp.asarrayVectorArray2D(*values), data)
values = np.random.randint(0, 100, [2, ]).astype(np.double)
data = np.vstack([values, values])
assert np.array_equal(NumCpp.asarrayVectorArray2DCopy(*values), data)
real = np.random.randint(0, 100, [2, ]).astype(np.double)
imag = np.random.randint(0, 100, [2, ]).astype(np.double)
values = real + 1j * imag
data = np.vstack([values, values])
assert np.array_equal(NumCpp.asarrayVectorArray2DCopy(*values), data)
values = np.random.randint(0, 100, [2, ]).astype(np.double)
assert np.array_equal(NumCpp.asarrayDeque1D(*values).flatten(), values)
real = np.random.randint(0, 100, [2, ]).astype(np.double)
imag = np.random.randint(0, 100, [2, ]).astype(np.double)
values = real + 1j * imag
assert np.array_equal(NumCpp.asarrayDeque1D(*values).flatten(), values)
values = np.random.randint(0, 100, [2, ]).astype(np.double)
data = np.vstack([values, values])
assert np.array_equal(NumCpp.asarrayDeque2D(*values), data)
real = np.random.randint(0, 100, [2, ]).astype(np.double)
imag = np.random.randint(0, 100, [2, ]).astype(np.double)
values = real + 1j * imag
data = np.vstack([values, values])
assert np.array_equal(NumCpp.asarrayDeque2D(*values), data)
values = np.random.randint(0, 100, [2, ]).astype(np.double)
assert np.array_equal(NumCpp.asarrayList(*values).flatten(), values)
real = np.random.randint(0, 100, [2, ]).astype(np.double)
imag = np.random.randint(0, 100, [2, ]).astype(np.double)
values = real + 1j * imag
assert np.array_equal(NumCpp.asarrayList(*values).flatten(), values)
values = np.random.randint(0, 100, [2, ]).astype(np.double)
assert np.array_equal(NumCpp.asarrayIterators(*values).flatten(), values)
real = np.random.randint(0, 100, [2, ]).astype(np.double)
imag = np.random.randint(0, 100, [2, ]).astype(np.double)
values = real + 1j * imag
assert np.array_equal(NumCpp.asarrayIterators(*values).flatten(), values)
values = np.random.randint(0, 100, [2, ]).astype(np.double)
assert np.array_equal(NumCpp.asarrayPointerIterators(*values).flatten(), values)
real = np.random.randint(0, 100, [2, ]).astype(np.double)
imag = np.random.randint(0, 100, [2, ]).astype(np.double)
values = real + 1j * imag
assert np.array_equal(NumCpp.asarrayPointerIterators(*values).flatten(), values)
values = np.random.randint(0, 100, [2, ]).astype(np.double)
assert np.array_equal(NumCpp.asarrayPointer(*values).flatten(), values)
real = np.random.randint(0, 100, [2, ]).astype(np.double)
imag = np.random.randint(0, 100, [2, ]).astype(np.double)
values = real + 1j * imag
assert np.array_equal(NumCpp.asarrayPointer(*values).flatten(), values)
values = np.random.randint(0, 100, [2, ]).astype(np.double)
data = np.vstack([values, values])
assert np.array_equal(NumCpp.asarrayPointer2D(*values), data)
real = np.random.randint(0, 100, [2, ]).astype(np.double)
imag = np.random.randint(0, 100, [2, ]).astype(np.double)
values = real + 1j * imag
data = np.vstack([values, values])
assert np.array_equal(NumCpp.asarrayPointer2D(*values), data)
values = np.random.randint(0, 100, [2, ]).astype(np.double)
assert np.array_equal(NumCpp.asarrayPointerShell(*values).flatten(), values)
real = np.random.randint(0, 100, [2, ]).astype(np.double)
imag = np.random.randint(0, 100, [2, ]).astype(np.double)
values = real + 1j * imag
assert np.array_equal(NumCpp.asarrayPointerShell(*values).flatten(), values)
values = np.random.randint(0, 100, [2, ]).astype(np.double)
data = np.vstack([values, values])
assert np.array_equal(NumCpp.asarrayPointerShell2D(*values), data)
real = np.random.randint(0, 100, [2, ]).astype(np.double)
imag = np.random.randint(0, 100, [2, ]).astype(np.double)
values = real + 1j * imag
data = np.vstack([values, values])
assert np.array_equal(NumCpp.asarrayPointerShell2D(*values), data)
values = np.random.randint(0, 100, [2, ]).astype(np.double)
assert np.array_equal(NumCpp.asarrayPointerShellTakeOwnership(*values).flatten(), values)
real = np.random.randint(0, 100, [2, ]).astype(np.double)
imag = np.random.randint(0, 100, [2, ]).astype(np.double)
values = real + 1j * imag
assert np.array_equal(NumCpp.asarrayPointerShellTakeOwnership(*values).flatten(), values)
values = np.random.randint(0, 100, [2, ]).astype(np.double)
data = np.vstack([values, values])
assert np.array_equal(NumCpp.asarrayPointerShell2DTakeOwnership(*values), data)
real = np.random.randint(0, 100, [2, ]).astype(np.double)
imag = np.random.randint(0, 100, [2, ]).astype(np.double)
values = real + 1j * imag
data = np.vstack([values, values])
assert np.array_equal(NumCpp.asarrayPointerShell2DTakeOwnership(*values), data)
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArray(shape)
data = np.random.randint(0, 100, [shape.rows, shape.cols])
cArray.setArray(data)
cArrayCast = NumCpp.astypeDoubleToUint32(cArray).getNumpyArray()
assert np.array_equal(cArrayCast, data.astype(np.uint32))
assert cArrayCast.dtype == np.uint32
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArray(shape)
data = np.random.randint(0, 100, [shape.rows, shape.cols])
cArray.setArray(data)
cArrayCast = NumCpp.astypeDoubleToComplex(cArray).getNumpyArray()
assert np.array_equal(cArrayCast, data.astype(np.complex128))
assert cArrayCast.dtype == np.complex128
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArrayComplexDouble(shape)
real = np.random.randint(1, 100, [shape.rows, shape.cols])
imag = np.random.randint(1, 100, [shape.rows, shape.cols])
data = real + 1j * imag
cArray.setArray(data)
cArrayCast = NumCpp.astypeComplexToComplex(cArray).getNumpyArray()
assert np.array_equal(cArrayCast, data.astype(np.complex64))
assert cArrayCast.dtype == np.complex64
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArrayComplexDouble(shape)
real = np.random.randint(1, 100, [shape.rows, shape.cols])
imag = np.random.randint(1, 100, [shape.rows, shape.cols])
data = real + 1j * imag
cArray.setArray(data)
cArrayCast = NumCpp.astypeComplexToDouble(cArray).getNumpyArray()
warnings.filterwarnings('ignore', category=np.ComplexWarning)
assert np.array_equal(cArrayCast, data.astype(np.double))
warnings.filters.pop() # noqa
assert cArrayCast.dtype == np.double
####################################################################################
def test_average():
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArray(shape)
data = np.random.randint(0, 100, [shape.rows, shape.cols])
cArray.setArray(data)
assert np.round(NumCpp.average(cArray, NumCpp.Axis.NONE).item(), 9) == np.round(np.average(data), 9)
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArrayComplexDouble(shape)
real = np.random.randint(1, 100, [shape.rows, shape.cols])
imag = np.random.randint(1, 100, [shape.rows, shape.cols])
data = real + 1j * imag
cArray.setArray(data)
assert np.round(NumCpp.average(cArray, NumCpp.Axis.NONE).item(), 9) == np.round(np.average(data), 9)
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArray(shape)
data = np.random.randint(0, 100, [shape.rows, shape.cols])
cArray.setArray(data)
assert np.array_equal(np.round(NumCpp.average(cArray, NumCpp.Axis.ROW).flatten(), 9),
np.round(np.average(data, axis=0), 9))
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArrayComplexDouble(shape)
real = np.random.randint(1, 100, [shape.rows, shape.cols])
imag = np.random.randint(1, 100, [shape.rows, shape.cols])
data = real + 1j * imag
cArray.setArray(data)
assert np.array_equal(np.round(NumCpp.average(cArray, NumCpp.Axis.ROW).flatten(), 9),
np.round(np.average(data, axis=0), 9))
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArray(shape)
data = np.random.randint(0, 100, [shape.rows, shape.cols])
cArray.setArray(data)
assert np.array_equal(np.round(NumCpp.average(cArray, NumCpp.Axis.COL).flatten(), 9),
np.round(np.average(data, axis=1), 9))
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArrayComplexDouble(shape)
real = np.random.randint(1, 100, [shape.rows, shape.cols])
imag = np.random.randint(1, 100, [shape.rows, shape.cols])
data = real + 1j * imag
cArray.setArray(data)
assert np.array_equal(np.round(NumCpp.average(cArray, NumCpp.Axis.COL).flatten(), 9),
np.round(np.average(data, axis=1), 9))
####################################################################################
def test_averageWeighted():
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArray(shape)
cWeights = NumCpp.NdArray(shape)
data = np.random.randint(0, 100, [shape.rows, shape.cols])
weights = np.random.randint(1, 5, [shape.rows, shape.cols])
cArray.setArray(data)
cWeights.setArray(weights)
assert np.round(NumCpp.averageWeighted(cArray, cWeights, NumCpp.Axis.NONE).item(), 9) == \
np.round(np.average(data, weights=weights), 9)
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArrayComplexDouble(shape)
cWeights = NumCpp.NdArray(shape)
real = np.random.randint(1, 100, [shape.rows, shape.cols])
imag = np.random.randint(1, 100, [shape.rows, shape.cols])
data = real + 1j * imag
weights = np.random.randint(1, 5, [shape.rows, shape.cols])
cArray.setArray(data)
cWeights.setArray(weights)
assert np.round(NumCpp.averageWeighted(cArray, cWeights, NumCpp.Axis.NONE).item(), 9) == \
np.round(np.average(data, weights=weights), 9)
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArray(shape)
cWeights = NumCpp.NdArray(1, shape.cols)
data = np.random.randint(0, 100, [shape.rows, shape.cols])
weights = np.random.randint(1, 5, [1, shape.rows])
cArray.setArray(data)
cWeights.setArray(weights)
assert np.array_equal(np.round(NumCpp.averageWeighted(cArray, cWeights, NumCpp.Axis.ROW).flatten(), 9),
np.round(np.average(data, weights=weights.flatten(), axis=0), 9))
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArrayComplexDouble(shape)
cWeights = NumCpp.NdArray(1, shape.cols)
real = np.random.randint(1, 100, [shape.rows, shape.cols])
imag = np.random.randint(1, 100, [shape.rows, shape.cols])
data = real + 1j * imag
weights = np.random.randint(1, 5, [1, shape.rows])
cArray.setArray(data)
cWeights.setArray(weights)
assert np.array_equal(np.round(NumCpp.averageWeighted(cArray, cWeights, NumCpp.Axis.ROW).flatten(), 9),
np.round(np.average(data, weights=weights.flatten(), axis=0), 9))
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArray(shape)
cWeights = NumCpp.NdArray(1, shape.rows)
data = np.random.randint(0, 100, [shape.rows, shape.cols])
weights = np.random.randint(1, 5, [1, shape.cols])
cWeights.setArray(weights)
cArray.setArray(data)
assert np.array_equal(np.round(NumCpp.averageWeighted(cArray, cWeights, NumCpp.Axis.COL).flatten(), 9),
np.round(np.average(data, weights=weights.flatten(), axis=1), 9))
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArrayComplexDouble(shape)
cWeights = NumCpp.NdArray(1, shape.rows)
real = np.random.randint(1, 100, [shape.rows, shape.cols])
imag = np.random.randint(1, 100, [shape.rows, shape.cols])
data = real + 1j * imag
weights = np.random.randint(1, 5, [1, shape.cols])
cWeights.setArray(weights)
cArray.setArray(data)
assert np.array_equal(np.round(NumCpp.averageWeighted(cArray, cWeights, NumCpp.Axis.COL).flatten(), 9),
np.round(np.average(data, weights=weights.flatten(), axis=1), 9))
####################################################################################
def test_binaryRepr():
value = np.random.randint(0, np.iinfo(np.uint64).max, [1, ], dtype=np.uint64).item()
assert NumCpp.binaryRepr(np.uint64(value)) == np.binary_repr(value, np.iinfo(np.uint64).bits)
####################################################################################
def test_bincount():
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArrayUInt32(shape)
data = np.random.randint(0, 100, [shape.rows, shape.cols]).astype(np.uint16)
cArray.setArray(data)
assert np.array_equal(NumCpp.bincount(cArray, 0).flatten(), np.bincount(data.flatten(), minlength=0))
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArrayUInt32(shape)
data = np.random.randint(0, 100, [shape.rows, shape.cols]).astype(np.uint16)
cArray.setArray(data)
minLength = int(np.max(data) + 10)
assert np.array_equal(NumCpp.bincount(cArray, minLength).flatten(),
np.bincount(data.flatten(), minlength=minLength))
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArrayUInt32(shape)
cWeights = NumCpp.NdArrayUInt32(shape)
data = np.random.randint(0, 100, [shape.rows, shape.cols]).astype(np.uint16)
weights = np.random.randint(0, 100, [shape.rows, shape.cols]).astype(np.uint16)
cArray.setArray(data)
cWeights.setArray(weights)
assert np.array_equal(NumCpp.bincountWeighted(cArray, cWeights, 0).flatten(),
np.bincount(data.flatten(), minlength=0, weights=weights.flatten()))
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArrayUInt32(shape)
cWeights = NumCpp.NdArrayUInt32(shape)
data = np.random.randint(0, 100, [shape.rows, shape.cols]).astype(np.uint16)
weights = np.random.randint(0, 100, [shape.rows, shape.cols]).astype(np.uint16)
cArray.setArray(data)
cWeights.setArray(weights)
minLength = int(np.max(data) + 10)
assert np.array_equal(NumCpp.bincountWeighted(cArray, cWeights, minLength).flatten(),
np.bincount(data.flatten(), minlength=minLength, weights=weights.flatten()))
####################################################################################
def test_bitwise_and():
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray1 = NumCpp.NdArrayUInt64(shape)
cArray2 = NumCpp.NdArrayUInt64(shape)
data1 = np.random.randint(0, 100, [shape.rows, shape.cols]).astype(np.uint64)
data2 = np.random.randint(0, 100, [shape.rows, shape.cols]).astype(np.uint64)
cArray1.setArray(data1)
cArray2.setArray(data2)
assert np.array_equal(NumCpp.bitwise_and(cArray1, cArray2), np.bitwise_and(data1, data2))
####################################################################################
def test_bitwise_not():
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArrayUInt64(shape)
data = np.random.randint(0, 100, [shape.rows, shape.cols]).astype(np.uint64)
cArray.setArray(data)
assert np.array_equal(NumCpp.bitwise_not(cArray), np.bitwise_not(data))
####################################################################################
def test_bitwise_or():
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray1 = NumCpp.NdArrayUInt64(shape)
cArray2 = NumCpp.NdArrayUInt64(shape)
data1 = np.random.randint(0, 100, [shape.rows, shape.cols]).astype(np.uint64)
data2 = np.random.randint(0, 100, [shape.rows, shape.cols]).astype(np.uint64)
cArray1.setArray(data1)
cArray2.setArray(data2)
assert np.array_equal(NumCpp.bitwise_or(cArray1, cArray2), np.bitwise_or(data1, data2))
####################################################################################
def test_bitwise_xor():
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray1 = NumCpp.NdArrayUInt64(shape)
cArray2 = NumCpp.NdArrayUInt64(shape)
data1 = np.random.randint(0, 100, [shape.rows, shape.cols]).astype(np.uint64)
data2 = np.random.randint(0, 100, [shape.rows, shape.cols]).astype(np.uint64)
cArray1.setArray(data1)
cArray2.setArray(data2)
assert np.array_equal(NumCpp.bitwise_xor(cArray1, cArray2), np.bitwise_xor(data1, data2))
####################################################################################
def test_byteswap():
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArrayUInt64(shape)
data = np.random.randint(0, 100, [shape.rows, shape.cols]).astype(np.uint64)
cArray.setArray(data)
assert np.array_equal(NumCpp.byteswap(cArray).shape, shapeInput)
####################################################################################
def test_cbrt():
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArray(shape)
data = np.random.randint(0, 100, [shape.rows, shape.cols]).astype(np.double)
cArray.setArray(data)
assert np.array_equal(np.round(NumCpp.cbrtArray(cArray), 9), np.round(np.cbrt(data), 9))
####################################################################################
def test_ceil():
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArray(shape)
data = np.random.randn(shape.rows, shape.cols).astype(np.double) * 1000
cArray.setArray(data)
assert np.array_equal(np.round(NumCpp.ceilArray(cArray), 9), np.round(np.ceil(data), 9))
####################################################################################
def test_center_of_mass():
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArray(shape)
data = np.random.randn(shape.rows, shape.cols).astype(np.double) * 1000
cArray.setArray(data)
assert np.array_equal(np.round(NumCpp.centerOfMass(cArray, NumCpp.Axis.NONE).flatten(), 9),
np.round(meas.center_of_mass(data), 9))
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArray(shape)
data = np.random.randn(shape.rows, shape.cols).astype(np.double) * 1000
cArray.setArray(data)
coms = list()
for col in range(data.shape[1]):
coms.append(np.round(meas.center_of_mass(data[:, col])[0], 9))
assert np.array_equal(np.round(NumCpp.centerOfMass(cArray, NumCpp.Axis.ROW).flatten(), 9), np.round(coms, 9))
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArray(shape)
data = np.random.randn(shape.rows, shape.cols).astype(np.double) * 1000
cArray.setArray(data)
coms = list()
for row in range(data.shape[0]):
coms.append(np.round(meas.center_of_mass(data[row, :])[0], 9))
assert np.array_equal(np.round(NumCpp.centerOfMass(cArray, NumCpp.Axis.COL).flatten(), 9), np.round(coms, 9))
####################################################################################
def test_clip():
value = np.random.randint(0, 100, [1, ]).item()
minValue = np.random.randint(0, 10, [1, ]).item()
maxValue = np.random.randint(90, 100, [1, ]).item()
assert NumCpp.clipScaler(value, minValue, maxValue) == np.clip(value, minValue, maxValue)
value = np.random.randint(0, 100, [1, ]).item() + 1j * np.random.randint(0, 100, [1, ]).item()
minValue = np.random.randint(0, 10, [1, ]).item() + 1j * np.random.randint(0, 10, [1, ]).item()
maxValue = np.random.randint(90, 100, [1, ]).item() + 1j * np.random.randint(0, 100, [1, ]).item()
assert NumCpp.clipScaler(value, minValue, maxValue) == np.clip(value, minValue, maxValue) # noqa
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArray(shape)
data = np.random.randint(0, 100, [shape.rows, shape.cols])
cArray.setArray(data)
minValue = np.random.randint(0, 10, [1, ]).item()
maxValue = np.random.randint(90, 100, [1, ]).item()
assert np.array_equal(NumCpp.clipArray(cArray, minValue, maxValue), np.clip(data, minValue, maxValue))
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArrayComplexDouble(shape)
real = np.random.randint(1, 100, [shape.rows, shape.cols])
imag = np.random.randint(1, 100, [shape.rows, shape.cols])
data = real + 1j * imag
cArray.setArray(data)
minValue = np.random.randint(0, 10, [1, ]).item() + 1j * np.random.randint(0, 10, [1, ]).item()
maxValue = np.random.randint(90, 100, [1, ]).item() + 1j * np.random.randint(0, 100, [1, ]).item()
assert np.array_equal(NumCpp.clipArray(cArray, minValue, maxValue), np.clip(data, minValue, maxValue)) # noqa
####################################################################################
def test_column_stack():
shapeInput = np.random.randint(20, 100, [2, ])
shape1 = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
shape2 = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item() + np.random.randint(1, 10, [1, ]).item())
shape3 = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item() + np.random.randint(1, 10, [1, ]).item())
shape4 = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item() + np.random.randint(1, 10, [1, ]).item())
cArray1 = NumCpp.NdArray(shape1)
cArray2 = NumCpp.NdArray(shape2)
cArray3 = NumCpp.NdArray(shape3)
cArray4 = NumCpp.NdArray(shape4)
data1 = np.random.randint(1, 100, [shape1.rows, shape1.cols])
data2 = np.random.randint(1, 100, [shape2.rows, shape2.cols])
data3 = np.random.randint(1, 100, [shape3.rows, shape3.cols])
data4 = np.random.randint(1, 100, [shape4.rows, shape4.cols])
cArray1.setArray(data1)
cArray2.setArray(data2)
cArray3.setArray(data3)
cArray4.setArray(data4)
assert np.array_equal(NumCpp.column_stack(cArray1, cArray2, cArray3, cArray4),
np.column_stack([data1, data2, data3, data4]))
####################################################################################
def test_complex():
real = np.random.rand(1).astype(np.double).item()
value = complex(real)
assert np.round(NumCpp.complexScaler(real), 9) == np.round(value, 9)
components = np.random.rand(2).astype(np.double)
value = complex(components[0], components[1])
assert np.round(NumCpp.complexScaler(components[0], components[1]), 9) == np.round(value, 9)
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
realArray = NumCpp.NdArray(shape)
real = np.random.rand(shape.rows, shape.cols)
realArray.setArray(real)
assert np.array_equal(np.round(NumCpp.complexArray(realArray), 9), np.round(real + 1j * np.zeros_like(real), 9))
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
realArray = NumCpp.NdArray(shape)
imagArray = NumCpp.NdArray(shape)
real = np.random.rand(shape.rows, shape.cols)
imag = np.random.rand(shape.rows, shape.cols)
realArray.setArray(real)
imagArray.setArray(imag)
assert np.array_equal(np.round(NumCpp.complexArray(realArray, imagArray), 9), np.round(real + 1j * imag, 9))
####################################################################################
def test_concatenate():
shapeInput = np.random.randint(20, 100, [2, ])
shape1 = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
shape2 = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item() + np.random.randint(1, 10, [1, ]).item())
shape3 = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item() + np.random.randint(1, 10, [1, ]).item())
shape4 = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item() + np.random.randint(1, 10, [1, ]).item())
cArray1 = NumCpp.NdArray(shape1)
cArray2 = NumCpp.NdArray(shape2)
cArray3 = NumCpp.NdArray(shape3)
cArray4 = NumCpp.NdArray(shape4)
data1 = np.random.randint(1, 100, [shape1.rows, shape1.cols])
data2 = np.random.randint(1, 100, [shape2.rows, shape2.cols])
data3 = np.random.randint(1, 100, [shape3.rows, shape3.cols])
data4 = np.random.randint(1, 100, [shape4.rows, shape4.cols])
cArray1.setArray(data1)
cArray2.setArray(data2)
cArray3.setArray(data3)
cArray4.setArray(data4)
assert np.array_equal(NumCpp.concatenate(cArray1, cArray2, cArray3, cArray4, NumCpp.Axis.NONE).flatten(),
np.concatenate([data1.flatten(), data2.flatten(), data3.flatten(), data4.flatten()]))
shapeInput = np.random.randint(20, 100, [2, ])
shape1 = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
shape2 = NumCpp.Shape(shapeInput[0].item() + np.random.randint(1, 10, [1, ]).item(), shapeInput[1].item())
shape3 = NumCpp.Shape(shapeInput[0].item() + np.random.randint(1, 10, [1, ]).item(), shapeInput[1].item())
shape4 = NumCpp.Shape(shapeInput[0].item() + np.random.randint(1, 10, [1, ]).item(), shapeInput[1].item())
cArray1 = NumCpp.NdArray(shape1)
cArray2 = NumCpp.NdArray(shape2)
cArray3 = NumCpp.NdArray(shape3)
cArray4 = NumCpp.NdArray(shape4)
data1 = np.random.randint(1, 100, [shape1.rows, shape1.cols])
data2 = np.random.randint(1, 100, [shape2.rows, shape2.cols])
data3 = np.random.randint(1, 100, [shape3.rows, shape3.cols])
data4 = np.random.randint(1, 100, [shape4.rows, shape4.cols])
cArray1.setArray(data1)
cArray2.setArray(data2)
cArray3.setArray(data3)
cArray4.setArray(data4)
assert np.array_equal(NumCpp.concatenate(cArray1, cArray2, cArray3, cArray4, NumCpp.Axis.ROW),
np.concatenate([data1, data2, data3, data4], axis=0))
shapeInput = np.random.randint(20, 100, [2, ])
shape1 = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
shape2 = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item() + np.random.randint(1, 10, [1, ]).item())
shape3 = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item() + np.random.randint(1, 10, [1, ]).item())
shape4 = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item() + np.random.randint(1, 10, [1, ]).item())
cArray1 = NumCpp.NdArray(shape1)
cArray2 = NumCpp.NdArray(shape2)
cArray3 = NumCpp.NdArray(shape3)
cArray4 = NumCpp.NdArray(shape4)
data1 = np.random.randint(1, 100, [shape1.rows, shape1.cols])
data2 = np.random.randint(1, 100, [shape2.rows, shape2.cols])
data3 = np.random.randint(1, 100, [shape3.rows, shape3.cols])
data4 = np.random.randint(1, 100, [shape4.rows, shape4.cols])
cArray1.setArray(data1)
cArray2.setArray(data2)
cArray3.setArray(data3)
cArray4.setArray(data4)
assert np.array_equal(NumCpp.concatenate(cArray1, cArray2, cArray3, cArray4, NumCpp.Axis.COL),
np.concatenate([data1, data2, data3, data4], axis=1))
####################################################################################
def test_conj():
components = np.random.rand(2).astype(np.double)
value = complex(components[0], components[1])
assert np.round(NumCpp.conjScaler(value), 9) == np.round(np.conj(value), 9)
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArrayComplexDouble(shape)
data = np.random.rand(shape.rows, shape.cols) + 1j * np.random.rand(shape.rows, shape.cols)
cArray.setArray(data)
assert np.array_equal(np.round(NumCpp.conjArray(cArray), 9), np.round(np.conj(data), 9))
####################################################################################
def test_contains():
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArray(shape)
data = np.random.randint(0, 100, [shape.rows, shape.cols])
value = np.random.randint(0, 100, [1, ]).item()
cArray.setArray(data)
assert NumCpp.contains(cArray, value, NumCpp.Axis.NONE).getNumpyArray().item() == (value in data)
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArrayComplexDouble(shape)
real = np.random.randint(1, 100, [shape.rows, shape.cols])
imag = np.random.randint(1, 100, [shape.rows, shape.cols])
data = real + 1j * imag
value = np.random.randint(0, 100, [1, ]).item() + 1j * np.random.randint(0, 100, [1, ]).item()
cArray.setArray(data)
assert NumCpp.contains(cArray, value, NumCpp.Axis.NONE).getNumpyArray().item() == (value in data)
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArray(shape)
data = np.random.randint(0, 100, [shape.rows, shape.cols])
value = np.random.randint(0, 100, [1, ]).item()
cArray.setArray(data)
truth = list()
for row in data:
truth.append(value in row)
assert np.array_equal(NumCpp.contains(cArray, value, NumCpp.Axis.COL).getNumpyArray().flatten(), np.asarray(truth))
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArrayComplexDouble(shape)
real = np.random.randint(1, 100, [shape.rows, shape.cols])
imag = np.random.randint(1, 100, [shape.rows, shape.cols])
data = real + 1j * imag
value = np.random.randint(0, 100, [1, ]).item() + 1j * np.random.randint(0, 100, [1, ]).item()
cArray.setArray(data)
truth = list()
for row in data:
truth.append(value in row)
assert np.array_equal(NumCpp.contains(cArray, value, NumCpp.Axis.COL).getNumpyArray().flatten(), np.asarray(truth))
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArray(shape)
data = np.random.randint(0, 100, [shape.rows, shape.cols])
value = np.random.randint(0, 100, [1, ]).item()
cArray.setArray(data)
truth = list()
for row in data.T:
truth.append(value in row)
assert np.array_equal(NumCpp.contains(cArray, value, NumCpp.Axis.ROW).getNumpyArray().flatten(), np.asarray(truth))
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArrayComplexDouble(shape)
real = np.random.randint(1, 100, [shape.rows, shape.cols])
imag = np.random.randint(1, 100, [shape.rows, shape.cols])
data = real + 1j * imag
value = np.random.randint(0, 100, [1, ]).item() + 1j * np.random.randint(0, 100, [1, ]).item()
cArray.setArray(data)
truth = list()
for row in data.T:
truth.append(value in row)
assert np.array_equal(NumCpp.contains(cArray, value, NumCpp.Axis.ROW).getNumpyArray().flatten(), np.asarray(truth))
####################################################################################
def test_copy():
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArray(shape)
data = np.random.randint(0, 100, [shape.rows, shape.cols])
cArray.setArray(data)
assert np.array_equal(NumCpp.copy(cArray), data)
####################################################################################
def test_copysign():
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray1 = NumCpp.NdArray(shape)
cArray2 = NumCpp.NdArray(shape)
data1 = np.random.randint(-100, 100, [shape.rows, shape.cols])
data2 = np.random.randint(-100, 100, [shape.rows, shape.cols])
cArray1.setArray(data1)
cArray2.setArray(data2)
assert np.array_equal(NumCpp.copysign(cArray1, cArray2), np.copysign(data1, data2))
####################################################################################
def test_copyto():
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray1 = NumCpp.NdArray(shape)
cArray2 = NumCpp.NdArray()
data1 = np.random.randint(-100, 100, [shape.rows, shape.cols])
cArray1.setArray(data1)
assert np.array_equal(NumCpp.copyto(cArray2, cArray1), data1)
####################################################################################
def test_cos():
value = np.abs(np.random.rand(1).item())
assert np.round(NumCpp.cosScaler(value), 9) == np.round(np.cos(value), 9)
components = np.random.rand(2).astype(np.double)
value = complex(components[0], components[1])
assert np.round(NumCpp.cosScaler(value), 9) == np.round(np.cos(value), 9)
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArray(shape)
data = np.random.rand(shape.rows, shape.cols)
cArray.setArray(data)
assert np.array_equal(np.round(NumCpp.cosArray(cArray), 9), np.round(np.cos(data), 9))
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArrayComplexDouble(shape)
data = np.random.rand(shape.rows, shape.cols) + 1j * np.random.rand(shape.rows, shape.cols)
cArray.setArray(data)
assert np.array_equal(np.round(NumCpp.cosArray(cArray), 9), np.round(np.cos(data), 9))
####################################################################################
def test_cosh():
value = np.abs(np.random.rand(1).item())
assert np.round(NumCpp.coshScaler(value), 9) == np.round(np.cosh(value), 9)
components = np.random.rand(2).astype(np.double)
value = complex(components[0], components[1])
assert np.round(NumCpp.coshScaler(value), 9) == np.round(np.cosh(value), 9)
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArray(shape)
data = np.random.rand(shape.rows, shape.cols)
cArray.setArray(data)
assert np.array_equal(np.round(NumCpp.coshArray(cArray), 9), np.round(np.cosh(data), 9))
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArrayComplexDouble(shape)
data = np.random.rand(shape.rows, shape.cols) + 1j * np.random.rand(shape.rows, shape.cols)
cArray.setArray(data)
assert np.array_equal(np.round(NumCpp.coshArray(cArray), 9), np.round(np.cosh(data), 9))
####################################################################################
def test_count_nonzero():
shapeInput = np.random.randint(1, 50, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArray(shape)
data = np.random.randint(0, 3, [shape.rows, shape.cols], dtype=np.uint32)
cArray.setArray(data)
assert NumCpp.count_nonzero(cArray, NumCpp.Axis.NONE) == np.count_nonzero(data)
shapeInput = np.random.randint(1, 50, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArrayComplexDouble(shape)
real = np.random.randint(1, 3, [shape.rows, shape.cols])
imag = np.random.randint(1, 3, [shape.rows, shape.cols])
data = real + 1j * imag
cArray.setArray(data)
assert NumCpp.count_nonzero(cArray, NumCpp.Axis.NONE) == np.count_nonzero(data)
shapeInput = np.random.randint(1, 50, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArray(shape)
data = np.random.randint(0, 3, [shape.rows, shape.cols], dtype=np.uint32)
cArray.setArray(data)
assert np.array_equal(NumCpp.count_nonzero(cArray, NumCpp.Axis.ROW).flatten(), np.count_nonzero(data, axis=0))
shapeInput = np.random.randint(1, 50, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArrayComplexDouble(shape)
real = np.random.randint(1, 3, [shape.rows, shape.cols])
imag = np.random.randint(1, 3, [shape.rows, shape.cols])
data = real + 1j * imag
cArray.setArray(data)
assert np.array_equal(NumCpp.count_nonzero(cArray, NumCpp.Axis.ROW).flatten(), np.count_nonzero(data, axis=0))
shapeInput = np.random.randint(1, 50, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArray(shape)
data = np.random.randint(0, 3, [shape.rows, shape.cols], dtype=np.uint32)
cArray.setArray(data)
assert np.array_equal(NumCpp.count_nonzero(cArray, NumCpp.Axis.COL).flatten(), np.count_nonzero(data, axis=1))
shapeInput = np.random.randint(1, 50, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArrayComplexDouble(shape)
real = np.random.randint(1, 3, [shape.rows, shape.cols])
imag = np.random.randint(1, 3, [shape.rows, shape.cols])
data = real + 1j * imag
cArray.setArray(data)
assert np.array_equal(NumCpp.count_nonzero(cArray, NumCpp.Axis.COL).flatten(), np.count_nonzero(data, axis=1))
####################################################################################
def test_cross():
shape = NumCpp.Shape(1, 2)
cArray1 = NumCpp.NdArray(shape)
cArray2 = NumCpp.NdArray(shape)
data1 = np.random.randint(1, 10, [shape.rows, shape.cols]).astype(np.double)
data2 = np.random.randint(1, 10, [shape.rows, shape.cols]).astype(np.double)
cArray1.setArray(data1)
cArray2.setArray(data2)
assert NumCpp.cross(cArray1, cArray2, NumCpp.Axis.NONE).item() == np.cross(data1, data2).item()
shape = NumCpp.Shape(1, 2)
cArray1 = NumCpp.NdArrayComplexDouble(shape)
cArray2 = NumCpp.NdArrayComplexDouble(shape)
real1 = np.random.randint(1, 100, [shape.rows, shape.cols])
imag1 = np.random.randint(1, 100, [shape.rows, shape.cols])
data1 = real1 + 1j * imag1
real2 = np.random.randint(1, 100, [shape.rows, shape.cols])
imag2 = np.random.randint(1, 100, [shape.rows, shape.cols])
data2 = real2 + 1j * imag2
cArray1.setArray(data1)
cArray2.setArray(data2)
assert NumCpp.cross(cArray1, cArray2, NumCpp.Axis.NONE).item() == np.cross(data1, data2).item()
shape = NumCpp.Shape(2, np.random.randint(1, 100, [1, ]).item())
cArray1 = NumCpp.NdArray(shape)
cArray2 = NumCpp.NdArray(shape)
data1 = np.random.randint(1, 10, [shape.rows, shape.cols]).astype(np.double)
data2 = np.random.randint(1, 10, [shape.rows, shape.cols]).astype(np.double)
cArray1.setArray(data1)
cArray2.setArray(data2)
assert np.array_equal(NumCpp.cross(cArray1, cArray2, NumCpp.Axis.ROW).getNumpyArray().flatten(),
np.cross(data1, data2, axis=0))
shape = NumCpp.Shape(2, np.random.randint(1, 100, [1, ]).item())
cArray1 = NumCpp.NdArrayComplexDouble(shape)
cArray2 = NumCpp.NdArrayComplexDouble(shape)
real1 = np.random.randint(1, 100, [shape.rows, shape.cols])
imag1 = np.random.randint(1, 100, [shape.rows, shape.cols])
data1 = real1 + 1j * imag1
real2 = np.random.randint(1, 100, [shape.rows, shape.cols])
imag2 = np.random.randint(1, 100, [shape.rows, shape.cols])
data2 = real2 + 1j * imag2
cArray1.setArray(data1)
cArray2.setArray(data2)
assert np.array_equal(NumCpp.cross(cArray1, cArray2, NumCpp.Axis.ROW).getNumpyArray().flatten(),
np.cross(data1, data2, axis=0))
shape = NumCpp.Shape(np.random.randint(1, 100, [1, ]).item(), 2)
cArray1 = NumCpp.NdArray(shape)
cArray2 = NumCpp.NdArray(shape)
data1 = np.random.randint(1, 10, [shape.rows, shape.cols]).astype(np.double)
data2 = np.random.randint(1, 10, [shape.rows, shape.cols]).astype(np.double)
cArray1.setArray(data1)
cArray2.setArray(data2)
assert np.array_equal(NumCpp.cross(cArray1, cArray2, NumCpp.Axis.COL).getNumpyArray().flatten(),
np.cross(data1, data2, axis=1))
shape = NumCpp.Shape(np.random.randint(1, 100, [1, ]).item(), 2)
cArray1 = NumCpp.NdArrayComplexDouble(shape)
cArray2 = NumCpp.NdArrayComplexDouble(shape)
real1 = np.random.randint(1, 100, [shape.rows, shape.cols])
imag1 = np.random.randint(1, 100, [shape.rows, shape.cols])
data1 = real1 + 1j * imag1
real2 = np.random.randint(1, 100, [shape.rows, shape.cols])
imag2 = np.random.randint(1, 100, [shape.rows, shape.cols])
data2 = real2 + 1j * imag2
cArray1.setArray(data1)
cArray2.setArray(data2)
assert np.array_equal(NumCpp.cross(cArray1, cArray2, NumCpp.Axis.COL).getNumpyArray().flatten(),
np.cross(data1, data2, axis=1))
shape = NumCpp.Shape(1, 3)
cArray1 = NumCpp.NdArray(shape)
cArray2 = NumCpp.NdArray(shape)
data1 = np.random.randint(1, 10, [shape.rows, shape.cols]).astype(np.double)
data2 = np.random.randint(1, 10, [shape.rows, shape.cols]).astype(np.double)
cArray1.setArray(data1)
cArray2.setArray(data2)
assert np.array_equal(NumCpp.cross(cArray1, cArray2, NumCpp.Axis.NONE).getNumpyArray().flatten(),
np.cross(data1, data2).flatten())
shape = NumCpp.Shape(1, 3)
cArray1 = NumCpp.NdArrayComplexDouble(shape)
cArray2 = NumCpp.NdArrayComplexDouble(shape)
real1 = np.random.randint(1, 100, [shape.rows, shape.cols])
imag1 = np.random.randint(1, 100, [shape.rows, shape.cols])
data1 = real1 + 1j * imag1
real2 = np.random.randint(1, 100, [shape.rows, shape.cols])
imag2 = np.random.randint(1, 100, [shape.rows, shape.cols])
data2 = real2 + 1j * imag2
cArray1.setArray(data1)
cArray2.setArray(data2)
assert np.array_equal(NumCpp.cross(cArray1, cArray2, NumCpp.Axis.NONE).getNumpyArray().flatten(),
np.cross(data1, data2).flatten())
shape = NumCpp.Shape(3, np.random.randint(1, 100, [1, ]).item())
cArray1 = NumCpp.NdArray(shape)
cArray2 = NumCpp.NdArray(shape)
data1 = np.random.randint(1, 10, [shape.rows, shape.cols]).astype(np.double)
data2 = np.random.randint(1, 10, [shape.rows, shape.cols]).astype(np.double)
cArray1.setArray(data1)
cArray2.setArray(data2)
assert np.array_equal(NumCpp.cross(cArray1, cArray2, NumCpp.Axis.ROW).getNumpyArray(),
np.cross(data1, data2, axis=0))
shape = NumCpp.Shape(3, np.random.randint(1, 100, [1, ]).item())
cArray1 = NumCpp.NdArrayComplexDouble(shape)
cArray2 = NumCpp.NdArrayComplexDouble(shape)
real1 = np.random.randint(1, 100, [shape.rows, shape.cols])
imag1 = np.random.randint(1, 100, [shape.rows, shape.cols])
data1 = real1 + 1j * imag1
real2 = np.random.randint(1, 100, [shape.rows, shape.cols])
imag2 = np.random.randint(1, 100, [shape.rows, shape.cols])
data2 = real2 + 1j * imag2
cArray1.setArray(data1)
cArray2.setArray(data2)
assert np.array_equal(NumCpp.cross(cArray1, cArray2, NumCpp.Axis.ROW).getNumpyArray(),
np.cross(data1, data2, axis=0))
shape = NumCpp.Shape(np.random.randint(1, 100, [1, ]).item(), 3)
cArray1 = NumCpp.NdArray(shape)
cArray2 = NumCpp.NdArray(shape)
data1 = np.random.randint(1, 10, [shape.rows, shape.cols]).astype(np.double)
data2 = np.random.randint(1, 10, [shape.rows, shape.cols]).astype(np.double)
cArray1.setArray(data1)
cArray2.setArray(data2)
assert np.array_equal(NumCpp.cross(cArray1, cArray2, NumCpp.Axis.COL).getNumpyArray(),
np.cross(data1, data2, axis=1))
shape = NumCpp.Shape(np.random.randint(1, 100, [1, ]).item(), 3)
cArray1 = NumCpp.NdArrayComplexDouble(shape)
cArray2 = NumCpp.NdArrayComplexDouble(shape)
real1 = np.random.randint(1, 100, [shape.rows, shape.cols])
imag1 = np.random.randint(1, 100, [shape.rows, shape.cols])
data1 = real1 + 1j * imag1
real2 = np.random.randint(1, 100, [shape.rows, shape.cols])
imag2 = np.random.randint(1, 100, [shape.rows, shape.cols])
data2 = real2 + 1j * imag2
cArray1.setArray(data1)
cArray2.setArray(data2)
assert np.array_equal(NumCpp.cross(cArray1, cArray2, NumCpp.Axis.COL).getNumpyArray(),
np.cross(data1, data2, axis=1))
####################################################################################
def test_cube():
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArray(shape)
data = np.random.rand(shape.rows, shape.cols)
cArray.setArray(data)
assert np.array_equal(np.round(NumCpp.cube(cArray), 9), np.round(data * data * data, 9))
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArrayComplexDouble(shape)
real = np.random.randint(1, 100, [shape.rows, shape.cols])
imag = np.random.randint(1, 100, [shape.rows, shape.cols])
data = real + 1j * imag
cArray.setArray(data)
assert np.array_equal(np.round(NumCpp.cube(cArray), 9), np.round(data * data * data, 9))
####################################################################################
def test_cumprod():
shapeInput = np.random.randint(1, 5, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArray(shape)
data = np.random.randint(1, 4, [shape.rows, shape.cols], dtype=np.uint32)
cArray.setArray(data)
assert np.array_equal(NumCpp.cumprod(cArray, NumCpp.Axis.NONE).flatten(), data.cumprod())
shapeInput = np.random.randint(1, 5, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArrayComplexDouble(shape)
real = np.random.randint(1, 4, [shape.rows, shape.cols])
imag = np.random.randint(1, 4, [shape.rows, shape.cols])
data = real + 1j * imag
cArray.setArray(data)
assert np.array_equal(NumCpp.cumprod(cArray, NumCpp.Axis.NONE).flatten(), data.cumprod())
shapeInput = np.random.randint(1, 5, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArray(shape)
data = np.random.randint(1, 4, [shape.rows, shape.cols])
cArray.setArray(data)
assert np.array_equal(NumCpp.cumprod(cArray, NumCpp.Axis.ROW), data.cumprod(axis=0))
shapeInput = np.random.randint(1, 5, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArrayComplexDouble(shape)
real = np.random.randint(1, 4, [shape.rows, shape.cols])
imag = np.random.randint(1, 4, [shape.rows, shape.cols])
data = real + 1j * imag
cArray.setArray(data)
assert np.array_equal(NumCpp.cumprod(cArray, NumCpp.Axis.ROW), data.cumprod(axis=0))
shapeInput = np.random.randint(1, 5, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArray(shape)
data = np.random.randint(1, 4, [shape.rows, shape.cols])
cArray.setArray(data)
assert np.array_equal(NumCpp.cumprod(cArray, NumCpp.Axis.COL), data.cumprod(axis=1))
shapeInput = np.random.randint(1, 5, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArrayComplexDouble(shape)
real = np.random.randint(1, 4, [shape.rows, shape.cols])
imag = np.random.randint(1, 4, [shape.rows, shape.cols])
data = real + 1j * imag
cArray.setArray(data)
assert np.array_equal(NumCpp.cumprod(cArray, NumCpp.Axis.COL), data.cumprod(axis=1))
####################################################################################
def test_cumsum():
shapeInput = np.random.randint(1, 50, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArray(shape)
data = np.random.randint(1, 50, [shape.rows, shape.cols])
cArray.setArray(data)
assert np.array_equal(NumCpp.cumsum(cArray, NumCpp.Axis.NONE).flatten(), data.cumsum())
shapeInput = np.random.randint(1, 50, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArrayComplexDouble(shape)
real = np.random.randint(1, 50, [shape.rows, shape.cols])
imag = np.random.randint(1, 50, [shape.rows, shape.cols])
data = real + 1j * imag
cArray.setArray(data)
assert np.array_equal(NumCpp.cumsum(cArray, NumCpp.Axis.NONE).flatten(), data.cumsum())
shapeInput = np.random.randint(1, 50, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArray(shape)
data = np.random.randint(1, 50, [shape.rows, shape.cols])
cArray.setArray(data)
assert np.array_equal(NumCpp.cumsum(cArray, NumCpp.Axis.ROW), data.cumsum(axis=0))
shapeInput = np.random.randint(1, 50, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArrayComplexDouble(shape)
real = np.random.randint(1, 50, [shape.rows, shape.cols])
imag = np.random.randint(1, 50, [shape.rows, shape.cols])
data = real + 1j * imag
cArray.setArray(data)
assert np.array_equal(NumCpp.cumsum(cArray, NumCpp.Axis.ROW), data.cumsum(axis=0))
shapeInput = np.random.randint(1, 50, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArray(shape)
data = np.random.randint(1, 50, [shape.rows, shape.cols])
cArray.setArray(data)
assert np.array_equal(NumCpp.cumsum(cArray, NumCpp.Axis.COL), data.cumsum(axis=1))
shapeInput = np.random.randint(1, 50, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArrayComplexDouble(shape)
real = np.random.randint(1, 50, [shape.rows, shape.cols])
imag = np.random.randint(1, 50, [shape.rows, shape.cols])
data = real + 1j * imag
cArray.setArray(data)
assert np.array_equal(NumCpp.cumsum(cArray, NumCpp.Axis.COL), data.cumsum(axis=1))
####################################################################################
def test_deg2rad():
value = np.abs(np.random.rand(1).item()) * 360
assert np.round(NumCpp.deg2radScaler(value), 9) == np.round(np.deg2rad(value), 9)
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArray(shape)
data = np.random.rand(shape.rows, shape.cols) * 360
cArray.setArray(data)
assert np.array_equal(np.round(NumCpp.deg2radArray(cArray), 9), np.round(np.deg2rad(data), 9))
####################################################################################
def test_degrees():
value = np.abs(np.random.rand(1).item()) * 2 * np.pi
assert np.round(NumCpp.degreesScaler(value), 9) == np.round(np.degrees(value), 9)
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArray(shape)
data = np.random.rand(shape.rows, shape.cols) * 2 * np.pi
cArray.setArray(data)
assert np.array_equal(np.round(NumCpp.degreesArray(cArray), 9), np.round(np.degrees(data), 9))
####################################################################################
def test_deleteIndices():
shapeInput = np.asarray([100, 100])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArray(shape)
data = np.random.randint(1, 100, [shape.rows, shape.cols])
indices = NumCpp.Slice(0, 100, 4)
indicesPy = slice(0, 99, 4)
cArray.setArray(data)
assert np.array_equal(NumCpp.deleteIndicesSlice(cArray, indices, NumCpp.Axis.NONE).flatten(),
np.delete(data, indicesPy, axis=None))
shapeInput = np.asarray([100, 100])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArray(shape)
data = np.random.randint(1, 100, [shape.rows, shape.cols])
indices = NumCpp.Slice(0, 100, 4)
indicesPy = slice(0, 99, 4)
cArray.setArray(data)
assert np.array_equal(NumCpp.deleteIndicesSlice(cArray, indices, NumCpp.Axis.ROW),
np.delete(data, indicesPy, axis=0))
shapeInput = np.asarray([100, 100])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArray(shape)
data = np.random.randint(1, 100, [shape.rows, shape.cols])
indices = NumCpp.Slice(0, 100, 4)
indicesPy = slice(0, 99, 4)
cArray.setArray(data)
assert np.array_equal(NumCpp.deleteIndicesSlice(cArray, indices, NumCpp.Axis.COL),
np.delete(data, indicesPy, axis=1))
shapeInput = np.asarray([100, 100])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArray(shape)
data = np.random.randint(1, 100, [shape.rows, shape.cols])
index = np.random.randint(0, shape.size(), [1, ]).item()
cArray.setArray(data)
assert np.array_equal(NumCpp.deleteIndicesScaler(cArray, index, NumCpp.Axis.NONE).flatten(),
np.delete(data, index, axis=None))
shapeInput = np.asarray([100, 100])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArray(shape)
data = np.random.randint(1, 100, [shape.rows, shape.cols])
index = np.random.randint(0, 100, [1, ]).item()
cArray.setArray(data)
assert np.array_equal(NumCpp.deleteIndicesScaler(cArray, index, NumCpp.Axis.ROW), np.delete(data, index, axis=0))
shapeInput = np.asarray([100, 100])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArray(shape)
data = np.random.randint(1, 100, [shape.rows, shape.cols])
index = np.random.randint(0, 100, [1, ]).item()
cArray.setArray(data)
assert np.array_equal(NumCpp.deleteIndicesScaler(cArray, index, NumCpp.Axis.COL), np.delete(data, index, axis=1))
####################################################################################
def test_diag():
shapeInput = np.random.randint(2, 25, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
k = np.random.randint(0, np.min(shapeInput), [1, ]).item()
elements = np.random.randint(1, 100, shapeInput)
cElements = NumCpp.NdArray(shape)
cElements.setArray(elements)
assert np.array_equal(NumCpp.diag(cElements, k).flatten(), np.diag(elements, k))
shapeInput = np.random.randint(2, 25, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
k = np.random.randint(0, np.min(shapeInput), [1, ]).item()
real = np.random.randint(1, 100, [shape.rows, shape.cols])
imag = np.random.randint(1, 100, [shape.rows, shape.cols])
elements = real + 1j * imag
cElements = NumCpp.NdArrayComplexDouble(shape)
cElements.setArray(elements)
assert np.array_equal(NumCpp.diag(cElements, k).flatten(), np.diag(elements, k))
####################################################################################
def test_diagflat():
numElements = np.random.randint(2, 25, [1, ]).item()
shape = NumCpp.Shape(1, numElements)
k = np.random.randint(0, 10, [1, ]).item()
elements = np.random.randint(1, 100, [numElements, ])
cElements = NumCpp.NdArray(shape)
cElements.setArray(elements)
assert np.array_equal(NumCpp.diagflat(cElements, k), np.diagflat(elements, k))
numElements = np.random.randint(2, 25, [1, ]).item()
shape = NumCpp.Shape(1, numElements)
k = np.random.randint(0, 10, [1, ]).item()
real = np.random.randint(1, 100, [numElements, ])
imag = np.random.randint(1, 100, [numElements, ])
elements = real + 1j * imag
cElements = NumCpp.NdArrayComplexDouble(shape)
cElements.setArray(elements)
assert np.array_equal(NumCpp.diagflat(cElements, k), np.diagflat(elements, k))
numElements = np.random.randint(1, 25, [1, ]).item()
shape = NumCpp.Shape(1, numElements)
k = np.random.randint(0, 10, [1, ]).item()
elements = np.random.randint(1, 100, [numElements, ])
cElements = NumCpp.NdArray(shape)
cElements.setArray(elements)
assert np.array_equal(NumCpp.diagflat(cElements, k), np.diagflat(elements, k))
numElements = np.random.randint(1, 25, [1, ]).item()
shape = NumCpp.Shape(1, numElements)
k = np.random.randint(0, 10, [1, ]).item()
real = np.random.randint(1, 100, [numElements, ])
imag = np.random.randint(1, 100, [numElements, ])
elements = real + 1j * imag
cElements = NumCpp.NdArrayComplexDouble(shape)
cElements.setArray(elements)
assert np.array_equal(NumCpp.diagflat(cElements, k), np.diagflat(elements, k))
####################################################################################
def test_diagonal():
shapeInput = np.random.randint(1, 50, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArray(shape)
data = np.random.randint(1, 50, [shape.rows, shape.cols])
cArray.setArray(data)
offset = np.random.randint(0, min(shape.rows, shape.cols), [1, ]).item()
assert np.array_equal(NumCpp.diagonal(cArray, offset, NumCpp.Axis.ROW).flatten(),
np.diagonal(data, offset, axis1=0, axis2=1))
shapeInput = np.random.randint(1, 50, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArrayComplexDouble(shape)
real = np.random.randint(1, 50, [shape.rows, shape.cols])
imag = np.random.randint(1, 50, [shape.rows, shape.cols])
data = real + 1j * imag
cArray.setArray(data)
offset = np.random.randint(0, min(shape.rows, shape.cols), [1, ]).item()
assert np.array_equal(NumCpp.diagonal(cArray, offset, NumCpp.Axis.ROW).flatten(),
np.diagonal(data, offset, axis1=0, axis2=1))
shapeInput = np.random.randint(1, 50, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArray(shape)
data = np.random.randint(1, 50, [shape.rows, shape.cols])
cArray.setArray(data)
offset = np.random.randint(0, min(shape.rows, shape.cols), [1, ]).item()
assert np.array_equal(NumCpp.diagonal(cArray, offset, NumCpp.Axis.COL).flatten(),
np.diagonal(data, offset, axis1=1, axis2=0))
shapeInput = np.random.randint(1, 50, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArrayComplexDouble(shape)
real = np.random.randint(1, 50, [shape.rows, shape.cols])
imag = np.random.randint(1, 50, [shape.rows, shape.cols])
data = real + 1j * imag
cArray.setArray(data)
offset = np.random.randint(0, min(shape.rows, shape.cols), [1, ]).item()
assert np.array_equal(NumCpp.diagonal(cArray, offset, NumCpp.Axis.COL).flatten(),
np.diagonal(data, offset, axis1=1, axis2=0))
####################################################################################
def test_diff():
shapeInput = np.random.randint(10, 50, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArray(shape)
data = np.random.randint(1, 50, [shape.rows, shape.cols])
cArray.setArray(data)
assert np.array_equal(NumCpp.diff(cArray, NumCpp.Axis.NONE).flatten(),
np.diff(data.flatten()))
shapeInput = np.random.randint(10, 50, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArrayComplexDouble(shape)
real = np.random.randint(1, 50, [shape.rows, shape.cols])
imag = np.random.randint(1, 50, [shape.rows, shape.cols])
data = real + 1j * imag
cArray.setArray(data)
assert np.array_equal(NumCpp.diff(cArray, NumCpp.Axis.NONE).flatten(),
np.diff(data.flatten()))
shapeInput = np.random.randint(10, 50, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArray(shape)
data = np.random.randint(1, 50, [shape.rows, shape.cols])
cArray.setArray(data)
assert np.array_equal(NumCpp.diff(cArray, NumCpp.Axis.ROW), np.diff(data, axis=0))
shapeInput = np.random.randint(10, 50, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArrayComplexDouble(shape)
real = np.random.randint(1, 50, [shape.rows, shape.cols])
imag = np.random.randint(1, 50, [shape.rows, shape.cols])
data = real + 1j * imag
cArray.setArray(data)
assert np.array_equal(NumCpp.diff(cArray, NumCpp.Axis.ROW), np.diff(data, axis=0))
shapeInput = np.random.randint(10, 50, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArray(shape)
data = np.random.randint(1, 50, [shape.rows, shape.cols]).astype(np.uint32)
cArray.setArray(data)
assert np.array_equal(NumCpp.diff(cArray, NumCpp.Axis.COL).astype(np.uint32), np.diff(data, axis=1))
shapeInput = np.random.randint(10, 50, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArrayComplexDouble(shape)
real = np.random.randint(1, 50, [shape.rows, shape.cols])
imag = np.random.randint(1, 50, [shape.rows, shape.cols])
data = real + 1j * imag
cArray.setArray(data)
assert np.array_equal(NumCpp.diff(cArray, NumCpp.Axis.COL), np.diff(data, axis=1))
####################################################################################
def test_divide():
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray1 = NumCpp.NdArray(shape)
cArray2 = NumCpp.NdArray(shape)
data1 = np.random.randint(-100, 100, [shape.rows, shape.cols])
data2 = np.random.randint(-100, 100, [shape.rows, shape.cols])
data2[data2 == 0] = 1
cArray1.setArray(data1)
cArray2.setArray(data2)
assert np.array_equal(np.round(NumCpp.divide(cArray1, cArray2), 9),
np.round(data1 / data2, 9))
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArray(shape)
data = np.random.randint(-100, 100, [shape.rows, shape.cols])
cArray.setArray(data)
value = 0
while value == 0:
value = np.random.randint(-100, 100)
assert np.array_equal(np.round(NumCpp.divide(cArray, value), 9),
np.round(data / value, 9))
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArray(shape)
data = np.random.randint(-100, 100, [shape.rows, shape.cols])
data[data == 0] = 1
cArray.setArray(data)
value = np.random.randint(-100, 100)
assert np.array_equal(np.round(NumCpp.divide(value, cArray), 9),
np.round(value / data, 9))
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray1 = NumCpp.NdArrayComplexDouble(shape)
cArray2 = NumCpp.NdArrayComplexDouble(shape)
real1 = np.random.randint(1, 100, [shape.rows, shape.cols])
imag1 = np.random.randint(1, 100, [shape.rows, shape.cols])
data1 = real1 + 1j * imag1
real2 = np.random.randint(1, 100, [shape.rows, shape.cols])
imag2 = np.random.randint(1, 100, [shape.rows, shape.cols])
data2 = real2 + 1j * imag2
data2[data2 == complex(0)] = complex(1)
cArray1.setArray(data1)
cArray2.setArray(data2)
assert np.array_equal(np.round(NumCpp.divide(cArray1, cArray2), 9),
np.round(data1 / data2, 9))
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArrayComplexDouble(shape)
real = np.random.randint(1, 100, [shape.rows, shape.cols])
imag = np.random.randint(1, 100, [shape.rows, shape.cols])
data = real + 1j * imag
cArray.setArray(data)
value = 0
while value == complex(0):
value = np.random.randint(-100, 100) + 1j * np.random.randint(-100, 100)
assert np.array_equal(np.round(NumCpp.divide(cArray, value), 9),
np.round(data / value, 9))
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArrayComplexDouble(shape)
real = np.random.randint(1, 100, [shape.rows, shape.cols])
imag = np.random.randint(1, 100, [shape.rows, shape.cols])
data = real + 1j * imag
data[data == complex(0)] = complex(1)
cArray.setArray(data)
value = np.random.randint(-100, 100) + 1j * np.random.randint(-100, 100)
assert np.array_equal(np.round(NumCpp.divide(value, cArray), 9),
np.round(value / data, 9))
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray1 = NumCpp.NdArrayComplexDouble(shape)
cArray2 = NumCpp.NdArray(shape)
real1 = np.random.randint(1, 100, [shape.rows, shape.cols])
imag1 = np.random.randint(1, 100, [shape.rows, shape.cols])
data1 = real1 + 1j * imag1
data2 = np.random.randint(1, 100, [shape.rows, shape.cols])
data2[data2 == 0] = 1
cArray1.setArray(data1)
cArray2.setArray(data2)
assert np.array_equal(np.round(NumCpp.divide(cArray1, cArray2), 9),
np.round(data1 / data2, 9))
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray1 = NumCpp.NdArray(shape)
cArray2 = NumCpp.NdArrayComplexDouble(shape)
data1 = np.random.randint(1, 100, [shape.rows, shape.cols])
real2 = np.random.randint(1, 100, [shape.rows, shape.cols])
imag2 = np.random.randint(1, 100, [shape.rows, shape.cols])
data2 = real2 + 1j * imag2
data2[data2 == complex(0)] = complex(1)
cArray1.setArray(data1)
cArray2.setArray(data2)
assert np.array_equal(np.round(NumCpp.divide(cArray1, cArray2), 9),
np.round(data1 / data2, 9))
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArray(shape)
data = np.random.randint(-100, 100, [shape.rows, shape.cols])
cArray.setArray(data)
while value == complex(0):
value = np.random.randint(-100, 100) + 1j * np.random.randint(-100, 100)
assert np.array_equal(np.round(NumCpp.divide(cArray, value), 9),
np.round(data / value, 9))
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArray(shape)
data = np.random.randint(-100, 100, [shape.rows, shape.cols])
data[data == 0] = 1
cArray.setArray(data)
value = np.random.randint(-100, 100) + 1j * np.random.randint(-100, 100)
assert np.array_equal(np.round(NumCpp.divide(value, cArray), 9),
np.round(value / data, 9))
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArrayComplexDouble(shape)
real = np.random.randint(1, 100, [shape.rows, shape.cols])
imag = np.random.randint(1, 100, [shape.rows, shape.cols])
data = real + 1j * imag
cArray.setArray(data)
value = 0
while value == 0:
value = np.random.randint(-100, 100)
assert np.array_equal(np.round(NumCpp.divide(cArray, value), 9),
np.round(data / value, 9))
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArrayComplexDouble(shape)
real = np.random.randint(1, 100, [shape.rows, shape.cols])
imag = np.random.randint(1, 100, [shape.rows, shape.cols])
data = real + 1j * imag
data[data == complex(0)] = complex(1)
cArray.setArray(data)
value = np.random.randint(-100, 100)
assert np.array_equal(np.round(NumCpp.divide(value, cArray), 9),
np.round(value / data, 9))
####################################################################################
def test_dot():
size = np.random.randint(1, 100, [1, ]).item()
shape = NumCpp.Shape(1, size)
cArray1 = NumCpp.NdArray(shape)
cArray2 = NumCpp.NdArray(shape)
data1 = np.random.randint(1, 50, [shape.rows, shape.cols])
data2 = np.random.randint(1, 50, [shape.rows, shape.cols])
cArray1.setArray(data1)
cArray2.setArray(data2)
assert NumCpp.dot(cArray1, cArray2).item() == np.dot(data1, data2.T).item()
size = np.random.randint(1, 100, [1, ]).item()
shape = NumCpp.Shape(1, size)
cArray1 = NumCpp.NdArray(shape)
cArray2 = NumCpp.NdArrayComplexDouble(shape)
data1 = np.random.randint(1, 50, [shape.rows, shape.cols])
real2 = np.random.randint(1, 50, [shape.rows, shape.cols])
imag2 = np.random.randint(1, 50, [shape.rows, shape.cols])
data2 = real2 + 1j * imag2
cArray1.setArray(data1)
cArray2.setArray(data2)
assert NumCpp.dot(cArray1, cArray2).item() == np.dot(data1, data2.T).item()
size = np.random.randint(1, 100, [1, ]).item()
shape = NumCpp.Shape(1, size)
cArray1 = NumCpp.NdArrayComplexDouble(shape)
cArray2 = NumCpp.NdArrayComplexDouble(shape)
real1 = np.random.randint(1, 50, [shape.rows, shape.cols])
imag1 = np.random.randint(1, 50, [shape.rows, shape.cols])
data1 = real1 + 1j * imag1
real2 = np.random.randint(1, 50, [shape.rows, shape.cols])
imag2 = np.random.randint(1, 50, [shape.rows, shape.cols])
data2 = real2 + 1j * imag2
cArray1.setArray(data1)
cArray2.setArray(data2)
assert NumCpp.dot(cArray1, cArray2).item() == np.dot(data1, data2.T).item()
size = np.random.randint(1, 100, [1, ]).item()
shape = NumCpp.Shape(1, size)
cArray1 = NumCpp.NdArrayComplexDouble(shape)
cArray2 = NumCpp.NdArray(shape)
real1 = np.random.randint(1, 50, [shape.rows, shape.cols])
imag1 = np.random.randint(1, 50, [shape.rows, shape.cols])
data1 = real1 + 1j * imag1
data2 = np.random.randint(1, 50, [shape.rows, shape.cols])
cArray1.setArray(data1)
cArray2.setArray(data2)
assert NumCpp.dot(cArray1, cArray2).item() == np.dot(data1, data2.T).item()
shapeInput = np.random.randint(1, 100, [2, ])
shape1 = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
shape2 = NumCpp.Shape(shapeInput[1].item(), np.random.randint(1, 100, [1, ]).item())
cArray1 = NumCpp.NdArray(shape1)
cArray2 = NumCpp.NdArray(shape2)
data1 = np.random.randint(1, 50, [shape1.rows, shape1.cols])
data2 = np.random.randint(1, 50, [shape2.rows, shape2.cols])
cArray1.setArray(data1)
cArray2.setArray(data2)
assert np.array_equal(NumCpp.dot(cArray1, cArray2), np.dot(data1, data2))
shapeInput = np.random.randint(1, 100, [2, ])
shape1 = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
shape2 = NumCpp.Shape(shapeInput[1].item(), np.random.randint(1, 100, [1, ]).item())
cArray1 = NumCpp.NdArrayComplexDouble(shape1)
cArray2 = NumCpp.NdArrayComplexDouble(shape2)
real1 = np.random.randint(1, 50, [shape1.rows, shape1.cols])
imag1 = np.random.randint(1, 50, [shape1.rows, shape1.cols])
data1 = real1 + 1j * imag1
real2 = np.random.randint(1, 50, [shape2.rows, shape2.cols])
imag2 = np.random.randint(1, 50, [shape2.rows, shape2.cols])
data2 = real2 + 1j * imag2
cArray1.setArray(data1)
cArray2.setArray(data2)
assert np.array_equal(NumCpp.dot(cArray1, cArray2), np.dot(data1, data2))
####################################################################################
def test_empty():
shapeInput = np.random.randint(1, 100, [2, ])
cArray = NumCpp.emptyRowCol(shapeInput[0].item(), shapeInput[1].item())
assert cArray.shape[0] == shapeInput[0]
assert cArray.shape[1] == shapeInput[1]
assert cArray.size == shapeInput.prod()
shapeInput = np.random.randint(1, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.emptyShape(shape)
assert cArray.shape[0] == shape.rows
assert cArray.shape[1] == shape.cols
assert cArray.size == shapeInput.prod()
shapeInput = np.random.randint(1, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray1 = NumCpp.NdArray(shape)
cArray2 = NumCpp.empty_like(cArray1)
assert cArray2.shape().rows == shape.rows
assert cArray2.shape().cols == shape.cols
assert cArray2.size() == shapeInput.prod()
####################################################################################
def test_endianess():
shapeInput = np.random.randint(1, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArray(shape)
assert NumCpp.endianess(cArray) == NumCpp.Endian.NATIVE
####################################################################################
def test_equal():
shapeInput = np.random.randint(1, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray1 = NumCpp.NdArray(shape)
cArray2 = NumCpp.NdArray(shape)
data1 = np.random.randint(0, 10, [shape.rows, shape.cols])
data2 = np.random.randint(0, 10, [shape.rows, shape.cols])
cArray1.setArray(data1)
cArray2.setArray(data2)
assert np.array_equal(NumCpp.equal(cArray1, cArray2), np.equal(data1, data2))
shapeInput = np.random.randint(1, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray1 = NumCpp.NdArrayComplexDouble(shape)
cArray2 = NumCpp.NdArrayComplexDouble(shape)
real1 = np.random.randint(1, 100, [shape.rows, shape.cols])
imag1 = np.random.randint(1, 100, [shape.rows, shape.cols])
data1 = real1 + 1j * imag1
real2 = np.random.randint(1, 100, [shape.rows, shape.cols])
imag2 = np.random.randint(1, 100, [shape.rows, shape.cols])
data2 = real2 + 1j * imag2
cArray1.setArray(data1)
cArray2.setArray(data2)
assert np.array_equal(NumCpp.equal(cArray1, cArray2), np.equal(data1, data2))
####################################################################################
def test_exp2():
value = np.abs(np.random.rand(1).item())
assert np.round(NumCpp.expScaler(value), 9) == np.round(np.exp(value), 9)
components = np.random.rand(2).astype(np.double)
value = complex(components[0], components[1])
assert np.round(NumCpp.expScaler(value), 9) == np.round(np.exp(value), 9)
value = np.abs(np.random.rand(1).item())
assert np.round(NumCpp.exp2Scaler(value), 9) == np.round(np.exp2(value), 9)
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArray(shape)
data = np.random.rand(shape.rows, shape.cols)
cArray.setArray(data)
assert np.array_equal(np.round(NumCpp.exp2Array(cArray), 9), np.round(np.exp2(data), 9))
####################################################################################
def test_exp():
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArray(shape)
data = np.random.rand(shape.rows, shape.cols)
cArray.setArray(data)
assert np.array_equal(np.round(NumCpp.expArray(cArray), 9), np.round(np.exp(data), 9))
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArrayComplexDouble(shape)
data = np.random.rand(shape.rows, shape.cols) + 1j * np.random.rand(shape.rows, shape.cols)
cArray.setArray(data)
assert np.array_equal(np.round(NumCpp.expArray(cArray), 9), np.round(np.exp(data), 9))
value = np.abs(np.random.rand(1).item())
assert np.round(NumCpp.expm1Scaler(value), 9) == np.round(np.expm1(value), 9)
components = np.random.rand(2).astype(np.double)
value = complex(components[0], components[1])
assert np.round(NumCpp.expm1Scaler(value), 9) == np.round(np.expm1(value), 9)
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArray(shape)
data = np.random.rand(shape.rows, shape.cols)
cArray.setArray(data)
assert np.array_equal(np.round(NumCpp.expm1Array(cArray), 9), np.round(np.expm1(data), 9))
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArrayComplexDouble(shape)
real = np.random.rand(shape.rows, shape.cols)
imag = np.random.rand(shape.rows, shape.cols)
data = real + 1j * imag
cArray.setArray(data)
assert np.array_equal(np.round(NumCpp.expm1Array(cArray), 9), np.round(np.expm1(data), 9))
####################################################################################
def test_eye():
shapeInput = np.random.randint(1, 100, [1, ]).item()
randK = np.random.randint(0, shapeInput, [1, ]).item()
assert np.array_equal(NumCpp.eye1D(shapeInput, randK), np.eye(shapeInput, k=randK))
shapeInput = np.random.randint(1, 100, [1, ]).item()
randK = np.random.randint(0, shapeInput, [1, ]).item()
assert np.array_equal(NumCpp.eye1DComplex(shapeInput, randK),
np.eye(shapeInput, k=randK) + 1j * np.zeros([shapeInput, shapeInput]))
shapeInput = np.random.randint(10, 100, [2, ])
randK = np.random.randint(0, np.min(shapeInput), [1, ]).item()
assert np.array_equal(NumCpp.eye2D(shapeInput[0].item(), shapeInput[1].item(), randK),
np.eye(shapeInput[0].item(), shapeInput[1].item(), k=randK))
shapeInput = np.random.randint(10, 100, [2, ])
randK = np.random.randint(0, np.min(shapeInput), [1, ]).item()
assert np.array_equal(NumCpp.eye2DComplex(shapeInput[0].item(), shapeInput[1].item(), randK),
np.eye(shapeInput[0].item(), shapeInput[1].item(), k=randK) +
1j * np.zeros(shapeInput))
shapeInput = np.random.randint(10, 100, [2, ])
cShape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
randK = np.random.randint(0, np.min(shapeInput), [1, ]).item()
assert np.array_equal(NumCpp.eyeShape(cShape, randK), np.eye(shapeInput[0].item(), shapeInput[1].item(), k=randK))
shapeInput = np.random.randint(10, 100, [2, ])
cShape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
randK = np.random.randint(0, np.min(shapeInput), [1, ]).item()
assert np.array_equal(NumCpp.eyeShapeComplex(cShape, randK),
np.eye(shapeInput[0].item(), shapeInput[1].item(), k=randK) +
1j * np.zeros(shapeInput))
####################################################################################
def test_fill_diagonal():
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArray(shape)
data = np.random.randn(shape.rows, shape.cols) * 100
cArray.setArray(data)
NumCpp.fillDiagonal(cArray, 666)
np.fill_diagonal(data, 666)
assert np.array_equal(cArray.getNumpyArray(), data)
####################################################################################
def test_find():
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArray(shape)
data = np.random.randn(shape.rows, shape.cols) * 100
cArray.setArray(data)
value = data.mean()
cMask = NumCpp.operatorGreater(cArray, value)
cMaskArray = NumCpp.NdArrayBool(cMask.shape[0], cMask.shape[1])
cMaskArray.setArray(cMask)
idxs = NumCpp.find(cMaskArray).astype(np.int64)
idxsPy = np.nonzero((data > value).flatten())[0]
assert np.array_equal(idxs.flatten(), idxsPy)
####################################################################################
def test_findN():
shapeInput = np.random.randint(20, 100, [2, ])
shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item())
cArray = NumCpp.NdArray(shape)
data = np.random.randn(shape.rows, shape.cols) * 100
cArray.setArray(data)
value = data.mean()
cMask = NumCpp.operatorGreater(cArray, value)
cMaskArray = NumCpp.NdArrayBool(cMask.shape[0], cMask.shape[1])
cMaskArray.setArray(cMask)
idxs = NumCpp.findN(cMaskArray, 8).astype(np.int64)
idxsPy = np.nonzero((data > value).flatten())[0]
assert np.array_equal(idxs.flatten(), idxsPy[:8])
####################################################################################
def fix():
value = np.random.randn(1).item() * 100
assert NumCpp.fixScaler(value) == | np.fix(value) | numpy.fix |
from __future__ import print_function, division
import os
import numpy as np
from . import get_data_home
from . import fetch_sdss_S82standards
from .tools import download_with_progress_bar
DATA_URL = ("https://github.com/astroML/astroML-data/raw/master/datasets/"
"RRLyrae.fit")
def fetch_rrlyrae_mags(data_home=None, download_if_missing=True):
"""Loader for RR-Lyrae data
Parameters
----------
data_home : optional, default=None
Specify another download and cache folder for the datasets. By default
all astroML data is stored in '~/astroML_data'.
download_if_missing : optional, default=True
If False, raise a IOError if the data is not locally available
instead of trying to download the data from the source site.
Returns
-------
data : recarray, shape = (483,)
record array containing imaging data
Examples
--------
>>> from astroML.datasets import fetch_rrlyrae_mags
>>> data = fetch_rrlyrae_mags() # doctest: +IGNORE_OUTPUT
>>> data.shape # number of objects in dataset
(483,)
Notes
-----
This data is from table 1 of Sesar et al 2010 ApJ 708:717
"""
# fits is an optional dependency: don't import globally
from astropy.io import fits
data_home = get_data_home(data_home)
archive_file = os.path.join(data_home, os.path.basename(DATA_URL))
if not os.path.exists(archive_file):
if not download_if_missing:
raise IOError('data not present on disk. '
'set download_if_missing=True to download')
fitsdata = download_with_progress_bar(DATA_URL)
open(archive_file, 'wb').write(fitsdata)
hdulist = fits.open(archive_file)
return np.asarray(hdulist[1].data)
def fetch_rrlyrae_combined(data_home=None, download_if_missing=True):
"""Loader for RR-Lyrae combined data
This returns the combined RR-Lyrae colors and SDSS standards colors.
The RR-Lyrae sample is confirmed through time-domain observations;
this result in a nice dataset for testing classification routines.
Parameters
----------
data_home : optional, default=None
Specify another download and cache folder for the datasets. By default
all astroML data is stored in '~/astroML_data'.
download_if_missing : optional, default=True
If False, raise a IOError if the data is not locally available
instead of trying to download the data from the source site.
Returns
-------
X : ndarray
a shape (n_samples, 4) array. Columns are u-g, g-r, r-i, i-z
y : ndarray
a shape (n_samples,) array of labels. 1 indicates an RR Lyrae,
0 indicates a background star.
"""
# ----------------------------------------------------------------------
# Load data
kwds = dict(data_home=data_home,
download_if_missing=download_if_missing)
rrlyrae = fetch_rrlyrae_mags(**kwds)
standards = fetch_sdss_S82standards(**kwds)
# ------------------------------------------------------------
# perform color cuts on standard stars
# these come from eqns 1-4 of Sesar et al 2010, ApJ 708:717
u_g = standards['mmu_u'] - standards['mmu_g']
g_r = standards['mmu_g'] - standards['mmu_r']
r_i = standards['mmu_r'] - standards['mmu_i']
i_z = standards['mmu_i'] - standards['mmu_z']
standards = standards[(u_g > 0.7) & (u_g < 1.35) &
(g_r > -0.15) & (g_r < 0.4) &
(r_i > -0.15) & (r_i < 0.22) &
(i_z > -0.21) & (i_z < 0.25)]
# ----------------------------------------------------------------------
# get magnitudes and colors; split into train and test sets
mags_rr = | np.vstack([rrlyrae[f + 'mag'] for f in 'ugriz']) | numpy.vstack |
import pytest
import numpy as np
from qibo import K
from numpy.random import random as rand
METHODS = [
("to_complex", [rand(3), rand(3)]),
("cast", [rand(4)]),
("diag", [rand(4)]),
("copy", [rand(5)]),
("zeros_like", [rand((4, 4))]),
("ones_like", [rand((4, 4))]),
("real", [rand(5)]),
("imag", [rand(5)]),
("conj", [rand(5)]),
("exp", [rand(5)]),
("sin", [rand(5)]),
("cos", [rand(5)]),
("square", [rand(5)]),
("sqrt", [rand(5)]),
("log", [rand(5)]),
("abs", [rand(5)]),
("trace", [rand((6, 6))]),
("sum", [rand((4, 4))]),
("matmul", [rand((4, 6)), rand((6, 5))]),
("outer", [rand((4,)), rand((3,))]),
("eigvalsh", [rand((4, 4))]),
("less", [rand(10), rand(10)]),
("array_equal", [ | rand(10) | numpy.random.random |
import sys
import numpy as np
from scipy.stats import multivariate_normal
from sklearn.base import BaseEstimator, ClassifierMixin, ClusterMixin
from sklearn.utils import check_X_y
from sklearn.utils.validation import check_array, check_is_fitted
EPS = 1e-10
FLOAT_MAX = sys.float_info.max
def normalize(v):
v_norm = np.linalg.norm(v)
if (v_norm == 0) and (EPS <= 0):
v = np.zeros_like(v)
else:
v = v / (v_norm + EPS)
return v
class ART1(BaseEstimator, ClusterMixin):
"""ART1.
Parameters
----------
max_iter : int
Maximum number of iterations of the ART2 algorithm to run.
max_class : int
Maximum number of the class to classify.
rho : float, default=0.75
Threshold for degree of match.
L : float, default=0.75
Larger values of L bias the selection of inactive nodes over active ones.
alpha : float, default=1e-5
Choice parameter.
"""
def __init__(
self,
max_iter=10,
max_class=100,
rho=0.75,
L=1.5,
alpha=1e-5):
super().__init__()
self.max_iter = max_iter
self.max_class = max_class
self.rho = rho
self.L = L
self.alpha = alpha
def _check_params(self, X):
# max_iter
if self.max_iter <= 0:
raise ValueError(
f"max_iter must be > 0, got {self.max_iter} instead.")
# max_class
if self.max_class <= 0:
raise ValueError(
f"max_class must be > 0, got {self.max_class} instead.")
# rho
if not (0.0 < self.rho < 1.0):
raise ValueError(
f"rho must be in range (0, 1), got {self.rho} instead.")
# L
if self.L <= 0:
raise ValueError(
f"L must be > 0, got {self.L} instead.")
# alpha
if self.alpha <= 0:
raise ValueError(
f"alpha must be > 0, got {self.alpha} instead.")
def _initialize(self, X):
self.history_ = {"gap": [], "similarity": []}
self._n_features = X.shape[1]
self._b = np.ones((self.max_class, self._n_features)) * \
self.L / (self.L - 1 + self._n_features) * 0.5
self._t = np.ones((self.max_class, self._n_features))
self._active_list = [False] * self.max_class
def fit(self, X):
"""Compute ART1 clustering.
Parameters
----------
X : array-like of shape (n_samples, n_features)
Training instances to cluster.
Returns
-------
self
Fitted estimator.
"""
X = check_array(X)
self._check_params(X)
self._initialize(X)
for _ in range(self.max_iter):
y = self._resonance_iter(X)
self.labels_ = y
return self
def partial_fit_predict(self, X):
check_is_fitted(self)
self.labels_ = self._resonance_iter(X)
return self.labels_
def predict(self, X):
"""Predict the closest cluster each sample in X belongs to.
Parameters
----------
X : array-like of shape (n_samples, n_features)
New data to predict.
Returns
-------
labels : ndarray of shape (n_samples,)
Index of the cluster each sample belongs to.
Returns -1 label if the match class does not exist.
"""
check_is_fitted(self)
X = check_array(X)
return self._resonance_iter(X, should_update=False)
def _resonance_iter(self, X, should_update=True):
y = -1 * np.ones(X.shape[0], dtype=np.int32)
for idx, s in enumerate(X):
# F1
T = np.sum(s * self._b, axis=1) / \
(self.alpha + np.sum(self._b, axis=1))
# Search match
for _ in range(self.max_class):
# F2 : Code selection
J = np.argmax(T)
# similarity = How much s is contained in t
similarity = np.sum(s * self._t[J]) / (self.alpha + np.sum(s))
# Match
if (not self._active_list[J]) or (similarity >= self.rho):
if should_update:
y[idx] = J
# Updata parameters
self._b[J] = self.L * s * self._t[J] / \
(self.L - 1 + np.sum(s * self._t[J]))
self._t[J] = s * self._t[J]
gap = np.mean(np.abs(self._b - self._t))
# logging
self.history_["gap"].append(gap)
self.history_["similarity"].append(similarity)
self._active_list[J] = True
else:
if self._active_list[J]:
y[idx] = J
break
# Do not match
else:
T[J] = 0
continue
return y
class ART2(BaseEstimator, ClusterMixin):
"""ART2.
Parameters
----------
max_iter : int, default=10
Maximum number of iterations of the ART2 algorithm to run.
max_class : int, default=100
Maximum number of the class to classify.
rho : float, default=0.95
Threshold for degree of match.
a : float, default=0.1
Degree of retaining memory of previous data.
b : float, default=0.1
Degree of retaining memory of the last classified class.
c : float, default=0.1
Control the range of degree of match.
d : float, default=0.9
Learning rata..
theta : float, default=0.0
Noise reduction threshold for normalized data.
alpha : float, default=None
Initialization factor of LTM Trace.
"""
def __init__(
self,
max_iter=10,
max_class=100,
rho=0.95,
a=0.1,
b=0.1,
c=0.1,
d=0.9,
theta=0.0,
alpha=None):
super().__init__()
self.max_iter = max_iter
self.max_class = max_class
self.rho = rho
self.a = a
self.b = b
self.c = c
self.d = d
self.theta = theta
self.alpha = alpha
self._big_m = 1
def _check_params(self, X):
# max_iter
if self.max_iter <= 0:
raise ValueError(
f"max_iter must be > 0, got {self.max_iter} instead.")
# max_class
if self.max_class <= 0:
raise ValueError(
f"max_class must be > 0, got {self.max_class} instead.")
# rho
if not (0.0 < self.rho < 1.0):
raise ValueError(
f"rho must be in range (0, 1), got {self.rho} instead.")
# a
if self.a < 0:
raise ValueError(
f"a must be >= 0, got {self.a} instead.")
# b
if self.b < 0:
raise ValueError(
f"b must be >= 0, got {self.b} instead.")
# c
if self.c <= 0:
raise ValueError(
f"c must be > 0, got {self.c} instead.")
# d
if not (0.0 < self.d < 1.0):
raise ValueError(
f"d must be in range (0, 1), got {self.d} instead.")
# theta
if not (0.0 <= self.theta < 1.0):
raise ValueError(
f"theta must be in range [0, 1), got {self.theta} instead.")
# alpha
alpha = 1 / ((1 - self.d) * X.shape[1]**0.5)
if self.alpha is None:
self.alpha = alpha
elif not (0.0 < self.theta < alpha):
raise ValueError(
f"theta must be in range (0, 1/((1-d)*sqrt(M)) ), got {self.alpha} instead.")
# constraint check
sigma = self.c * self.d / (1 - self.d)
if sigma > 1:
raise ValueError(
f"cd/(1-d) must be <= 1, got {sigma} instead.")
def _initialize(self, X):
self.history_ = {"gap": [], "r_norm": []}
self._n_features = X.shape[1]
self._u = np.zeros(self._n_features)
self._p = np.zeros(self._n_features)
self._z = self.alpha * np.ones((self._n_features, self.max_class))
self._active_list = [False] * self.max_class
def fit(self, X):
"""Compute ART2 clustering.
Parameters
----------
X : array-like of shape (n_samples, n_features)
Training instances to cluster.
Returns
-------
self
Fitted estimator.
"""
# validation
X = check_array(X)
self._check_params(X)
self._initialize(X)
# learning
for _ in range(self.max_iter):
y = self._resonance_iter(X)
self.labels_ = y
return self
def partial_fit_predict(self, X):
check_is_fitted(self)
self.labels_ = self._resonance_iter(X)
return self.labels_
def predict(self, X):
"""Predict the closest cluster each sample in X belongs to.
Parameters
----------
X : array-like of shape (n_samples, n_features)
New data to predict.
Returns
-------
labels : ndarray of shape (n_samples,)
Index of the cluster each sample belongs to.
Returns -1 label if the match class does not exist.
"""
check_is_fitted(self)
X = check_array(X)
return self._resonance_iter(X, should_update=False)
def _resonance_iter(self, X, should_update=True):
y = -1 * np.ones(X.shape[0], dtype=np.int32)
for idx, s in enumerate(X):
# F1 : Update the value of each node
w = s + self.a * self._u
x = normalize(w)
q = normalize(self._p)
v = self._activate(x) + self.b * self._activate(q)
u = normalize(v)
T = np.dot(u, self._z)
# Search match
for _ in range(self.max_class):
# F2 : Code selection
J = np.argmax(T)
# Caluculate degree of match
p = u + self.d * self._z[:, J]
r = (u + self.c * p) / \
(np.linalg.norm(u) + np.linalg.norm(self.c * p))
r_norm = np.linalg.norm(r)
# Match
if (not self._active_list[J]) or (r_norm >= self.rho):
self._u = u
self._p = p
if should_update:
y[idx] = J
# Updata parameters
z_previous = self._z.copy()
self._z[:, J] = (1 - self.d) * \
self._z[:, J] + self.d * self._p
gap = np.mean(np.abs(z_previous - self._z))
# logging
self.history_["gap"].append(gap)
self.history_["r_norm"].append(r_norm)
self._active_list[J] = True
else:
if self._active_list[J]:
y[idx] = J
break
# Do not match
else:
T[J] = - self._big_m
continue
return y
def _activate(self, x):
x[np.abs(x) < self.theta] = 0
return x
class ART2A(BaseEstimator, ClusterMixin):
"""ART2-A.
Parameters
----------
max_iter : int
Maximum number of iterations of the ART2 algorithm to run.
max_class : int
Maximum number of the class to classify.
rho_star : float, default=0.95
Threshold for degree of match.
eta : float, default=0.1
Learning rata.
theta : float, default=0.0
Noise reduction threshold for normalized data.
alpha : float, default=None
Initialization factor of LTM Trace.
"""
def __init__(
self,
max_iter=10,
max_class=100,
rho_star=0.95,
eta=0.1,
theta=0.01,
alpha=None):
super().__init__()
self.max_iter = max_iter
self.max_class = max_class
self.theta = theta
self.alpha = alpha
self.eta = eta
self.rho_star = rho_star
self._big_m = 1
def _check_params(self, X):
# max_iter
if self.max_iter <= 0:
raise ValueError(
f"max_iter must be > 0, got {self.max_iter} instead.")
# max_class
if self.max_class <= 0:
raise ValueError(
f"max_class must be > 0, got {self.max_class} instead.")
# rho
if not (0.0 < self.rho_star < 1.0):
raise ValueError(
f"rho must be in range (0, 1), got {self.rho} instead.")
# eta
if not (0.0 < self.eta < 1.0):
raise ValueError(
f"eta must be in range (0, 1), got {self.eta} instead.")
# theta
if not (0.0 <= self.theta < 1.0):
raise ValueError(
f"theta must be in range [0, 1), got {self.theta} instead.")
# alpha
alpha = 1 / (X.shape[1]**0.5)
if self.alpha is None:
self.alpha = alpha
elif not (0.0 < self.theta <= alpha):
raise ValueError(
f"theta must be in range (0, 1/sqrt(M)], got {self.alpha} instead.")
def _initialize(self, X):
self.history_ = {"gap": [], "similarity": []}
self._n_features = X.shape[1]
self._z = self.alpha * np.ones((self._n_features, self.max_class))
self._active_list = [False] * self.max_class
def fit(self, X):
"""Compute ART2 clustering.
Parameters
----------
X : array-like of shape (n_samples, n_features)
Training instances to cluster.
Returns
-------
self
Fitted estimator.
"""
X = check_array(X)
self._check_params(X)
self._initialize(X)
for _ in range(self.max_iter):
y = self._resonance_iter(X)
self.labels_ = y
return self
def partial_fit_predict(self, X):
check_is_fitted(self)
self.labels_ = self._resonance_iter(X)
return self.labels_
def predict(self, X):
"""Predict the closest cluster each sample in X belongs to.
Parameters
----------
X : array-like of shape (n_samples, n_features)
New data to predict.
Returns
-------
labels : ndarray of shape (n_samples,)
Index of the cluster each sample belongs to.
Returns -1 label if the match class does not exist.
"""
check_is_fitted(self)
X = check_array(X)
return self._resonance_iter(X, should_update=False)
def _resonance_iter(self, X, should_update=True):
y = -1 * np.ones(X.shape[0], dtype=np.int32)
for idx, s in enumerate(X):
# F1 : Update the value of each node
u = normalize(self._activate(normalize(s)))
T = np.dot(u, self._z)
# Search match
for _ in range(self.max_class):
# F2 : Code selection
J = np.argmax(T)
# Match
if (not self._active_list[J]) or (T[J] >= self.rho_star):
if should_update:
y[idx] = J
# Updata parameters
z_previous = self._z.copy()
if self._active_list[J]:
psi = u.copy()
psi[self._z[:, J] <= self.theta] = 0
self._z[:, J] = normalize(
self.eta * psi + (1 - self.eta) * self._z[:, J])
else:
self._z[:, J] = u
gap = np.mean(np.abs(z_previous - self._z))
# logging
self.history_["gap"].append(gap)
self.history_["similarity"].append(T[J])
self._active_list[J] = True
else:
if self._active_list[J]:
y[idx] = J
break
# Do not match
else:
T[J] = - self._big_m
continue
return y
def _activate(self, x):
x[np.abs(x) < self.theta] = 0
return x
class FuzzyART(BaseEstimator, ClusterMixin):
"""FuzzyART.
Parameters
----------
max_iter : int
Maximum number of iterations of the ART2 algorithm to run.
max_class : int
Maximum number of the class to classify.
rho : float, default=0.75
Threshold for degree of match.
alpha : float, default=1e-5
Choice parameter.
beta : float, default=0.1
Learning rata.
"""
def __init__(
self,
max_iter=10,
max_class=100,
rho=0.75,
alpha=1e-5,
beta=0.1):
super().__init__()
self.max_iter = max_iter
self.max_class = max_class
self.rho = rho
self.alpha = alpha
self.beta = beta
self._big_m = 1
def _check_params(self, X):
# max_iter
if self.max_iter <= 0:
raise ValueError(
f"max_iter must be > 0, got {self.max_iter} instead.")
# max_class
if self.max_class <= 0:
raise ValueError(
f"max_class must be > 0, got {self.max_class} instead.")
# rho
if not (0.0 < self.rho < 1.0):
raise ValueError(
f"rho must be in range (0, 1), got {self.rho} instead.")
# alpha
if self.alpha <= 0:
raise ValueError(
f"alpha must be > 0, got {self.alpha} instead.")
# beta
if not (0.0 < self.beta < 1.0):
raise ValueError(
f"beta must be in range (0, 1), got {self.beta} instead.")
def _initialize(self, X):
self.history_ = {"gap": [], "similarity": []}
self._n_features = X.shape[1]
self._w = np.ones((self.max_class, self._n_features))
self._active_list = [False] * self.max_class
def fit(self, X):
"""Compute FuzzyART clustering.
Parameters
----------
X : array-like of shape (n_samples, n_features)
Training instances to cluster.
Returns
-------
self
Fitted estimator.
"""
X = check_array(X)
self._check_params(X)
self._initialize(X)
for _ in range(self.max_iter):
y = self._resonance_iter(X)
self.labels_ = y
return self
def partial_fit_predict(self, X):
check_is_fitted(self)
self.labels_ = self._resonance_iter(X)
return self.labels_
def predict(self, X):
"""Predict the closest cluster each sample in X belongs to.
Parameters
----------
X : array-like of shape (n_samples, n_features)
New data to predict.
Returns
-------
labels : ndarray of shape (n_samples,)
Index of the cluster each sample belongs to.
Returns -1 label if the match class does not exist.
"""
check_is_fitted(self)
X = check_array(X)
return self._resonance_iter(X, should_update=False)
def _resonance_iter(self, X, should_update=True):
y = -1 * np.ones(X.shape[0], dtype=np.int32)
for idx, s in enumerate(X):
# F1
T = np.sum(np.minimum(s, self._w), axis=1) / \
(self.alpha + np.sum(self._w, axis=1))
# Search match
for _ in range(self.max_class):
# F2 : Code selection
J = np.argmax(T)
similarity = np.sum(np.minimum(s, self._w[J])) / np.sum(s)
# Match
if (not self._active_list[J]) or (similarity >= self.rho):
if should_update:
y[idx] = J
# Updata parameters
w_previous = self._w.copy()
if self._active_list[J]:
self._w[J] = self.beta * \
np.minimum(s, self._w[J]) + (1 - self.beta) * self._w[J]
else:
self._w[J] = np.minimum(s, self._w[J])
gap = np.mean(np.abs(w_previous - self._w))
# logging
self.history_["gap"].append(gap)
self.history_["similarity"].append(similarity)
self._active_list[J] = True
else:
if self._active_list[J]:
y[idx] = J
break
# Do not match
else:
T[J] = - self._big_m
continue
return y
class SFAM(BaseEstimator, ClassifierMixin):
"""SFAM.
Parameters
----------
max_iter : int
Maximum number of iterations of the ART2 algorithm to run.
max_class : int
Maximum number of the class to classify.
rho : float, default=0.75
Threshold for degree of match.
alpha : float, default=1e-5
Choice parameter.
beta : float, default=0.1
Learning rata.
epsilon : float, default=0.0001
Paramter to increase vigilance rho.
"""
def __init__(
self,
max_iter=10,
max_class=100,
rho=0.75,
alpha=1e-5,
beta=0.1,
epsilon=0.0001):
super().__init__()
self.max_iter = max_iter
self.max_class = max_class
self.rho = rho
self.alpha = alpha
self.beta = beta
self.epsilon = epsilon
self._big_m = 1
def _check_params(self, X):
# max_iter
if self.max_iter <= 0:
raise ValueError(
f"max_iter must be > 0, got {self.max_iter} instead.")
# max_class
if self.max_class <= 0:
raise ValueError(
f"max_class must be > 0, got {self.max_class} instead.")
# rho
if not (0.0 < self.rho < 1.0):
raise ValueError(
f"rho must be in range (0, 1), got {self.rho} instead.")
# alpha
if self.alpha <= 0:
raise ValueError(
f"alpha must be > 0, got {self.alpha} instead.")
# beta
if not (0.0 < self.beta < 1.0):
raise ValueError(
f"beta must be in range (0, 1), got {self.beta} instead.")
# epsilon
if self.epsilon <= 0:
raise ValueError(
f"epsilon must be > 0, got {self.epsilon} instead.")
def _initialize(self, X):
self.history_ = {"gap": [], "similarity": []}
self._n_features = X.shape[1]
self._w = np.ones((self.max_class, self._n_features))
self._active_list = [False] * self.max_class
self._inner_label2y = dict()
def fit(self, X, y):
"""Compute SFAM clustering.
Parameters
----------
X : array-like of shape (n_samples, n_features)
Training instances to cluster.
y : array-like of shape (n_samples, )
Label vector relative to X.
Returns
-------
self
Fitted estimator.
"""
X, y = check_X_y(X, y)
self._check_params(X)
self._initialize(X)
for _ in range(self.max_iter):
self._resonance_iter(X, y)
return self
def predict(self, X):
"""Predict the closest cluster each sample in X belongs to.
Parameters
----------
X : array-like of shape (n_samples, n_features)
New data to predict.
Returns
-------
y : ndarray of shape (n_samples,)
Class labels for samples in X.
Returns -1 label if the match class does not exist.
"""
check_is_fitted(self)
X = check_array(X)
y = -1 * np.ones(X.shape[0], dtype=np.int32)
for idx, s in enumerate(X):
T = np.sum(np.minimum(s, self._w), axis=1) / \
(self.alpha + np.sum(self._w, axis=1))
for _ in range(self.max_class):
J = np.argmax(T)
similarity = np.sum(np.minimum(s, self._w[J])) / np.sum(s)
# Do resonance
if (self._active_list[J]) and (similarity >= self.rho):
# Do resonance
y[idx] = self._inner_label2y[J]
# inactive or dont resonance
else:
T[J] = - self._big_m
continue
return y
def _resonance_iter(self, X, y):
for idx, s in enumerate(X):
# F1
rho = self.rho
T = np.sum(np.minimum(s, self._w), axis=1) / \
(self.alpha + np.sum(self._w, axis=1))
w_previous = self._w.copy()
# Search match
for _ in range(self.max_class):
# Data mismatch
if rho > 1:
break
# F2 : Code selection
J = np.argmax(T)
similarity = np.sum(np.minimum(s, self._w[J])) / np.sum(s)
# active
if self._active_list[J]:
# Do resonance
if similarity >= self.rho:
# Class match
if self._inner_label2y[J] == y[idx]:
self._w[J] = self.beta * \
np.minimum(s, self._w[J]) + (1 - self.beta) * self._w[J]
break
# Class does not match
else:
T[J] = - self._big_m
rho += self.epsilon
continue
# Do not resonance
else:
T[J] = - self._big_m
continue
# inactive
else:
self._inner_label2y[J] = y[idx]
self._w[J] = np.minimum(s, self._w[J])
self._active_list[J] = True
break
else:
pass
# break then logging
gap = np.mean(np.abs(w_previous - self._w))
self.history_["gap"].append(gap)
self.history_["similarity"].append(similarity)
class BayesianART(BaseEstimator, ClusterMixin):
"""BayesianART.
Parameters
----------
max_iter : int
Maximum number of iterations of the ART2 algorithm to run.
max_class : int
Maximum number of the class to classify.
rho : float, default=0.75
Threshold for degree of match.
sigma : float, default=0.1
Choice parameter.
max_hyper_volume : float, default=None
Maximum allowed hyper-volume of classes.
"""
def __init__(self, max_iter=10, max_class=100, rho=0.75, sigma=0.1, max_hyper_volume=FLOAT_MAX):
super().__init__()
self.max_iter = max_iter
self.max_class = max_class
self.rho = rho
self.sigma = sigma
self.max_hyper_volume = max_hyper_volume
self._big_m = 1
def _check_params(self, X):
# max_iter
if self.max_iter <= 0:
raise ValueError(
f"max_iter must be > 0, got {self.max_iter} instead.")
# max_class
if self.max_class <= 0:
raise ValueError(
f"max_class must be > 0, got {self.max_class} instead.")
# rho
if not (0.0 < self.rho < 1.0):
raise ValueError(
f"rho must be in range (0, 1), got {self.rho} instead.")
# sigma
if self.sigma <= 0:
raise ValueError(
f"sigma must be > 0, got {self.sigma} instead.")
# max_hyper_volume
if self.max_hyper_volume <= 0:
raise ValueError(
f"max_hyper_volume must be > 0, got {self.max_hyper_volume} instead.")
def _initialize(self, X):
self.history_ = {"gap_mu": [], "gap_cov": [], "likelihood": [], "hyper_volume": []}
self._n_features = X.shape[1]
self._mu = np.zeros((self.max_class, self._n_features))
self._cov = np.repeat(
np.diag([self.sigma**2] * self._n_features)[None, ...], self.max_class, axis=0)
self._counter = np.array([0] * self.max_class)
# constraint
if self.sigma**2 > np.power(self.rho, 1 / self._n_features):
raise ValueError(
f"sigma**2 must be < rho**(1/n_feature), sigma**2={self.sigma**2}, rho**(1/n_feature)={np.power(self.rho, 1 / self._n_features)}")
def fit(self, X):
"""Compute FuzzyART clustering.
Parameters
----------
X : array-like of shape (n_samples, n_features)
Training instances to cluster.
Returns
-------
self
Fitted estimator.
"""
X = check_array(X)
self._check_params(X)
self._initialize(X)
for _ in range(self.max_iter):
y = self._resonance_iter(X)
self.labels_ = y
return self
def partial_fit_predict(self, X):
check_is_fitted(self)
self.labels_ = self._resonance_iter(X)
return self.labels_
def predict(self, X):
"""Predict the closest cluster each sample in X belongs to.
Parameters
----------
X : array-like of shape (n_samples, n_features)
New data to predict.
Returns
-------
labels : ndarray of shape (n_samples,)
Index of the cluster each sample belongs to.
Returns -1 label if the match class does not exist.
"""
check_is_fitted(self)
X = check_array(X)
return self._resonance_iter(X, should_update=False)
def _gaussian(self, x, j):
return multivariate_normal.pdf(x, mean=self._mu[j], cov=self._cov[j])
def _resonance_iter(self, X, should_update=True):
y = -1 * np.ones(X.shape[0], dtype=np.int32)
# first trial
begin = 0
if self._counter[0] == 0:
self._mu[0] = X[0].copy()
self._counter[0] = 1
begin = 1
for idx in range(begin, len(X)):
s = X[idx].copy()
# F1
T_denominator = np.sum(
[
self._gaussian(
s,
j) *
self._counter[j] /
np.sum(
self._counter) for j in np.where(
self._counter > 0)[0]])
T = np.array([self._gaussian(s, j) *
self._counter[j] /
np.sum(self._counter) /
T_denominator for j in np.where(self._counter > 0)[0]])
# Search match
for _ in range(len(T)):
# F2 : Code selection
J = np.argmax(T)
likelihood = self._gaussian(s, J)
hyper_volume = np.power(np.linalg.det(self._cov[J]), 1 / (2 * self._n_features))
# Match
if ((likelihood >= self.rho) and (hyper_volume <= self.max_hyper_volume)):
y[idx] = J
if should_update:
mu_previous = self._mu.copy()
cov_previous = self._cov.copy()
# Updata parameters
self._counter[J] += 1
self._mu[J] = (1 - 1 / self._counter[J]) * \
self._mu[J] + 1 / self._counter[J] * s
self._cov[J] = (1 - 1 / self._counter[J]) * self._cov[J] + 1 / \
self._counter[J] * | np.outer(s - self._mu[J], s - self._mu[J]) | numpy.outer |
from __future__ import division, print_function, absolute_import
print('Importing libraries...')
import numpy as np
import imageio
import math
import pandas as pd
import tensorflow as tf
from PIL import Image
from skimage import transform #For downsizing images
from sklearn.model_selection import train_test_split
print('Done')
#----------------------------------------------------------------------------------------------------------------
#--------------------------------------------------DATA PREPARATION----------------------------------------------
#----------------------------------------------------------------------------------------------------------------
def scale_range (input, min, max):
input += -(np.min(input))
input /= | np.max(input) | numpy.max |
import time
from sklearn.model_selection import train_test_split,KFold
from sklearn.tree import DecisionTreeClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.svm import SVC
import numpy as np
from sklearn.decomposition import PCA
start=time.clock() # 显示程序开始运行时的时间
with open('K9.data') as df: #打开文件
dataMat=[]; labels=[]
for line in df.readlines(): #逐行读取文件
lineArr=line.strip().split(',') #文件以','分隔每一行的因素
if '?' not in lineArr: #数据中有部分缺失的数据用?替代了,在训练模型的时候应该无视这些样本
dataMat.append(lineArr[:-2]) #每一行中倒数第二个元素之前的都是输入变量
labels.append(lineArr[-2]) #倒数第二个为分类标签,而倒数第一个为','
pca=PCA(n_components=20) # 保留20个主成分
X_pca=pca.fit_transform(dataMat) # 降维后的数据
explained=sum(pca.explained_variance_ratio_) #方差累计贡献率
print('方差贡献率累计:%f' %explained)
X= | np.array(X_pca) | numpy.array |
######################################################################################
#
# Authors : <NAME>, <NAME>
# KTH
# Email : <EMAIL>, <EMAIL>
#
# computations.py: implements, for the SEM, necessary computational methods
#####################################################################################
import numpy as np
import networkx as nx
# define each letter of alphabet as a vector
nuc_vec = {'A': [1., 0., 0., 0.], 'C': [0., 1., 0., 0.], 'G': [0., 0., 1., 0.], 'T': [0., 0., 0., 1.]}
alphabet_size = 4 # number of letters in alphabet
# compute upward messages
def compute_up_messages(data, tree, evo_model):
n_leaves, n_sites = data.shape
root = len(tree) - 1
# store up message for each node internal+external = 2n-1
up_table = np.ones((len(tree), alphabet_size, n_sites))
for i in range(n_leaves):
up_table[i] = | np.transpose([nuc_vec[c] for c in data[i]]) | numpy.transpose |
#!/usr/bin/python
"""
Student name: <NAME>
Student ID: 21230987
Github URL: https://github.com/SaiPramodh128/ARC
"""
import os, sys
import json
import numpy as np
import re
### YOUR CODE HERE: write at least three functions which solve
### specific tasks by transforming the input x and returning the
### result. Name them according to the task ID as in the three
### examples below. Delete the three examples. The tasks you choose
### must be in the data/training directory, not data/evaluation.
"""
Summary : In the resoning corpus, here we are supposed to indentify patterns and predict the output for the patterns that might be missing.
As we are suposed to write functions to predict the patterns based on the train dataset
I have written to solve few shapes based on pattern , with colour occurance and boundary pattern.
I have used numpy a lot on working in this assignment I had the chance to go through a lot in numpy libraries.
Helped in better understanding of working with arrays in python.
"""
# ====================================Task solve_5ad4f10b============================================
"""
On analysis here the input contains two unique colour, one scattered all over the grid and other appears to be grid of square shape.
The square shaped grid consists of random colour which appears to be in m x n but the output is in 3 x 3 grid.
The subgrid which is inside the main input grid is then transformed to 3 x 3, difference with swap of the unique colours found in input.
Pattern:
1. The background colour of the input here appears to be black(0) which will the background of the output grid too.
2. The scattered colour are found initial as I think scattered appears first in the input before the subgrid. There might be also be a
scenario where scatterd occurs less than the subgrid colour.
3. The subgrid may be in any m x n which is always square matrix array. It appears to be a grid with unique colours filling the m x n which is resembles a
3 x 3 matric with missing same unique colours.
Transformation:
1. The scattered colour and the subgrid colour are found which are later going to be swapped.
2.The boundary of the subgrid is found by the first occurence of the subgrid color in the input by gramming the index as
top left and bottom right occurance of the subgrid colour
3. Then framing the output grid with the stepsize of 3 since the output grid is a 3 x 3 grid.
4. The subgrid values are swapped with scattered colour value in the output grid which is filled. With spliting the row in three parts.
These three parts resembles the output grid and black(0) as the missing value
"""
def solve_5ad4f10b(x):
#the unique colours with index which is used to identify the scatterd and grid colours
unique_elem_list, indexes = np.unique(x, return_index=True)
map_color_index = zip(unique_elem_list, indexes)
sorted_color = sorted(map_color_index, key=lambda y: y[1])
unique_elems = [sorted_color[i][0] for i in range(len(sorted_color))]
#Removing black as it is the background colour
unique_elems = np.delete(unique_elems, 0)
# calling a method to get the boundaries of the unique colour value which might be of m x n grid.
sub_grid = get_boundaries(x, unique_elems[1])
#splitting the subgrid into three parts
step_size = (int)(len(sub_grid) / 3)
output = []
# filling the output array with rows of array with the scattered colour value.
for y in range(0, len(sub_grid), step_size):
row_arr = []
for x in range(0, len(sub_grid), step_size):
if sub_grid[y][x] == unique_elems[1]:
row_arr.append(unique_elems[0])
else:
row_arr.append(0)
output.append(row_arr)
return np.array(output)
# used to get the boundaries of the value
def get_boundaries(X, unique_elem):
row , col = X.shape
for y in range(row):
if (unique_elem in X[y]):
top = y
break;
for y in range(row):
yval = row - (y + 1)
if (unique_elem in X[yval]):
bottom = yval
break;
t = np.transpose(X)
for x in range(col):
if (unique_elem in t[x]):
left = x
break;
for x in range(col):
xval = col - (x + 1)
if (unique_elem in t[xval]):
right = xval
break;
return np.array(X)[top:bottom + 1, left:right + 1]
# ====================================Task solve_5ad4f10b===============================================
# ====================================Task solve_1b60fb0c===============================================
"""
On analysis the input and output are going to the same.
The background of the input are mostly black (0) and has blue shapes of pattern and the missing pattern are in red.
Patterns:
1. If we consider in a symetrical view of lets say top and bottom halves both are symetrical to each other
similarly the left and right should also be symetrical.
2. For this input if we consider the top and bottom parts if they are adjusted, the left and right will also
follow the same funcionality since they are symetrical.
On Comparing the first and last rows, as well as the first + 1 and last - 1 rows
On Comparing the first and last columns, as well as the first + 1 and last - 1 columns
Transformations :
1. The goal is to fill the empty blue cells in the output grid with red to satisfy the pattern criteria.
2. If the bottom row of the grid is displaced by one along the x axis as compared to the top row,
when compared to the right column of the grid, the left column is displaced by one along the y axis.
The pattern shape is iterated in a loop to fill the colour same as the symetrical side.
"""
def solve_1b60fb0c(x):
output = np.copy(x)
# Getting the unique values and occurence of them
unique_elem_list, no_of_times = np.unique(x, return_counts=True)
map_color_count = zip(unique_elem_list, no_of_times)
sorted_color_count = sorted(map_color_count, key=lambda y: y[1])
unique_color = 0
for i in sorted_color_count:
# since black(0) is the background colour the other unique colour is fetched. which is the pattern's colour
if i[0] != 0:
unique_color = i[0]
m, n = output.shape
b = m - 1
t = 0
r = n - 1
l = 0
# Here the colour that is missing in the pattern is replaced with red(2)
color_to_be_filled = 2
# Iterate the loop till the center of the grid to get the missing values
while t < m / 2:
if unique_color in output[b][:]:
if unique_color in output[t][:]:
previous_shape = output[t:b, l]
if (output[b, l:r] == output[t, l:r]).all():
new_shape = output[t:b, r]
else:
# Here roll method is used rotate over the axis
new_shape = np.roll(output[t:b, r], axis=0, shift=1)
output[t:b, l] = np.where(previous_shape == new_shape, previous_shape, color_to_be_filled)
else:
t = t + 1
l = l + 1
continue
b = b - 1
t = t + 1
l = l + 1
r = r - 1
return output
# ====================================Task solve_1b60fb0c==================================================
# ====================================Task solve_c8cbb738==================================================
"""
On analysis the input may be of any size m x n.
The output size depends on the input as of the biggest sub pattern in the input
Patterns:
1. Two or more distinct colors, with one color notably found in the input grid cells
2. By connecting the same coloured cells, you can make shapes like squares, rectangles, and diamonds.
Transformation:
1. Calculate the size of the largest square-shaped colored cells and create an output grid with that size and dominant color as the background colour.
2. Now, start looking at the various colored cells and map them in the output grid in the same form (rectangle, diamond, square)
with the same color and size as the input grid.
"""
def solve_c8cbb738(x):
# Getting the unique values and occurence of them
unique_elem_list, no_of_times = np.unique(x, return_counts=True)
map_color_count = zip(unique_elem_list, no_of_times)
sorted_color_count = sorted(map_color_count, key=lambda y: y[1])
# max occurence colour which will the background colour of the output
max_num, max_count = sorted_color_count[len(sorted_color_count) - 1]
min_num, min_count = sorted_color_count[0]
# Find the indexes of the less frequent color and determine the maximum distance in X axis.
# Using the calculated distance, find the centre position and generate the output grid with dominant color
m, n = np.where(x == min_num)
output_size = np.max(m) - np.min(m) + 1
mid_point = int(np.floor(output_size / 2))
output = np.full((output_size, output_size), max_num)
for color in unique_elem_list:
if color != max_num:
m, n = np.where(x == color)
if len( | np.unique(m) | numpy.unique |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 6 17:54:53 2018
@author: haskig
"""
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: yan
Check registration quality by varying translation or rotation.
Compare with MI in the same time.
"""
# %%
from utils import registration_reader as rr
from utils import volume_data_generator as vdg
from utils import volume_resampler_3d as vr3d
import glob
from keras.models import load_model
from matplotlib import pyplot as plt
import numpy as np
from os import path
import SimpleITK as sitk
from resizeimage import resizeimage
from PIL import Image
import random
import scipy
from utils import volume_resampler_3d as vr3D
from stl import mesh
from keras import backend as K
# %% input image dimensions
img_rows, img_cols = 96, 96
depth = 32
#
img_channels = 2
batch_size = 64
tmp_folder = '/home/haskig/tmp'
# %%
a=0.1
if not 'deep_network' in globals():
print('Loading deep network...')
#fn_model = 'trained_binary_model_3d.h5'
"""
fn_model = 'trained_3d_regression_20170627_refined.h5'
folder_model = '/home/data/models'
fn_full = path.join(folder_model, fn_model)
"""
fn_model = '/zion/common/experimental_results/haskins_mrus_reg/trained_3d_regression_new_data.h5'
deep_network = load_model(fn_model)
#fn_model = '/home/haskig/tmp/trained_3d_regression_OG_smooth_stdev.h5'
#deep_network = load_model(fn_model, custom_objects={'mse_var_reg':mse_var_reg})
print('Deep network loaded from <{}>'.format(fn_model))
# %%
data_folder = '/home/data/uronav_data'
"""
if not 'vdg_train' in globals():
vdg_train = vdg.VolumeDataGenerator(data_folder, (1,500))
print('{} cases for using'.format(vdg_train.get_num_cases()))
"""
vdg_train = vdg.VolumeDataGenerator(data_folder, (71,750))
print('{} cases for using'.format(vdg_train.get_num_cases()))
#trainGen = vdg_train.generate_batch_with_parameters(batch_size=batch_size, shape=(img_cols,img_rows,depth))
# %% Generate samples and check predict values
case_idx = 1
case_folder = 'Case{:04d}'.format(case_idx)
full_case_path = path.join(data_folder, case_folder)
fn_stl = path.join(full_case_path, 'segmentationrtss.uronav.stl')
segMesh = mesh.Mesh.from_file(fn_stl)
folder = '/home/haskig/data/uronav_data'
"""
US_mat_path = path.join(folder, 'Case{:04}/SSC_US'.format(case_idx))
MR_mat_path = path.join(folder, 'Case{:04}/SSC_MR'.format(case_idx))
SSC_moving = scipy.io.loadmat(US_mat_path)['US_SSC']
SSC_fixed = scipy.io.loadmat(MR_mat_path)['MR_SSC']
"""
def get_array_from_itk_matrix(itk_mat):
mat = np.reshape(np.asarray(itk_mat), (3,3))
return mat
fns = glob.glob(path.join(full_case_path, '*.txt'))
if len(fns) < 1:
print('No registration file found!')
fn_gt = fns[0]
for fn_registration in fns:
if 'refined' in fn_registration:
fn_gt = fn_registration
trans_gt = rr.load_registration(fn_gt)
print(trans_gt)
R = sitk.ImageRegistrationMethod()
R.SetMetricAsJointHistogramMutualInformation()
scores = []
mis = []
var_range = np.arange(-20, 20, 0.5)
n = 1
e = 0
for x in var_range:
trans = np.copy(trans_gt)
trans0 = np.copy(trans_gt)
x0 = x
score = 0
for j in range(n):
if j == 0:
trans0[2,3] = trans_gt[2,3] + x
sample0 = vdg_train.create_sample(case_idx, (img_cols,img_rows,depth), trans0)
sampledFixed0 = sample0[0]
sampledMoving0 = sample0[1]
x += random.uniform(-e,e)
trans[2,3] = trans_gt[2,3] + x
sample = vdg_train.create_sample(case_idx, (img_cols,img_rows,depth), trans)
sampledFixed = sample[0]
sampledMoving = sample[1]
x = sitk.GetArrayFromImage(sampledFixed)
y = sitk.GetArrayFromImage(sampledMoving)
#pos_neg = sample[2]
error_trans = sample[2]
(angleX, angleY, angleZ, tX, tY, tZ) = sample[3]
sample4D = np.zeros((1, 32, 96, 96, 2), dtype=np.ubyte)
#print(sample4D.shape)
sample4D[0, :,:,:, 0] = sitk.GetArrayFromImage(sampledFixed)
sample4D[0, :,:,:, 1] = sitk.GetArrayFromImage(sampledMoving)
prediction = deep_network.predict(sample4D)
score_dl = prediction[0,0]
score += score_dl
x=x0
score /= n
scores.append(score)
"""
SSD = 0
trans[2,3] = trans_gt[2,3] + x
for i in range(SSC_fixed.shape[3]):
resampler3D = vr3D.VolumeResampler(sitk.GetImageFromArray(SSC_fixed[:,:,:,i]), segMesh,
sitk.GetImageFromArray(SSC_moving[:,:,:,i]),
trans)
resampler3D.set_transform(trans)
sampledFixed, sampledMoving = resampler3D.resample(96, 96, 32)
fixed_img = sitk.GetArrayFromImage(sampledFixed)
moving_img = sitk.GetArrayFromImage(sampledMoving)
diff = np.subtract(fixed_img, moving_img)
sq_diff = np.square(diff)
SSD += np.sum(sq_diff)
SSC = SSD
"""
score_mi = R.MetricEvaluate(sampledFixed0, sampledMoving0)
mis.append(score_mi)
print('DL: %.4g <--> MI: %.4g' % (score, score_mi))
# %%
fig, ax1 = plt.subplots()
#num_pts = len(scores)
ax1.plot(var_range, scores, c='b', label='DL')
ax1.set_title('Translation along Z-axis', fontsize=14)
ax1.set_xlabel('Translation along Z axis (mm)'.format(n,e), fontsize=14)
# Make the y-axis label, ticks and tick labels match the line color.
ax1.set_ylabel('CNN score (mm)', color='b', fontsize=14)
ax1.tick_params('y', colors='b')
ax1.legend(loc='lower left',prop={'size': 11})
ax2 = ax1.twinx()
ax2.plot(var_range, -np.asarray(mis), c='r', label='MI')
ax2.set_ylabel('Mutual Information', color='r', fontsize=14)
ax2.tick_params('y', colors='r')
ax2.legend(loc="lower right",prop={'size': 11})
fig.tight_layout()
plt.savefig('/home/haskig/Pictures/MIvLM_trans_bad_case_56.pdf', dpi=600, format='pdf')
# %% Rotations
#import transformations as tfms
scores = []
mis = []
var_range = np.arange(-20, 20, 0.5)
n = 1
e = 0
for x in var_range:
x0 = x
trans = np.copy(trans_gt)
trans0 = np.copy(trans_gt)
score = 0
#trans[2,3] = trans_gt[2,3] + x
#mat_rot = tfms.rotation_matrix(x/180.0 * np.pi, (0,0,1))
#trans = mat_rot.dot(trans)
rot0, t0 = vdg_train.create_transform(x0, x0, x0, 0, 0, 0, trans_gt)
trans0[:3,:3] = rot0
trans0[:3, 3] = t0 + trans_gt[:3,3]
sample0 = vdg_train.create_sample(case_idx, (img_cols,img_rows,depth), trans0)
sampledFixed0 = sample0[0]
sampledMoving0 = sample0[1]
#pos_neg = sample[2]
error_trans0 = sample0[2]
(angleX, angleY, angleZ, tX, tY, tZ) = sample0[3]
for j in range(n):
x += random.uniform(-e,e)
rot, t = vdg_train.create_transform(x, x, x, 0, 0, 0, trans_gt)
trans[:3,:3] = rot
trans[:3, 3] = t + trans_gt[:3,3]
sample = vdg_train.create_sample(case_idx, (img_cols,img_rows,depth), trans)
sampledFixed = sample[0]
sampledMoving = sample[1]
#pos_neg = sample[2]
error_trans0 = sample[2]
(angleX, angleY, angleZ, tX, tY, tZ) = sample[3]
sample4D = np.zeros((1, 32, 96, 96, 2), dtype=np.ubyte)
#print(sample4D.shape)
sample4D[0, :,:,:, 0] = sitk.GetArrayFromImage(sampledFixed)
sample4D[0, :,:,:, 1] = sitk.GetArrayFromImage(sampledMoving)
prediction = deep_network.predict(sample4D)
score_dl = prediction[0,0]
score += score_dl
score /= n
scores.append(score)
score_mi = R.MetricEvaluate(sampledFixed0, sampledMoving0)
mis.append(score_mi)
print('DL: %.4g <--> MI: %.4g' % (score_dl, score_mi))
# %
fig, ax1 = plt.subplots()
#num_pts = len(scores)
ax1.plot(var_range, scores, c='b', label='DL')
ax1.set_title('Rotation around all axes simultaneously', fontsize=14)
ax1.set_xlabel('Rotation around all axes (degree)'.format(n,e), fontsize=14)
# Make the y-axis label, ticks and tick labels match the line color.
ax1.set_ylabel('CNN score (mm)', color='b', fontsize=14)
ax1.tick_params('y', colors='b')
ax1.legend(loc='lower left',prop={'size': 11})
ax2 = ax1.twinx()
ax2.plot(var_range, - | np.asarray(mis) | numpy.asarray |
############################################################################
# Copyright ESIEE Paris (2020) #
# #
# Contributor(s) : <NAME> #
# #
# Distributed under the terms of the CECILL-B License. #
# #
# The full license is in the file LICENSE, distributed with this software. #
############################################################################
import unittest
import numpy as np
import higra as hg
class TestTreeMonotonicRegression(unittest.TestCase):
def test_tree_monotonic_regression_trivial(self):
tree = hg.Tree((7, 7, 8, 8, 8, 9, 9, 10, 10, 11, 11, 11))
altitudes = np.asarray((0, 1, 0, 2, 0, 0, 0, 2, 3, 0, 5, 10))
res = hg.tree_monotonic_regression(tree, altitudes, "max")
self.assertTrue(np.all(altitudes == res))
res = hg.tree_monotonic_regression(tree, altitudes, "min")
self.assertTrue(np.all(altitudes == res))
res = hg.tree_monotonic_regression(tree, altitudes, "least_square")
self.assertTrue(np.all(altitudes == res))
res = hg.tree_monotonic_regression(tree, altitudes, "max")
self.assertTrue(np.all(altitudes == res))
with self.assertRaises(Exception):
hg.tree_monotonic_regression(tree, altitudes, "truc")
def test_tree_monotonic_regression_max(self):
tree = hg.Tree((7, 7, 8, 8, 8, 9, 9, 10, 10, 11, 11, 11))
altitudes = np.asarray((0, 3, 0, 2, 0, 0, 0, 2, 3, 0, 5, 4))
ref = np.asarray((0, 3, 0, 2, 0, 0, 0, 3, 3, 0, 5, 5))
res = hg.tree_monotonic_regression(tree, altitudes, "max")
self.assertTrue(np.all(ref == res))
def test_tree_monotonic_regression_min(self):
tree = hg.Tree((7, 7, 8, 8, 8, 9, 9, 10, 10, 11, 11, 11))
altitudes = np.asarray((0, 3, 0, 2, 0, 0, 0, 2, 3, 0, 5, 4))
ref = np.asarray((0, 2, 0, 2, 0, 0, 0, 2, 3, 0, 4, 4))
res = hg.tree_monotonic_regression(tree, altitudes, "min")
self.assertTrue( | np.all(ref == res) | numpy.all |
import time
from collections import deque
import cv2
import math
import queue
import threading
import traceback
import curses
import numpy as np
from joblib import load
import logging
from detect import Detector
import olympe
from olympe.messages.ardrone3.Piloting import TakeOff, Landing, moveBy, CancelMoveBy
from olympe.messages.ardrone3.PilotingState import FlyingStateChanged
from olympe.messages.ardrone3.PilotingSettings import MaxTilt
from olympe.messages.ardrone3.SpeedSettings import MaxVerticalSpeed, MaxRotationSpeed
olympe.log.update_config({"loggers": {"olympe": {"level": "ERROR"}}})
logging.basicConfig(filename='log.log', level=logging.INFO, format="%(asctime)s.%(msecs)03d;%(levelname)s;%(message)s;",
datefmt='%Y-%m-%d,%H:%M:%S')
logging.info("message;distance;time(seconds)")
DRONE_IP = "192.168.42.1"
event_time = time.time()
# get euclidean distance between two points in instances
def get_point_distance(instances, one, two):
p1 = instances[0][one]
p2 = instances[0][two]
return math.sqrt((p1[0] - p2[0]) ** 2 + (p1[1] - p2[1]) ** 2)
# get a point as tuple
def get_point(instances, number):
point = instances[0][number]
return int(point[0]), int(point[1])
# remove outliers from two-dimensional array a
def remove_outliers(a):
if len(a.shape) == 2:
q1 = np.percentile(a, 25, interpolation='midpoint', axis=0)
q3 = np.percentile(a, 75, interpolation='midpoint', axis=0)
iqr = q3 - q1
out1 = np.where(a + (1.5 * iqr) - q1 < 0)[0]
out2 = np.where(a - (1.5 * iqr) - q3 > 0)[0]
out = np.unique(np.append(out1, out2))
a = np.delete(a, out, axis=0)
return a
class FlightListener(olympe.EventListener):
@olympe.listen_event(FlyingStateChanged())
def onStateChanged(self, event, scheduler):
# log flight state
logging.error("{};{};{:.3f}".format(event.message.name, event.args["state"], time.time() - event_time))
def get_distance_height(height):
return 211.08 * math.pow(height, -1.045)
def get_distance_width(width):
return 223.05 * math.pow(width, -1.115)
class MainClass(threading.Thread):
def __init__(self):
# Create the olympe.Drone object from its IP address
self.drone = olympe.Drone(DRONE_IP)
# subscribe to flight listener
listener = FlightListener(self.drone)
listener.subscribe()
self.last_frame = np.zeros((1, 1, 3), np.uint8)
self.frame_queue = queue.Queue()
self.flush_queue_lock = threading.Lock()
self.detector = Detector()
self.keypoints_image = np.zeros((1, 1, 3), np.uint8)
self.keypoints = deque(maxlen=5)
self.faces = deque(maxlen=10)
self.f = open("distances.csv", "w")
self.face_distances = deque(maxlen=10)
self.image_width = 1280
self.image_height = 720
self.half_face_detection_size = 150
self.poses_model = load("models/posesmodel.joblib")
self.pose_predictions = deque(maxlen=5)
self.pause_finding_condition = threading.Condition(threading.Lock())
self.pause_finding_condition.acquire()
self.pause_finding = True
self.person_thread = threading.Thread(target=self.fly_to_person)
self.person_thread.start()
# flight parameters in meter
self.flight_height = 0.0
self.max_height = 1.0
self.min_dist = 1.5
# keypoint map
self.nose = 0
self.left_eye = 1
self.right_eye = 2
self.left_ear = 3
self.right_ear = 4
self.left_shoulder = 5
self.right_shoulder = 6
self.left_elbow = 7
self.right_elbow = 8
self.left_wrist = 9
self.right_wrist = 10
self.left_hip = 11
self.right_hip = 12
self.left_knee = 13
self.right_knee = 14
self.left_ankle = 15
self.right_ankle = 16
# person distance
self.eye_dist = 0.0
# save images
self.save_image = False
self.image_counter = 243
self.pose_file = open("poses.csv", "w")
super().__init__()
super().start()
def start(self):
self.drone.connect()
# Setup your callback functions to do some live video processing
self.drone.set_streaming_callbacks(
raw_cb=self.yuv_frame_cb,
start_cb=self.start_cb,
end_cb=self.end_cb,
flush_raw_cb=self.flush_cb,
)
# Start video streaming
self.drone.start_video_streaming()
# set maximum speeds
print("rotation", self.drone(MaxRotationSpeed(1)).wait().success())
print("vertical", self.drone(MaxVerticalSpeed(0.1)).wait().success())
print("tilt", self.drone(MaxTilt(5)).wait().success())
def stop(self):
# Properly stop the video stream and disconnect
self.drone.stop_video_streaming()
self.drone.disconnect()
def yuv_frame_cb(self, yuv_frame):
"""
This function will be called by Olympe for each decoded YUV frame.
:type yuv_frame: olympe.VideoFrame
"""
yuv_frame.ref()
self.frame_queue.put_nowait(yuv_frame)
def flush_cb(self):
with self.flush_queue_lock:
while not self.frame_queue.empty():
self.frame_queue.get_nowait().unref()
return True
def start_cb(self):
pass
def end_cb(self):
pass
def show_yuv_frame(self, window_name, yuv_frame):
# the VideoFrame.info() dictionary contains some useful information
# such as the video resolution
info = yuv_frame.info()
height, width = info["yuv"]["height"], info["yuv"]["width"]
# yuv_frame.vmeta() returns a dictionary that contains additional
# metadata from the drone (GPS coordinates, battery percentage, ...)
# convert pdraw YUV flag to OpenCV YUV flag
cv2_cvt_color_flag = {
olympe.PDRAW_YUV_FORMAT_I420: cv2.COLOR_YUV2BGR_I420,
olympe.PDRAW_YUV_FORMAT_NV12: cv2.COLOR_YUV2BGR_NV12,
}[info["yuv"]["format"]]
# yuv_frame.as_ndarray() is a 2D numpy array with the proper "shape"
# i.e (3 * height / 2, width) because it's a YUV I420 or NV12 frame
# Use OpenCV to convert the yuv frame to RGB
cv2frame = cv2.cvtColor(yuv_frame.as_ndarray(), cv2_cvt_color_flag)
# show video stream
cv2.imshow(window_name, cv2frame)
cv2.moveWindow(window_name, 0, 500)
# show other windows
self.show_face_detection(cv2frame)
self.show_keypoints()
cv2.waitKey(1)
def show_keypoints(self):
if len(self.keypoints) > 2:
# display eye distance
cv2.putText(self.keypoints_image, 'Distance(eyes): ' + "{:.2f}".format(self.eye_dist) + "m", (0, 20),
cv2.FONT_HERSHEY_SIMPLEX, 0.9,
(36, 255, 12), 2)
# display nose height
cv2.putText(self.keypoints_image, 'Nose: ' + "{:.2f}".format(
get_point(np.average(self.keypoints, axis=0), self.nose)[1] / self.image_height)
, (0, 80), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (36, 255, 12), 2)
cv2.imshow("keypoints", self.keypoints_image)
cv2.moveWindow("keypoints", 500, 0)
def show_face_detection(self, cv2frame):
# get sub image
img = self.get_face_detection_crop(cv2frame)
# get face rectangle
face, img = self.detector.detect_face(img)
if face.size > 0:
self.faces.append(face)
width = face[2] - face[0]
height = face[3] - face[1]
# get distances for rectangle width and height
width = get_distance_width(width)
height = get_distance_height(height)
# display distances
cv2.putText(img, 'width: ' + "{:.2f}".format(width), (0, 20),
cv2.FONT_HERSHEY_SIMPLEX, 0.9,
(36, 255, 12), 2)
cv2.putText(img, 'height: ' + "{:.2f}".format(height), (0, 50),
cv2.FONT_HERSHEY_SIMPLEX, 0.9,
(36, 255, 12), 2)
cv2.putText(img, 'mean: ' + "{:.2f}".format(np.mean(np.array([width, height]))), (0, 80),
cv2.FONT_HERSHEY_SIMPLEX, 0.9,
(36, 255, 12), 2)
# append outlier free distance to log
self.face_distances.append(self.get_face_distance())
elif len(self.faces) > 0:
# remove from dequeue if no face was detected
self.faces.popleft()
# show detection
cv2.imshow("face", img)
cv2.moveWindow("face", 0, 0)
# get 300*300 crop of frame based on nose location or from the middle
def get_face_detection_crop(self, cv2frame):
if len(self.keypoints) > 0:
x, y = get_point(np.array(self.keypoints, dtype=object)[-1], self.nose)
else:
x = cv2frame.shape[1] / 2
y = cv2frame.shape[0] / 2
x = max(self.half_face_detection_size, x)
y = max(self.half_face_detection_size, y)
x = min(cv2frame.shape[1] - self.half_face_detection_size, x)
y = min(cv2frame.shape[0] - self.half_face_detection_size, y)
img = cv2frame[int(y - self.half_face_detection_size):int(y + self.half_face_detection_size),
int(x - self.half_face_detection_size):int(x + self.half_face_detection_size)]
return img
def get_face_distance(self):
if len(self.faces) > 2:
try:
faces = remove_outliers(np.array(self.faces, dtype=object))
face = np.mean(faces, axis=0)
width = face[2] - face[0]
height = face[3] - face[1]
width = get_distance_width(width)
height = get_distance_height(height)
return np.mean(np.array([width, height]))
except ZeroDivisionError:
logging.error("ZeroDivisionError in get_face_distance()")
logging.error(self.faces)
return -1
def run(self):
window_name = "videostream"
cv2.namedWindow(window_name, cv2.WINDOW_NORMAL)
main_thread = next(
filter(lambda t: t.name == "MainThread", threading.enumerate())
)
while main_thread.is_alive():
with self.flush_queue_lock:
try:
yuv_frame = self.frame_queue.get(timeout=0.01)
except queue.Empty:
continue
try:
# the VideoFrame.info() dictionary contains some useful information
# such as the video resolution
info = yuv_frame.info()
height, width = info["yuv"]["height"], info["yuv"]["width"]
# yuv_frame.vmeta() returns a dictionary that contains additional
# metadata from the drone (GPS coordinates, battery percentage, ...)
# convert pdraw YUV flag to OpenCV YUV flag
cv2_cvt_color_flag = {
olympe.PDRAW_YUV_FORMAT_I420: cv2.COLOR_YUV2BGR_I420,
olympe.PDRAW_YUV_FORMAT_NV12: cv2.COLOR_YUV2BGR_NV12,
}[info["yuv"]["format"]]
# yuv_frame.as_ndarray() is a 2D numpy array with the proper "shape"
# i.e (3 * height / 2, width) because it's a YUV I420 or NV12 frame
# Use OpenCV to convert the yuv frame to RGB
cv2frame = cv2.cvtColor(yuv_frame.as_ndarray(), cv2_cvt_color_flag)
self.last_frame = cv2frame
self.show_yuv_frame(window_name, yuv_frame)
except Exception:
# We have to continue popping frame from the queue even if
# we fail to show one frame
traceback.print_exc()
finally:
# Don't forget to unref the yuv frame. We don't want to
# starve the video buffer pool
yuv_frame.unref()
cv2.destroyWindow(window_name)
def command_window_thread(self, win):
win.nodelay(True)
key = ""
win.clear()
win.addstr("Detected key:")
while 1:
try:
key = win.getkey()
win.clear()
win.addstr("Detected key:")
win.addstr(str(key))
# disconnect drone
if str(key) == "c":
win.clear()
win.addstr("c, stopping")
self.f.close()
self.pose_file.close()
self.drone.disconnect()
# takeoff
if str(key) == "t":
win.clear()
win.addstr("takeoff")
assert self.drone(TakeOff()).wait().success()
win.addstr("completed")
# land
if str(key) == "l":
win.clear()
win.addstr("landing")
assert self.drone(Landing()).wait().success()
# turn left
if str(key) == "q":
win.clear()
win.addstr("turning left")
assert self.drone(
moveBy(0, 0, 0, -math.pi / 4)
>> FlyingStateChanged(state="hovering", _timeout=5)
).wait().success()
win.addstr("completed")
# turn right
if str(key) == "e":
win.clear()
win.addstr("turning right")
assert self.drone(
moveBy(0, 0, 0, math.pi / 4)
>> FlyingStateChanged(state="hovering", _timeout=5)
).wait().success()
win.addstr("completed")
# move front
if str(key) == "w":
win.clear()
win.addstr("front")
assert self.drone(
moveBy(0.2, 0, 0, 0)
>> FlyingStateChanged(state="hovering", _timeout=5)
).wait().success()
win.addstr("completed")
# move back
if str(key) == "s":
win.clear()
win.addstr("back")
assert self.drone(
moveBy(-0.2, 0, 0, 0)
>> FlyingStateChanged(state="hovering", _timeout=5)
).wait().success()
win.addstr("completed")
# move up
if str(key) == "r":
win.clear()
win.addstr("up")
assert self.drone(
moveBy(0, 0, -0.15, 0)
>> FlyingStateChanged(state="hovering", _timeout=5)
).wait().success()
win.addstr("completed")
# move down
if str(key) == "f":
win.clear()
win.addstr("down")
assert self.drone(
moveBy(0, 0, 0.15, 0)
>> FlyingStateChanged(state="hovering", _timeout=5)
).wait().success()
win.addstr("completed")
# move left
if str(key) == "a":
win.clear()
win.addstr("left")
assert self.drone(
moveBy(0, -0.2, 0, 0)
>> FlyingStateChanged(state="hovering", _timeout=5)
).wait().success()
win.addstr("completed")
# move right
if str(key) == "d":
win.clear()
win.addstr("right")
assert self.drone(
moveBy(0, 0.2, 0, 0)
>> FlyingStateChanged(state="hovering", _timeout=5)
).wait().success()
win.addstr("completed")
# start person detection thread
if str(key) == "p":
win.clear()
pause = self.check_for_pause()
if pause:
win.addstr("cannot start because of stop gesture")
else:
win.addstr("start detecting")
self.pause_finding = False
self.pause_finding_condition.notify()
self.pause_finding_condition.release()
# pause person detecting thread
if str(key) == "o":
win.clear()
win.addstr("stop detecting")
self.pause_finding = True
self.pause_finding_condition.acquire()
# self.person_thread.stop = True
# win.addstr("joined")
# measure distances
if str(key) == "x":
win.clear()
win.addstr("distances:")
arr = np.array(self.keypoints, dtype=object)
string = ""
for i in range(arr.shape[0]):
string += "{:.6f};".format(get_point_distance(arr[i], self.left_eye, self.right_eye))
win.addstr(string)
self.f.write(string + "\n")
# measure faces
if str(key) == "y":
win.clear()
win.addstr("distances:")
arr = np.array(self.faces, dtype=object)
width = ""
height = ""
for i in range(arr.shape[0]):
width += str(arr[i][2] - arr[i][0]) + ";"
height += str(arr[i][3] - arr[i][1]) + ";"
win.addstr(width + height)
self.f.write(width + "\n")
self.f.write(height + "\n")
# log user gesture
if str(key) == "g":
win.clear()
win.addstr("gesture made")
global event_time
event_time = time.time()
logging.info("stop gesture by user;{:.3f};{:.3f}".format(self.get_face_distance(), time.time()))
# log face distances
if str(key) == "k":
win.clear()
win.addstr("distances logged")
string = ""
arr = np.array(self.face_distances, dtype=object)
win.addstr(str(len(arr)))
for i in range(len(arr)):
string += "{:.2f}".format(arr[i]) + ";"
logging.info("distances;{}".format(string))
win.addstr(string)
except Exception as e:
# No input
pass
def fly_to_person(self):
t = threading.currentThread()
while not getattr(t, "stop", False):
with self.pause_finding_condition:
# wait if thread is paused
while self.pause_finding:
self.pause_finding_condition.wait()
arr = np.array(self.keypoints, dtype=object)
if len(arr) > 2:
pose_predictions = | np.array(self.pose_predictions, dtype=object) | numpy.array |
""" cnvpytor.root
class Root: main CNVpytor class
"""
from __future__ import absolute_import, print_function, division
from .io import *
from .bam import Bam
from .vcf import Vcf
from .fasta import Fasta
from .genome import Genome
from .viewer import anim_plot_likelihood, anim_plot_rd, anim_plot_rd_likelihood
import numpy as np
import logging
import os.path
import matplotlib.pyplot as plt
_logger = logging.getLogger("cnvpytor.root")
class Root:
def __init__(self, filename, create=False, max_cores=8):
"""
Class constructor opens CNVpytor file. The class implements all core CNVpytor calculations.
Parameters
----------
filename : str
CNVpytor filename
create : bool
Creates cnvpytor file if not exists
max_cores : int
Maximal number of cores used in parallel calculations
"""
_logger.debug("App class init: filename '%s'; max cores %d." % (filename, max_cores))
self.io = IO(filename, create=create)
self.max_cores = max_cores
self.io_gc = self.io
self.io_mask = self.io
if self.io.signal_exists(None, None, "reference genome") and self.io.signal_exists(None, None, "use reference"):
rg_name = np.array(self.io.get_signal(None, None, "reference genome")).astype("str")[0]
if rg_name in Genome.reference_genomes:
rg_use = self.io.get_signal(None, None, "use reference")
if "gc_file" in Genome.reference_genomes[rg_name] and rg_use[0] == 1:
_logger.debug("Using GC content from database for reference genome '%s'." % rg_name)
self.io_gc = IO(Genome.reference_genomes[rg_name]["gc_file"], ro=True, buffer=True)
if "mask_file" in Genome.reference_genomes[rg_name] and rg_use[1] == 1:
_logger.debug("Using strict mask from database for reference genome '%s'." % rg_name)
self.io_mask = IO(Genome.reference_genomes[rg_name]["mask_file"], ro=True, buffer=True)
def _read_bam(self, bf, chroms, reference_filename=False, overwrite=False):
bamf = Bam(bf, reference_filename=reference_filename)
if bamf.reference_genome:
self.io.create_signal(None, None, "reference genome", np.array([np.string_(bamf.reference_genome)]))
self.io.create_signal(None, None, "use reference", np.array([1, 1]).astype("uint8"))
def read_chromosome(x):
chrs, lens = x
_logger.info("Reading data for chromosome %s with length %d" % (chrs, lens))
l_rd_p, l_rd_u, l_his_read_frg = bamf.read_chromosome(chrs)
return l_rd_p, l_rd_u, l_his_read_frg
chrname, chrlen = bamf.get_chr_len()
chr_len = [(c, l) for (c, l) in zip(chrname, chrlen) if len(chroms) == 0 or c in chroms]
if self.max_cores == 1:
count = 0
cum_his_read_frg = None
for cl in chr_len:
rd_p, rd_u, his_read_frg = read_chromosome(cl)
if not rd_p is None:
if cum_his_read_frg is None:
cum_his_read_frg = his_read_frg
else:
cum_his_read_frg += his_read_frg
if (cl[0] in self.io.rd_chromosomes()) and not overwrite:
self.io.add_rd(cl[0], rd_p, rd_u)
else:
self.io.save_rd(cl[0], rd_p, rd_u, chromosome_length=cl[1])
count += 1
if not cum_his_read_frg is None:
self.io.create_signal(None, None, "read frg dist", cum_his_read_frg)
return count
else:
from .pool import parmap
res = parmap(read_chromosome, chr_len, cores=self.max_cores)
count = 0
cum_his_read_frg = None
for c, r in zip(chr_len, res):
if not r[0] is None:
if cum_his_read_frg is None:
cum_his_read_frg = r[2]
else:
cum_his_read_frg += r[2]
if (c[0] in self.io.rd_chromosomes()) and not overwrite:
self.io.add_rd(c[0], r[0], r[1])
else:
self.io.save_rd(c[0], r[0], r[1], chromosome_length=c[1])
count += 1
if not cum_his_read_frg is None:
self.io.create_signal(None, None, "read frg dist", cum_his_read_frg)
return count
def rd_stat(self, chroms=[]):
""" Calculate RD statistics for 100 bp bins.
Parameters
----------
chroms : list of str
List of chromosomes. Calculates for all available if empty.
"""
rd_stat = []
auto, sex, mt = False, False, False
rd_gc_chromosomes = {}
for c in self.io_gc.gc_chromosomes():
rd_name = self.io.rd_chromosome_name(c)
if not rd_name is None:
rd_gc_chromosomes[rd_name] = c
for c in rd_gc_chromosomes:
if (len(chroms) == 0 or c in chroms):
rd_p, rd_u = self.io.read_rd(c)
max_bin = max(int(10 * np.mean(rd_u) + 1), int(10 * np.mean(rd_p) + 1))
dist_p, bins = np.histogram(rd_p, bins=range(max_bin + 1))
dist_u, bins = np.histogram(rd_u, bins=range(max_bin + 1))
n_p, m_p, s_p = fit_normal(bins[1:-1], dist_p[1:])[0]
n_u, m_u, s_u = fit_normal(bins[1:-1], dist_u[1:])[0]
_logger.info(
"Chromosome '%s' stat - RD parity distribution gaussian fit: %.2f +- %.2f" % (c, m_p, s_p))
_logger.info(
"Chromosome '%s' stat - RD unique distribution gaussian fit: %.2f +- %.2f" % (c, m_u, s_u))
rd_stat.append((c, m_p, s_p, m_u, s_u))
auto = auto or Genome.is_autosome(c)
sex = sex or Genome.is_sex_chrom(c)
mt = mt or Genome.is_mt_chrom(c)
if auto:
max_bin_auto = int(
max(map(lambda x: 5 * x[1] + 5 * x[2], filter(lambda x: Genome.is_autosome(x[0]), rd_stat))))
_logger.debug("Max RD for autosomes calculated: %d" % max_bin_auto)
dist_p_auto = np.zeros(max_bin_auto)
dist_u_auto = np.zeros(max_bin_auto)
dist_p_gc_auto = np.zeros((max_bin_auto, 101))
bins_auto = range(max_bin_auto + 1)
if sex:
max_bin_sex = int(
max(map(lambda x: 5 * x[1] + 5 * x[2], filter(lambda x: Genome.is_sex_chrom(x[0]), rd_stat))))
_logger.debug("Max RD for sex chromosomes calculated: %d" % max_bin_sex)
dist_p_sex = np.zeros(max_bin_sex)
dist_u_sex = np.zeros(max_bin_sex)
dist_p_gc_sex = np.zeros((max_bin_sex, 101))
bins_sex = range(max_bin_sex + 1)
if mt:
max_bin_mt = int(
max(map(lambda x: 5 * x[1] + 5 * x[2], filter(lambda x: Genome.is_mt_chrom(x[0]), rd_stat))))
_logger.debug("Max RD for mitochondria calculated: %d" % max_bin_mt)
if max_bin_mt < 100:
max_bin_mt = 100
bin_size_mt = max_bin_mt // 100
bins_mt = range(0, max_bin_mt // bin_size_mt * bin_size_mt + bin_size_mt, bin_size_mt)
n_bins_mt = len(bins_mt) - 1
_logger.debug("Using %d bin size, %d bins for mitochondria chromosome." % (bin_size_mt, n_bins_mt))
dist_p_mt = np.zeros(n_bins_mt)
dist_u_mt = np.zeros(n_bins_mt)
dist_p_gc_mt = np.zeros((n_bins_mt, 101))
for c in rd_gc_chromosomes:
if len(chroms) == 0 or c in chroms:
_logger.info("Chromosome '%s' stat " % c)
rd_p, rd_u = self.io.read_rd(c)
if Genome.is_autosome(c):
dist_p, bins = np.histogram(rd_p, bins=bins_auto)
dist_u, bins = np.histogram(rd_u, bins=bins_auto)
gcat = self.io_gc.get_signal(rd_gc_chromosomes[c], None, "GC/AT")
gcp = gcp_decompress(gcat)
dist_p_gc, xbins, ybins = np.histogram2d(rd_p, gcp, bins=(bins_auto, range(102)))
dist_p_auto += dist_p
dist_u_auto += dist_u
dist_p_gc_auto += dist_p_gc
elif Genome.is_sex_chrom(c):
dist_p, bins = np.histogram(rd_p, bins=bins_sex)
dist_u, bins = np.histogram(rd_u, bins=bins_sex)
gcat = self.io_gc.get_signal(rd_gc_chromosomes[c], None, "GC/AT")
gcp = gcp_decompress(gcat)
dist_p_gc, xbins, ybins = np.histogram2d(rd_p, gcp, bins=(bins_sex, range(102)))
dist_p_sex += dist_p
dist_u_sex += dist_u
dist_p_gc_sex += dist_p_gc
elif Genome.is_mt_chrom(c):
dist_p, bins = np.histogram(rd_p, bins=bins_mt)
dist_u, bins = np.histogram(rd_u, bins=bins_mt)
gcat = self.io_gc.get_signal(rd_gc_chromosomes[c], None, "GC/AT")
gcp = gcp_decompress(gcat)
dist_p_gc, xbins, ybins = np.histogram2d(rd_p, gcp, bins=(bins_mt, range(102)))
dist_p_mt += dist_p
dist_u_mt += dist_u
dist_p_gc_mt += dist_p_gc
if auto:
n_auto, m_auto, s_auto = fit_normal(np.array(bins_auto[1:-1]), dist_p_auto[1:])[0]
_logger.info("Autosomes stat - RD parity distribution gaussian fit: %.2f +- %.2f" % (m_auto, s_auto))
stat_auto = np.array([max_bin_auto, 1, max_bin_auto, n_auto, m_auto, s_auto])
self.io.create_signal(None, 100, "RD p dist", dist_p_auto, flags=FLAG_AUTO)
self.io.create_signal(None, 100, "RD u dist", dist_u_auto, flags=FLAG_AUTO)
self.io.create_signal(None, 100, "RD GC dist", dist_p_gc_auto, flags=FLAG_AUTO)
self.io.create_signal(None, 100, "RD stat", stat_auto, flags=FLAG_AUTO)
gc_corr_auto = calculate_gc_correction(dist_p_gc_auto, m_auto, s_auto)
self.io.create_signal(None, 100, "GC corr", gc_corr_auto, flags=FLAG_AUTO)
if sex:
n_sex, m_sex, s_sex = fit_normal(np.array(bins_sex[1:-1]), dist_p_sex[1:])[0]
_logger.info("Sex chromosomes stat - RD parity distribution gaussian fit: %.2f +- %.2f" % (m_sex, s_sex))
stat_sex = np.array([max_bin_sex, 1, max_bin_sex, n_sex, m_sex, s_sex])
self.io.create_signal(None, 100, "RD p dist", dist_p_sex, flags=FLAG_SEX)
self.io.create_signal(None, 100, "RD u dist", dist_u_sex, flags=FLAG_SEX)
self.io.create_signal(None, 100, "RD GC dist", dist_p_gc_sex, flags=FLAG_SEX)
self.io.create_signal(None, 100, "RD stat", stat_sex, flags=FLAG_SEX)
gc_corr_sex = calculate_gc_correction(dist_p_gc_sex, m_sex, s_sex)
self.io.create_signal(None, 100, "GC corr", gc_corr_sex, flags=FLAG_SEX)
if mt:
n_mt, m_mt, s_mt = fit_normal(np.array(bins_mt[1:-1]), dist_p_mt[1:])[0]
_logger.info("Mitochondria stat - RD parity distribution gaussian fit: %.2f +- %.2f" % (m_mt, s_mt))
if auto:
_logger.info("Mitochondria stat - number of mitochondria per cell: %.2f +- %.2f" % (
2. * m_mt / m_auto, 2. * s_mt / m_auto + s_auto * m_mt / (m_auto * m_auto)))
stat_mt = np.array([max_bin_mt, bin_size_mt, n_bins_mt, n_mt, m_mt, s_mt])
self.io.create_signal(None, 100, "RD p dist", dist_p_mt, flags=FLAG_MT)
self.io.create_signal(None, 100, "RD u dist", dist_u_mt, flags=FLAG_MT)
self.io.create_signal(None, 100, "RD GC dist", dist_p_gc_mt, flags=FLAG_MT)
self.io.create_signal(None, 100, "RD stat", stat_mt, flags=FLAG_MT)
gc_corr_mt = calculate_gc_correction(dist_p_gc_mt, m_mt, s_mt, bin_size_mt)
self.io.create_signal(None, 100, "GC corr", gc_corr_mt, flags=FLAG_MT)
def _read_vcf(self, vcf_file, chroms, sample='', use_index=False, no_counts=False, ad_tag="AD", gt_tag="GT",
filter=True, callset=None):
vcff = Vcf(vcf_file)
chrs = [c for c in vcff.get_chromosomes() if len(chroms) == 0 or c in chroms]
use_index = use_index and os.path.exists(vcf_file + ".tbi")
def save_data(chr, pos, ref, alt, nref, nalt, gt, flag, qual):
if (len(chroms) == 0 or chr in chroms) and (not pos is None) and (len(pos) > 0):
self.io.save_snp(chr, pos, ref, alt, nref, nalt, gt, flag, qual, callset=callset,
chromosome_length=vcff.lengths[chr])
# TODO: Stop reading if all from chrom list are read.
def save_data_no_counts(chr, pos, ref, alt, gt, flag, qual):
if (len(chroms) == 0 or chr in chroms) and (not pos is None) and (len(pos) > 0):
self.io.save_snp(chr, pos, ref, alt, np.zeros_like(pos), np.zeros_like(pos), gt, flag, qual,
callset=callset, chromosome_length=vcff.lengths[chr])
if use_index:
count = 0
for c in chrs:
_logger.info("Reading variant data for chromosome %s" % c)
if no_counts:
pos, ref, alt, gt, flag, qual = vcff.read_chromosome_snp_no_counts(c, sample, gt_tag=gt_tag,
filter=filter)
nref, nalt = np.zeros_like(pos), np.zeros_like(pos)
else:
pos, ref, alt, nref, nalt, gt, flag, qual = vcff.read_chromosome_snp(c, sample, ad_tag=ad_tag,
gt_tag=gt_tag, filter=filter)
if not pos is None and len(pos) > 0:
self.io.save_snp(c, pos, ref, alt, nref, nalt, gt, flag, qual, callset=callset,
chromosome_length=vcff.lengths[c])
count += 1
return count
else:
if no_counts:
return vcff.read_all_snp_no_counts(save_data_no_counts, sample, gt_tag=gt_tag, filter=filter)
else:
return vcff.read_all_snp(save_data, sample, ad_tag=ad_tag, gt_tag=gt_tag, filter=filter)
def rd(self, bamfiles, chroms=[], reference_filename=False, overwrite=False):
""" Read chromosomes from bam/sam/cram file(s) and store in cnvpytor file.
Parameters
----------
bamfiles : list of str
List of bam/sam/cram files
chroms : list of str
List of chromosomes. Import all available if empty.
reference_filename : str
Only for CRAM files - reference genome filename
"""
for bf in bamfiles:
self._read_bam(bf, chroms, reference_filename=reference_filename, overwrite=overwrite)
self.io.add_meta_attribute("BAM", bf)
if self.io.signal_exists(None, None, "reference genome"):
rg_name = np.array(self.io.get_signal(None, None, "reference genome")).astype("str")[0]
if "mask_file" in Genome.reference_genomes[rg_name]:
_logger.info("Strict mask for reference genome '%s' found in database." % rg_name)
self.io_mask = IO(Genome.reference_genomes[rg_name]["mask_file"])
if "gc_file" in Genome.reference_genomes[rg_name]:
_logger.info("GC content for reference genome '%s' found in database." % rg_name)
self.io_gc = IO(Genome.reference_genomes[rg_name]["gc_file"])
self.rd_stat()
def vcf(self, vcf_files, chroms=[], sample='', no_counts=False, ad_tag="AD", gt_tag="GT", filter=True,
callset=None, use_index=True):
""" Read SNP data from variant file(s) and store in .cnvpytor file
Parameters
----------
vcf_files : list of str
List of variant filenames.
chroms : list of str
List of chromosomes. Import all available if empty.
sample : str
Name of the sample. It will read first sample if empty string is provided.
no_counts : bool
Do not read AD counts if true.
ad_tag : str
AD tag (default 'AD').
gt_tag : str
GT tag (default 'GT').
filter : bool
If True it will read only variants with PASS filter, otherwise all
callset : str or None
It will assume SNP data if None. Otherwise it will assume SNV data and
store under the name provided by callset variable.
use_index : bool
Use index file for vcf parsing. Default is False.
"""
for vcf_file in vcf_files:
self._read_vcf(vcf_file, chroms, sample, no_counts=no_counts, ad_tag=ad_tag, gt_tag=gt_tag, filter=filter,
callset=callset, use_index=use_index)
self.io.add_meta_attribute("VCF", vcf_file)
def rd_from_vcf(self, vcf_file, chroms=[], sample='', ad_tag="AD", dp_tag="DP", use_index=False):
"""
Read RD from variant file(s) and store in .cnvpytor file
Parameters
----------
vcf_file : str
Variant filename
chroms : list of str
List of chromosomes. Imports all available if empty.
sample : str
Name of the sample. It will read first sample if empty string is provided.
ad_tag : str
AD tag (default 'AD')
dp_tag : str
DP tag (default 'DP')
use_index : bool
Use index file for vcf parsing. Default is False.
"""
vcff = Vcf(vcf_file)
chrs = [c for c in vcff.get_chromosomes() if len(chroms) == 0 or c in chroms]
def save_data(chr, rd_p, rd_u):
if (len(chroms) == 0 or chr in chroms) and (not rd_p is None) and (len(rd_p) > 0):
self.io.save_rd(chr, rd_p, rd_u, chromosome_length=vcff.lengths[chr])
# TODO: Stop reading if all from chroms list are already read.
if use_index:
count = 0
for c in chrs:
_logger.info("Reading variant data for chromosome %s" % c)
rd_p, rd_u = vcff.read_chromosome_rd(c, sample, ad_tag=ad_tag, dp_tag=dp_tag)
if not rd_p is None and len(rd_p) > 0:
self.io.save_rd(chr, rd_p, rd_u, chromosome_length=vcff.lengths[chr])
count += 1
self.io.add_meta_attribute("RD from VCF", vcf_file)
return count
else:
count = vcff.read_all_rd(save_data, sample, ad_tag=ad_tag, dp_tag=dp_tag)
self.io.add_meta_attribute("RD from VCF", vcf_file)
return count
def _pileup_bam(self, bamfile, chroms, pos, ref, alt, nref, nalt, reference_filename):
_logger.info("Calculating pileup from bam file '%s'." % bamfile)
bamf = Bam(bamfile, reference_filename=reference_filename)
def pileup_chromosome(x):
c, l, snpc = x
_logger.info("Pileup chromosome %s with length %d" % (c, l))
return bamf.pileup(c, pos[snpc], ref[snpc], alt[snpc])
chrname, chrlen = bamf.get_chr_len()
chr_len = [(c, l, self.io.snp_chromosome_name(c)) for (c, l) in zip(chrname, chrlen) if
self.io.snp_chromosome_name(c) in chroms]
if self.max_cores == 1:
for cl in chr_len:
r = pileup_chromosome(cl)
nref[cl[2]] = [x + y for x, y in zip(nref[cl[2]], r[0])]
nalt[cl[2]] = [x + y for x, y in zip(nalt[cl[2]], r[1])]
else:
from .pool import parmap
res = parmap(pileup_chromosome, chr_len, cores=self.max_cores)
for cl, r in zip(chr_len, res):
nref[cl[2]] = [x + y for x, y in zip(nref[cl[2]], r[0])]
nalt[cl[2]] = [x + y for x, y in zip(nalt[cl[2]], r[1])]
def pileup(self, bamfiles, chroms=[], reference_filename=False):
"""
Read bam/sam/cram file(s) and pile up SNP counts at positions imported with vcf(vcf_files, ...) method
Parameters
----------
bamfiles : list of str
Bam files.
chroms : list of str
List of chromosomes. Calculates for all available if empty.
reference_filename : str
Only for CRAM files - reference genome filename
"""
chrs = [c for c in self.io.snp_chromosomes() if (len(chroms) == 0 or c in chroms)]
pos, ref, alt, nref, nalt, gt, flag, qual = {}, {}, {}, {}, {}, {}, {}, {}
for c in chrs:
_logger.info("Decompressing and setting all SNP counts to zero for chromosome '%s'." % c)
pos[c], ref[c], alt[c], nref[c], nalt[c], gt[c], flag[c], qual[c] = self.io.read_snp(c)
nref[c] = [0] * len(nref[c])
nalt[c] = [0] * len(nalt[c])
for bf in bamfiles:
self._pileup_bam(bf, chrs, pos, ref, alt, nref, nalt, reference_filename=reference_filename)
for c in chrs:
_logger.info("Saving SNP data for chromosome '%s' in file '%s'." % (c, self.io.filename))
self.io.save_snp(c, pos[c], ref[c], alt[c], nref[c], nalt[c], gt[c], flag[c], qual[c])
def rd_from_snp(self, chroms=[], use_mask=True, use_id=False, callset=None):
""" Create RD signal from already imported SNP signal
Parameters
----------
chroms : list of str
List of chromosomes. Calculates for all available if empty.
use_mask : bool
Use P-mask filter if True. Default: True.
use_id : bool
Use id flag filter if True. Default: False.
callset : str or None
It will assume SNP data if None. Otherwise it will assume SNV data
stored under the name provided by callset variable.
Returns
-------
"""
chromosomes = [c for c in self.io.snp_chromosomes() if (len(chroms) == 0 or c in chroms)]
snp_mask_chromosomes = {}
for c in self.io_mask.mask_chromosomes():
snp_name = self.io.snp_chromosome_name(c)
if snp_name is not None:
snp_mask_chromosomes[snp_name] = c
for c in chromosomes:
_logger.info("Calculating RD signal for chromosome '%s' using SNP counts." % c)
pos, ref, alt, nref, nalt, gt, flag, qual = self.io.read_snp(c, callset=callset)
n = self.io.get_chromosome_length(c) // 100 + 1
rd = np.zeros(n)
ncg = self.io.get_chromosome_length(c) // 10000 + 1
rdcg = np.zeros(ncg)
rdc = np.zeros(ncg)
for p, c1, c2, f in zip(pos, nref, nalt, flag):
if (c1 + c2) > 0 and (not use_id or (f & 1)) and (not use_mask or (f & 2)):
rdcg[(p - 1) // 10000] += c1 + c2
rdc[(p - 1) // 10000] += 1
rdcg = rdcg / rdc
for i in range(n):
rd[i] = rdcg[i // 100]
self.io.save_rd(c, rd, rd)
def gc(self, filename, chroms=[], make_gc_genome_file=False):
""" Read GC content from reference fasta file and store in .cnvnator file
Arguments:
* FASTA filename
* list of chromosome names
"""
fasta = Fasta(filename)
chrname, chrlen = fasta.get_chr_len()
chr_len_rdn = []
if make_gc_genome_file:
_logger.debug("GC data for all reference genome contigs will be read and stored in cnvnator file.")
for (c, l) in zip(chrname, chrlen):
chr_len_rdn.append((c, l, c))
else:
for (c, l) in zip(chrname, chrlen):
rd_name = self.io.rd_chromosome_name(c)
if len(chroms) == 0 or (rd_name in chroms) or (c in chroms):
if rd_name is None:
_logger.debug("Not found RD signal for chromosome '%s'. Skipping..." % c)
else:
_logger.debug("Found RD signal for chromosome '%s' with name '%s'." % (c, rd_name))
chr_len_rdn.append((c, l, rd_name))
count = 0
for c, l, rdn in chr_len_rdn:
_logger.info("Reading data for chromosome '%s' with length %d" % (c, l))
gc, at = fasta.read_chromosome_gc(c)
if not gc is None:
self.io.create_signal(rdn, None, "GC/AT", gc_at_compress(gc, at))
count += 1
_logger.info("GC data for chromosome '%s' saved in file '%s'." % (rdn, self.io.filename))
if count > 0:
_logger.info("Running RD statistics on chromosomes with imported GC data.")
self.rd_stat()
return count
def copy_gc(self, filename, chroms=[]):
""" Copy GC content from another cnvnator file
Arguments:
* cnvnator filename
* list of chromosome names
"""
io_src = IO(filename)
chr_rdn = []
for c in io_src.chromosomes_with_signal(None, "GC/AT"):
rd_name = self.io.rd_chromosome_name(c)
if len(chroms) == 0 or (rd_name in chroms) or (c in chroms):
if rd_name is None:
_logger.debug("Not found RD signal for chromosome '%s'. Skipping..." % c)
else:
_logger.debug("Found RD signal for chromosome '%s' with name '%s'." % (c, rd_name))
chr_rdn.append((c, rd_name))
count = 0
for c, rdn in chr_rdn:
_logger.info(
"Copying GC data for chromosome '%s' from file '%s' in file '%s'." % (c, filename, self.io.filename))
self.io.create_signal(rdn, None, "GC/AT", io_src.get_signal(c, None, "GC/AT").astype(dtype="uint8"))
return count
def mask(self, filename, chroms=[], make_mask_genome_file=False):
""" Read strict mask fasta file and store in .cnvnator file
Arguments:
* FASTA filename
* list of chromosome names
"""
fasta = Fasta(filename)
chrname, chrlen = fasta.get_chr_len()
chr_len_rdn = []
if make_mask_genome_file:
_logger.debug("Strict mask data for all reference genome contigs will be read and stored in cnvnator file.")
for (c, l) in zip(chrname, chrlen):
chr_len_rdn.append((c, l, c))
else:
for (c, l) in zip(chrname, chrlen):
rd_name = self.io.rd_chromosome_name(c)
snp_name = self.io.snp_chromosome_name(c)
if len(chroms) == 0 or (rd_name in chroms) or (snp_name in chroms) or (c in chroms):
if (rd_name is None) and (snp_name is None):
_logger.debug("Not found RD or SNP signal for chromosome '%s'. Skipping..." % c)
elif (rd_name is None):
_logger.debug("Found SNP signal for chromosome '%s' with name '%s'." % (c, snp_name))
chr_len_rdn.append((c, l, snp_name))
else:
_logger.debug("Found RD signal for chromosome '%s' with name '%s'." % (c, rd_name))
chr_len_rdn.append((c, l, rd_name))
count = 0
for c, l, rdn in chr_len_rdn:
_logger.info("Reading data for chromosome '%s' with length %d" % (c, l))
mask = fasta.read_chromosome_mask_p_regions(c)
if not mask is None:
self.io.create_signal(rdn, None, "mask", mask_compress(mask))
count += 1
_logger.info("Strict mask data for chromosome '%s' saved in file '%s'." % (rdn, self.io.filename))
return count
def copy_mask(self, filename, chroms=[]):
""" Copy strict mask data from another cnvnator file
Arguments:
* cnvnator filename
* list of chromosome names
"""
io_src = IO(filename)
chr_rdn = []
for c in io_src.chromosomes_with_signal(None, "mask"):
rd_name = self.io.rd_chromosome_name(c)
snp_name = self.snp_chromosome_name(c)
if len(chroms) == 0 or (rd_name in chroms) or (snp_name in chroms) or (c in chroms):
if (rd_name is None) and (snp_name is None):
_logger.debug("Not found RD or SNP signal for chromosome '%s'. Skipping..." % c)
elif (rd_name is None):
_logger.debug("Found SNP signal for chromosome '%s' with name '%s'." % (c, snp_name))
chr_rdn.append((c, snp_name))
else:
_logger.debug("Found RD signal for chromosome '%s' with name '%s'." % (c, rd_name))
chr_rdn.append((c, rd_name))
count = 0
for c, rdn in chr_rdn:
_logger.info(
"Copying strict mask data for chromosome '%s' from file '%s' in file '%s'." % (
c, filename, self.io.filename))
self.io.create_signal(rdn, None, "mask", io_src.get_signal(c, None, "mask").astype(dtype="uint32"))
return count
def set_reference_genome(self, rg):
""" Manually sets reference genome.
Parameters
----------
rg: str
Name of reference genome
Returns
-------
True if genome exists in database
"""
if rg in Genome.reference_genomes:
_logger.info("Reference genome '%s' found in database." % rg)
self.io.create_signal(None, None, "reference genome", np.array([np.string_(rg)]))
self.io.create_signal(None, None, "use reference", np.array([1, 1]).astype("uint8"))
if "mask_file" in Genome.reference_genomes[rg]:
_logger.info("Strict mask for reference genome '%s' found in database." % rg)
if "gc_file" in Genome.reference_genomes[rg]:
_logger.info("GC content for reference genome '%s' found in database." % rg)
else:
_logger.warning("Reference genome '%s' not found in database." % rg)
def calculate_histograms(self, bin_sizes, chroms=[]):
"""
Calculates RD histograms and store data into cnvpytor file.
Parameters
----------
bin_sizes : list of int
List of histogram bin sizes
chroms : list of str
List of chromosomes. Calculates for all available if empty.
"""
rd_gc_chromosomes = {}
for c in self.io_gc.gc_chromosomes():
rd_name = self.io.rd_chromosome_name(c)
if not rd_name is None and (len(chroms) == 0 or (rd_name in chroms) or (c in chroms)):
rd_gc_chromosomes[rd_name] = c
rd_mask_chromosomes = {}
for c in self.io_mask.mask_chromosomes():
rd_name = self.io.rd_chromosome_name(c)
if not rd_name is None and (len(chroms) == 0 or (rd_name in chroms) or (c in chroms)):
rd_mask_chromosomes[rd_name] = c
for bin_size in bin_sizes:
his_stat = []
auto, sex, mt = False, False, False
bin_ratio = bin_size // 100
for c in self.io.rd_chromosomes():
if c in rd_gc_chromosomes:
_logger.info("Calculating histograms using bin size %d for chromosome '%s'." % (bin_size, c))
flag = FLAG_MT if Genome.is_mt_chrom(c) else FLAG_SEX if Genome.is_sex_chrom(c) else FLAG_AUTO
rd_p, rd_u = self.io.read_rd(c)
his_p = np.concatenate(
(rd_p, np.zeros(bin_ratio - len(rd_p) + (len(rd_p) // bin_ratio * bin_ratio))))
his_p.resize((len(his_p) // bin_ratio, bin_ratio))
his_p = his_p.sum(axis=1)
his_u = np.concatenate(
(rd_u, np.zeros(bin_ratio - len(rd_u) + (len(rd_u) // bin_ratio * bin_ratio))))
his_u.resize((len(his_u) // bin_ratio, bin_ratio))
his_u = his_u.sum(axis=1)
if bin_ratio == 1:
his_p = his_p[:-1]
his_u = his_u[:-1]
self.io.create_signal(c, bin_size, "RD", his_p)
self.io.create_signal(c, bin_size, "RD unique", his_u)
max_bin = max(int(10 * np.mean(his_u) + 1), int(10 * np.mean(his_p) + 1))
if max_bin < 10000:
max_bin = 10000
rd_bin_size = max_bin // 10000
rd_bins = range(0, max_bin // rd_bin_size * rd_bin_size + rd_bin_size, rd_bin_size)
dist_p, bins = np.histogram(his_p, bins=rd_bins)
dist_u, bins = np.histogram(his_u, bins=rd_bins)
n_p, m_p, s_p = fit_normal(bins[1:-1], dist_p[1:])[0]
n_u, m_u, s_u = fit_normal(bins[1:-1], dist_u[1:])[0]
_logger.info(
"Chromosome '%s' bin size %d stat - RD parity distribution gaussian fit: %.2f +- %.2f" % (
c, bin_size, m_p, s_p))
_logger.info(
"Chromosome '%s' bin size %d stat - RD unique distribution gaussian fit: %.2f +- %.2f" % (
c, bin_size, m_u, s_u))
his_stat.append((c, m_p, s_p, m_u, s_u))
auto = auto or Genome.is_autosome(c)
sex = sex or Genome.is_sex_chrom(c)
mt = mt or Genome.is_mt_chrom(c)
mt = mt and (bin_size <= 1000)
if auto:
max_bin_auto = int(
max(map(lambda x: 5 * x[1] + 5 * x[2], filter(lambda x: Genome.is_autosome(x[0]), his_stat))))
_logger.debug("Max RD for autosome histograms calculated: %d." % max_bin_auto)
if max_bin_auto < 1000:
max_bin_auto = 1000
bin_size_auto = max_bin_auto // 1000
bins_auto = range(0, max_bin_auto // bin_size_auto * bin_size_auto + bin_size_auto, bin_size_auto)
n_bins_auto = len(bins_auto) - 1
_logger.debug(
"Using %d RD bin size, %d bins for autosome RD - GC distributions." % (bin_size_auto, n_bins_auto))
dist_p_auto = np.zeros(n_bins_auto)
dist_p_gccorr_auto = np.zeros(n_bins_auto)
dist_u_auto = np.zeros(n_bins_auto)
dist_p_gc_auto = np.zeros((n_bins_auto, 101))
if sex:
max_bin_sex = int(
max(map(lambda x: 5 * x[1] + 5 * x[2], filter(lambda x: Genome.is_sex_chrom(x[0]), his_stat))))
_logger.debug("Max RD for sex chromosome histograms calculated: %d." % max_bin_sex)
if max_bin_sex < 1000:
max_bin_sex = 1000
bin_size_sex = max_bin_sex // 1000
bins_sex = range(0, max_bin_sex // bin_size_sex * bin_size_sex + bin_size_sex, bin_size_sex)
n_bins_sex = len(bins_sex) - 1
_logger.debug(
"Using %d RD bin size, %d bins for sex chromosome RD - GC distributions." % (
bin_size_sex, n_bins_sex))
dist_p_sex = np.zeros(n_bins_sex)
dist_p_gccorr_sex = np.zeros(n_bins_sex)
dist_u_sex = np.zeros(n_bins_sex)
dist_p_gc_sex = np.zeros((n_bins_sex, 101))
if mt:
max_bin_mt = int(
max(map(lambda x: 5 * x[1] + 5 * x[2], filter(lambda x: Genome.is_mt_chrom(x[0]), his_stat))))
_logger.debug("Max RD for mitochondria histogram calculated: %d." % max_bin_mt)
if max_bin_mt < 1000:
max_bin_mt = 1000
bin_size_mt = max_bin_mt // 1000
bins_mt = range(0, max_bin_mt // bin_size_mt * bin_size_mt + bin_size_mt, bin_size_mt)
n_bins_mt = len(bins_mt) - 1
_logger.debug("Using %d bin size, %d bins for mitochondria chromosome." % (bin_size_mt, n_bins_mt))
dist_p_mt = np.zeros(n_bins_mt)
dist_p_gccorr_mt = np.zeros(n_bins_mt)
dist_u_mt = np.zeros(n_bins_mt)
dist_p_gc_mt = np.zeros((n_bins_mt, 101))
_logger.info("Calculating global statistics.")
for c in self.io.rd_chromosomes():
if c in rd_gc_chromosomes:
_logger.debug("Chromosome '%s'." % c)
his_p = self.io.get_signal(c, bin_size, "RD")
his_u = self.io.get_signal(c, bin_size, "RD unique")
if Genome.is_autosome(c):
dist_p, bins = np.histogram(his_p, bins=bins_auto)
dist_u, bins = np.histogram(his_u, bins=bins_auto)
gcat = self.io_gc.get_signal(rd_gc_chromosomes[c], None, "GC/AT")
dist_p_gc, xbins, ybins = np.histogram2d(his_p, gcp_decompress(gcat, bin_ratio),
bins=(bins_auto, range(102)))
dist_p_auto += dist_p
dist_u_auto += dist_u
dist_p_gc_auto += dist_p_gc
elif Genome.is_sex_chrom(c):
dist_p, bins = np.histogram(his_p, bins=bins_sex)
dist_u, bins = np.histogram(his_u, bins=bins_sex)
gcat = self.io_gc.get_signal(rd_gc_chromosomes[c], None, "GC/AT")
dist_p_gc, xbins, ybins = np.histogram2d(his_p, gcp_decompress(gcat, bin_ratio),
bins=(bins_sex, range(102)))
dist_p_sex += dist_p
dist_u_sex += dist_u
dist_p_gc_sex += dist_p_gc
elif Genome.is_mt_chrom(c) and mt:
dist_p, bins = np.histogram(his_p, bins=bins_mt)
dist_u, bins = np.histogram(his_u, bins=bins_mt)
gcat = self.io_gc.get_signal(rd_gc_chromosomes[c], None, "GC/AT")
dist_p_gc, xbins, ybins = np.histogram2d(his_p, gcp_decompress(gcat, bin_ratio),
bins=(bins_mt, range(102)))
dist_p_mt += dist_p
dist_u_mt += dist_u
dist_p_gc_mt += dist_p_gc
if auto:
n_auto, m_auto, s_auto = fit_normal(np.array(bins_auto[1:-1]), dist_p_auto[1:])[0]
_logger.info("Autosomes stat - RD parity distribution gaussian fit: %.2f +- %.2f" % (m_auto, s_auto))
stat_auto = np.array([max_bin_auto, bin_size_auto, n_bins_auto, n_auto, m_auto, s_auto])
self.io.create_signal(None, bin_size, "RD p dist", dist_p_auto, flags=FLAG_AUTO)
self.io.create_signal(None, bin_size, "RD u dist", dist_u_auto, flags=FLAG_AUTO)
self.io.create_signal(None, bin_size, "RD GC dist", dist_p_gc_auto, flags=FLAG_AUTO)
self.io.create_signal(None, bin_size, "RD stat", stat_auto, flags=FLAG_AUTO)
gc_corr_auto = calculate_gc_correction(dist_p_gc_auto, m_auto, s_auto, bin_size_auto)
self.io.create_signal(None, bin_size, "GC corr", gc_corr_auto, flags=FLAG_AUTO)
if sex:
n_sex, m_sex, s_sex = fit_normal(np.array(bins_sex[1:-1]), dist_p_sex[1:])[0]
_logger.info(
"Sex chromosomes stat - RD parity distribution gaussian fit: %.2f +- %.2f" % (m_sex, s_sex))
stat_sex = np.array([max_bin_sex, bin_size_sex, n_bins_sex, n_sex, m_sex, s_sex])
self.io.create_signal(None, bin_size, "RD p dist", dist_p_sex, flags=FLAG_SEX)
self.io.create_signal(None, bin_size, "RD u dist", dist_u_sex, flags=FLAG_SEX)
self.io.create_signal(None, bin_size, "RD GC dist", dist_p_gc_sex, flags=FLAG_SEX)
self.io.create_signal(None, bin_size, "RD stat", stat_sex, flags=FLAG_SEX)
gc_corr_sex = calculate_gc_correction(dist_p_gc_sex, m_sex, s_sex, bin_size_sex)
self.io.create_signal(None, bin_size, "GC corr", gc_corr_sex, flags=FLAG_SEX)
if mt:
n_mt, m_mt, s_mt = fit_normal(np.array(bins_mt[1:-1]), dist_p_mt[1:])[0]
_logger.info("Mitochondria stat - RD parity distribution gaussian fit: %.2f +- %.2f" % (m_mt, s_mt))
if auto:
_logger.info("Mitochondria stat - number of mitochondria per cell: %.2f +- %.2f" % (
2. * m_mt / m_auto, 2. * s_mt / m_auto + s_auto * m_mt / (m_auto * m_auto)))
stat_mt = np.array([max_bin_mt, bin_size_mt, n_bins_mt, n_mt, m_mt, s_mt])
self.io.create_signal(None, bin_size, "RD p dist", dist_p_mt, flags=FLAG_MT)
self.io.create_signal(None, bin_size, "RD u dist", dist_u_mt, flags=FLAG_MT)
self.io.create_signal(None, bin_size, "RD GC dist", dist_p_gc_mt, flags=FLAG_MT)
self.io.create_signal(None, bin_size, "RD stat", stat_mt, flags=FLAG_MT)
gc_corr_mt = calculate_gc_correction(dist_p_gc_mt, m_mt, s_mt, bin_size_mt)
self.io.create_signal(None, bin_size, "GC corr", gc_corr_mt, flags=FLAG_MT)
for c in self.io.rd_chromosomes():
if c in rd_gc_chromosomes and (mt or not Genome.is_mt_chrom(c)):
_logger.info(
"Calculating GC corrected RD histogram using bin size %d for chromosome '%s'." % (bin_size, c))
flag = FLAG_MT if Genome.is_mt_chrom(c) else FLAG_SEX if Genome.is_sex_chrom(c) else FLAG_AUTO
his_p = self.io.get_signal(c, bin_size, "RD")
_logger.debug("Calculating GC corrected RD")
gc_corr = self.io.get_signal(None, bin_size, "GC corr", flag)
gcat = self.io_gc.get_signal(rd_gc_chromosomes[c], None, "GC/AT")
his_p_corr = his_p / np.array(list(map(lambda x: gc_corr[int(x)], gcp_decompress(gcat, bin_ratio))))
self.io.create_signal(c, bin_size, "RD", his_p_corr, flags=FLAG_GC_CORR)
if Genome.is_autosome(c):
dist_p_gc, bins = np.histogram(his_p_corr, bins=bins_auto)
dist_p_gccorr_auto += dist_p_gc
elif Genome.is_sex_chrom(c):
dist_p_gc, bins = np.histogram(his_p_corr, bins=bins_sex)
dist_p_gccorr_sex += dist_p_gc
elif Genome.is_mt_chrom(c) and mt:
dist_p_gc, bins = np.histogram(his_p_corr, bins=bins_mt)
dist_p_gccorr_mt += dist_p_gc
if auto:
n_auto, m_auto, s_auto = fit_normal(np.array(bins_auto[1:-1]), dist_p_gccorr_auto[1:])[0]
_logger.info(
"Autosomes stat - RD parity distribution gaussian fit after GC correction: %.2f +- %.2f" % (
m_auto, s_auto))
stat_auto = np.array([max_bin_auto, bin_size_auto, n_bins_auto, n_auto, m_auto, s_auto])
self.io.create_signal(None, bin_size, "RD p dist", dist_p_gccorr_auto, flags=(FLAG_AUTO | FLAG_GC_CORR))
self.io.create_signal(None, bin_size, "RD stat", stat_auto, flags=(FLAG_AUTO | FLAG_GC_CORR))
if sex:
n_sex, m_sex, s_sex = fit_normal(np.array(bins_sex[1:-1]), dist_p_gccorr_sex[1:])[0]
_logger.info(
"Sex chromosomes stat - RD parity distribution gaussian fit after GC correction: %.2f +- %.2f" % (
m_sex, s_sex))
stat_sex = np.array([max_bin_sex, bin_size_sex, n_bins_sex, n_sex, m_sex, s_sex])
self.io.create_signal(None, bin_size, "RD p dist", dist_p_gccorr_sex, flags=(FLAG_SEX | FLAG_GC_CORR))
self.io.create_signal(None, bin_size, "RD stat", stat_sex, flags=(FLAG_SEX | FLAG_GC_CORR))
if mt:
n_mt, m_mt, s_mt = fit_normal(np.array(bins_mt[1:-1]), dist_p_gccorr_mt[1:])[0]
_logger.info(
"Mitochondria stat - RD parity distribution gaussian fit after GC correction: %.2f +- %.2f" % (
m_mt, s_mt))
if auto:
_logger.info(
"Mitochondria stat - number of mitochondria per cell after GC correction: %.2f +- %.2f" % (
2. * m_mt / m_auto, 2. * s_mt / m_auto + s_auto * m_mt / (m_auto * m_auto)))
stat_mt = np.array([max_bin_mt, bin_size_mt, n_bins_mt, n_mt, m_mt, s_mt])
self.io.create_signal(None, bin_size, "RD p dist", dist_p_gccorr_mt, flags=(FLAG_MT | FLAG_GC_CORR))
self.io.create_signal(None, bin_size, "RD stat", stat_mt, flags=(FLAG_MT | FLAG_GC_CORR))
for c in self.io.rd_chromosomes():
if (c in rd_gc_chromosomes) and (c in rd_mask_chromosomes):
_logger.info("Calculating P-mask histograms using bin size %d for chromosome '%s'." % (bin_size, c))
flag = FLAG_MT if Genome.is_mt_chrom(c) else FLAG_SEX if Genome.is_sex_chrom(c) else FLAG_AUTO
rd_p, rd_u = self.io.read_rd(c)
mask = mask_decompress(self.io_mask.get_signal(rd_mask_chromosomes[c], None, "mask"))
bin_ratio = bin_size // 100
n_bins = len(rd_p) // bin_ratio + 1
his_p = np.zeros(n_bins)
his_p_corr = np.zeros(n_bins)
his_u = np.zeros(n_bins)
his_count = np.zeros(n_bins)
for (b, e) in mask:
for p in range((b - 1) // 100 + 2, (e - 1) // 100):
his_p[p // bin_ratio] += rd_p[p]
his_u[p // bin_ratio] += rd_u[p]
his_count[p // bin_ratio] += 1
np.seterr(divide='ignore', invalid='ignore')
his_p = his_p / his_count * bin_ratio
his_u = his_u / his_count * bin_ratio
if bin_ratio == 1:
his_p = his_p[:-1]
his_u = his_u[:-1]
gc_corr = self.io.get_signal(None, bin_size, "GC corr", flag)
gcat = self.io_gc.get_signal(rd_gc_chromosomes[c], None, "GC/AT")
his_p_corr = his_p / np.array(list(map(lambda x: gc_corr[int(x)], gcp_decompress(gcat, bin_ratio))))
self.io.create_signal(c, bin_size, "RD", his_p, flags=FLAG_USEMASK)
self.io.create_signal(c, bin_size, "RD unique", his_u, flags=FLAG_USEMASK)
self.io.create_signal(c, bin_size, "RD", his_p_corr, flags=FLAG_GC_CORR | FLAG_USEMASK)
def partition(self, bin_sizes, chroms=[], use_gc_corr=True, use_mask=False, repeats=3, genome_size=2.9e9):
"""
Calculates segmentation of RD signal.
Parameters
----------
bin_sizes : list of int
List of histogram bin sizes
chroms : list of str
List of chromosomes. Calculates for all available if empty.
use_gc_corr : bool
Use GC corrected signal if True. Default: True.
use_mask : bool
Use P-mask filter if True. Default: False.
"""
bin_bands = [2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56, 64, 80, 96, 112, 128]
rd_gc_chromosomes = {}
for c in self.io_gc.gc_chromosomes():
rd_name = self.io.rd_chromosome_name(c)
if not rd_name is None:
rd_gc_chromosomes[rd_name] = c
rd_mask_chromosomes = {}
for c in self.io_mask.mask_chromosomes():
rd_name = self.io.rd_chromosome_name(c)
if not rd_name is None:
rd_mask_chromosomes[rd_name] = c
for bin_size in bin_sizes:
for c in self.io.rd_chromosomes():
if (c in rd_gc_chromosomes or not use_gc_corr) and (c in rd_mask_chromosomes or not use_mask) and (
len(chroms) == 0 or (c in chroms)):
flag_stat = FLAG_MT if Genome.is_mt_chrom(c) else FLAG_SEX if Genome.is_sex_chrom(c) else FLAG_AUTO
if use_gc_corr:
flag_stat |= FLAG_GC_CORR
flag_rd = (FLAG_GC_CORR if use_gc_corr else 0) | (FLAG_USEMASK if use_mask else 0)
if self.io.signal_exists(c, bin_size, "RD stat", flag_stat) and self.io.signal_exists(c, bin_size,
"RD",
flag_rd):
_logger.info("Calculating partition using bin size %d for chromosome '%s'." % (bin_size, c))
stat = self.io.get_signal(c, bin_size, "RD stat", flag_stat)
mean = stat[4]
std = stat[5]
rd = self.io.get_signal(c, bin_size, "RD", flag_rd)
rd = np.nan_to_num(rd)
masked = np.zeros_like(rd, dtype=bool)
levels = np.copy(rd)
for bin_band in bin_bands:
_logger.debug("Bin band is %d." % bin_band)
levels[np.logical_not(masked)] = rd[np.logical_not(masked)]
nm_levels = levels[np.logical_not(masked)]
mask_borders = [0]
count = 0
for i in range(len(masked)):
if masked[i]:
if count > 0:
mask_borders.append(mask_borders[-1] + count - 1)
count = 0
else:
count += 1
mask_borders = mask_borders[1:]
kk = np.arange(3 * bin_band + 1)
exp_kk = kk * np.exp(-0.5 * kk ** 2 / bin_band ** 2)
for step in range(repeats):
isig = np.ones_like(nm_levels) * 4. / std ** 2
isig[nm_levels >= (mean / 4)] = mean / std ** 2 / nm_levels[nm_levels >= (mean / 4)]
def calc_grad(k):
if k < len(nm_levels):
t1 = np.concatenate((
np.exp(-0.5 * (nm_levels - np.roll(nm_levels, -k)) ** 2 * isig)[:-k],
[0] * k))
t2 = np.concatenate(([0] * k,
np.exp(-0.5 * (nm_levels - np.roll(nm_levels,
k)) ** 2 * isig)[k:]))
return exp_kk[k] * (t1 - t2)
else:
return np.zeros_like(nm_levels)
grad = np.sum([calc_grad(k) for k in range(1, 3 * bin_band + 1)], axis=0)
border = [i for i in range(grad.size - 1) if grad[i] < 0 and grad[i + 1] >= 0]
border.append(grad.size - 1)
border = sorted(list(set(border + mask_borders)))
# border = sorted(list(set([0]+border+[len(nm_levels)-1])))
pb = 0
for b in border:
nm_levels[pb:b + 1] = np.mean(nm_levels[pb:b + 1])
pb = b + 1
levels[np.logical_not(masked)] = nm_levels
border = [0] + list(np.argwhere(np.abs(np.diff(levels)) > 0.01)[:, 0] + 1) + [levels.size]
masked = np.zeros_like(rd, dtype=bool)
for i in range(1, len(border)):
seg = [border[i - 1], border[i]]
seg_left = [border[i - 1], border[i - 1]]
if i > 1:
seg_left[0] = border[i - 2]
else:
continue
seg_right = [border[i], border[i]]
if i < (len(border) - 1):
seg_right[1] = border[i + 1]
else:
continue
n = seg[1] - seg[0]
n_left = seg_left[1] - seg_left[0]
n_right = seg_right[1] - seg_right[0]
if n <= 1:
continue
seg_mean = np.mean(levels[seg[0]:seg[1]])
seg_std = np.std(levels[seg[0]:seg[1]])
if (n_right <= 15) or (n_left <= 15) or (n <= 15):
ns = 1.8 * np.sqrt(levels[seg_left[0]] / mean) * std
if np.abs(levels[seg_left[0]] - levels[seg[0]]) < ns:
continue
ns = 1.8 * np.sqrt(levels[seg_right[0]] / mean) * std
if np.abs(levels[seg_right[0]] - levels[seg[0]]) < ns:
continue
else:
seg_left_mean = np.mean(levels[seg_left[0]:seg_left[1]])
seg_left_std = np.std(levels[seg_left[0]:seg_left[1]])
seg_right_mean = np.mean(levels[seg_right[0]:seg_right[1]])
seg_right_std = np.std(levels[seg_right[0]:seg_right[1]])
if t_test_2_samples(seg_mean, seg_std, n, seg_left_mean, seg_left_std, n_left) > (
0.01 / genome_size * bin_size * (n + n_left)):
continue
if t_test_2_samples(seg_mean, seg_std, n, seg_right_mean, seg_right_std,
n_right) > (
0.01 / genome_size * bin_size * (n + n_right)):
continue
if t_test_1_sample(mean, seg_mean, seg_std, n) > 0.05:
continue
masked[seg[0]:seg[1]] = True
levels[seg[0]:seg[1]] = np.mean(rd[seg[0]:seg[1]])
self.io.create_signal(c, bin_size, "RD partition", levels, flags=flag_rd)
def call(self, bin_sizes, chroms=[], print_calls=False, use_gc_corr=True, use_mask=False, genome_size=2.9e9,
genome_cnv_fraction=0.01):
"""
CNV caller based on the segmented RD signal.
Parameters
----------
bin_sizes : list of int
List of histogram bin sizes
chroms : list of str
List of chromosomes. Calculates for all available if empty.
print_calls : bool
Print to stdout list of calls if true.
use_gc_corr : bool
Use GC corrected signal if True. Default: True.
use_mask : bool
Use P-mask filter if True. Default: False.
Returns
-------
calls: dist
Dictionary bin_size -> list of calls
Each call is list with values:
type ("deletion" or "duplication"),
chromosome name, start, end,
size, cnv level
e1, e2, e3, e4 - estimations of p-Value
q0 - percentage of uniquely mapped reads in cnv region
"""
ret = {}
normal_genome_size = genome_size * (1 - genome_cnv_fraction)
rd_gc_chromosomes = {}
for c in self.io_gc.gc_chromosomes():
rd_name = self.io.rd_chromosome_name(c)
if not rd_name is None:
rd_gc_chromosomes[rd_name] = c
rd_mask_chromosomes = {}
for c in self.io_mask.mask_chromosomes():
rd_name = self.io.rd_chromosome_name(c)
if not rd_name is None:
rd_mask_chromosomes[rd_name] = c
for bin_size in bin_sizes:
ret[bin_size] = []
for c in self.io.rd_chromosomes():
if (c in rd_gc_chromosomes or not use_gc_corr) and (c in rd_mask_chromosomes or not use_mask) and (
len(chroms) == 0 or (c in chroms)):
flag_stat = FLAG_MT if Genome.is_mt_chrom(c) else FLAG_SEX if Genome.is_sex_chrom(c) else FLAG_AUTO
flag_auto = FLAG_AUTO
if use_gc_corr:
flag_stat |= FLAG_GC_CORR
flag_auto |= FLAG_GC_CORR
flag_rd = (FLAG_GC_CORR if use_gc_corr else 0) | (FLAG_USEMASK if use_mask else 0)
if self.io.signal_exists(c, bin_size, "RD stat", flag_stat) and \
self.io.signal_exists(c, bin_size, "RD", flag_rd) and \
self.io.signal_exists(c, bin_size, "RD partition", flag_rd):
_logger.debug("Calculating CNV calls using bin size %d for chromosome '%s'." % (bin_size, c))
calls_list = []
stat = self.io.get_signal(c, bin_size, "RD stat", flag_stat)
mean = stat[4]
std = stat[5]
rd = self.io.get_signal(c, bin_size, "RD", flag_rd)
rd = np.nan_to_num(rd)
gc, at, NN, distN = False, False, False, False
if c in rd_gc_chromosomes and self.io_gc.signal_exists(rd_gc_chromosomes[c], None, "GC/AT"):
gcat = self.io_gc.get_signal(rd_gc_chromosomes[c], None, "GC/AT")
gc, at = gc_at_decompress(gcat)
NN = 100 - np.array(gc) - np.array(at)
distN = np.zeros_like(NN,dtype="long") - 1
distN[NN == 100] = 0
prev = 0
for Ni in range(0, distN.size):
if distN[Ni] == -1:
prev += 100
distN[Ni] = prev
else:
prev = 0
prev = 0
for Ni in range(distN.size - 1, -1, -1):
if distN[Ni] > 0:
prev += 100
if prev < distN[Ni]:
distN[Ni] = prev
else:
prev = 0
levels = self.io.get_signal(c, bin_size, "RD partition", flag_rd)
delta = 0.25
if Genome.is_sex_chrom(c) and self.io.signal_exists(c, bin_size, "RD stat", flag_auto):
stat_auto = self.io.get_signal(c, bin_size, "RD stat", flag_auto)
if stat_auto[4] * 0.66 > mean:
_logger.debug("Assuming male individual!")
delta *= 2
_logger.debug("Merging levels with relative difference smaller than %f.", delta)
delta *= mean
done = False
while not done:
done = True
# border - list of borders between segments
border = [0] + list(np.argwhere(np.abs(np.diff(levels)) > 0.01)[:, 0] + 1) + [levels.size]
for ix in range(len(border) - 2):
if ix < len(border) - 2:
v1 = np.abs(levels[border[ix]] - levels[border[ix + 1]])
if v1 < delta:
v2 = v1 + 1
v3 = v1 + 1
if ix > 0:
v2 = np.abs(levels[border[ix]] - levels[border[ix - 1]])
if ix < len(border) - 3:
v3 = np.abs(levels[border[ix + 1]] - levels[border[ix + 2]])
if v1 < v2 and v1 < v3:
done = False
levels[border[ix]:border[ix + 2]] = np.mean(
levels[border[ix]:border[ix + 2]])
del border[ix + 1]
_logger.debug("Calling segments")
min = mean - delta
max = mean + delta
flags = [""] * len(levels)
segments = []
b = 0
while b < len(levels):
b0 = b
bs = b
while b < len(levels) and levels[b] < min:
b += 1
be = b
if be > bs + 1:
adj = adjustToEvalue(mean, std, rd, bs, be, 0.05 * bin_size / normal_genome_size)
if adj is not None:
bs, be = adj
segments.append([bs, be, -1])
flags[bs:be] = ["D"] * (be - bs)
bs = b
while b < len(levels) and levels[b] > max:
b += 1
be = b
if be > bs + 1:
adj = adjustToEvalue(mean, std, rd, bs, be, 0.05 * bin_size / normal_genome_size)
if adj is not None:
bs, be = adj
segments.append([bs, be, +1])
flags[bs:be] = ["A"] * (be - bs)
if b == b0:
b += 1
_logger.debug("Calling additional deletions")
b = 0
while b < len(levels):
while b < len(levels) and flags[b] != "":
b += 1
bs = b
while b < len(levels) and levels[b] < min:
b += 1
be = b
if be > bs + 1:
if gaussianEValue(mean, std, rd, bs, be) < 0.05 / normal_genome_size:
segments.append([bs, be, -1])
flags[bs:be] = ["d"] * (be - bs)
b -= 1
b += 1
b = 0
if b < len(levels):
cf = flags[b]
bs = 0
merge = rd.copy()
while b < len(levels):
while flags[b] == cf:
b += 1
if b >= len(flags):
break
if b > bs:
merge[bs:b] = np.mean(merge[bs:b])
if b < len(levels):
cf = flags[b]
bs = b
self.io.create_signal(c, bin_size, "RD call", merge, flags=flag_rd)
_logger.debug("Calculate/print calls")
b = 0
while b < len(levels):
cf = flags[b]
if cf == "":
b += 1
continue
bs = b
while b < len(levels) and cf == flags[b]:
b += 1
cnv = np.mean(rd[bs:b]) / mean
if cf.upper() == "D":
etype = "deletion"
netype = -1
else:
etype = "duplication"
netype = 1
start = bin_size * bs + 1
end = bin_size * b
size = end - start + 1
e1 = getEValue(mean, std, rd, bs, b) * normal_genome_size / bin_size
e2 = gaussianEValue(mean, std, rd, bs, b) * normal_genome_size
e3, e4 = 1, 1
tmp = int(1000. / bin_size + 0.5)
if bs + tmp < b - tmp:
e3 = getEValue(mean, std, rd, bs + tmp, b - tmp) * normal_genome_size / bin_size
e4 = gaussianEValue(mean, std, rd, bs + tmp, b - tmp) * normal_genome_size
rd_p = self.io.get_signal(c, bin_size, "RD")
rd_u = self.io.get_signal(c, bin_size, "RD unique")
q0 = -1
if sum(rd_p[bs:b]) > 0:
q0 = (sum(rd_p[bs:b]) - sum(rd_u[bs:b])) / sum(rd_p[bs:b])
pN = -1
dG = -1
if gc:
pN = (size - sum(gc[start // 100:end // 100]) - sum(at[start // 100:end // 100])) / size
dG = np.min(distN[start // 100:end // 100])
if print_calls:
print("%s\t%s:%d-%d\t%d\t%.4f\t%e\t%e\t%e\t%e\t%.4f\t%.4f\t%d" % (
etype, c, start, end, size, cnv, e1, e2, e3, e4, q0, pN, dG))
ret[bin_size].append([etype, c, start, end, size, cnv, e1, e2, e3, e4, q0, pN, dG])
calls_list.append({
"type": netype,
"start": start,
"end": end,
"size": size,
"cnv": cnv,
"p_val": e1,
"p_val_2": e2,
"p_val_3": e3,
"p_val_4": e4,
"Q0": q0,
"pN": pN,
"dG": dG
})
self.io.save_calls(c, bin_size, "calls", calls_list, flags=flag_rd)
return ret
def call_mosaic(self, bin_sizes, chroms=[], use_gc_corr=True, use_mask=False, omin=None,
max_distance=0.3, anim=""):
"""
CNV caller based on likelihood merger.
Parameters
----------
bin_sizes : list of int
List of histogram bin sizes
chroms : list of str
List of chromosomes. Calculates for all available if empty.
use_gc_corr : bool
Use GC corrected signal if True. Default: True.
use_mask : bool
Use P-mask filter if True. Default: False.
"""
rd_gc_chromosomes = {}
for c in self.io_gc.gc_chromosomes():
rd_name = self.io.rd_chromosome_name(c)
if not rd_name is None:
rd_gc_chromosomes[rd_name] = c
rd_mask_chromosomes = {}
for c in self.io_mask.mask_chromosomes():
rd_name = self.io.rd_chromosome_name(c)
if not rd_name is None:
rd_mask_chromosomes[rd_name] = c
for bin_size in bin_sizes:
if omin is None:
overlap_min = 0.05 * bin_size / 3e9
else:
overlap_min = omin
for c in self.io.rd_chromosomes():
if (c in rd_gc_chromosomes or not use_gc_corr) and (c in rd_mask_chromosomes or not use_mask) and (
len(chroms) == 0 or (c in chroms)):
flag_stat = FLAG_MT if Genome.is_mt_chrom(c) else FLAG_SEX if Genome.is_sex_chrom(c) else FLAG_AUTO
flag_auto = FLAG_AUTO
if use_gc_corr:
flag_stat |= FLAG_GC_CORR
flag_auto |= FLAG_GC_CORR
flag_rd = (FLAG_GC_CORR if use_gc_corr else 0) | (FLAG_USEMASK if use_mask else 0)
if self.io.signal_exists(c, bin_size, "RD stat", flag_stat) and \
self.io.signal_exists(c, bin_size, "RD", flag_rd):
_logger.info("Calculating mosaic calls using bin size %d for chromosome '%s'." % (bin_size, c))
stat = self.io.get_signal(c, bin_size, "RD stat", flag_stat)
mean = stat[4]
std = stat[5]
rd = self.io.get_signal(c, bin_size, "RD", flag_rd)
bins = len(rd)
valid = np.isfinite(rd)
level = rd[valid]
error = np.sqrt(level) ** 2 + std ** 2
loc_fl = np.min(list(zip(np.abs(np.diff(level))[:-1], np.abs(np.diff(level))[1:])), axis=1)
loc_fl = np.concatenate(([0], loc_fl, [0]))
error += (loc_fl / 2) ** 2
error = np.sqrt(error)
level = list(level)
error = list(error)
segments = [[i] for i in range(bins) if np.isfinite(rd[i])]
overlaps = [normal_overlap(level[i], error[i], level[i + 1], error[i + 1]) for i in
range(len(segments) - 1)]
iter = 0
if anim != "":
anim_plot_rd(level, error, segments, bins, iter, anim + c + "_0_" + str(bin_size), 0,
0, mean)
while len(overlaps) > 0:
maxo = max(overlaps)
if maxo < overlap_min:
break
i = overlaps.index(maxo)
nl, ne = normal_merge(level[i], error[i], level[i + 1], error[i + 1])
level[i] = nl
error[i] = ne
segments[i] += segments[i + 1]
del level[i + 1]
del error[i + 1]
del segments[i + 1]
del overlaps[i]
if i < len(overlaps):
overlaps[i] = normal_overlap(level[i], error[i], level[i + 1], error[i + 1])
if i > 0:
overlaps[i - 1] = normal_overlap(level[i - 1], error[i - 1], level[i], error[i])
iter = iter + 1
if anim != "" and (iter % 100) == 0:
anim_plot_rd(level, error, segments, bins, iter, anim + c + "_0_" + str(bin_size), maxo,
mino, mean)
iter = 0
ons = -1
_logger.info("Second stage. Number of segments: %d." % len(level))
while True:
overlaps = [normal_overlap(level[i], error[i], level[j], error[j]) for i in
range(len(level)) for j in range(i + 1, len(level)) if
(segments[j][0] - segments[i][-1]) < max_distance * (
len(segments[i]) + len(segments[j]))]
if len(overlaps) == 0:
break
maxo = max(overlaps)
if maxo < overlap_min:
break
i, j = 0, 1
while i < len(segments) - 1:
if (segments[j][0] - segments[i][-1]) < max_distance * (
len(segments[i]) + len(segments[j])) and normal_overlap(level[i], error[i],
level[j],
error[j]) == maxo:
nl, ne = normal_merge(level[i], error[i], level[j], error[j])
level[i] = nl
error[i] = ne
segments[i] += segments[j]
segments[i] = sorted(segments[i])
del level[j]
del error[j]
del segments[j]
if j >= len(segments):
i += 1
j = i + 1
else:
j += 1
if j >= len(segments):
i += 1
j = i + 1
iter = iter + 1
if anim != "" and (iter % 100) == 0:
anim_plot_rd(level, error, segments, bins, iter, anim + c + "_1_" + str(bin_size), maxo,
mino, mean)
_logger.info("Iteration: %d. Number of segments: %d." % (iter, len(level)))
if ons == len(segments):
break
ons = len(segments)
for i in range(len(segments)):
i1 = level[i] / mean
i2 = t_test_1_sample(mean, level[i], error[i], len(segments[i]))
if i2 is not None and i2 < (0.05 * bin_size / 3e9) and abs(i1 - 1.) > 0.01:
print(c + ":" + str(segments[i][0] * bin_size + 1) + "-" + str(
segments[i][-1] * bin_size + bin_size),
(segments[i][-1] - segments[i][0] + 1) * bin_size, bin_size, len(segments[i]),
i1, i2)
self.io.create_signal(c, bin_size, "RD mosaic segments",
data=segments_code(segments), flags=flag_rd)
self.io.create_signal(c, bin_size, "RD mosaic call",
data=np.array([level, error], dtype="float32"), flags=flag_rd)
def mask_snps(self, callset=None):
""" Flags SNPs in P-region (sets second bit of the flag to 1 for SNP inside P region, or to 0 otherwise).
Requires imported mask data or recognized reference genome with mask data.
Parameters
----------
callset : str or None
It will assume SNP data if None. Otherwise it will assume SNV data
stored under the name provided by callset variable.
"""
snp_mask_chromosomes = {}
for c in self.io_mask.mask_chromosomes():
snp_name = self.io.snp_chromosome_name(c)
if snp_name is not None:
snp_mask_chromosomes[snp_name] = c
for c in self.io.snp_chromosomes():
if c in snp_mask_chromosomes:
_logger.info("Masking SNP data for chromosome '%s'." % c)
pos, ref, alt, nref, nalt, gt, flag, qual = self.io.read_snp(c, callset=callset)
mask = mask_decompress(self.io_mask.get_signal(snp_mask_chromosomes[c], None, "mask"))
mask_ix = 0
for snp_ix in range(len(pos)):
while mask_ix < len(mask) and mask[mask_ix][1] < pos[snp_ix]:
mask_ix += 1
if mask_ix < len(mask) and mask[mask_ix][0] < pos[snp_ix] and pos[snp_ix] < (
mask[mask_ix][1] + 1):
flag[snp_ix] = flag[snp_ix] | 2
else:
flag[snp_ix] = flag[snp_ix] & 1
if len(pos) > 0:
self.io.save_snp(c, pos, ref, alt, nref, nalt, gt, flag, qual, update=True, callset=callset)
def variant_id(self, vcf_file, chroms, callset=None):
vcff = Vcf(vcf_file)
chrs = [c for c in vcff.get_chromosomes() if len(chroms) == 0 or c in chroms]
def set_id_flag(chr, id_pos, id_ref, id_alt):
snp_chr_name = self.io.snp_chromosome_name(chr)
if snp_chr_name is not None:
pos, ref, alt, nref, nalt, gt, flag, qual = self.io.read_snp(snp_chr_name, callset=callset)
id_ix = 0
f0 = 0
f1 = 0
for snp_ix in range(len(pos)):
while id_ix < len(id_pos) and id_pos[id_ix] < pos[snp_ix]:
id_ix += 1
if id_ix < len(id_pos):
if id_pos[id_ix] == pos[snp_ix] and id_ref[id_ix] == ref[snp_ix] and id_alt[id_ix] == alt[
snp_ix]:
flag[snp_ix] = flag[snp_ix] | 1
f1 += 1
else:
flag[snp_ix] = flag[snp_ix] & 2
f0 += 1
_logger.info("%d of %d variants found in '%s'." % (f1, f0 + f1, vcf_file))
if len(pos) > 0:
self.io.save_snp(snp_chr_name, pos, ref, alt, nref, nalt, gt, flag, qual, update=True,
callset=callset)
return vcff.read_all_snp_positions(set_id_flag)
def calculate_baf(self, bin_sizes, chroms=[], use_mask=True, use_id=False, use_phase=False, res=200,
reduce_noise=False, blw=0.8, use_hom=False):
"""
Calculates BAF histograms and store data into cnvpytor file.
Parameters
----------
bin_sizes : list of int
List of histogram bin sizes
chroms : list of str
List of chromosomes. Calculates for all available if empty.
use_mask : bool
Use P-mask filter if True. Default: True.
use_id : bool
Use id flag filter if True. Default: False.
use_phase : bool
Use phasing information if True and available. Default: False.
res: int
Likelihood function resolution. Default: 200.
"""
snp_flag = (FLAG_USEMASK if use_mask else 0) | (FLAG_USEID if use_id else 0)
for c in self.io.snp_chromosomes():
if len(chroms) == 0 or c in chroms:
_logger.info("Calculating BAF histograms for chromosome '%s'." % c)
pos, ref, alt, nref, nalt, gt, flag, qual = self.io.read_snp(c)
max_bin = {}
count00 = {}
count01 = {}
count10 = {}
count11 = {}
reads00 = {}
reads01 = {}
reads10 = {}
reads11 = {}
baf = {}
maf = {}
likelihood = {}
i1 = {}
i2 = {}
lh_x = np.arange(1.0 / res, 1., 1.0 / res)
for bs in bin_sizes:
max_bin[bs] = (pos[-1] - 1) // bs + 1
count00[bs] = np.zeros(max_bin[bs])
count01[bs] = np.zeros(max_bin[bs])
count10[bs] = np.zeros(max_bin[bs])
count11[bs] = np.zeros(max_bin[bs])
reads00[bs] = np.zeros(max_bin[bs])
reads01[bs] = np.zeros(max_bin[bs])
reads10[bs] = np.zeros(max_bin[bs])
reads11[bs] = np.zeros(max_bin[bs])
baf[bs] = np.zeros(max_bin[bs])
maf[bs] = np.zeros(max_bin[bs])
likelihood[bs] = np.ones((max_bin[bs], res - 1)).astype("float") / (res - 1)
i1[bs] = np.zeros(max_bin[bs])
i2[bs] = np.zeros(max_bin[bs])
for i in range(len(pos)):
if (nalt[i] + nref[i]) > 0 and (not use_id or (flag[i] & 1)) and (not use_mask or (flag[i] & 2)):
if gt[i] == 1 or gt[i] == 5 or gt[i] == 6:
for bs in bin_sizes:
b = (pos[i] - 1) // bs
if use_phase and (gt[i] == 5):
reads01[bs][b] += nref[i]
reads10[bs][b] += nalt[i]
count10[bs][b] += 1
snp_baf = 1.0 * nalt[i] / (nalt[i] + nref[i])
likelihood[bs][b] *= beta(nalt[i], nref[i], lh_x, phased=True)
s = np.sum(likelihood[bs][b])
if s != 0.0:
likelihood[bs][b] /= s
elif use_phase and (gt[i] == 6):
reads01[bs][b] += nalt[i]
reads10[bs][b] += nref[i]
count01[bs][b] += 1
snp_baf = 1.0 * nref[i] / (nalt[i] + nref[i])
likelihood[bs][b] *= beta(nref[i], nalt[i], lh_x, phased=True)
s = np.sum(likelihood[bs][b])
if s != 0.0:
likelihood[bs][b] /= s
else:
snp_baf = 1.0 * nalt[i] / (nalt[i] + nref[i])
reads01[bs][b] += nalt[i]
reads10[bs][b] += nref[i]
count01[bs][b] += 1
if reduce_noise:
likelihood[bs][b] *= beta(nalt[i] + (1 if nalt[i] < nref[i] else 0),
nref[i] + (1 if nref[i] < nalt[i] else 0), lh_x)
else:
likelihood[bs][b] *= beta(nalt[i] * blw, nref[i] * blw, lh_x)
s = np.sum(likelihood[bs][b])
if s != 0.0:
likelihood[bs][b] /= s
baf[bs][b] += snp_baf
maf[bs][b] += 1.0 - snp_baf if snp_baf > 0.5 else snp_baf
else:
for bs in bin_sizes:
b = (pos[i] - 1) // bs
if use_phase and (gt[i] == 7):
count11[bs][b] += 1
reads11[bs][b] += nalt[i]
reads00[bs][b] += nref[i]
elif use_phase and (gt[i] == 4):
count00[bs][b] += 1
else:
count11[bs][b] += 1
reads11[bs][b] += nalt[i]
reads00[bs][b] += nref[i]
for bs in bin_sizes:
for i in range(max_bin[bs]):
count = count01[bs][i] + count10[bs][i]
if count > 0:
baf[bs][i] /= count
maf[bs][i] /= count
max_lh = np.amax(likelihood[bs][i])
ix = np.where(likelihood[bs][i] == max_lh)[0][0]
i1[bs][i] = 1.0 * (res // 2 - 1 - ix) / res if ix <= (res // 2 - 1) else 1.0 * (
ix - res // 2 + 1) / res
i2[bs][i] = likelihood[bs][i][res // 2 - 1] / max_lh
elif use_hom:
likelihood[bs][i] = lh_x * 0. + 1 / res
likelihood[bs][i][0] = 0.5 * (count11[bs][i] + count00[bs][i])
likelihood[bs][i][-1] = 0.5 * (count11[bs][i] + count00[bs][i])
s = np.sum(likelihood[bs][i])
likelihood[bs][i] /= s
max_lh = np.amax(likelihood[bs][i])
ix = np.where(likelihood[bs][i] == max_lh)[0][0]
i1[bs][i] = 1.0 * (res // 2 - 1 - ix) / res if ix <= (res // 2 - 1) else 1.0 * (
ix - res // 2 + 1) / res
i2[bs][i] = likelihood[bs][i][res // 2 - 1] / max_lh
_logger.info("Saving BAF histograms with bin size %d for chromosome '%s'." % (bs, c))
self.io.create_signal(c, bs, "SNP bin count 0|0", count00[bs].astype("uint16"), snp_flag)
self.io.create_signal(c, bs, "SNP bin count 0|1", count01[bs].astype("uint16"), snp_flag)
self.io.create_signal(c, bs, "SNP bin count 1|0", count10[bs].astype("uint16"), snp_flag)
self.io.create_signal(c, bs, "SNP bin count 1|1", count11[bs].astype("uint16"), snp_flag)
self.io.create_signal(c, bs, "SNP bin reads 0|0", reads00[bs].astype("uint16"), snp_flag)
self.io.create_signal(c, bs, "SNP bin reads 0|1", reads01[bs].astype("uint16"), snp_flag)
self.io.create_signal(c, bs, "SNP bin reads 1|0", reads10[bs].astype("uint16"), snp_flag)
self.io.create_signal(c, bs, "SNP bin reads 1|1", reads11[bs].astype("uint16"), snp_flag)
self.io.create_signal(c, bs, "SNP baf", baf[bs].astype("float32"), snp_flag)
self.io.create_signal(c, bs, "SNP maf", maf[bs].astype("float32"), snp_flag)
self.io.create_signal(c, bs, "SNP likelihood", likelihood[bs].astype("float32"), snp_flag)
self.io.create_signal(c, bs, "SNP i1", i1[bs].astype("float32"), snp_flag)
self.io.create_signal(c, bs, "SNP i2", i2[bs].astype("float32"), snp_flag)
def call_baf(self, bin_sizes, chroms=[], use_mask=True, use_id=False, odec=0.9, omin=None, mcount=None,
max_distance=0.1, anim=""):
""" CNV caller based on BAF likelihood mearger
Parameters
----------
bin_sizes : list of int
List of histogram bin sizes
chroms : list of str
List of chromosomes. Calculates for all available if empty.
use_mask : bool
Use P-mask filter if True. Default: False.
use_id : bool
Use ID filter if True. Default: False.
"""
for bin_size in bin_sizes:
if omin is None:
overlap_min = 1e-7 * bin_size
else:
overlap_min = omin
if mcount is None:
min_count = bin_size // 10000
else:
min_count = mcount
snp_flag = (FLAG_USEMASK if use_mask else 0) | (FLAG_USEID if use_id else 0)
for c in self.io.snp_chromosomes():
if len(chroms) == 0 or c in chroms and self.io.signal_exists(c, bin_size, "SNP likelihood", snp_flag):
# _logger.info(
# "Caling CNV-s by merging BAF likelihood with bin size %d for chromosome '%s'." % (bin_size, c))
likelihood = list(self.io.get_signal(c, bin_size, "SNP likelihood", snp_flag).astype("float64"))
snp_hets = self.io.get_signal(c, bin_size, "SNP bin count 0|1", snp_flag)
snp_hets += self.io.get_signal(c, bin_size, "SNP bin count 1|0", snp_flag)
bins = len(likelihood)
res = likelihood[0].size
segments = [[i] for i in range(bins) if
snp_hets[i] >= min_count and np.sum(likelihood[i]) > 0.0]
likelihood = [likelihood[i] for i in range(bins) if
snp_hets[i] >= min_count and np.sum(likelihood[i]) > 0.0]
overlaps = [likelihood_overlap(likelihood[i], likelihood[i + 1]) for i in range(len(segments) - 1)]
iter = 0
while len(overlaps) > 0:
maxo = max(overlaps)
mino = max(maxo * odec, overlap_min)
if maxo < overlap_min:
break
i = 0
while i < len(overlaps):
if overlaps[i] > mino:
nlh = likelihood[i] * likelihood[i + 1]
likelihood[i] = nlh / | np.sum(nlh) | numpy.sum |
# This module has been generated automatically from space group information
# obtained from the Computational Crystallography Toolbox
#
"""
Space groups
This module contains a list of all the 230 space groups that can occur in
a crystal. The variable space_groups contains a dictionary that maps
space group numbers and space group names to the corresponding space
group objects.
.. moduleauthor:: <NAME> <<EMAIL>>
"""
#-----------------------------------------------------------------------------
# Copyright (C) 2013 The Mosaic Development Team
#
# Distributed under the terms of the BSD License. The full license is in
# the file LICENSE.txt, distributed as part of this software.
#-----------------------------------------------------------------------------
import numpy as N
class SpaceGroup(object):
"""
Space group
All possible space group objects are created in this module. Other
modules should access these objects through the dictionary
space_groups rather than create their own space group objects.
"""
def __init__(self, number, symbol, transformations):
"""
:param number: the number assigned to the space group by
international convention
:type number: int
:param symbol: the Hermann-Mauguin space-group symbol as used
in PDB and mmCIF files
:type symbol: str
:param transformations: a list of space group transformations,
each consisting of a tuple of three
integer arrays (rot, tn, td), where
rot is the rotation matrix and tn/td
are the numerator and denominator of the
translation vector. The transformations
are defined in fractional coordinates.
:type transformations: list
"""
self.number = number
self.symbol = symbol
self.transformations = transformations
self.transposed_rotations = N.array([N.transpose(t[0])
for t in transformations])
self.phase_factors = N.exp(N.array([(-2j*N.pi*t[1])/t[2]
for t in transformations]))
def __repr__(self):
return "SpaceGroup(%d, %s)" % (self.number, repr(self.symbol))
def __len__(self):
"""
:return: the number of space group transformations
:rtype: int
"""
return len(self.transformations)
def symmetryEquivalentMillerIndices(self, hkl):
"""
:param hkl: a set of Miller indices
:type hkl: Scientific.N.array_type
:return: a tuple (miller_indices, phase_factor) of two arrays
of length equal to the number of space group
transformations. miller_indices contains the Miller
indices of each reflection equivalent by symmetry to the
reflection hkl (including hkl itself as the first element).
phase_factor contains the phase factors that must be applied
to the structure factor of reflection hkl to obtain the
structure factor of the symmetry equivalent reflection.
:rtype: tuple
"""
hkls = N.dot(self.transposed_rotations, hkl)
p = N.multiply.reduce(self.phase_factors**hkl, -1)
return hkls, p
space_groups = {}
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(1, 'P 1', transformations)
space_groups[1] = sg
space_groups['P 1'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(2, 'P -1', transformations)
space_groups[2] = sg
space_groups['P -1'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(3, 'P 1 2 1', transformations)
space_groups[3] = sg
space_groups['P 1 2 1'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(4, 'P 1 21 1', transformations)
space_groups[4] = sg
space_groups['P 1 21 1'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(5, 'C 1 2 1', transformations)
space_groups[5] = sg
space_groups['C 1 2 1'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(6, 'P 1 m 1', transformations)
space_groups[6] = sg
space_groups['P 1 m 1'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(7, 'P 1 c 1', transformations)
space_groups[7] = sg
space_groups['P 1 c 1'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(8, 'C 1 m 1', transformations)
space_groups[8] = sg
space_groups['C 1 m 1'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(9, 'C 1 c 1', transformations)
space_groups[9] = sg
space_groups['C 1 c 1'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(10, 'P 1 2/m 1', transformations)
space_groups[10] = sg
space_groups['P 1 2/m 1'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(11, 'P 1 21/m 1', transformations)
space_groups[11] = sg
space_groups['P 1 21/m 1'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(12, 'C 1 2/m 1', transformations)
space_groups[12] = sg
space_groups['C 1 2/m 1'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(13, 'P 1 2/c 1', transformations)
space_groups[13] = sg
space_groups['P 1 2/c 1'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(14, 'P 1 21/c 1', transformations)
space_groups[14] = sg
space_groups['P 1 21/c 1'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(15, 'C 1 2/c 1', transformations)
space_groups[15] = sg
space_groups['C 1 2/c 1'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(16, 'P 2 2 2', transformations)
space_groups[16] = sg
space_groups['P 2 2 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(17, 'P 2 2 21', transformations)
space_groups[17] = sg
space_groups['P 2 2 21'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(18, 'P 21 21 2', transformations)
space_groups[18] = sg
space_groups['P 21 21 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(19, 'P 21 21 21', transformations)
space_groups[19] = sg
space_groups['P 21 21 21'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(20, 'C 2 2 21', transformations)
space_groups[20] = sg
space_groups['C 2 2 21'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(21, 'C 2 2 2', transformations)
space_groups[21] = sg
space_groups['C 2 2 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(22, 'F 2 2 2', transformations)
space_groups[22] = sg
space_groups['F 2 2 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(23, 'I 2 2 2', transformations)
space_groups[23] = sg
space_groups['I 2 2 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(24, 'I 21 21 21', transformations)
space_groups[24] = sg
space_groups['I 21 21 21'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(25, 'P m m 2', transformations)
space_groups[25] = sg
space_groups['P m m 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(26, 'P m c 21', transformations)
space_groups[26] = sg
space_groups['P m c 21'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(27, 'P c c 2', transformations)
space_groups[27] = sg
space_groups['P c c 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(28, 'P m a 2', transformations)
space_groups[28] = sg
space_groups['P m a 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(29, 'P c a 21', transformations)
space_groups[29] = sg
space_groups['P c a 21'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(30, 'P n c 2', transformations)
space_groups[30] = sg
space_groups['P n c 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(31, 'P m n 21', transformations)
space_groups[31] = sg
space_groups['P m n 21'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(32, 'P b a 2', transformations)
space_groups[32] = sg
space_groups['P b a 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(33, 'P n a 21', transformations)
space_groups[33] = sg
space_groups['P n a 21'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(34, 'P n n 2', transformations)
space_groups[34] = sg
space_groups['P n n 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(35, 'C m m 2', transformations)
space_groups[35] = sg
space_groups['C m m 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(36, 'C m c 21', transformations)
space_groups[36] = sg
space_groups['C m c 21'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(37, 'C c c 2', transformations)
space_groups[37] = sg
space_groups['C c c 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(38, 'A m m 2', transformations)
space_groups[38] = sg
space_groups['A m m 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(39, 'A b m 2', transformations)
space_groups[39] = sg
space_groups['A b m 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(40, 'A m a 2', transformations)
space_groups[40] = sg
space_groups['A m a 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(41, 'A b a 2', transformations)
space_groups[41] = sg
space_groups['A b a 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(42, 'F m m 2', transformations)
space_groups[42] = sg
space_groups['F m m 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([3,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([3,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([3,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([3,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(43, 'F d d 2', transformations)
space_groups[43] = sg
space_groups['F d d 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(44, 'I m m 2', transformations)
space_groups[44] = sg
space_groups['I m m 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(45, 'I b a 2', transformations)
space_groups[45] = sg
space_groups['I b a 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(46, 'I m a 2', transformations)
space_groups[46] = sg
space_groups['I m a 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(47, 'P m m m', transformations)
space_groups[47] = sg
space_groups['P m m m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(48, 'P n n n :2', transformations)
space_groups[48] = sg
space_groups['P n n n :2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(49, 'P c c m', transformations)
space_groups[49] = sg
space_groups['P c c m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(50, 'P b a n :2', transformations)
space_groups[50] = sg
space_groups['P b a n :2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(51, 'P m m a', transformations)
space_groups[51] = sg
space_groups['P m m a'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(52, 'P n n a', transformations)
space_groups[52] = sg
space_groups['P n n a'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(53, 'P m n a', transformations)
space_groups[53] = sg
space_groups['P m n a'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(54, 'P c c a', transformations)
space_groups[54] = sg
space_groups['P c c a'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(55, 'P b a m', transformations)
space_groups[55] = sg
space_groups['P b a m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(56, 'P c c n', transformations)
space_groups[56] = sg
space_groups['P c c n'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(57, 'P b c m', transformations)
space_groups[57] = sg
space_groups['P b c m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(58, 'P n n m', transformations)
space_groups[58] = sg
space_groups['P n n m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(59, 'P m m n :2', transformations)
space_groups[59] = sg
space_groups['P m m n :2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(60, 'P b c n', transformations)
space_groups[60] = sg
space_groups['P b c n'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(61, 'P b c a', transformations)
space_groups[61] = sg
space_groups['P b c a'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(62, 'P n m a', transformations)
space_groups[62] = sg
space_groups['P n m a'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(63, 'C m c m', transformations)
space_groups[63] = sg
space_groups['C m c m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(64, 'C m c a', transformations)
space_groups[64] = sg
space_groups['C m c a'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(65, 'C m m m', transformations)
space_groups[65] = sg
space_groups['C m m m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(66, 'C c c m', transformations)
space_groups[66] = sg
space_groups['C c c m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(67, 'C m m a', transformations)
space_groups[67] = sg
space_groups['C m m a'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(68, 'C c c a :2', transformations)
space_groups[68] = sg
space_groups['C c c a :2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(69, 'F m m m', transformations)
space_groups[69] = sg
space_groups['F m m m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([4,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([4,4,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([4,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([4,4,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,3,3])
trans_den = N.array([1,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([4,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,3,1])
trans_den = N.array([4,4,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,1,1])
trans_den = N.array([4,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,1,1])
trans_den = N.array([4,4,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([2,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([3,0,3])
trans_den = N.array([4,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([3,1,1])
trans_den = N.array([4,4,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,-1,1])
trans_den = N.array([2,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([4,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,-1,1])
trans_den = N.array([4,4,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,3,1])
trans_den = N.array([2,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([3,1,1])
trans_den = N.array([4,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([3,3,0])
trans_den = N.array([4,4,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,-1])
trans_den = N.array([2,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,-1])
trans_den = N.array([4,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([4,4,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(70, 'F d d d :2', transformations)
space_groups[70] = sg
space_groups['F d d d :2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(71, 'I m m m', transformations)
space_groups[71] = sg
space_groups['I m m m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(72, 'I b a m', transformations)
space_groups[72] = sg
space_groups['I b a m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(73, 'I b c a', transformations)
space_groups[73] = sg
space_groups['I b c a'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(74, 'I m m a', transformations)
space_groups[74] = sg
space_groups['I m m a'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(75, 'P 4', transformations)
space_groups[75] = sg
space_groups['P 4'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,3])
trans_den = N.array([1,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(76, 'P 41', transformations)
space_groups[76] = sg
space_groups['P 41'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(77, 'P 42', transformations)
space_groups[77] = sg
space_groups['P 42'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,3])
trans_den = N.array([1,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(78, 'P 43', transformations)
space_groups[78] = sg
space_groups['P 43'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(79, 'I 4', transformations)
space_groups[79] = sg
space_groups['I 4'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,3])
trans_den = N.array([2,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,3])
trans_den = N.array([2,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,5])
trans_den = N.array([1,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,5])
trans_den = N.array([1,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(80, 'I 41', transformations)
space_groups[80] = sg
space_groups['I 41'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(81, 'P -4', transformations)
space_groups[81] = sg
space_groups['P -4'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(82, 'I -4', transformations)
space_groups[82] = sg
space_groups['I -4'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(83, 'P 4/m', transformations)
space_groups[83] = sg
space_groups['P 4/m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(84, 'P 42/m', transformations)
space_groups[84] = sg
space_groups['P 42/m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(85, 'P 4/n :2', transformations)
space_groups[85] = sg
space_groups['P 4/n :2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(86, 'P 42/n :2', transformations)
space_groups[86] = sg
space_groups['P 42/n :2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(87, 'I 4/m', transformations)
space_groups[87] = sg
space_groups['I 4/m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-3,-3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([3,5,5])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([3,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,-1,-1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(88, 'I 41/a :2', transformations)
space_groups[88] = sg
space_groups['I 41/a :2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(89, 'P 4 2 2', transformations)
space_groups[89] = sg
space_groups['P 4 2 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(90, 'P 4 21 2', transformations)
space_groups[90] = sg
space_groups['P 4 21 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,3])
trans_den = N.array([1,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,3])
trans_den = N.array([1,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,4])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(91, 'P 41 2 2', transformations)
space_groups[91] = sg
space_groups['P 41 2 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([2,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([2,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(92, 'P 41 21 2', transformations)
space_groups[92] = sg
space_groups['P 41 21 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(93, 'P 42 2 2', transformations)
space_groups[93] = sg
space_groups['P 42 2 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(94, 'P 42 21 2', transformations)
space_groups[94] = sg
space_groups['P 42 21 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,3])
trans_den = N.array([1,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,3])
trans_den = N.array([1,1,4])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(95, 'P 43 2 2', transformations)
space_groups[95] = sg
space_groups['P 43 2 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([2,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([2,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(96, 'P 43 21 2', transformations)
space_groups[96] = sg
space_groups['P 43 21 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(97, 'I 4 2 2', transformations)
space_groups[97] = sg
space_groups['I 4 2 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,3])
trans_den = N.array([2,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,3])
trans_den = N.array([2,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,3])
trans_den = N.array([2,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,3])
trans_den = N.array([2,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,5])
trans_den = N.array([1,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,5])
trans_den = N.array([1,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,5])
trans_den = N.array([1,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,5])
trans_den = N.array([1,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(98, 'I 41 2 2', transformations)
space_groups[98] = sg
space_groups['I 41 2 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(99, 'P 4 m m', transformations)
space_groups[99] = sg
space_groups['P 4 m m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(100, 'P 4 b m', transformations)
space_groups[100] = sg
space_groups['P 4 b m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(101, 'P 42 c m', transformations)
space_groups[101] = sg
space_groups['P 42 c m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(102, 'P 42 n m', transformations)
space_groups[102] = sg
space_groups['P 42 n m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(103, 'P 4 c c', transformations)
space_groups[103] = sg
space_groups['P 4 c c'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(104, 'P 4 n c', transformations)
space_groups[104] = sg
space_groups['P 4 n c'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(105, 'P 42 m c', transformations)
space_groups[105] = sg
space_groups['P 42 m c'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(106, 'P 42 b c', transformations)
space_groups[106] = sg
space_groups['P 42 b c'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(107, 'I 4 m m', transformations)
space_groups[107] = sg
space_groups['I 4 m m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(108, 'I 4 c m', transformations)
space_groups[108] = sg
space_groups['I 4 c m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,3])
trans_den = N.array([2,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,3])
trans_den = N.array([2,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,3])
trans_den = N.array([2,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,3])
trans_den = N.array([2,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,5])
trans_den = N.array([1,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,5])
trans_den = N.array([1,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,5])
trans_den = N.array([1,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,5])
trans_den = N.array([1,2,4])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(109, 'I 41 m d', transformations)
space_groups[109] = sg
space_groups['I 41 m d'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,3])
trans_den = N.array([2,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,3])
trans_den = N.array([2,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,5])
trans_den = N.array([1,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,5])
trans_den = N.array([1,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([1,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([1,2,4])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(110, 'I 41 c d', transformations)
space_groups[110] = sg
space_groups['I 41 c d'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(111, 'P -4 2 m', transformations)
space_groups[111] = sg
space_groups['P -4 2 m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(112, 'P -4 2 c', transformations)
space_groups[112] = sg
space_groups['P -4 2 c'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(113, 'P -4 21 m', transformations)
space_groups[113] = sg
space_groups['P -4 21 m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(114, 'P -4 21 c', transformations)
space_groups[114] = sg
space_groups['P -4 21 c'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(115, 'P -4 m 2', transformations)
space_groups[115] = sg
space_groups['P -4 m 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(116, 'P -4 c 2', transformations)
space_groups[116] = sg
space_groups['P -4 c 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(117, 'P -4 b 2', transformations)
space_groups[117] = sg
space_groups['P -4 b 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(118, 'P -4 n 2', transformations)
space_groups[118] = sg
space_groups['P -4 n 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(119, 'I -4 m 2', transformations)
space_groups[119] = sg
space_groups['I -4 m 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(120, 'I -4 c 2', transformations)
space_groups[120] = sg
space_groups['I -4 c 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(121, 'I -4 2 m', transformations)
space_groups[121] = sg
space_groups['I -4 2 m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,3])
trans_den = N.array([2,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,3])
trans_den = N.array([2,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,3])
trans_den = N.array([2,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,3])
trans_den = N.array([2,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,5])
trans_den = N.array([1,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,5])
trans_den = N.array([1,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,5])
trans_den = N.array([1,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,5])
trans_den = N.array([1,2,4])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(122, 'I -4 2 d', transformations)
space_groups[122] = sg
space_groups['I -4 2 d'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(123, 'P 4/m m m', transformations)
space_groups[123] = sg
space_groups['P 4/m m m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(124, 'P 4/m c c', transformations)
space_groups[124] = sg
space_groups['P 4/m c c'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(125, 'P 4/n b m :2', transformations)
space_groups[125] = sg
space_groups['P 4/n b m :2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(126, 'P 4/n n c :2', transformations)
space_groups[126] = sg
space_groups['P 4/n n c :2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(127, 'P 4/m b m', transformations)
space_groups[127] = sg
space_groups['P 4/m b m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(128, 'P 4/m n c', transformations)
space_groups[128] = sg
space_groups['P 4/m n c'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(129, 'P 4/n m m :2', transformations)
space_groups[129] = sg
space_groups['P 4/n m m :2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(130, 'P 4/n c c :2', transformations)
space_groups[130] = sg
space_groups['P 4/n c c :2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(131, 'P 42/m m c', transformations)
space_groups[131] = sg
space_groups['P 42/m m c'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(132, 'P 42/m c m', transformations)
space_groups[132] = sg
space_groups['P 42/m c m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(133, 'P 42/n b c :2', transformations)
space_groups[133] = sg
space_groups['P 42/n b c :2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(134, 'P 42/n n m :2', transformations)
space_groups[134] = sg
space_groups['P 42/n n m :2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(135, 'P 42/m b c', transformations)
space_groups[135] = sg
space_groups['P 42/m b c'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(136, 'P 42/m n m', transformations)
space_groups[136] = sg
space_groups['P 42/m n m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(137, 'P 42/n m c :2', transformations)
space_groups[137] = sg
space_groups['P 42/n m c :2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(138, 'P 42/n c m :2', transformations)
space_groups[138] = sg
space_groups['P 42/n c m :2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(139, 'I 4/m m m', transformations)
space_groups[139] = sg
space_groups['I 4/m m m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(140, 'I 4/m c m', transformations)
space_groups[140] = sg
space_groups['I 4/m c m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-3,-1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-3,-1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([3,5,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([3,3,5])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([3,5,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([3,3,5])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,-1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,-1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,-1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,-1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(141, 'I 41/a m d :2', transformations)
space_groups[141] = sg
space_groups['I 41/a m d :2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-3,-1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-3,-3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([3,5,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([3,3,5])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([3,5,5])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([3,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,-1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,-1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,-1,-1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(142, 'I 41/a c d :2', transformations)
space_groups[142] = sg
space_groups['I 41/a c d :2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(143, 'P 3', transformations)
space_groups[143] = sg
space_groups['P 3'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(144, 'P 31', transformations)
space_groups[144] = sg
space_groups['P 31'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(145, 'P 32', transformations)
space_groups[145] = sg
space_groups['P 32'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(146, 'R 3 :H', transformations)
space_groups[146] = sg
space_groups['R 3 :H'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(147, 'P -3', transformations)
space_groups[147] = sg
space_groups['P -3'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(148, 'R -3 :H', transformations)
space_groups[148] = sg
space_groups['R -3 :H'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(149, 'P 3 1 2', transformations)
space_groups[149] = sg
space_groups['P 3 1 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(150, 'P 3 2 1', transformations)
space_groups[150] = sg
space_groups['P 3 2 1'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(151, 'P 31 1 2', transformations)
space_groups[151] = sg
space_groups['P 31 1 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(152, 'P 31 2 1', transformations)
space_groups[152] = sg
space_groups['P 31 2 1'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(153, 'P 32 1 2', transformations)
space_groups[153] = sg
space_groups['P 32 1 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(154, 'P 32 2 1', transformations)
space_groups[154] = sg
space_groups['P 32 2 1'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(155, 'R 3 2 :H', transformations)
space_groups[155] = sg
space_groups['R 3 2 :H'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(156, 'P 3 m 1', transformations)
space_groups[156] = sg
space_groups['P 3 m 1'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(157, 'P 3 1 m', transformations)
space_groups[157] = sg
space_groups['P 3 1 m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(158, 'P 3 c 1', transformations)
space_groups[158] = sg
space_groups['P 3 c 1'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(159, 'P 3 1 c', transformations)
space_groups[159] = sg
space_groups['P 3 1 c'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(160, 'R 3 m :H', transformations)
space_groups[160] = sg
space_groups['R 3 m :H'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,7])
trans_den = N.array([3,3,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,7])
trans_den = N.array([3,3,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,7])
trans_den = N.array([3,3,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,5])
trans_den = N.array([3,3,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,5])
trans_den = N.array([3,3,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,5])
trans_den = N.array([3,3,6])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(161, 'R 3 c :H', transformations)
space_groups[161] = sg
space_groups['R 3 c :H'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(162, 'P -3 1 m', transformations)
space_groups[162] = sg
space_groups['P -3 1 m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(163, 'P -3 1 c', transformations)
space_groups[163] = sg
space_groups['P -3 1 c'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(164, 'P -3 m 1', transformations)
space_groups[164] = sg
space_groups['P -3 m 1'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(165, 'P -3 c 1', transformations)
space_groups[165] = sg
space_groups['P -3 c 1'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(166, 'R -3 m :H', transformations)
space_groups[166] = sg
space_groups['R -3 m :H'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,2,7])
trans_den = N.array([3,3,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,2,7])
trans_den = N.array([3,3,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,2,7])
trans_den = N.array([3,3,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,1])
trans_den = N.array([3,3,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,1])
trans_den = N.array([3,3,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,1])
trans_den = N.array([3,3,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([2,1,5])
trans_den = N.array([3,3,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([2,1,5])
trans_den = N.array([3,3,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([2,1,5])
trans_den = N.array([3,3,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,-1])
trans_den = N.array([3,3,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,-1])
trans_den = N.array([3,3,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,-1])
trans_den = N.array([3,3,6])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(167, 'R -3 c :H', transformations)
space_groups[167] = sg
space_groups['R -3 c :H'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(168, 'P 6', transformations)
space_groups[168] = sg
space_groups['P 6'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,5])
trans_den = N.array([1,1,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(169, 'P 61', transformations)
space_groups[169] = sg
space_groups['P 61'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,5])
trans_den = N.array([1,1,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(170, 'P 65', transformations)
space_groups[170] = sg
space_groups['P 65'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(171, 'P 62', transformations)
space_groups[171] = sg
space_groups['P 62'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(172, 'P 64', transformations)
space_groups[172] = sg
space_groups['P 64'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(173, 'P 63', transformations)
space_groups[173] = sg
space_groups['P 63'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(174, 'P -6', transformations)
space_groups[174] = sg
space_groups['P -6'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(175, 'P 6/m', transformations)
space_groups[175] = sg
space_groups['P 6/m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(176, 'P 63/m', transformations)
space_groups[176] = sg
space_groups['P 63/m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(177, 'P 6 2 2', transformations)
space_groups[177] = sg
space_groups['P 6 2 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,5])
trans_den = N.array([1,1,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,5])
trans_den = N.array([1,1,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,6])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(178, 'P 61 2 2', transformations)
space_groups[178] = sg
space_groups['P 61 2 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,5])
trans_den = N.array([1,1,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,5])
trans_den = N.array([1,1,6])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(179, 'P 65 2 2', transformations)
space_groups[179] = sg
space_groups['P 65 2 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(180, 'P 62 2 2', transformations)
space_groups[180] = sg
space_groups['P 62 2 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(181, 'P 64 2 2', transformations)
space_groups[181] = sg
space_groups['P 64 2 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(182, 'P 63 2 2', transformations)
space_groups[182] = sg
space_groups['P 63 2 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(183, 'P 6 m m', transformations)
space_groups[183] = sg
space_groups['P 6 m m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(184, 'P 6 c c', transformations)
space_groups[184] = sg
space_groups['P 6 c c'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(185, 'P 63 c m', transformations)
space_groups[185] = sg
space_groups['P 63 c m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(186, 'P 63 m c', transformations)
space_groups[186] = sg
space_groups['P 63 m c'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(187, 'P -6 m 2', transformations)
space_groups[187] = sg
space_groups['P -6 m 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(188, 'P -6 c 2', transformations)
space_groups[188] = sg
space_groups['P -6 c 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(189, 'P -6 2 m', transformations)
space_groups[189] = sg
space_groups['P -6 2 m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(190, 'P -6 2 c', transformations)
space_groups[190] = sg
space_groups['P -6 2 c'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(191, 'P 6/m m m', transformations)
space_groups[191] = sg
space_groups['P 6/m m m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(192, 'P 6/m c c', transformations)
space_groups[192] = sg
space_groups['P 6/m c c'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(193, 'P 63/m c m', transformations)
space_groups[193] = sg
space_groups['P 63/m c m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(194, 'P 63/m m c', transformations)
space_groups[194] = sg
space_groups['P 63/m m c'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(195, 'P 2 3', transformations)
space_groups[195] = sg
space_groups['P 2 3'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(196, 'F 2 3', transformations)
space_groups[196] = sg
space_groups['F 2 3'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(197, 'I 2 3', transformations)
space_groups[197] = sg
space_groups['I 2 3'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(198, 'P 21 3', transformations)
space_groups[198] = sg
space_groups['P 21 3'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(199, 'I 21 3', transformations)
space_groups[199] = sg
space_groups['I 21 3'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(200, 'P m -3', transformations)
space_groups[200] = sg
space_groups['P m -3'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(201, 'P n -3 :2', transformations)
space_groups[201] = sg
space_groups['P n -3 :2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(202, 'F m -3', transformations)
space_groups[202] = sg
space_groups['F m -3'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([4,4,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([4,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([4,4,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([4,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([4,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([4,4,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([4,4,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([4,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([4,4,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([4,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([4,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([4,4,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,1])
trans_den = N.array([4,4,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,3,3])
trans_den = N.array([1,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([4,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,1])
trans_den = N.array([4,4,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([4,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,3,3])
trans_den = N.array([1,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,3,3])
trans_den = N.array([1,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([4,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,3,1])
trans_den = N.array([4,4,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([-1,1,1])
trans_den = N.array([4,4,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([-1,1,1])
trans_den = N.array([4,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([-1,1,1])
trans_den = N.array([4,4,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([-1,1,1])
trans_den = N.array([4,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,1,1])
trans_den = N.array([4,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,1,1])
trans_den = N.array([4,4,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([3,1,1])
trans_den = N.array([4,4,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([2,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([3,0,3])
trans_den = N.array([4,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([3,1,1])
trans_den = N.array([4,4,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([3,0,3])
trans_den = N.array([4,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([2,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([2,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([3,0,3])
trans_den = N.array([4,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([3,1,1])
trans_den = N.array([4,4,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,-1,1])
trans_den = N.array([4,4,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,-1,1])
trans_den = N.array([2,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([4,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,-1,1])
trans_den = N.array([4,4,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([4,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,-1,1])
trans_den = N.array([2,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,-1,1])
trans_den = N.array([2,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([4,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,-1,1])
trans_den = N.array([4,4,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([3,3,0])
trans_den = N.array([4,4,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,1])
trans_den = N.array([2,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([3,1,1])
trans_den = N.array([4,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([3,3,0])
trans_den = N.array([4,4,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([3,1,1])
trans_den = N.array([4,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,1])
trans_den = N.array([2,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,3,1])
trans_den = N.array([2,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([3,1,1])
trans_den = N.array([4,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([3,3,0])
trans_den = N.array([4,4,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([4,4,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,-1])
trans_den = N.array([2,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,-1])
trans_den = N.array([4,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([4,4,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,-1])
trans_den = N.array([4,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,-1])
trans_den = N.array([2,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,-1])
trans_den = N.array([2,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,-1])
trans_den = N.array([4,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([4,4,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(203, 'F d -3 :2', transformations)
space_groups[203] = sg
space_groups['F d -3 :2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(204, 'I m -3', transformations)
space_groups[204] = sg
space_groups['I m -3'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(205, 'P a -3', transformations)
space_groups[205] = sg
space_groups['P a -3'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(206, 'I a -3', transformations)
space_groups[206] = sg
space_groups['I a -3'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(207, 'P 4 3 2', transformations)
space_groups[207] = sg
space_groups['P 4 3 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(208, 'P 42 3 2', transformations)
space_groups[208] = sg
space_groups['P 42 3 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(209, 'F 4 3 2', transformations)
space_groups[209] = sg
space_groups['F 4 3 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([3,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([3,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([3,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([3,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([3,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([3,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([3,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([3,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([3,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([3,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([3,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([3,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([3,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([3,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([3,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([3,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([3,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([3,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([3,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([3,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([3,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([3,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([3,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([3,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(210, 'F 41 3 2', transformations)
space_groups[210] = sg
space_groups['F 41 3 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(211, 'I 4 3 2', transformations)
space_groups[211] = sg
space_groups['I 4 3 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([3,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([3,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([3,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([3,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([3,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([3,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(212, 'P 43 3 2', transformations)
space_groups[212] = sg
space_groups['P 43 3 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([3,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([3,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([3,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([3,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([3,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([3,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(213, 'P 41 3 2', transformations)
space_groups[213] = sg
space_groups['P 41 3 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([3,3,5])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([3,5,5])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([3,5,5])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([3,5,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([3,5,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([3,3,5])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([3,5,5])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([3,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([3,3,5])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([3,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([3,5,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([3,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(214, 'I 41 3 2', transformations)
space_groups[214] = sg
space_groups['I 41 3 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(215, 'P -4 3 m', transformations)
space_groups[215] = sg
space_groups['P -4 3 m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(216, 'F -4 3 m', transformations)
space_groups[216] = sg
space_groups['F -4 3 m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(217, 'I -4 3 m', transformations)
space_groups[217] = sg
space_groups['I -4 3 m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(218, 'P -4 3 n', transformations)
space_groups[218] = sg
space_groups['P -4 3 n'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(219, 'F -4 3 c', transformations)
space_groups[219] = sg
space_groups['F -4 3 c'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([3,3,5])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([3,5,5])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([3,5,5])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([3,5,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([3,5,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([3,3,5])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([3,5,5])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([3,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([3,3,5])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([3,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([3,5,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([3,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(220, 'I -4 3 d', transformations)
space_groups[220] = sg
space_groups['I -4 3 d'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(221, 'P m -3 m', transformations)
space_groups[221] = sg
space_groups['P m -3 m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(222, 'P n -3 n :2', transformations)
space_groups[222] = sg
space_groups['P n -3 n :2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(223, 'P m -3 n', transformations)
space_groups[223] = sg
space_groups['P m -3 n'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(224, 'P n -3 m :2', transformations)
space_groups[224] = sg
space_groups['P n -3 m :2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(225, 'F m -3 m', transformations)
space_groups[225] = sg
space_groups['F m -3 m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([-1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([-1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([-1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([-1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([-1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([-1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([-1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([-1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(226, 'F m -3 c', transformations)
space_groups[226] = sg
space_groups['F m -3 c'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([4,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([4,4,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([4,4,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([4,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([4,4,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([4,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([4,4,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([4,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([4,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([4,4,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([4,4,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([4,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([4,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([4,4,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([4,4,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([4,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([4,4,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([4,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([4,4,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([4,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([4,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([4,4,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([4,4,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([4,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([4,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,1])
trans_den = N.array([4,4,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,1])
trans_den = N.array([4,4,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,3,3])
trans_den = N.array([1,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,3,3])
trans_den = N.array([1,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([4,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,1])
trans_den = N.array([4,4,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,3,3])
trans_den = N.array([1,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([4,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,1])
trans_den = N.array([4,4,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([4,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,3,3])
trans_den = N.array([1,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,3,3])
trans_den = N.array([1,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([4,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,3,1])
trans_den = N.array([4,4,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,3,1])
trans_den = N.array([4,4,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([4,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,3,3])
trans_den = N.array([1,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([-1,1,1])
trans_den = N.array([4,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([-1,1,1])
trans_den = N.array([4,4,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([-1,1,1])
trans_den = N.array([4,4,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,1,1])
trans_den = N.array([4,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([-1,1,1])
trans_den = N.array([4,4,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([-1,1,1])
trans_den = N.array([4,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([-1,1,1])
trans_den = N.array([4,4,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([-1,1,1])
trans_den = N.array([4,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,1,1])
trans_den = N.array([4,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,1,1])
trans_den = N.array([4,4,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,1,1])
trans_den = N.array([4,4,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([-1,1,1])
trans_den = N.array([4,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([3,0,3])
trans_den = N.array([4,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([3,1,1])
trans_den = N.array([4,4,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([3,1,1])
trans_den = N.array([4,4,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([2,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([2,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([3,0,3])
trans_den = N.array([4,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([3,1,1])
trans_den = N.array([4,4,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([2,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([3,0,3])
trans_den = N.array([4,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([3,1,1])
trans_den = N.array([4,4,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([3,0,3])
trans_den = N.array([4,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([2,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([2,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([3,0,3])
trans_den = N.array([4,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([3,1,1])
trans_den = N.array([4,4,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([3,1,1])
trans_den = N.array([4,4,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([3,0,3])
trans_den = N.array([4,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([2,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([4,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,-1,1])
trans_den = N.array([4,4,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,-1,1])
trans_den = N.array([4,4,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,-1,1])
trans_den = N.array([2,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,-1,1])
trans_den = N.array([2,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([4,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,-1,1])
trans_den = N.array([4,4,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,-1,1])
trans_den = N.array([2,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([4,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,-1,1])
trans_den = N.array([4,4,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([4,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,-1,1])
trans_den = N.array([2,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,-1,1])
trans_den = N.array([2,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([4,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,-1,1])
trans_den = N.array([4,4,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,-1,1])
trans_den = N.array([4,4,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([4,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,-1,1])
trans_den = N.array([2,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([3,1,1])
trans_den = N.array([4,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([3,3,0])
trans_den = N.array([4,4,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([3,3,0])
trans_den = N.array([4,4,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,1])
trans_den = N.array([2,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,3,1])
trans_den = N.array([2,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([3,1,1])
trans_den = N.array([4,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([3,3,0])
trans_den = N.array([4,4,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,1])
trans_den = N.array([2,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([3,1,1])
trans_den = N.array([4,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([3,3,0])
trans_den = N.array([4,4,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([3,1,1])
trans_den = N.array([4,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,1])
trans_den = N.array([2,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,3,1])
trans_den = N.array([2,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([3,1,1])
trans_den = N.array([4,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([3,3,0])
trans_den = N.array([4,4,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([3,3,0])
trans_den = N.array([4,4,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([3,1,1])
trans_den = N.array([4,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,1])
trans_den = N.array([2,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,-1])
trans_den = N.array([4,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([4,4,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([4,4,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,-1])
trans_den = N.array([2,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,-1])
trans_den = N.array([2,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,-1])
trans_den = N.array([4,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([4,4,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,-1])
trans_den = N.array([2,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,-1])
trans_den = N.array([4,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([4,4,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,-1])
trans_den = N.array([4,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,-1])
trans_den = N.array([2,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,-1])
trans_den = N.array([2,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,-1])
trans_den = N.array([4,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([4,4,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([4,4,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,-1])
trans_den = N.array([4,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,-1])
trans_den = N.array([2,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(227, 'F d -3 m :2', transformations)
space_groups[227] = sg
space_groups['F d -3 m :2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,3])
trans_den = N.array([4,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,0])
trans_den = N.array([4,4,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,0])
trans_den = N.array([4,4,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,3])
trans_den = N.array([1,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,3])
trans_den = N.array([1,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,3])
trans_den = N.array([4,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([4,4,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([4,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([4,4,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([4,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([4,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([4,4,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,3,0])
trans_den = N.array([4,4,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,3])
trans_den = N.array([4,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,3])
trans_den = N.array([1,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-3])
trans_den = N.array([4,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([-1,-3,0])
trans_den = N.array([4,4,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([-1,-3,0])
trans_den = N.array([4,4,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-3])
trans_den = N.array([1,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-3])
trans_den = N.array([1,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-3])
trans_den = N.array([4,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = | N.array([0,0,0]) | numpy.array |
import torch
import cv2
import os
import datetime
import numpy as np
import pandas as pd
from tqdm import tqdm
from network.utils import bbox_iou
from datetime import datetime
import multiprocessing
from scipy.optimize import linear_sum_assignment
class Track:
'''
Track is the class of track. it contains all the node and manages the node. it contains the following information:
1) all the nodes
2) track id. it is unique it identify each track
3) track pool id. it is a number to give a new id to a new track
4) age. age indicates how old is the track
5) max_age. indicates the dead age of this track
'''
_id_pool = 1
def __init__(self):
self.nodes = list()
self.frames = {}
self.mid_frames = {}
self.id = Track._id_pool
Track._id_pool += 1
self.color = tuple((np.random.rand(3) * 255).astype(int).tolist())
self.prev_direction = None
def update_frames(self, all_tube_frames, tube_boxes, mid_frame, mid_box, score, tube_direction):
for frame, frame_box in zip(all_tube_frames, tube_boxes):
if frame not in self.frames:
self.frames[frame] = [frame_box, 1, score]
else:
self.frames[frame][0] += frame_box.astype(np.float)
self.frames[frame][1] += 1
self.frames[frame][2] += score
if mid_frame not in self.mid_frames:
self.mid_frames[mid_frame] = [mid_box.astype(np.float), 1, score]
else:
self.mid_frames[mid_frame][0] += mid_box.astype(np.float)
self.mid_frames[mid_frame][1] += 1
self.mid_frames[mid_frame][2] += score
def get_center(box):
return np.array(((box[0] + box[2]) / 2, (box[1] + box[3]) / 2))
front_frame = np.max(all_tube_frames)
back_frame = np.min(all_tube_frames)
end_box = self.frames[front_frame][0] / self.frames[front_frame][1]
start_box = self.frames[back_frame][0] / self.frames[back_frame][1]
self.prev_direction = np.zeros(3)
self.prev_direction[:2] = get_center(end_box) - get_center(start_box)
self.prev_direction[2] = front_frame - back_frame
def track_tube_iou(track_boxes, tube_boxes):
track_boxes = np.atleast_3d(track_boxes).astype(np.float) # (n_track, n_tbbox, 4)
tube_boxes = np.atleast_2d(tube_boxes).astype(np.float) # (n_tbbox, 4)
def track_tube_overlaps(bboxes1, bboxes2):
lt = np.maximum(np.minimum(bboxes1[:, :, :2], bboxes1[:, :, 2:]), np.minimum(bboxes2[:, :2], bboxes2[:, 2:])) # [rows, 2]
rb = np.minimum(np.maximum(bboxes1[:, :, 2:], bboxes1[:, :, :2]), np.maximum(bboxes2[:, 2:], bboxes2[:, :2])) # [rows, 2]
wh = np.clip(rb - lt, 0, None)
overlap = wh[:, :, 0] * wh[:, :, 1]
return overlap
overlap = track_tube_overlaps(track_boxes, tube_boxes)
area1 = (track_boxes[:, :, 2] - track_boxes[:, :, 0]) * (track_boxes[:, :, 3] - track_boxes[:, :, 1])
area1 = np.abs(area1)
area2 = (tube_boxes[:, 2] - tube_boxes[:, 0]) * (tube_boxes[:, 3] - tube_boxes[:, 1])
area2 = np.abs(area2)
ious = overlap / (area1 + area2 - overlap)
return ious
def get_shape_diff(track_boxes, tube_boxes):
track_boxes = np.atleast_3d(track_boxes).astype(np.float) # (n_track, n_tbbox, 4)
tube_boxes = np.atleast_2d(tube_boxes).astype(np.float) # (n_tbbox, 4)
track_height = track_boxes[:, :, 2] - track_boxes[:, :, 0]
track_width = track_boxes[:, :, 3] - track_boxes[:, :, 1]
tube_height = tube_boxes[:, 2] - tube_boxes[:, 0]
tube_width = tube_boxes[:, 3] - tube_boxes[:, 1]
diff = np.abs(track_height - tube_height) / (track_height + tube_height) + \
np.abs(track_width - tube_width) / (track_width + tube_width)
return np.exp(1.5 * -diff)
def update_tracks_fast(tracks, tube, arg):
mid_frame = tube[0].astype(np.int)
mid_box = tube[1:5]
end_frame = tube[5].astype(np.int)
end_box = tube[6:10]
start_frame = tube[10].astype(np.int)
start_box = tube[11:15]
score = tube[15]
def get_center(box):
return np.array(((box[0] + box[2]) / 2, (box[1] + box[3]) / 2))
back_frames = np.arange(start_frame, mid_frame)
front_frames = np.arange(mid_frame + 1, end_frame + 1)
all_tube_frames = np.arange(start_frame, end_frame + 1)
back_start_coef = (mid_frame - back_frames) / (mid_frame - start_frame)
back_mid_coef = (back_frames - start_frame) / (mid_frame - start_frame)
front_mid_coef = (end_frame - front_frames) / (end_frame - mid_frame)
front_end_coef = (front_frames - mid_frame) / (end_frame - mid_frame)
back_frame_boxes = np.outer(back_start_coef, start_box) + np.outer(back_mid_coef, mid_box)
front_frame_boxes = np.outer(front_end_coef, end_box) + np.outer(front_mid_coef, mid_box)
tube_boxes = np.concatenate((back_frame_boxes, mid_box[None], front_frame_boxes))
tube_frame_num = len(all_tube_frames)
depth_divider = 8
tube_direction = np.zeros(3)
tube_direction[:2] = get_center(end_box) - get_center(start_box)
tube_direction[2] = np.max(all_tube_frames) - np.min(all_tube_frames)
tube_direction[2] /= depth_divider
if len(tracks) == 0:
new_track = Track()
new_track.update_frames(all_tube_frames, tube_boxes, mid_frame, mid_box, score, tube_direction)
tracks.append(new_track)
return
all_has_frame = np.zeros((len(tracks), tube_frame_num), dtype=np.bool)
all_track_boxes = np.zeros((len(tracks), *tube_boxes.shape))
track_direction = np.zeros((len(tracks), 3))
for track_idx, track in enumerate(tracks):
# overlap_area = [1e8, -1]
if track.prev_direction is not None:
track_direction[track_idx, :] = track.prev_direction
for i, frame in enumerate(all_tube_frames):
if frame not in track.frames:
continue
all_has_frame[track_idx, i] = True
all_track_boxes[track_idx, i, :] = \
track.frames[frame][0] / track.frames[frame][1]
# overlap_area[0] = min(overlap_area[0], frame)
# overlap_area[1] = max(overlap_area[1], frame)
# if overlap_area[1] < 0:
# continue
# while overlap_area[0] - 1 in track.frames and overlap_area[1] - overlap_area[0] + 1 < tube_frame_num:
# overlap_area[0] -= 1
# while overlap_area[1] + 1 in track.frames and overlap_area[1] - overlap_area[0] + 1 < tube_frame_num:
# overlap_area[1] += 1
# track_direction[track_idx, :2] = get_center(track.frames[overlap_area[1]][0] / track.frames[overlap_area[1]][1]) - \
# get_center(track.frames[overlap_area[0]][0] / track.frames[overlap_area[0]][1])
# track_direction[track_idx, 2] = overlap_area[1] - overlap_area[0]
track_direction[:, 2] /= depth_divider
has_overlap = (np.sum(all_has_frame, axis=1) > 0)
all_iou = np.zeros(all_has_frame.shape, dtype=np.float)
shape_diff = np.zeros(all_has_frame.shape, dtype=np.float)
all_iou[has_overlap] = track_tube_iou(all_track_boxes[has_overlap], tube_boxes)
shape_diff[has_overlap] = get_shape_diff(all_track_boxes[has_overlap], tube_boxes)
mean_all_iou = np.zeros(has_overlap.shape, dtype=np.float)
mean_all_iou[has_overlap] = np.sum(all_iou[has_overlap], axis=1) / | np.sum(all_has_frame[has_overlap], axis=1) | numpy.sum |
import glob, time
import numpy as np
from PIL import Image
import os
import os.path as osp
import cv2
import torch
from torchvision import transforms
from torchvision.transforms import Normalize
import torchvision
import itertools
import copy
import joblib
from pymatreader import read_mat
from lib.data_utils.img_utils import normalize_2d_kp, transfrom_keypoints, get_single_image_crop
from dataset.data_utils import (
xyz2uvd,
kp_to_bbox_param,
get_dataset_path,
crop,
transform
)
class SPINDataset():
def __init__(self, dataset):
self.dataset = dataset
self.data = joblib.load("/data/3dpw/3dpw_train_db.pt")
def __len__(self):
return len(self.data)
def __getitem__(self, idx):
feature = self.data["features"][idx]
joints3d = self.data["joints3D"][idx]
joints2d = self.data["joints2D"][idx]
shape = self.data["shape"][idx]
pose = self.data["pose"][idx]
return feature, joints3d, joints2d, shape, pose
class TrainDataset():
def __init__(self, train_data, use_seg_gt=False, joints_dataset="3dpw", train_texture_net=False, use_augmentation=False, use_coco_gt=False):
self.num_patch = 4
self.divider = 2
self.use_seg_gt = use_seg_gt
self.joints_dataset = joints_dataset
self.use_augmentation = use_augmentation
self.list = list(range(4))
self.permutations = np.array(list(itertools.permutations(self.list, len(self.list))))
self.augment_tile_256_224 = transforms.Compose([
transforms.Resize((256, 256)),
transforms.RandomCrop(224),
transforms.ToTensor(),
transforms.Normalize(mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225))
])
self.transform_224 = transforms.Compose([
transforms.Resize((224, 224), Image.BILINEAR),
])
self.transform_224_tensor = transforms.Compose([
transforms.Resize((224, 224), Image.BILINEAR),
transforms.ToTensor(),
transforms.Normalize(mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225))
])
self.angle_list = [0, 90, 180, 270]
if train_texture_net:
h36m_train_data_path = "/data/human3.6m/h36m_train_db_simple.pt"
self.h36m_train_dataset = self.load_dataset(h36m_train_data_path, prop_sample=0.08) # 5013
print("H36M Train dataset: {}".format(format(self.h36m_train_dataset["len_data"], ",")))
# three_dp_train_data_path = "/data/3dpw/3dpw_train_db_simple.pt"
# self.three_dp_train_dataset = self.load_dataset(three_dp_train_data_path, prop_sample=0.2)
# print("3DPW Train dataset: {}".format(format(self.three_dp_train_dataset["len_data"], ",")))
mpi_inf_train_data_path = "/data/MPI-INF-3D-HP/mpi-inf-3d-hp_train_db_simple.pt"
self.mpi_inf_train_dataset = self.load_dataset(mpi_inf_train_data_path, prop_sample=0.05) # 4835
print("MPI-INF Train dataset: {}".format(format(self.mpi_inf_train_dataset["len_data"], ",")))
mpii_train_data_path = "/data/MPII/mpii_train_db_simple.pt"
self.mpii_train_dataset = self.load_dataset(mpii_train_data_path, prop_sample=1) # 5445
print("MPII Train dataset: {}".format(format(self.mpii_train_dataset["len_data"], ",")))
coco_train_data_path = "/data/coco/coco_train_db_simple.pt"
self.coco_train_dataset = self.load_dataset(coco_train_data_path, prop_sample=1) # 4040
print("COCO Train dataset: {}".format(format(self.coco_train_dataset["len_data"], ",")))
youtube_train_data_path = "/data/youtube_collection/youtube_collection_train_db_simple.pt"
self.youtube_train_dataset = self.load_dataset(youtube_train_data_path, prop_sample=1) # 3045
print("Youtube Train dataset: {}".format(format(self.youtube_train_dataset["len_data"], ",")))
key_list = ["p_id_list", "img_path_list", "bbox_list",
"joints3D_list", "has_joints3D", "joints2D_list",
"has_joints2D", "shape_list", "has_shape",
"pose_list", "has_pose", "has_camera"]
dataset_dict = {}
for key in key_list:
dataset_dict[key] = np.concatenate((
self.h36m_train_dataset[key],
self.mpi_inf_train_dataset[key],
self.mpii_train_dataset[key],
self.coco_train_dataset[key],
self.youtube_train_dataset[key],))
self.p_id_list = dataset_dict["p_id_list"]
self.img_path_list = dataset_dict["img_path_list"]
self.bbox_list = dataset_dict["bbox_list"]
self.joints3D_list = dataset_dict["joints3D_list"]
self.has_joints3D = dataset_dict["has_joints3D"]
self.joints2D_list = dataset_dict["joints2D_list"]
self.has_joints2D = dataset_dict["has_joints2D"]
self.shape_list = dataset_dict["shape_list"]
self.has_shape = dataset_dict["has_shape"]
self.pose_list = dataset_dict["pose_list"]
self.has_pose = dataset_dict["has_pose"]
self.has_camera = dataset_dict["has_camera"]
del dataset_dict
del self.h36m_train_dataset
del self.mpi_inf_train_dataset
del self.mpii_train_dataset
del self.coco_train_dataset
del self.youtube_train_dataset
else:
if train_data == 0:
if self.use_seg_gt:
train_dataset_path = "/data/human3.6m/h36m_train_db_simple_seg.pt"
else:
train_dataset_path = "/data/human3.6m/h36m_train_db_simple.pt"
self.train_dataset = self.load_dataset(train_dataset_path, use_gt=True)
print("{} Train dataset: {}".format(joints_dataset.upper(), format(self.train_dataset["len_data"], ",")))
if self.use_seg_gt:
test_dataset_path = "/data/human3.6m/h36m_test_db_simple_seg.pt"
else:
test_dataset_path = "/data/human3.6m/h36m_test_db_simple.pt"
self.test_dataset = self.load_dataset(test_dataset_path, use_gt=True)
print("{} Train dataset: {}".format(joints_dataset.upper(), format(self.test_dataset["len_data"], ",")))
if train_data in [1, 2, 3, 4, 5]:
### 3DPW ###
if joints_dataset == "3dpw":
dataset_path = "/data/3dpw/3dpw_train_db_simple.pt"
elif joints_dataset == "h36m":
if self.use_seg_gt:
dataset_path = "/data/human3.6m/h36m_train_db_simple_seg.pt"
else:
dataset_path = "/data/human3.6m/h36m_train_db_simple.pt"
self.dataset = self.load_dataset(dataset_path, use_gt=True)
print("{} Train dataset: {}".format(joints_dataset.upper(), format(self.dataset["len_data"], ",")))
if train_data in [2, 4]:
### Human 3.6M ###
if joints_dataset == "3dpw":
dataset2_path = "/data/human3.6m/h36m_train_db_simple.pt"
self.dataset2 = self.load_dataset(dataset2_path)
print("H36M Train dataset: {}".format(format(self.dataset2["len_data"], ",")))
elif joints_dataset == "h36m":
dataset2_path = "/data/3dpw/3dpw_train_db_simple.pt"
self.dataset2 = self.load_dataset(dataset2_path)
print("3DPW Train dataset: {}".format(format(self.dataset2["len_data"], ",")))
### MPII ###
mpii_dataset_path = "/data/MPI-INF-3D-HP/mpi-inf-3d-hp_train_db_simple.pt"
self.mpii_dataset = self.load_dataset(mpii_dataset_path)
print("MPII Train dataset: {}".format(format(self.mpii_dataset["len_data"], ",")))
### SYSU ###
sysu_dataset_path = "/data/SYSU3DAction/sysu_train_db_simple.pt"
self.sysu_dataset = self.load_dataset(sysu_dataset_path)
print("SYSU Train dataset: {}".format(format(self.sysu_dataset["len_data"], ",")))
### Nucla ###
nucla_dataset_path = "/data/nucla/nucla_train_db_simple.pt"
self.nucla_dataset = self.load_dataset(nucla_dataset_path)
print("Nucla Train dataset: {}".format(format(self.nucla_dataset["len_data"], ",")))
if train_data in [3, 4]:
### ETH ###
eth_dataset_path = "/data/ETH_padding/ETH_train_db_simple.pt"
self.eth_dataset = self.load_dataset(eth_dataset_path)
print("ETH Train dataset: {}".format(format(self.eth_dataset["len_data"], ",")))
### Penn Fudan ###
penn_fudan_dataset_path = "/data/Penn-Fudan/Penn-Fudan_train_db_simple.pt"
self.penn_fudan_dataset = self.load_dataset(penn_fudan_dataset_path)
print("Penn-Fudan Train dataset: {}".format(format(self.penn_fudan_dataset["len_data"], ",")))
if train_data == 5:
if self.use_seg_gt:
coco_dataset_path = "/data/coco/coco_train_db_simple_seg.pt"
else:
coco_dataset_path = "/data/coco/coco_train_db_simple.pt"
if use_coco_gt:
self.coco_dataset = self.load_dataset(coco_dataset_path, use_gt=True)
else:
self.coco_dataset = self.load_dataset(coco_dataset_path)
print("COCO Train dataset: {}".format(format(self.coco_dataset["len_data"], ",")))
if train_data == 0:
key_list = ["p_id_list", "img_path_list", "bbox_list",
"joints3D_list", "has_joints3D", "joints2D_list",
"has_joints2D", "shape_list", "has_shape",
"pose_list", "has_pose", "has_camera"]
dataset_dict = {}
for key in key_list:
dataset_dict[key] = np.concatenate((
self.train_dataset[key],
self.test_dataset[key]))
self.p_id_list = dataset_dict["p_id_list"]
self.img_path_list = dataset_dict["img_path_list"]
self.bbox_list = dataset_dict["bbox_list"]
self.joints3D_list = dataset_dict["joints3D_list"]
self.has_joints3D = dataset_dict["has_joints3D"]
self.joints2D_list = dataset_dict["joints2D_list"]
self.has_joints2D = dataset_dict["has_joints2D"]
self.shape_list = dataset_dict["shape_list"]
self.has_shape = dataset_dict["has_shape"]
self.pose_list = dataset_dict["pose_list"]
self.has_pose = dataset_dict["has_pose"]
self.has_camera = dataset_dict["has_camera"]
del dataset_dict
del self.train_dataset
del self.test_dataset
if train_data == 1:
self.p_id_list = self.dataset["p_id_list"]
self.img_path_list = self.dataset["img_path_list"]
self.bbox_list = self.dataset["bbox_list"]
self.joints3D_list = self.dataset["joints3D_list"]
self.has_joints3D = self.dataset["has_joints3D"]
self.joints2D_list = self.dataset["joints2D_list"]
self.has_joints2D = self.dataset["has_joints2D"]
self.shape_list = self.dataset["shape_list"]
self.has_shape = self.dataset["has_shape"]
self.pose_list = self.dataset["pose_list"]
self.has_pose = self.dataset["has_pose"]
self.has_camera = self.dataset["has_camera"]
del self.dataset
if train_data == 2:
key_list = ["p_id_list", "img_path_list", "bbox_list",
"joints3D_list", "has_joints3D", "joints2D_list",
"has_joints2D", "shape_list", "has_shape",
"pose_list", "has_pose", "has_camera"]
dataset_dict = {}
for key in key_list:
dataset_dict[key] = np.concatenate((
self.dataset[key],
self.dataset2[key],
self.mpii_dataset[key],
self.sysu_dataset[key],
self.nucla_dataset[key]))
self.p_id_list = dataset_dict["p_id_list"]
self.img_path_list = dataset_dict["img_path_list"]
self.bbox_list = dataset_dict["bbox_list"]
self.joints3D_list = dataset_dict["joints3D_list"]
self.has_joints3D = dataset_dict["has_joints3D"]
self.joints2D_list = dataset_dict["joints2D_list"]
self.has_joints2D = dataset_dict["has_joints2D"]
self.shape_list = dataset_dict["shape_list"]
self.has_shape = dataset_dict["has_shape"]
self.pose_list = dataset_dict["pose_list"]
self.has_pose = dataset_dict["has_pose"]
self.has_camera = dataset_dict["has_camera"]
del dataset_dict
del self.dataset
del self.dataset2
del self.mpii_dataset
del self.sysu_dataset
del self.nucla_dataset
if train_data == 3:
key_list = ["p_id_list", "img_path_list", "bbox_list",
"joints3D_list", "has_joints3D", "joints2D_list",
"has_joints2D", "shape_list", "has_shape",
"pose_list", "has_pose", "has_camera"]
dataset_dict = {}
for key in key_list:
dataset_dict[key] = np.concatenate((
self.dataset[key],
self.eth_dataset[key],
self.penn_fudan_dataset[key]))
self.p_id_list = dataset_dict["p_id_list"]
self.img_path_list = dataset_dict["img_path_list"]
self.bbox_list = dataset_dict["bbox_list"]
self.joints3D_list = dataset_dict["joints3D_list"]
self.has_joints3D = dataset_dict["has_joints3D"]
self.joints2D_list = dataset_dict["joints2D_list"]
self.has_joints2D = dataset_dict["has_joints2D"]
self.shape_list = dataset_dict["shape_list"]
self.has_shape = dataset_dict["has_shape"]
self.pose_list = dataset_dict["pose_list"]
self.has_pose = dataset_dict["has_pose"]
self.has_camera = dataset_dict["has_camera"]
del dataset_dict
del self.dataset
del self.eth_dataset
del self.penn_fudan_dataset
if train_data == 4:
key_list = ["p_id_list", "img_path_list", "bbox_list",
"joints3D_list", "has_joints3D", "joints2D_list",
"has_joints2D", "shape_list", "has_shape",
"pose_list", "has_pose", "has_camera"]
dataset_dict = {}
for key in key_list:
dataset_dict[key] = np.concatenate((
self.dataset[key],
self.dataset2[key],
self.mpii_dataset[key],
self.sysu_dataset[key],
self.nucla_dataset[key],
self.eth_dataset[key],
self.penn_fudan_dataset[key]))
self.p_id_list = dataset_dict["p_id_list"]
self.img_path_list = dataset_dict["img_path_list"]
self.bbox_list = dataset_dict["bbox_list"]
self.joints3D_list = dataset_dict["joints3D_list"]
self.has_joints3D = dataset_dict["has_joints3D"]
self.joints2D_list = dataset_dict["joints2D_list"]
self.has_joints2D = dataset_dict["has_joints2D"]
self.shape_list = dataset_dict["shape_list"]
self.has_shape = dataset_dict["has_shape"]
self.pose_list = dataset_dict["pose_list"]
self.has_pose = dataset_dict["has_pose"]
self.has_camera = dataset_dict["has_camera"]
del dataset_dict
del self.dataset
del self.dataset2
del self.mpii_dataset
del self.sysu_dataset
del self.nucla_dataset
del self.eth_dataset
del self.penn_fudan_dataset
if train_data == 5:
key_list = ["p_id_list", "img_path_list", "bbox_list",
"joints3D_list", "has_joints3D", "joints2D_list",
"has_joints2D", "shape_list", "has_shape",
"pose_list", "has_pose", "has_camera"]
dataset_dict = {}
for key in key_list:
dataset_dict[key] = np.concatenate((
self.dataset[key],
self.coco_dataset[key]))
self.p_id_list = dataset_dict["p_id_list"]
self.img_path_list = dataset_dict["img_path_list"]
self.bbox_list = dataset_dict["bbox_list"]
self.joints3D_list = dataset_dict["joints3D_list"]
self.has_joints3D = dataset_dict["has_joints3D"]
self.joints2D_list = dataset_dict["joints2D_list"]
self.has_joints2D = dataset_dict["has_joints2D"]
self.shape_list = dataset_dict["shape_list"]
self.has_shape = dataset_dict["has_shape"]
self.pose_list = dataset_dict["pose_list"]
self.has_pose = dataset_dict["has_pose"]
self.has_camera = dataset_dict["has_camera"]
del dataset_dict
del self.dataset
del self.coco_dataset
self.scale = 1.2
print("Total Train dataset: {}".format(format(self.__len__(), ",")))
def load_dataset(self, dataset_path, use_gt=False, prop_sample=None):
dataset_dict = {}
data = joblib.load(dataset_path)
p_id_list = np.array(data["p_id"])
img_path_list = np.array(data["img_name"])
bbox_list = np.array(data["bbox"])
len_data = len(img_path_list)
J24_TO_J17 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 18, 14, 16, 17]
J24_TO_J14 = J24_TO_J17[:14]
UNIVERSAL_BODIES = [
16, # R ankle
14, # R knee
12, # R hip
11, # L hip
13, # L knee
15, # L ankle
10, # R Wrist
8, # R Elbow
6, # R shoulder
5, # L shoulder
7, # L Elbow
9, # L Wrist
0,
0,
]
if use_gt:
try:
joints3D_list = data["joints3D"]
joints3D_list = np.array(joints3D_list)
if self.joints_dataset == "h36m":
joints3D_list = joints3D_list[:, :, :-1]
has_joints3D = np.ones((len_data, 14, 1))
except KeyError:
print("Has No 3D joints")
if self.joints_dataset == "h36m":
joints3D_list = np.zeros((len_data, 24, 3))
else:
joints3D_list = np.zeros((len_data, 49, 3))
has_joints3D = np.zeros((len_data, 14, 1))
try:
joints2D_list = data["joints2D"]
joints2D_list = np.array(joints2D_list)
if self.joints_dataset == "h36m":
if joints2D_list.shape[1] == 24:
joints2D_list = joints2D_list[:, J24_TO_J14, :]
elif joints2D_list.shape[1] == 17:
joints2D_list = joints2D_list[:, UNIVERSAL_BODIES, :]
joints2D_list[: :13, 2] = 1
joints2D_list[:, 13, 2] = 0
joints2D_list[:, 14, 2] = 0
has_joints2D = np.ones((len_data, 14, 1))
except KeyError:
print("Has No 2D joints")
joints2D_list = np.zeros((len_data, 14, 3))
has_joints2D = np.zeros((len_data, 14, 1))
try:
shape_list = data["shape"]
has_shape = np.ones((len_data, 1))
except KeyError:
print("Has No Shape")
shape_list = np.zeros((len_data, 10))
has_shape = np.zeros((len_data, 1))
try:
pose_list = data["pose"]
has_pose = np.ones((len_data, 24, 3, 1))
except KeyError:
print("Has No Pose")
pose_list = np.zeros((len_data, 72))
has_pose = np.zeros((len_data, 24, 3, 1))
has_camera = np.ones((len_data, 1))
else:
if self.joints_dataset == "h36m":
joints3D_list = np.zeros((len_data, 24, 3))
else:
joints3D_list = np.zeros((len_data, 49, 3))
has_joints3D = np.zeros((len_data, 14, 1))
joints2D_list = np.zeros((len_data, 14, 3))
has_joints2D = np.zeros((len_data, 14, 1))
shape_list = np.zeros((len_data, 10))
has_shape = np.zeros((len_data, 1))
pose_list = np.zeros((len_data, 72))
has_pose = np.zeros((len_data, 24, 3, 1))
has_camera = np.zeros((len_data, 1))
if prop_sample:
np.random.seed(0)
random_idx = np.random.choice(range(len_data), int(len_data*prop_sample))
dataset_dict["p_id_list"] = p_id_list[random_idx]
dataset_dict["img_path_list"] = img_path_list[random_idx]
print(np.random.choice(dataset_dict["img_path_list"], 10))
dataset_dict["bbox_list"] = bbox_list[random_idx]
dataset_dict["len_data"] = int(len_data*prop_sample)
dataset_dict["joints3D_list"] = joints3D_list[random_idx]
dataset_dict["has_joints3D"] = has_joints3D[random_idx]
dataset_dict["joints2D_list"] = joints2D_list[random_idx]
dataset_dict["has_joints2D"] = has_joints2D[random_idx]
dataset_dict["shape_list"] = shape_list[random_idx]
dataset_dict["has_shape"] = has_shape[random_idx]
dataset_dict["pose_list"] = pose_list[random_idx]
dataset_dict["has_pose"] = has_pose[random_idx]
dataset_dict["has_camera"] = has_camera[random_idx]
else:
dataset_dict["p_id_list"] = p_id_list
dataset_dict["img_path_list"] = img_path_list
dataset_dict["bbox_list"] = bbox_list
dataset_dict["len_data"] = len_data
dataset_dict["joints3D_list"] = joints3D_list
dataset_dict["has_joints3D"] = has_joints3D
dataset_dict["joints2D_list"] = joints2D_list
dataset_dict["has_joints2D"] = has_joints2D
dataset_dict["shape_list"] = shape_list
dataset_dict["has_shape"] = has_shape
dataset_dict["pose_list"] = pose_list
dataset_dict["has_pose"] = has_pose
dataset_dict["has_camera"] = has_camera
return dataset_dict
def __len__(self):
return len(self.img_path_list)
def __getitem__(self, idx):
p_id = int(self.p_id_list[idx])
img_path = self.img_path_list[idx]
bbox = self.bbox_list[idx]
if self.use_seg_gt:
seg_img_path = img_path.split("/")
seg_img_path[3] = "segFiles"
seg_img_path[-1] = str(p_id) + "_" + seg_img_path[-1]
seg_img_path = "/".join(seg_img_path)
_, seg_img = get_single_image_crop(seg_img_path, bbox, self.scale)
image, _ = get_single_image_crop(img_path, bbox, self.scale)
image = Image.fromarray(image)
img = self.transform_224_tensor(image)
image_224 = self.transform_224(image)
W, H = image_224.size # W, H 224
s = W/self.divider # 112
a = s/2 # 56
tiles_jigsaw = [None] * self.num_patch
for n in range(self.num_patch):
i = n//self.divider
j = n%self.divider
c = [a * i * 2 + a, a * j * 2 + a]
c = np.array([c[1] - a, c[0] - a, c[1] + a + 1, c[0] + a + 1]).astype(int)
tile = image_224.crop(c.tolist())
tile_jigsaw = self.augment_tile_256_224(tile)
tiles_jigsaw[n] = tile_jigsaw
# Context Encoder
context_encoder_input = copy.deepcopy(img)
center_crop_img = copy.deepcopy(context_encoder_input[:, 80:144, 80:144])
context_encoder_input[:, 80:144, 80:144] = 0
# Jigsaw Puzzle
jigsaw_order = np.random.randint(len(self.permutations))
jigsaw_input = [tiles_jigsaw[self.permutations[jigsaw_order][t]] for t in range(self.num_patch)]
jigsaw_input = torch.stack(jigsaw_input, 0)
# Rotation
rotation_idx = np.random.randint(4)
angle = self.angle_list[rotation_idx]
rotation_input = self.rotate_img(image, angle)
rotation_input = self.transform_224_tensor(rotation_input)
joints3d = self.joints3D_list[idx]
joints3d = torch.FloatTensor(joints3d)
has_joints3d = self.has_joints3D[idx]
has_joints3d = torch.FloatTensor(has_joints3d)
joints2d = self.joints2D_list[idx]
joints2d[:,:2], trans = transfrom_keypoints(
kp_2d=joints2d[:,:2],
center_x=bbox[0],
center_y=bbox[1],
width=bbox[2],
height=bbox[3],
patch_width=224,
patch_height=224,
do_augment=False,
)
joints2d[:,:2] = normalize_2d_kp(joints2d[:,:2], 224)
joints2d = torch.FloatTensor(joints2d)
has_joints2d = self.has_joints2D[idx]
has_joints2d = torch.FloatTensor(has_joints2d)
shape = self.shape_list[idx]
shape = torch.FloatTensor(shape)
has_shape = self.has_shape[idx]
has_shape = torch.FloatTensor(has_shape)
pose = self.pose_list[idx]
pose = torch.FloatTensor(pose)
has_pose = self.has_pose[idx]
has_pose = torch.FloatTensor(has_pose)
has_camera = self.has_camera[idx]
has_camera = torch.FloatTensor(has_camera)
item = {}
item['img_path'] = img_path
item['p_id'] = p_id
item['img'] = img
item['context_encoder_input'] = context_encoder_input
item['center_crop_img'] = center_crop_img
item['jigsaw_input'] = jigsaw_input
item['rotation_input'] = rotation_input
item['jigsaw_order'] = jigsaw_order
item['rotation_idx'] = rotation_idx
item['joints3d'] = joints3d
item['has_joints3d'] = has_joints3d
item['joints2d'] = joints2d
item['has_joints2d'] = has_joints2d
item['shape'] = shape
item['has_shape'] = has_shape
item['pose'] = pose
item['has_pose'] = has_pose
item['has_camera'] = has_camera
if self.use_seg_gt:
item['target_seg'] = seg_img[:1, :, :]
return item
def rotate_img(self, img, rot):
img = np.array(img)
if rot == 0: # 0 degrees rotation
img = img
elif rot == 90: # 90 degrees rotation
img = np.flipud(np.transpose(img, (1,0,2)))
elif rot == 180: # 180 degrees rotation
img = np.fliplr(np.flipud(img))
elif rot == 270: # 270 degrees rotation / or -90
img = np.transpose( | np.flipud(img) | numpy.flipud |
import pickle
import os.path
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches
from collections import OrderedDict
face_data = OrderedDict()
with open(os.path.join(os.path.dirname(os.path.realpath(__file__)), "face_data.pickle"), 'rb') as f:
face_data = pickle.load(f)
def save() :
'''
Saves face_data to a .pickle file
'''
with open(os.path.join(os.path.dirname(os.path.realpath(__file__)), "face_data.pickle"), 'wb') as f:
pickle.dump(face_data, f, pickle.HIGHEST_PROTOCOL)
def add_face(descriptor, name) :
'''
Adds descriptor and name to face_data, or averages current descriptor for name
Parameters
-----------
descriptor: ndarray
descriptor for face, returned by face_recognition.detections.face_detection
name: str
name of person to be stored in database with given descriptor
'''
if name not in face_data :
face_data[name] = descriptor
else:
face_data[name] = (face_data[name] + descriptor) / 2
save()
def remove_person(name) :
'''
Removes name's descriptor and name from database
Parameters
-----------
name: str
name of person to be removed
'''
if name not in face_data :
return "%s is not in the database" % (name)
else :
del face_data[name]
save()
def clear_database():
'''
Clears database of descriptors and names
'''
face_data.clear()
def list_names() :
'''
Lists names of all people in database
'''
return list(face_data.keys())
def match_face(descriptor) :
'''
Finds the face descriptor from database that best matches descriptor
Parameters
-----------
descriptor: ndarray
descriptor of detected face
'''
descriptors = np.vstack(list(face_data.values()))
dist = np.sqrt(np.abs(np.sum(descriptors**2, axis=1) + np.sum(descriptor**2) - 2 * np.dot(descriptors, descriptor)))
dist_index = np.argmin(dist)
print(dist)
if dist[dist_index] > .3 :
best_match = None
best_descriptor = None
else :
best_match = list(face_data.keys())[dist_index]
best_descriptor = face_data[best_match]
print(best_match)
return best_match, best_descriptor
def get_names(face_descriptors) :
'''
Returns list of names corresponding to descriptors
Parameters
-----------
face_descriptors: iterable of ndarrays
iterable of face descriptors detected in a photo
Returns
--------
names: list of str
list of names best matching face descriptors
'''
names = []
for descriptor in face_descriptors :
names.append(match_face(descriptor)[0])
return names
def format_names(names, face_descriptors, alexa) :
'''
Returns formatted string of user's names
Parameters
-----------
names: list of str
list of names of people in picture
face_descriptors: iterable of ndarrays
iterable of face descriptors detected in a photo
alexa: boolean
whether to prompt user to save photo or enter new name
'''
print(names)
if len(names) == 0 :
return "No face is detected", False
elif len(names) == 1 :
if names[0] is None :
if alexa :
return "An unknown face is detected", False
else :
name = input("An unknown face is detected. If you would like to save this image, please enter the person's name. Otherwise, please enter 'None': ")
if name.lower() != 'none' :
add_face(face_descriptors[0], name)
save()
return "Picture saved in database for %s" % (name), True
else :
return "Picture not saved", False
else :
if alexa :
return "%s is detected" % (names[0]), False
else :
should_save = input("%s is detected. Would you like you save this picture? Please enter 'Yes' or 'No': " % (names[0]))
if should_save.lower() == "yes" :
add_face(face_descriptors[0], names[0])
return "Picture was saved", False
elif should_save.lower() == "no" :
return "Picture not saved", False
else :
raise Exception("Input is not valid")
elif len(names) == 2 :
nones = names.count(None)
to_return = ", ".join(filter(None, names))
if nones > 0 :
if nones == 1 :
to_return = to_return + " and 1 unknown person are detected"
else :
split = to_return.rpartition(", ")
to_return = split[0] + " and " + split[2] + " are detected"
return to_return, False
else :
nones = names.count(None)
to_return = ", ".join(filter(None, names))
if nones > 0 :
if nones == 1 :
to_return = to_return + ", and 1 unknown person are detected"
else :
to_return = to_return + ", and %s unknown people are detected" % nones
else :
split = to_return.rpartition(", ")
to_return = split[0] + split[1] + "and " + split[2] + " are detected"
return to_return, False
def show_image(img_array, face_borders, names) :
'''
Shows the image with faces boxed and labeled
Parameters
-----------
img_array: np.array
matrix of the image information
face_borders: iterable of ints
iterable of box coordinates for all faces recognized
names: iterable of strs
iterable of all names of faces recognized
'''
# Create figure and axes
fig, ax = plt.subplots(1)
# Display the image
ax.imshow(img_array)
for i, border in enumerate(face_borders):
# Get borders for descriptor
l, r, t, b = border
# Create a Rectangle patch
rect = patches.Rectangle((l, t), r - l, b - t, linewidth=1, edgecolor='y', facecolor='none')
if names[i] is not None :
ax.annotate(names[i], (r, t), color='w', weight='bold', fontsize=10, ha='right', va='bottom')
# Add the patch to the Axes
ax.add_patch(rect)
plt.show()
# work in progress
def rgb_to_hsv(rgb_img) :
'''
Parameters
-----------
rgb_img: numpy array of shape NxMx3
'''
rgb_prime = rgb_img / 255
rgb_max_index = np.argmax(rgb_img, axis=2)
Cmax = np.amax(rgb_prime, axis=2)
Cmin = np.amin(rgb_prime, axis=2)
delta = Cmax - Cmin
hue = np.zeros(rgb_img.shape)
sat = np.zeros(rgb_img.shape)
# gets indices of maximum prime colors
r_prime_indices = list(zip(np.where(rgb_max_index == 0 & delta != 0, rgb_prime)))
b_prime_indices = list(zip(np.where(rgb_max_index == 1 & delta != 0, rgb_prime)))
g_prime_indices = list(zip( | np.where(rgb_max_index == 2 & delta != 0, rgb_prime) | numpy.where |
'''
TIEGCM Kamodo reader, adapted to new structure for satellite flythrough software
Initial version - <NAME> (?)
Initial version of model_varnames contributed by <NAME>
New code: <NAME> (June 2021 and on)
NOTE: The current logic for variables that depend on imlev slices off self._imlev coordinate
This only works because there is one variable that depends on imlev: H_imlev
The logic on lines 311-313 will have to be reworked a bit if other variables depend on imlev later.
Remaining tasks:
- check variable dictionary for proper naming, and use of units in Kamodo
'''
from numpy import vectorize
from datetime import datetime, timezone, timedelta
### Make a dict of the possible variable names in TIEGCM
### the intended format is: "Output VarName":['Latex_Varname', 'Latex_Unit' ]
### The constituent species are output in units of mass mixing ratio (mmr).
### Denoted by \psi_i, mmr is the fractional contribution of
### a species i to the total mass density \rho_{total}, and
### is calculated as \psi_i = \rho_i / \rho_{total}, where
### \rho_i is the mass density of a constituent species.
model_varnames={
### 4D Variables, vertical coordinate on midpoint levels (lev)
"ZGMID" : ["H_ilev",'variable description',0,'GDZ','sph',['time','lon','lat','ilev'],"cm"], # geometric height- interpolated to the mid points
"TN" : ["T_n",'variable description',1,'GDZ','sph',['time','lon','lat','ilev'],"K"], # neutral temperature
"O2" : ["psi_O2",'variable description',2,'GDZ','sph',['time','lon','lat','ilev'],""], # molecular oxygen, mmr
"O1" : ["psi_O",'variable description',3,'GDZ','sph',['time','lon','lat','ilev'],""], # atomic oxygen , mmr
"N2" : ["psi_N2",'variable description',4,'GDZ','sph',['time','lon','lat','ilev'],""], # molecular nitrogen,mmr
"HE" : ["psi_He",'variable description',5,'GDZ','sph',['time','lon','lat','ilev'],""], # helium , mmr
"NO" : ["psi_NO",'variable description',6,'GDZ','sph',['time','lon','lat','ilev'],""], # nitric oxide , mmr
"N4S" : ["psi_N4S",'variable description',7,'GDZ','sph',['time','lon','lat','ilev'],""], # N4S ?,mmr
"N2D" : ["psi_N2D", 'variable description',8,'GDZ','sph',['time','lon','lat','ilev'],""], # N(2D) mmr
"TE" : ["T_e",'variable description',9,'GDZ','sph',['time','lon','lat','ilev'],"K"], # ELECTRON TEMPERATURE,
"TI" : ["T_i",'variable description',10,'GDZ','sph',['time','lon','lat','ilev'],"K"], # ION TEMPERATURE
"O2P" : ["N_O2plus",'variable description',11,'GDZ','sph',['time','lon','lat','ilev'],"1/cm**3"], # O2+ ION
"OP" : ["N_Oplus",'variable description',12,'GDZ','sph',['time','lon','lat','ilev'],"1/cm**3"], # O+ ION
"N2N" : ["N_N2",'variable description',13,'GDZ','sph',['time','lon','lat','ilev'],"1/cm**3"], # molecular nitrogen (maybe number density),mmr
"CO2_COOL" : ["Q_CO2cool",'variable description',14,'GDZ','sph',['time','lon','lat','ilev'],"erg/g/s"], # CO2 cooling rates
"NO_COOL" : ["Q_NOcool",'variable description',15,'GDZ','sph',['time','lon','lat','ilev'],"erg/g/s"], # NO cooling rates
"UN" : ["u_n",'variable description',16,'GDZ','sph',['time','lon','lat','ilev'],"cm/s"], # neutral ZONAL wind (+EAST)
"VN" : ["v_n",'variable description',17,'GDZ','sph',['time','lon','lat','ilev'],"cm/s"], # neutral MERIDIONAL wind (+NORTH)
"O2P_ELD" : ['O2P_ELD','variable description',18,'GDZ','sph',['time','lon','lat','ilev'],''], #NO DESCRIPTION GIVEN
"N2P_ELD" :['N2P_ELD','variable description',19,'GDZ','sph',['time','lon','lat','ilev'],''], #NO DESCRIPTION GIVEN
"NPLUS" :['N_Nplus','variable description',20,'GDZ','sph',['time','lon','lat','ilev'],'1/cm**3'], #GUESS ONLY based on other number densities
"NOP_ELD" :['NOP_ELD','variable description',21,'GDZ','sph',['time','lon','lat','ilev'],''], #NO DESCRIPTION GIVEN
"SIGMA_PED" :['Sigma_P','variable description',22,'GDZ','sph',['time','lon','lat','ilev'],'S/m'], #Pedersen Conductivity
"SIGMA_HAL" :['Sigma_H','variable description',23,'GDZ','sph',['time','lon','lat','ilev'],'S/m'], #Hall Conductivity
"QJOULE" :['Q_Joule','variable description',24,'GDZ','sph',['time','lon','lat','ilev'],'erg/g/s'], #Joule Heating
"O_N2" :['psi_ON2','variable description',25,'GDZ','sph',['time','lon','lat','ilev'],''], #O/N2 RATIO
"N2D_ELD" :['N2D_ELD','variable description',26,'GDZ','sph',['time','lon','lat','ilev'],''], #NO DESCRIPTION GIVEN
"O2N" :['r_OtoN','variable description',27,'GDZ','sph',['time','lon','lat','ilev'],'1/cm**3'], #GUESS ONLY
#
### 4D Variables, vertical coordinate on interface levels (ilev)
"DEN" :["rho",'variable description',28,'GDZ','sph',['time','lon','lat','ilev1'],"g/cm**3"], # total neutral mass density
"ZG" :["H_ilev1",'variable description',29,'GDZ','sph',['time','lon','lat','ilev1'],"cm"], # geometric height
"Z" :["H_geopot",'variable description',30,'GDZ','sph',['time','lon','lat','ilev1'],"cm"], # geopotential height (cm)
"NE" : ["N_e",'variable description',31,'GDZ','sph',['time','lon','lat','ilev1'],"1/cm**3"], # ELECTRON DENSITY
"OMEGA" : ["omega",'variable description',32,'GDZ','sph',['time','lon','lat','ilev1'],"1/s"], # VERTICAL MOTION
"POTEN" : ["V",'variable description',33,'GDZ','sph',['time','lon','lat','ilev1'],"V"], # ELECTRIC POTENTIAL
"UI_ExB" : ["u_iExB",'variable description',34,'GDZ','sph',['time','lon','lat','ilev1'],'cm/s'], #Zonal ExB Velocity
"VI_ExB" :["v_iExB",'variable description',35,'GDZ','sph',['time','lon','lat','ilev1'],'cm/s'], #Meridional ExB Velocity
"WI_ExB" :["w_iExB", 'variable description',36,'GDZ','sph',['time','lon','lat','ilev1'], 'cm/s'], #Vertical ExB Velocity
### 4D Variables, vertical coordinate on interface mag levels (imlev)
"ZMAG" : ["H_mag",'variable description',37,'MAG','sph',['time','mlon','mlat','milev'],"km"], # Geopotential Height on Geomagnetic Grid
#
### 3D Variables, (time, lat, lon)
"TEC" : ["TEC",'variable description',38,'GDZ','sph',['time','lon','lat'],"1/cm**2"], # Total Electron Content
"TLBC" : ["T_nLBC",'variable description',39,'GDZ','sph',['time','lon','lat'],"K"], # Lower boundary condition for TN
"ULBC" : ["u_nLBC",'variable description',40,'GDZ','sph',['time','lon','lat'],"cm/s"], # Lower boundary condition for UN
"VLBC" : ["v_nLBC",'variable description',41,'GDZ','sph',['time','lon','lat'],"cm/s"], # Lower boundary condition for VN
"TLBC_NM" : ["T_nLBCNM",'variable description',42,'GDZ','sph',['time','lon','lat'],"K"], # Lower boundary condition for TN (TIME N-1)
"ULBC_NM" : ["u_nLBCNM",'variable description',43,'GDZ','sph',['time','lon','lat'],"cm/s"], # Lower boundary condition for UN (TIME N-1)
"VLBC_NM" : ["v_nLBCNM",'variable description',44,'GDZ','sph',['time','lon','lat'],"cm/s"], # Lower boundary condition for VN (TIME N-1)
"QJOULE_INTEG":["W_Joule",'variable description',45,'GDZ','sph',['time','lon','lat'],'erg/cm**2/s'], #Height-integrated Joule Heating
"EFLUX" :['Eflux_aurora','variable description',46,'GDZ','sph',['time','lon','lat'],'erg/cm**2/s'], #Aurora Energy Flux
"HMF2" :['HmF2','variable description',47,'GDZ','sph',['time','lon','lat'],'km'], # Height of the F2 Layer
"NMF2" :['NmF2','variable description',48,'GDZ','sph',['time','lon','lat'],'1/cm**3'], #Peak Density of the F2 Layer
}
#####--------------------------------------------------------------------------------------
##### Define some helpful functions for dealing with time systems
def dts_to_ts(file_dts):
'''Get datetime timestamp in UTC from datetime string'''
return datetime.timestamp(datetime.strptime(file_dts, '%Y-%m-%d %H:%M:%S'
).replace(tzinfo=timezone.utc))
def year_mtime_todt0(year, mtime): #self.filedate
'''Convert year and day to datetime object in UTC at midnight'''
day, hour, minute = mtime #unpack mtime values
return datetime(int(year),1,1).replace(tzinfo=timezone.utc)+\
timedelta(days=int(day-1))
def year_mtime_todt(year, mtime):
'''Convert year and [day,hour,minute] to datetime object in UTC'''
day, hour, minute = mtime #unpack mtime values
return datetime(int(year),1,1).replace(tzinfo=timezone.utc)+\
timedelta(days=int(day-1),hours=int(hour),minutes=int(minute))
def year_mtime_todts(year, mtime):
'''Convert year and mtime to a datetime string'''
return datetime.strftime(year_mtime_todt(year, mtime), '%Y-%m-%d %H:%M:%S')
def year_mtime_todate(year, mtime):
'''Use year and mtime to determine the date in the file. Returns a datetime object.'''
date_string = datetime.strftime(year_mtime_todt(year, mtime), '%Y-%m-%d') #'YYYY-MM-DD'
return datetime.strptime(date_string, '%Y-%m-%d').replace(tzinfo=timezone.utc)
@vectorize
def year_mtime_tohrs(year, day, hour, minute, filedate):
'''Convert year and mtime to hours since midnight using predetermined datetime object.'''
mtime = [day, hour, minute]
return (year_mtime_todt(year, mtime)-filedate).total_seconds()/3600.
def ts_to_hrs(time_val, filedate):
'''Convert utc timestamp to hours since midnight on filedate.'''
return (datetime.utcfromtimestamp(time_val).replace(tzinfo=timezone.utc)-filedate).total_seconds()/3600.
def MODEL():
from time import perf_counter
from os.path import basename
from numpy import zeros, transpose, array, append, insert, where, unique
from numpy import NaN, diff, abs, mean, broadcast_to, cos, sin, repeat, sqrt, sum
from numpy import pi as nppi
from netCDF4 import Dataset
from kamodo import Kamodo
#print('KAMODO IMPORTED!')
from kamodo.readers.reader_utilities import regdef_3D_interpolators, regdef_4D_interpolators
class MODEL(Kamodo):
'''TIEGCM model data reader.'''
def __init__(self, full_filename, variables_requested=[], runname="noname",
filetime=False, verbose=False, gridded_int=True, printfiles=False,
fulltime=True, **kwargs): #filename should include the full path
#### Use a super init so that your class inherits any methods from Kamodo
super(MODEL, self).__init__()
#store time information for satellite flythrough layer to choose the right file
t0 = perf_counter()
filename = basename(full_filename)
file_dir = full_filename.split(filename)[0]
cdf_data = Dataset(full_filename, 'r')
#calculate time information
year = array(cdf_data.variables['year'])
mtime = array(cdf_data.variables['mtime'])
day, hour, minute = mtime.T #only matters for the vectorized function
self.filedate = year_mtime_todt0(year[0], mtime[0]) #datetime object for file date at midnight UTC
self.datetimes = [year_mtime_todts(y, m) for y, m \
in zip([year[0], year[-1]],[mtime[0],mtime[-1]])] #strings in format = YYYY-MM-DD HH:MM:SS
self.filetimes=[dts_to_ts(file_dts) for file_dts in self.datetimes] #timestamps in UTC
time = year_mtime_tohrs(year, day, hour, minute, self.filedate)
#time = array([year_mtime_tohrs(y, m, self.filedate) for y, m in \
# zip(year, mtime)]) #hours since midnight of self.filedate
self.dt = diff(time).max()*3600. #time is in hours
if filetime and not fulltime: #(used when searching for neighboring files below)
return #return times as is to prevent recursion
#if variables are given as integers, convert to standard names
if len(variables_requested)>0:
if isinstance(variables_requested[0], int):
tmp_var = [value[0] for key, value in model_varnames.items()\
if value[2] in variables_requested]
variables_requested = tmp_var
if fulltime: #add boundary time (default value)
#find other files with same pattern
from glob import glob
file_pattern = file_dir+'s*.nc' #returns a string for tiegcm
files = sorted(glob(file_pattern))
filenames = unique([basename(f) for f in files])
#find closest file by utc timestamp
#tiegcm has an open time at the beginning, so need an end time from the previous file
#files are automatically sorted by YYMMDD, so previous file is previous in the list
current_idx = where(filenames==filename)[0]
if current_idx==0:
print('No earlier file available.')
filecheck = False
if filetime:
return
else:
min_filename = file_dir+filenames[current_idx-1][0] #-1 for adding a beginning time
kamodo_test = MODEL(min_filename, filetime=True, fulltime=False)
time_test = abs(kamodo_test.filetimes[1]-self.filetimes[0])
if time_test<=self.dt: #if nearest file time at least within one timestep (hrs)
filecheck = True
#time only version if returning time for searching
if filetime:
kamodo_neighbor = MODEL(min_filename, fulltime=False, filetime=True)
self.datetimes[0] = kamodo_neighbor.datetimes[1]
self.filetimes[0] = kamodo_neighbor.filetimes[1]
return #return object with additional time (for SF code)
#get kamodo object with same requested variables to add to each array below
if verbose: print(f'Took {perf_counter()-t0:.3f}s to find closest file.')
kamodo_neighbor = MODEL(min_filename, variables_requested=variables_requested,
fulltime=False)
self.datetimes[0] = kamodo_neighbor.datetimes[1]
self.filetimes[0] = kamodo_neighbor.filetimes[1]
short_data = kamodo_neighbor.short_data
if verbose: print(f'Took {perf_counter()-t0:.3f}s to get data from previous file.')
else:
print(f'No earlier file found within {self.dt:.1f}s')
filecheck = False
if filetime:
return
#These lists need to be the standardized variable name to match that above,
#not the names from the data file.
self.ilev1_list = [value[0] for key, value in model_varnames.items() if value[5][-1]=='ilev1']
self.ilev_list = [value[0] for key, value in model_varnames.items() if value[5][-1]=='ilev']
self.milev_list = [value[0] for key, value in model_varnames.items() if value[5][-1]=='milev']
#don't need an internal coord dict because there is only one lat/lon (other than magnetic)
#perform initial check on variables_requested list
if len(variables_requested)>0 and fulltime:
test_list = [value[0] for key, value in model_varnames.items()]
err_list = [item for item in variables_requested if item not in test_list]
if len(err_list)>0: print('Variable name(s) not recognized:', err_list)
#translate from standardized variables to names in file
#remove variables requested that are not in the file
if len(variables_requested)>0:
gvar_list = [key for key, value in model_varnames.items() \
if value[0] in variables_requested and \
key in cdf_data.variables.keys()] # file variable names
#check for variables requested but not available
if len(gvar_list)!=len(variables_requested):
err_list = [value[0] for key, value in model_varnames.items() \
if value[0] in variables_requested and \
key not in cdf_data.variables.keys()]
if len(err_list)>0: print('Some requested variables are not available:', err_list)
#check that the appropriate height variable is added for the variables requested
check_list = [key for key, value in model_varnames.items()\
if value[0] in self.ilev1_list and key in gvar_list]
if 'ZG' not in gvar_list and len(check_list)>0:
gvar_list.append('ZG') #force addition of H for conversion of ilev to H and back
check_list = [key for key, value in model_varnames.items()\
if value[0] in self.ilev_list and key in gvar_list]
if 'ZGMID' not in gvar_list and len(check_list)>0:
gvar_list.append('ZGMID')
check_list = [key for key, value in model_varnames.items()\
if value[0] in self.milev_list and key in gvar_list]
if 'ZMAG' not in gvar_list and len(check_list)>0:
gvar_list.append('ZMAG')
else: #only input variables on the avoid_list if specifically requested
avoid_list = ['TLBC','ULBC','VLBC','TLBC_NM','ULBC_NM','VLBC_NM',
'NOP_ELD','O2P_ELD','N2P_ELD','N2D_ELD']
gvar_list = [key for key in cdf_data.variables.keys() \
if key in model_varnames.keys() and \
key not in avoid_list]
# Store the requested variables into a dictionary
variables = {model_varnames[key][0]:{'units':model_varnames[key][-1],
'data':array(cdf_data.variables[key])}\
for key in gvar_list} #store with key = standardized name
#prepare and return data only for last timestamp
if not fulltime:
cdf_data.close()
variables['time'] = self.filetimes[1] #utc timestamp
self.short_data = variables
return
#### Store our inputs as class attributes to the class
self.filename = full_filename
self.runname = runname
self.missing_value = NaN
self._registered = 0
self.variables = dict()
self.modelname = 'TIEGCM'
if printfiles:
print('Files:', self.filename)
#### Store coordinate data as class attributes
if filecheck: #new_time iis a utc timestamp
new_time = ts_to_hrs(short_data['time'], self.filedate) #new time in hours since midnight
self._time = insert(time, 0, new_time) #insert new value
else:
self._time = time
#store coordinates
lat = array(cdf_data.variables['lat']) #NOT FULL RANGE IN LATITIUDE!!!
lat = insert(lat, 0, -90) #insert a grid point at beginning (before -87.5)
self._lat = append(lat, 90.) #and at the end (after 87.5)
lon = array(cdf_data.variables['lon']) #NOT WRAPPED IN LONGITUDE!!!!!
self._lon = append(lon, 180.) #add 180. to end of array
self._ilev = array(cdf_data.variables['lev'])
self._ilev1 = array(cdf_data.variables['ilev'])
self._milev = | array(cdf_data.variables['imlev']) | numpy.array |
import os
import matplotlib.pyplot as plt
import numpy as np
import torch
from nuscenes.nuscenes import NuScenes
from custom_lidar_api import CustomLidarApi
from custom_map_api_expansion import CustomNuScenesMap
plt.style.use('seaborn-bright')
class NusceneDataHelper():
def __init__(self, version,
dataroot='./data/sets/nuscenes',
locations=['singapore-onenorth', 'singapore-hollandvillage', 'singapore-queenstown', 'boston-seaport'],
target_layer_names=['road_block', 'walkway', 'road_divider', 'traffic_light'],
max_objs=64,
max_points=30,
max_point_cloud=1200,
patch_size=[-1, -1]):
self.class_names = ["None"] + target_layer_names
self.dataroot = dataroot
self.locations = locations
self.target_layer_names = target_layer_names
self.max_objs = max_objs
self.max_points = max_points
self.max_point_clouds = max_point_cloud
self.patch_size = patch_size
self.class_dict = dict()
for i, name in enumerate(self.target_layer_names):
self.class_dict[name] = i + 1
self.class_array = np.eye(len(self.class_names))
self.nusc = NuScenes(version=version, dataroot=dataroot, verbose=False)
self.ldr_api = CustomLidarApi(self.nusc)
self.map_api = dict()
for loc in locations:
self.map_api[loc] = CustomNuScenesMap(dataroot=dataroot, map_name=loc,
target_layer_names=target_layer_names, max_objs=max_objs,
max_points=max_points)
def get_frame_from_token(self, token):
sample = self.nusc.get('sample', token)
scene = self.nusc.get('scene', sample['scene_token'])
log_meta = self.nusc.get('log', scene['log_token'])
location = log_meta['location']
sample_data = self.nusc.get('sample_data', sample['data']['LIDAR_TOP'])
pc = self.ldr_api.get_lidar_from_keyframe(token, max_points=self.max_point_clouds, car_coord=True)
ego = self.ldr_api.get_egopose_from_keyframe(token)
structures = self.map_api[log_meta['location']].get_closest_structures(ego,
patch=self.patch_size,
global_coord=False,
mode='intersect'
)
return pc, structures, ego
def get_all_sample_tokens(self):
sample_tokens = []
for scene in self.nusc.scene:
token = scene['first_sample_token']
while token != scene['last_sample_token']:
sample_tokens.append(token)
sample = self.nusc.get('sample', token)
token = sample['next']
return sample_tokens
def get_label(self, structures):
classes = list(map(lambda x: np.array(self.class_array[self.class_dict[x["layer"]], :]).reshape(len(self.class_names),1),structures))
classes = np.concatenate(classes, axis=1)
objects = list(map(lambda x: np.array(x['nodes'].reshape(1, self.max_points, 2)), structures))
objects = np.concatenate(objects, axis=0)
if len(structures) < self.max_objs:
diff = self.max_objs - len(structures)
classes = np.concatenate([classes, np.zeros((5, diff))], axis = 1)
objects = np.concatenate([objects, np.zeros((diff, 30, 2))], axis = 0)
return classes, objects
def draw_data(self,
token,
ax=None,
model=None,
view_2d=True,
save_name=""):
pc, structures, ego = self.get_frame_from_token(token)
pc_array = pc.points
if model is None:
pred_class = np.array([])
pred_pose = np.array([])
else:
X = torch.Tensor( | np.expand_dims(pc_array, axis=0) | numpy.expand_dims |
# -*- coding: utf-8 -*-
"""
.. invisible:
_ _ _____ _ _____ _____
| | | | ___| | | ___/ ___|
| | | | |__ | | | |__ \ `--.
| | | | __|| | | __| `--. \
\ \_/ / |___| |___| |___/\__/ /
\___/\____/\_____|____/\____/
Created on May 19, 2014
Unit test for convolutional layer forward propagation, compared to CAFFE data.
███████████████████████████████████████████████████████████████████████████████
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
███████████████████████████████████████████████████████████████████████████████
"""
import numpy
import os
from scipy.signal import correlate2d, convolve2d # pylint: disable=E0611
from veles.dummy import DummyUnit
from veles.memory import Array
import veles.znicz.all2all as all2all
import veles.znicz.conv as conv
import veles.znicz.evaluator as evaluator
import veles.znicz.gd_conv as gd_conv
import veles.znicz.gd as gd
import veles.znicz.gd_pooling as gd_pooling
import veles.znicz.normalization as normalization
import veles.znicz.pooling as pooling
from veles.znicz.tests.functional import StandardTest
class CaffeTestBase(StandardTest):
def _read_array(self, array_name, lines, shape=None):
"""
Reads a pic array from from export file, splitted to lines.
NB: last line should be empty
Arguments:
array_name(str): name of array to read
lines(array): lines of file to read from
shape(tuple): shape=(n_pics, height, width, n_chans), must be given if
not set in file.
Returns:
:class:`numpy.ndarray`
"""
cur_line = None
for i, line in enumerate(lines):
line = line.replace("\n", "")
nibbles = line.split("\t")
if nibbles[0] == array_name:
if len(nibbles) >= 5: # shape is set in file
dimensions = {}
for nibble in nibbles[1:]:
[nibble_name, nibble_val] = nibble.split(":")
dimensions[nibble_name] = int(nibble_val)
n_pics = dimensions["num"]
height = dimensions["height"]
width = dimensions["width"]
n_chans = dimensions["channels"]
if shape is not None:
assert shape == (n_pics, height, width, n_chans)
else: # shape is set externally
assert len(shape) == 4
n_pics, height, width, n_chans = shape
out_array = numpy.zeros((n_pics, height, width, n_chans),
numpy.float64)
cur_line = i + 1
break
assert cur_line is not None
assert cur_line < len(lines)
for cur_pic in range(n_pics):
nibbles = lines[cur_line].split(":")
assert nibbles[0] == "num"
assert int(nibbles[1]) == cur_pic
cur_line += 1
for cur_chan in range(n_chans):
nibbles = lines[cur_line].split(":")
assert nibbles[0] == "channels"
assert int(nibbles[1]) == cur_chan
cur_line += 1
for i in range(height):
data = [float(x) for x in lines[cur_line].split("\t")]
cur_line += 1
for j in range(width):
out_array[cur_pic, i, j, cur_chan] = data[j]
return out_array
def _read_lines(self, data_filename):
"""
Returns all lines from a file maned `data_filename`.
File is searched in ``self.data_dir_path``.
Arguments:
data_filename(str): name to file with pooling data,
exported from CAFFE (searched in ``self.data_dir_path``)
Returns:
list: list of all lines read
"""
full_path = os.path.join(self.data_dir_path, data_filename)
return self._read_lines_by_abspath(full_path)
def _read_lines_by_abspath(self, full_path):
with open(full_path, 'r') as in_file:
return in_file.readlines()
class TestConvCaffe(CaffeTestBase):
def test_caffe_conv(self, data_filename="conv.txt"):
"""
Compare CAFFE conv layer fwd prop with Veles conv layer.
Args:
data_filename(str): name of file with pooling data
(relative from data dir)
"""
lines = self._read_lines(data_filename)
kernel_size = 5
padding_size = 2
bottom = self._read_array("bottom", lines=lines, shape=(2, 32, 32, 3))
weights = self._read_array("weights", lines=lines, shape=(2, 5, 5, 3))
top = self._read_array("top", lines=lines, shape=(2, 32, 32, 2))
fwd_conv = conv.Conv(self.parent, kx=kernel_size, ky=kernel_size,
padding=(padding_size, padding_size,
padding_size, padding_size),
sliding=(1, 1),
n_kernels=2)
fwd_conv.input = Array()
fwd_conv.input.mem = bottom
fwd_conv.initialize(self.device)
fwd_conv.weights.map_invalidate()
fwd_conv.weights.mem[:] = weights.reshape(2, 75)[:]
fwd_conv.bias.map_invalidate()
fwd_conv.bias.mem[:] = 0
fwd_conv.run()
self.info("Veles vs CAFFE data:")
fwd_conv.output.map_read()
self.info("Veles top shape:" + str(fwd_conv.output.mem.shape))
delta_with_veles = fwd_conv.output.mem - top
self.info("CONV: diff with Veles: %.2f%%" % (
100. * numpy.sum(numpy.abs(delta_with_veles)) /
numpy.sum(numpy.abs(fwd_conv.output.mem)),))
self.info("COMPARED TO HANDMADE CORRELATION:")
scipy_conv_out = numpy.zeros(shape=(2, 32, 32, 2), dtype=numpy.float64)
for pic in range(2):
for color_chan in range(3):
for weight_id in range(2):
correlation = correlate2d(
bottom[pic, :, :, color_chan],
weights[weight_id, :, :, color_chan], mode="same")
scipy_conv_out[pic, :, :, weight_id] += correlation
delta_with_scipy = fwd_conv.output.mem - scipy_conv_out
self.info("CONV: diff with SciPy: %.2f%%" % (
100. * numpy.sum(numpy.abs(delta_with_scipy)) /
numpy.sum(numpy.abs(fwd_conv.output.mem)),))
def test_caffe_grad_conv(self, data_filename="conv_grad.txt"):
"""
Compare CAFFE conv layer with Veles conv layer (FwdProp and BackProp).
Args:
data_filename(str): name of file with pooling data
(relative from data dir)
"""
lines = self._read_lines(data_filename)
# stride = 1
bot_size = 32
top_size = 32
kernel_size = 5
padding_size = 2
n_kernels = 2
batch_size = 2
bottom = self._read_array("bottom", lines=lines,
shape=(batch_size, bot_size, bot_size, 3))
weights = self._read_array("weights", lines=lines,
shape=(n_kernels,
kernel_size,
kernel_size,
3))
top = self._read_array("top", lines=lines,
shape=(batch_size, top_size, top_size, 2))
top_err = self._read_array("top_diff", lines=lines,
shape=(batch_size,
top_size,
top_size,
2))
bot_err = self._read_array("bottom_diff", lines=lines,
shape=(batch_size,
bot_size,
bot_size,
3))
fwd_conv = conv.Conv(self.parent, kx=kernel_size, ky=kernel_size,
padding=(padding_size, padding_size,
padding_size, padding_size),
sliding=(1, 1), n_kernels=n_kernels)
fwd_conv.input = Array(bottom)
fwd_conv.initialize(self.device)
fwd_conv.weights.map_invalidate()
fwd_conv.weights.mem[:] = weights.reshape(2, 75)[:]
fwd_conv.bias.map_invalidate()
fwd_conv.bias.mem[:] = 0
fwd_conv.run()
self.info("Veles vs CAFFE data:")
fwd_conv.output.map_read()
self.info("Veles top shape:" + str(fwd_conv.output.mem.shape))
delta_with_veles = fwd_conv.output.mem - top
self.info("CONV: diff with CAFFE: %.2f%%" % (
100. * numpy.sum(numpy.abs(delta_with_veles)) /
numpy.sum(numpy.abs(fwd_conv.output.mem)),))
back_conv = gd_conv.GradientDescentConv(self.parent)
back_conv.input = Array(bottom)
back_conv.output = Array(top)
back_conv.err_output = Array(top_err)
back_conv.weights = Array()
back_conv.weights.mem = fwd_conv.weights.mem
back_conv.bias = Array(fwd_conv.bias.mem)
back_conv.batch_size = 2
back_conv.link_conv_attrs(fwd_conv)
back_conv.initialize(self.device)
back_conv.run()
back_conv.err_input.map_read()
# BACKPROP: difference with CAFFE export
back_delta = back_conv.err_input.mem - bot_err
self.info("GDCONV: diff with CAFFE: %.3f%%" %
(100. * numpy.sum(numpy.fabs(back_delta)) /
numpy.sum(numpy.fabs(back_conv.err_input.mem)),))
# perform manual GD CONV
manual_bot_err = numpy.zeros(shape=(2, bot_size, bot_size, 3),
dtype=numpy.float64)
for pic in range(batch_size):
for color_chan in range(3):
for weight_id in range(n_kernels):
conv_result = convolve2d(
top_err[pic, :, :, weight_id],
weights[weight_id, :, :, color_chan], mode="same")
manual_bot_err[pic, :, :, color_chan] += conv_result
self.info("Manual GDCONV: diff with CAFFE: %.3f%%" % (
100. * numpy.sum(numpy.fabs(manual_bot_err - bot_err)) /
numpy.sum(numpy.fabs(bot_err))))
def test_caffe_pooling(self, data_filename="pool.txt"):
"""
Compare CAFFE pooling unit fwd_prop with Veles one
Args:
data_filename(str): name to file with pooling data,
exported from CAFFE (searched in ``self.data_dir_path``)
"""
# load pooling data from CAFFE dumps
in_file = open(os.path.join(self.data_dir_path, data_filename), 'r')
lines = in_file.readlines()
in_file.close()
# max pooling: 3x3 kernel, 2x2 stride
kernel_size = 3
stride = 2
in_height, in_width = 32, 32
out_height, out_width = 16, 16
bottom = self._read_array("bottom", lines=lines,
shape=(2, in_height, in_width, 2))
# do pooling with VELES
fwd_pool = pooling.MaxPooling(self.parent, kx=kernel_size,
ky=kernel_size, sliding=(stride, stride),
device=self.device)
fwd_pool.input = Array(bottom)
fwd_pool.input.map_write()
fwd_pool.initialize(device=self.device)
fwd_pool.numpy_run()
fwd_pool.output.map_read()
# do MANUAL pooling
manual_pooling_out = numpy.zeros(shape=(2, out_height, out_width, 2),
dtype=numpy.float64)
for pic in range(2):
for chan in range(2):
for i_out in range(out_height):
for j_out in range(out_width):
min_i = i_out * 2
max_i = i_out * 2 + kernel_size - 1
min_j = j_out * 2
max_j = j_out * 2 + kernel_size - 1
zone = bottom[pic, min_i: max_i + 1, min_j:
max_j + 1, chan]
manual_pooling_out[pic, i_out, j_out,
chan] = numpy.max((zone))
def test_caffe_grad_pooling(self, data_filename="pool_grad.txt"):
"""
Compare CAFFE pooling unit with Veles ones (fwd and back propagations)
Args:
data_filename(str): name of file with pooling data
(relative from data dir)
"""
bot_size = 32
top_size = 16
kernel_size = 3
stride = 2
n_chans = 2
n_pics = 2
lines = self._read_lines(data_filename)
lines = [line.replace("\t\n", "").replace("\n", "") for line in lines]
bottom = self._read_array("bottom", lines,
shape=(n_pics, bot_size, bot_size, n_chans))
top = self._read_array("top", lines,
shape=(n_pics, top_size, top_size, n_chans))
bot_err = self._read_array("bottom_diff", lines,
shape=(n_pics, bot_size, bot_size, n_chans))
top_err = self._read_array("top_diff", lines,
shape=(n_pics, top_size, top_size, n_chans))
# FORWARD PROP
fwd_pool = pooling.MaxPooling(self.parent, kx=kernel_size,
ky=kernel_size, sliding=(stride, stride))
fwd_pool.input = Array(bottom)
fwd_pool.input.map_write()
fwd_pool.initialize(device=self.device)
fwd_pool.numpy_run()
fwd_pool.output.map_read()
self.info("FWD POOL: Veles vs CAFFE: %.3f%%" %
(100. * (numpy.sum(numpy.abs(fwd_pool.output.mem - top)) /
numpy.sum(numpy.abs(top)))))
# Do MANUAL pooling
out_height, out_width = top_size, top_size
manual_pooling_out = numpy.zeros(shape=(2, out_height, out_width, 2),
dtype=numpy.float64)
for pic in range(2):
for chan in range(2):
for i_out in range(out_height):
for j_out in range(out_width):
min_i = i_out * stride
max_i = i_out * stride + kernel_size - 1
min_j = j_out * stride
max_j = j_out * stride + kernel_size - 1
zone = bottom[pic, min_i: max_i + 1,
min_j: max_j + 1, chan]
manual_pooling_out[pic, i_out, j_out,
chan] = numpy.max((zone))
# BACK PROP
grad_pool = gd_pooling.GDMaxPooling(self.parent, kx=kernel_size,
ky=kernel_size,
sliding=(stride, stride),
device=self.device)
grad_pool.input = Array(bottom)
grad_pool.input.map_write()
grad_pool.err_output = Array(top_err)
grad_pool.err_output.map_write()
grad_pool.input_offset = fwd_pool.input_offset
grad_pool.link_pool_attrs(fwd_pool)
grad_pool.initialize(device=self.device)
grad_pool.numpy_run()
grad_pool.err_input.map_read()
self.info("BACK POOL: Veles vs CAFFE, %.3f%%" % (100 * numpy.sum(
numpy.abs(grad_pool.err_input.mem - bot_err)) /
numpy.sum(numpy.abs(bot_err))))
def test_caffe_grad_normalization(self, data_filename="norm_gd.txt"):
"""
Tests LRU normalization unit: compares it with CAFFE one.
Fwd and back props made.
Args:
data_filename(str): name of file with pooling data
(relative from data dir)
"""
lines = self._read_lines(data_filename)
size = 16
n_chans = 2
n_pics = 2
max_percent_delta = 2. # max difference with CAFFE (percents)
bottom = self._read_array("bottom", lines,
shape=(n_pics, size, size, n_chans))
top = self._read_array("top", lines,
shape=(n_pics, size, size, n_chans))
bot_err = self._read_array("bottom_diff", lines,
shape=(n_pics, size, size, n_chans))
top_err = self._read_array("top_diff", lines,
shape=(n_pics, size, size, n_chans))
fwd_norm = normalization.LRNormalizerForward(self.parent,
k=1, device=self.device)
# FWD PROP
fwd_norm.input = Array(bottom)
fwd_norm.initialize(self.device)
fwd_norm.run()
fwd_norm.output.map_read()
fwd_percent_delta = 100. * (
numpy.sum(numpy.abs(fwd_norm.output.mem - top)) /
numpy.sum(numpy.abs(top)))
self.info("FWD NORM DELTA: %.2f%%" % fwd_percent_delta)
self.assertLess(fwd_percent_delta, max_percent_delta,
"Fwd norm differs by %.2f%%" % fwd_percent_delta)
# BACK PROP
back_norm = normalization.LRNormalizerBackward(self.parent,
k=1, device=self.device)
back_norm.output = Array(top)
back_norm.input = Array(bottom)
back_norm.err_output = Array(top_err)
back_norm.initialize(self.device)
back_norm.run()
back_norm.err_input.map_read()
back_percent_delta = 100. * numpy.sum(
numpy.abs(back_norm.err_output.mem - bot_err)) / \
numpy.sum(numpy.abs(bot_err))
self.info("BACK NORM DELTA: %.2f%%" % back_percent_delta)
self.assertLess(back_percent_delta, max_percent_delta,
"Fwd norm differs by %.2f%%" % (back_percent_delta))
def test_caffe_relu(self, data_filename="conv_relu.txt"):
"""
Tests CONV+RELU unit: compares it with CAFFE one.
Fwd prop only.
Args:
data_filename(str): name of file with pooling data
(relative from data dir)
"""
lines = self._read_lines(data_filename)
in_size = 32
out_size = 32
n_chans = 3
n_kernels = 2
n_pics = 2
kernel_size = 5
padding_size = 2
max_percent_delta = 2.0
conv_bottom = self._read_array(
"conv_bottom", lines, shape=(n_pics, in_size, in_size, n_chans))
conv_top = self._read_array(
"conv_top", lines, shape=(n_pics, out_size, out_size, n_kernels))
relu_top_flat = self._read_array(
"relu_top_flat", lines, shape=(1, 1, conv_top.size, 1)).ravel()
relu_top = numpy.ndarray(
shape=(n_pics, out_size, out_size, n_kernels), dtype=numpy.float64)
cur_pos = 0
for pic in range(n_pics):
for kernel in range(n_kernels):
for i in range(out_size):
for j in range(out_size):
relu_top[pic, i, j, kernel] = relu_top_flat[cur_pos]
cur_pos += 1
conv_weights = self._read_array("conv_weights", lines, shape=(
n_kernels, kernel_size, kernel_size, n_chans))
fwd_conv_relu = conv.ConvStrictRELU(
self.parent, kx=kernel_size, ky=kernel_size,
padding=(padding_size, padding_size, padding_size, padding_size),
sliding=(1, 1), n_kernels=n_kernels, device=self.device)
fwd_conv_relu.input = Array(conv_bottom)
fwd_conv_relu.initialize(self.device)
fwd_conv_relu.weights.map_invalidate()
fwd_conv_relu.weights.mem[:] = conv_weights.reshape(2, 75)[:]
fwd_conv_relu.bias.map_invalidate()
fwd_conv_relu.bias.mem[:] = 0
fwd_conv_relu.run()
fwd_conv_relu.output.map_read()
percent_delta = 100. * (numpy.sum(numpy.abs(
fwd_conv_relu.output.mem - relu_top)) /
numpy.sum(numpy.abs(relu_top)))
self.info("CONV_RELU: diff with CAFFE %.3f%%" % percent_delta)
self.assertLess(percent_delta, max_percent_delta,
"Fwd ConvRELU differs by %.2f%%" % percent_delta)
relu_top_manual = numpy.where(numpy.greater(conv_top, 0), conv_top, 0)
manual_delta = 100. * numpy.sum(
numpy.abs(relu_top_manual - relu_top)) /\
(numpy.sum(numpy.abs(relu_top)))
self.info("SciPy CONV_RELU: diff with CAFFE %.3f%%" % manual_delta)
def test_caffe_grad_relu(self, data_filename="conv_relu.txt"):
"""
Tests CONV+RELU unit: compares it with CAFFE one.
Fwd prop only.
Args:
data_filename(str): name of file with pooling data
(relative from data dir)
"""
lines = self._read_lines(data_filename)
in_size = 32
out_size = 32
n_chans = 3
n_kernels = 2
n_pics = 2
kernel_size = 5
padding_size = 2
max_percent_delta = 2.0
conv_bottom = self._read_array(
"conv_bottom", lines, shape=(n_pics, in_size, in_size, n_chans))
conv_top = self._read_array(
"conv_top", lines, shape=(n_pics, out_size, out_size, n_kernels))
relu_top_flat = self._read_array(
"relu_top_flat", lines, shape=(1, 1, conv_top.size, 1)).ravel()
relu_top = numpy.ndarray(shape=(n_pics, out_size, out_size, n_kernels),
dtype=numpy.float64)
cur_pos = 0
for pic in range(n_pics):
for kernel in range(n_kernels):
for i in range(out_size):
for j in range(out_size):
relu_top[pic, i, j, kernel] = relu_top_flat[cur_pos]
cur_pos += 1
conv_weights = self._read_array("conv_weights", lines, shape=(
n_kernels, kernel_size, kernel_size, n_chans))
fwd_conv_relu = conv.ConvStrictRELU(
self.parent, kx=kernel_size, ky=kernel_size,
padding=(padding_size, padding_size, padding_size, padding_size),
sliding=(1, 1), n_kernels=n_kernels, device=self.device)
fwd_conv_relu.input = Array(conv_bottom)
fwd_conv_relu.initialize(self.device)
fwd_conv_relu.weights.map_invalidate()
fwd_conv_relu.weights.mem[:] = conv_weights.reshape(2, 75)[:]
fwd_conv_relu.bias.map_invalidate()
fwd_conv_relu.bias.mem[:] = 0
fwd_conv_relu.run()
fwd_conv_relu.output.map_read()
percent_delta = 100. * (numpy.sum(numpy.abs(
fwd_conv_relu.output.mem - relu_top)) /
numpy.sum(numpy.abs(relu_top)))
self.info("CONV_RELU: diff with CAFFE %.3f%%" % percent_delta)
self.assertLess(percent_delta, max_percent_delta,
"Fwd ConvRELU differs by %.2f%%" % percent_delta)
relu_top_manual = numpy.where(numpy.greater(conv_top, 0), conv_top, 0)
manual_delta = 100. * numpy.sum(numpy.abs(relu_top_manual - relu_top))\
/ numpy.sum(numpy.abs(relu_top))
self.info("SciPy CONV_RELU: diff with CAFFE %.3f%%" % manual_delta)
def test_grad_conv_relu(self, data_filename="conv_relu_grad.txt"):
"""
Tests GDDRELU_CONV unit: compares it with CAFFE one.
Backward prop only
Args:
data_filename(str): name of file with pooling data
(relative from data dir)
"""
lines = self._read_lines(data_filename)
in_size = 32
out_size = 32
n_chans = 3
n_kernels = 2
n_pics = 2
kernel_size = 5
padding = 2
max_percent_delta = 2.0
conv_bot_err = self._read_array("conv_bottom_diff", lines,
shape=(n_pics, in_size, in_size,
n_chans))
conv_bottom = self._read_array(
"conv_bottom", lines, shape=(n_pics, in_size, in_size, n_chans))
conv_weights = self._read_array("conv_weights", lines, shape=(
n_kernels, kernel_size, kernel_size, n_chans))
conv_weight_delta = self._read_array(
"conv_weight_delta", lines,
shape=(n_kernels, kernel_size, kernel_size, n_chans))
relu_top_err = self._read_array("relu_top_diff", lines, shape=(n_pics,
in_size, in_size, n_kernels))
relu_top_flat = self._read_array("relu_top_flat", lines, shape=(
1, 1, relu_top_err.size, 1)).ravel()
relu_top = numpy.ndarray(shape=(n_pics, out_size, out_size, n_kernels),
dtype=numpy.float64)
cur_pos = 0
for pic in range(n_pics):
for kernel in range(n_kernels):
for i in range(out_size):
for j in range(out_size):
relu_top[pic, i, j, kernel] = relu_top_flat[cur_pos]
cur_pos += 1
# Testing back prop
back_conv_relu = gd_conv.GDStrictRELUConv(self.parent,
device=self.device,
learning_rate=1,
weights_decay=0,
batch_size=n_pics)
back_conv_relu.err_output = Array(relu_top_err)
back_conv_relu.input = Array(conv_bottom)
back_conv_relu.weights = Array(conv_weights.reshape(2, 75))
back_conv_relu.bias = Array( | numpy.zeros(shape=n_kernels) | numpy.zeros |
# Copyright (C) 2011 <NAME>
# All rights reserved.
#
# This file is part of phonopy.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
#
# * Neither the name of the phonopy project nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
import numpy as np
import phonopy.structure.spglib as spg
from phonopy.structure.atoms import PhonopyAtoms as Atoms
def get_supercell(unitcell, supercell_matrix, symprec=1e-5):
return Supercell(unitcell, supercell_matrix, symprec=symprec)
def get_primitive(supercell, primitive_frame, symprec=1e-5):
return Primitive(supercell, primitive_frame, symprec=symprec)
def trim_cell(relative_axes, cell, symprec):
"""
relative_axes: relative axes to supercell axes
Trim positions outside relative axes
"""
positions = cell.get_scaled_positions()
numbers = cell.get_atomic_numbers()
masses = cell.get_masses()
magmoms = cell.get_magnetic_moments()
lattice = cell.get_cell()
trimed_lattice = np.dot(relative_axes.T, lattice)
trimed_positions = []
trimed_numbers = []
if masses is None:
trimed_masses = None
else:
trimed_masses = []
if magmoms is None:
trimed_magmoms = None
else:
trimed_magmoms = []
extracted_atoms = []
positions_in_new_lattice = np.dot(positions, np.linalg.inv(relative_axes).T)
positions_in_new_lattice -= np.floor(positions_in_new_lattice)
trimed_positions = np.zeros_like(positions_in_new_lattice)
num_atom = 0
mapping_table = np.arange(len(positions), dtype='intc')
for i, pos in enumerate(positions_in_new_lattice):
is_overlap = False
if num_atom > 0:
diff = trimed_positions[:num_atom] - pos
diff -= np.rint(diff)
# Older numpy doesn't support axis argument.
# distances = np.linalg.norm(np.dot(diff, trimed_lattice), axis=1)
# overlap_indices = np.where(distances < symprec)[0]
distances = np.sqrt(
np.sum(np.dot(diff, trimed_lattice) ** 2, axis=1))
overlap_indices = np.where(distances < symprec)[0]
if len(overlap_indices) > 0:
assert len(overlap_indices) == 1
is_overlap = True
mapping_table[i] = extracted_atoms[overlap_indices[0]]
if not is_overlap:
trimed_positions[num_atom] = pos
num_atom += 1
trimed_numbers.append(numbers[i])
if masses is not None:
trimed_masses.append(masses[i])
if magmoms is not None:
trimed_magmoms.append(magmoms[i])
extracted_atoms.append(i)
trimed_cell = Atoms(numbers=trimed_numbers,
masses=trimed_masses,
magmoms=trimed_magmoms,
scaled_positions=trimed_positions[:num_atom],
cell=trimed_lattice,
pbc=True)
return trimed_cell, extracted_atoms, mapping_table
def print_cell(cell, mapping=None, stars=None):
symbols = cell.get_chemical_symbols()
masses = cell.get_masses()
magmoms = cell.get_magnetic_moments()
lattice = cell.get_cell()
print("Lattice vectors:")
print(" a %20.15f %20.15f %20.15f" % tuple(lattice[0]))
print(" b %20.15f %20.15f %20.15f" % tuple(lattice[1]))
print(" c %20.15f %20.15f %20.15f" % tuple(lattice[2]))
print("Atomic positions (fractional):")
for i, v in enumerate(cell.get_scaled_positions()):
num = " "
if stars is not None:
if i in stars:
num = "*"
num += "%d" % (i + 1)
line = ("%5s %-2s%18.14f%18.14f%18.14f" %
(num, symbols[i], v[0], v[1], v[2]))
if masses is not None:
line += " %7.3f" % masses[i]
if magmoms is not None:
line += " %5.3f" % magmoms[i]
if mapping is None:
print(line)
else:
print(line + " > %d" % (mapping[i] + 1))
class Supercell(Atoms):
"""Build supercell from supercell matrix
In this function, unit cell is considered
[1,0,0]
[0,1,0]
[0,0,1].
Supercell matrix is given by relative ratio, e.g,
[-1, 1, 1]
[ 1,-1, 1] is for FCC from simple cubic.
[ 1, 1,-1]
In this case multiplicities of surrounding simple lattice are [2,2,2].
First, create supercell with surrounding simple lattice.
Second, trim the surrounding supercell with the target lattice.
"""
def __init__(self, unitcell, supercell_matrix, symprec=1e-5):
self._s2u_map = None
self._u2s_map = None
self._u2u_map = None
self._supercell_matrix = np.array(supercell_matrix, dtype='intc')
self._create_supercell(unitcell, symprec)
def get_supercell_matrix(self):
return self._supercell_matrix
def get_supercell_to_unitcell_map(self):
return self._s2u_map
def get_unitcell_to_supercell_map(self):
return self._u2s_map
def get_unitcell_to_unitcell_map(self):
return self._u2u_map
def _create_supercell(self, unitcell, symprec):
mat = self._supercell_matrix
frame = self._get_surrounding_frame(mat)
sur_cell, u2sur_map = self._get_simple_supercell(frame, unitcell)
# Trim the simple supercell by the supercell matrix
trim_frame = np.array([mat[0] / float(frame[0]),
mat[1] / float(frame[1]),
mat[2] / float(frame[2])])
supercell, sur2s_map, mapping_table = trim_cell(trim_frame,
sur_cell,
symprec)
num_satom = supercell.get_number_of_atoms()
num_uatom = unitcell.get_number_of_atoms()
multi = num_satom // num_uatom
if multi != determinant(self._supercell_matrix):
print("Supercell creation failed.")
print("Probably some atoms are overwrapped. "
"The mapping table is give below.")
print(mapping_table)
Atoms.__init__(self)
else:
Atoms.__init__(self,
numbers=supercell.get_atomic_numbers(),
masses=supercell.get_masses(),
magmoms=supercell.get_magnetic_moments(),
scaled_positions=supercell.get_scaled_positions(),
cell=supercell.get_cell(),
pbc=True)
self._u2s_map = np.arange(num_uatom) * multi
self._u2u_map = dict([(j, i) for i, j in enumerate(self._u2s_map)])
self._s2u_map = np.array(u2sur_map)[sur2s_map] * multi
def _get_surrounding_frame(self, supercell_matrix):
# Build a frame surrounding supercell lattice
# For example,
# [2,0,0]
# [0,2,0] is the frame for FCC from simple cubic.
# [0,0,2]
m = np.array(supercell_matrix)
axes = np.array([[0, 0, 0],
m[:,0],
m[:,1],
m[:,2],
m[:,1] + m[:,2],
m[:,2] + m[:,0],
m[:,0] + m[:,1],
m[:,0] + m[:,1] + m[:,2]])
frame = [max(axes[:,i]) - min(axes[:,i]) for i in (0,1,2)]
return frame
def _get_simple_supercell(self, multi, unitcell):
# Scaled positions within the frame, i.e., create a supercell that
# is made simply to multiply the input cell.
positions = unitcell.get_scaled_positions()
numbers = unitcell.get_atomic_numbers()
masses = unitcell.get_masses()
magmoms = unitcell.get_magnetic_moments()
lattice = unitcell.get_cell()
atom_map = []
positions_multi = []
numbers_multi = []
if masses is None:
masses_multi = None
else:
masses_multi = []
if magmoms is None:
magmoms_multi = None
else:
magmoms_multi = []
for l, pos in enumerate(positions):
for i in range(multi[2]):
for j in range(multi[1]):
for k in range(multi[0]):
positions_multi.append([(pos[0] + k) / multi[0],
(pos[1] + j) / multi[1],
(pos[2] + i) / multi[2]])
numbers_multi.append(numbers[l])
if masses is not None:
masses_multi.append(masses[l])
atom_map.append(l)
if magmoms is not None:
magmoms_multi.append(magmoms[l])
simple_supercell = Atoms(numbers=numbers_multi,
masses=masses_multi,
magmoms=magmoms_multi,
scaled_positions=positions_multi,
cell=np.dot( | np.diag(multi) | numpy.diag |
# Authors: <NAME> <<EMAIL>>
# <NAME> <<EMAIL>>
#
# License: BSD (3-clause)
import math
import numpy as np
from scipy import linalg
from scipy.fftpack import fft, ifft
import six
def _framing(a, L):
shape = a.shape[:-1] + (a.shape[-1] - L + 1, L)
strides = a.strides + (a.strides[-1],)
return np.lib.stride_tricks.as_strided(a, shape=shape,
strides=strides)[::L // 2].T.copy()
def mdct_waveform(scale, freq_bin):
L = float(scale)
K = L / 2.0
fact = math.sqrt(2.0 / K)
const_fact = (np.pi / K) * (float(freq_bin) + 0.5)
const_offset = (L + 1.0) / 2.0
f = np.pi / L
i = np.arange(scale, dtype=np.float)
wf = (fact * np.sin(f * (i + 0.5)) *
np.cos(const_fact * ((i - K / 2.0) + const_offset)))
return wf / linalg.norm(wf)
def mdct(x, L):
"""Modified Discrete Cosine Transform (MDCT)
Returns the Modified Discrete Cosine Transform with fixed
window size L of the signal x.
The window is based on a sine window.
Parameters
----------
x : ndarray, shape (N,)
The signal
L : int
The window length
Returns
-------
y : ndarray, shape (L/2, 2 * N / L)
The MDCT coefficients
See also
--------
imdct
"""
x = np.asarray(x, dtype=np.float)
N = x.size
# Number of frequency channels
K = L // 2
# Test length
if N % K != 0:
raise RuntimeError('Input length must be a multiple of the half of '
'the window size')
# Pad edges with zeros
xx = np.zeros(L // 4 + N + L // 4)
xx[L // 4:-L // 4] = x
x = xx
del xx
# Number of frames
P = N // K
if P < 2:
raise ValueError('Signal too short')
# Framing
x = _framing(x, L)
# Windowing
aL = np.arange(L, dtype=np.float)
w_long = np.sin((np.pi / L) * (aL + 0.5))
w_edge_L = w_long.copy()
w_edge_L[:L // 4] = 0.
w_edge_L[L // 4:L // 2] = 1.
w_edge_R = w_long.copy()
w_edge_R[L // 2:L // 2 + L // 4] = 1.
w_edge_R[L // 2 + L // 4:] = 0.
x[:, 0] *= w_edge_L
x[:, 1:-1] *= w_long[:, None]
x[:, -1] *= w_edge_R
# Pre-twiddle
x = x.astype(np.complex)
x *= np.exp((-1j * np.pi / L) * aL)[:, None]
# FFT
y = fft(x, axis=0)
# Post-twiddle
y = y[:L // 2, :]
y *= np.exp((-1j * np.pi * (L // 2 + 1.) / L)
* (0.5 + aL[:L // 2]))[:, None]
# Real part and scaling
y = math.sqrt(2. / K) * np.real(y)
return y
def imdct(y, L):
"""Inverse Modified Discrete Cosine Transform (MDCT)
Returns the Inverse Modified Discrete Cosine Transform
with fixed window size L of the vector of coefficients y.
The window is based on a sine window.
Parameters
----------
y : ndarray, shape (L/2, 2 * N / L)
The MDCT coefficients
L : int
The window length
Returns
-------
x : ndarray, shape (N,)
The reconstructed signal
See also
--------
mdct
"""
# Signal length
N = y.size
# Number of frequency channels
K = L // 2
# Test length
if N % K != 0:
raise ValueError('Input length must be a multiple of the half of '
'the window size')
# Number of frames
P = N // K
if P < 2:
raise ValueError('Signal too short')
# Reshape
temp = y
y = np.zeros((L, P), dtype=np.float)
y[:K, :] = temp
del temp
# Pre-twiddle
aL = np.arange(L, dtype=np.float)
y = y * np.exp((1j * np.pi * (L / 2. + 1.) / L) * aL)[:, None]
# IFFT
x = ifft(y, axis=0)
# Post-twiddle
x *= np.exp((1j * np.pi / L) * (aL + (L / 2. + 1.) / 2.))[:, None]
# Windowing
w_long = np.sin((np.pi / L) * (aL + 0.5))
w_edge_L = w_long.copy()
w_edge_L[:L // 4] = 0.
w_edge_L[L // 4:L // 2] = 1.
w_edge_R = w_long.copy()
w_edge_R[L // 2:L // 2 + L // 4] = 1.
w_edge_R[L // 2 + L // 4:L] = 0.
x[:, 0] *= w_edge_L
x[:, 1:-1] *= w_long[:, None]
x[:, -1] *= w_edge_R
# Real part and scaling
x = math.sqrt(2. / K) * L * np.real(x)
# Overlap and add
def overlap_add(y, x):
z = np.concatenate((y, | np.zeros((K,)) | numpy.zeros |
import logging
import os
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
import scipy
from scipy import stats
import datetime
import networkx as nx
import matplotlib as mpl
import sys
import tqdm
from matplotlib import animation, rc
from matplotlib.ticker import MaxNLocator
from IPython.display import clear_output, HTML, Image
from neurolib.utils import atlases
import neurolib.utils.paths as paths
import neurolib.utils.functions as func
class Brainplot:
def __init__(self, Cmat, data, nframes=None, dt=0.1, fps=25, labels=False, darkmode=True):
self.sc = Cmat
self.n = self.sc.shape[0]
self.data = data
self.darkmode = darkmode
self.G = nx.Graph()
self.G.add_nodes_from(range(self.n))
coords = {}
atlas = atlases.AutomatedAnatomicalParcellation2()
for i, c in enumerate(atlas.coords()):
coords[i] = [c[0], c[1]]
self.position = coords
self.edge_threshold = 0.01
self.fps = fps
self.dt = dt
nframes = nframes or int((data.shape[1] * self.dt / 1000) * self.fps) # 20 fps default
logging.info(f"Defaulting to {nframes} frames at {self.fps} fp/s")
self.nframes = nframes
self.frame_interval = self.data.shape[1] // self.nframes
self.interval = int(self.frame_interval * self.dt)
self.draw_labels = labels
for t in range(self.n):
# print t
for s in range(t):
# print( n, t, s)
if self.sc[t, s] > self.edge_threshold:
# print( 'edge', t, s, self.sc[t,s])
self.G.add_edge(t, s)
# node color map
self.cmap = plt.get_cmap("plasma") # mpl.cm.cool
# default style
self.imagealpha = 0.5
self.edgecolor = "k"
self.edgealpha = 0.8
self.edgeweight = 1.0
self.nodesize = 50
self.nodealpha = 0.8
self.vmin = 0
self.vmax = 50
self.lw = 0.5
if self.darkmode:
plt.style.use("dark")
# let's choose a cyberpunk style for the dark theme
self.edgecolor = "#37f522"
self.edgeweight = 0.5
self.edgealpha = 0.6
self.nodesize = 40
self.nodealpha = 0.8
self.vmin = 0
self.vmax = 30
self.cmap = plt.get_cmap("cool") # mpl.cm.cool
self.imagealpha = 0.5
self.lw = 1
fname = os.path.join("neurolib", "data", "resources", "clean_brain_white.png")
else:
# plt.style.use("light")
fname = os.path.join("neurolib", "data", "resources", "clean_brain.png")
self.imgTopView = mpl.image.imread(fname)
self.pbar = tqdm.tqdm(total=self.nframes)
def update(self, i, ax, ax_rates=None, node_color=None, node_size=None, node_alpha=None, clear=True):
frame = int(i * self.frame_interval)
node_color = node_color or self.data[:, frame]
node_size = node_size or self.nodesize
node_alpha = node_alpha or self.nodealpha
if clear:
ax.cla()
im = ax.imshow(self.imgTopView, alpha=self.imagealpha, origin="upper", extent=[40, 202, 28, 240])
ns = nx.draw_networkx_nodes(
self.G,
pos=self.position,
node_color=node_color,
cmap=self.cmap,
vmin=self.vmin,
vmax=self.vmax,
node_size=node_size,
alpha=node_alpha,
ax=ax,
edgecolors="k",
)
es = nx.draw_networkx_edges(
self.G, pos=self.position, alpha=self.edgealpha, edge_color=self.edgecolor, ax=ax, width=self.edgeweight
)
labels = {}
for ni in range(self.n):
labels[ni] = str(ni)
if self.draw_labels:
nx.draw_networkx_labels(self.G, self.position, labels, font_size=8)
ax.set_axis_off()
ax.set_xlim(20, 222)
ax.set_ylim(25, 245)
# timeseries
if ax_rates:
ax_rates.cla()
ax_rates.set_xticks([])
ax_rates.set_yticks([])
ax_rates.set_ylabel("Brain activity", fontsize=8)
t = np.linspace(0, frame * self.dt, frame)
ax_rates.plot(t, np.mean(self.data[:, :frame], axis=0).T, lw=self.lw)
t_total = self.data.shape[1] * self.dt
ax_rates.set_xlim(0, t_total)
self.pbar.update(1)
plt.tight_layout()
if clear:
clear_output(wait=True)
def plot_rates(model):
plt.figure(figsize=(4, 1))
plt_until = 10 * 1000
plt.plot(model.t[model.t < plt_until], model.output[:, model.t < plt_until].T, lw=0.5)
def plot_brain(
model, ds, color=None, size=None, title=None, cbar=True, cmap="RdBu", clim=None, cbarticks=None, cbarticklabels=None
):
"""Dump and easy wrapper around the brain plotting function.
:param color: colors of nodes, defaults to None
:type color: numpy.ndarray, optional
:param size: size of the nodes, defaults to None
:type size: numpy.ndarray, optional
:raises ValueError: Raises error if node size is too big.
"""
s = Brainplot(ds.Cmat, model.output, fps=10, darkmode=False)
s.cmap = plt.get_cmap(cmap)
dpi = 300
fig = plt.figure(dpi=dpi)
ax = plt.gca()
if title:
ax.set_title(title, fontsize=26)
if clim is None:
s.vmin, s.vmax = np.min(color), np.max(color)
else:
s.vmin, s.vmax = clim[0], clim[1]
if size is not None:
node_size = size
else:
# some weird scaling of the color to a size
def norm(what):
what = what.copy()
what -= np.min(what)
what /= np.max(what)
return what
node_size = list(np.exp((norm(color) + 2) * 2))
if isinstance(color, np.ndarray):
color = list(color)
if isinstance(node_size, np.ndarray):
node_size = list(node_size)
if np.max(node_size) > 2000:
raise ValueError(f"node_size too big: {np.max(node_size)}")
s.update(0, ax, node_color=color, node_size=node_size, clear=False)
if cbar:
cbaxes = fig.add_axes([0.68, 0.1, 0.015, 0.7])
sm = plt.cm.ScalarMappable(cmap=s.cmap, norm=plt.Normalize(vmin=s.vmin, vmax=s.vmax))
cbar = plt.colorbar(sm, cbaxes, ticks=cbarticks)
cbar.ax.tick_params(labelsize=16)
if cbarticklabels:
cbar.ax.set_yticklabels(cbarticklabels)
# other plotting
def plot_average_timeseries(model, xticks=False, kwargs={}, xlim=None, figsize=(8, 1)):
# print("{} Peaks found ({} p/s)".format(len(peaks), len(peaks)/(model.params['duration']/1000)))
plt.figure(figsize=figsize, dpi=300)
# cut rates if xlim is given
if xlim:
rates = model.output[:, (model.t / 1000 > xlim[0]) & (model.t / 1000 < xlim[1])]
t = model.t[(model.t / 1000 > xlim[0]) & (model.t / 1000 < xlim[1])]
print(rates.shape)
else:
rates = model.output
t = model.t
plt.plot(t / 1000, np.mean(rates, axis=0), **kwargs)
# plt.plot(model.t/1000, signal, lw=2, label = 'smoothed')
plt.autoscale(enable=True, axis="x", tight=True)
# for p in peaks:
# plt.vlines(p*params['dt']*10, 0, 0.008, color='b', lw=2, alpha=0.6)
# plt.xlim(0, 10000)
# plt.plot(model.t/1000, states*10, lw=2, c='C1', alpha=0.4, label='detected state')
# plt.xlabel("Time [s]")
if not xticks:
plt.xticks([])
if xlim:
plt.xlim(*xlim)
plt.ylabel("Rate [Hz]")
# plt.legend(loc=1, fontsize=8)
# import matplotlib as mpl
# mpl.rcParams['axes.spines.left'] = False
# mpl.rcParams['axes.spines.right'] = False
# mpl.rcParams['axes.spines.top'] = False
# mpl.rcParams['axes.spines.bottom'] = False
plt.gca().spines["right"].set_visible(False)
plt.gca().spines["top"].set_visible(False)
plt.gca().spines["left"].set_visible(False)
plt.gca().spines["bottom"].set_visible(False)
plt.tight_layout()
set_axis_size(*figsize)
def detectSWStates(output, threshold=1):
states = np.zeros(output.shape)
# super_threshold_indices = rates > threshold
# works with 1D thresholds, per node
super_threshold_indices = np.greater(output.T, threshold).T
states[super_threshold_indices] = 1
return states
def filter_long_states(model, states):
states = states.copy()
LENGTH_THRESHOLD = int(50 / model.params["dt"]) # ms
for s in states:
lengths = get_state_lengths(s)
current_idx = 0
last_long_state = lengths[0][0] # first state
for state, length in lengths:
if length >= LENGTH_THRESHOLD:
last_long_state = state
else:
s[current_idx : current_idx + length] = last_long_state
current_idx += length
return states
def detectSWs(model, up_thresh=0.01, detectSWStates_kw=None, filter_long=True):
threshold_per_node = up_thresh * np.max(model.output, axis=1) # as per Nghiem et al., 2020, Renart et al., 2010
states = np.zeros(model.output.shape)
if detectSWStates_kw:
logging.warning(f"Warning: detectSWStates_kw is not implemented anymore, using up_thresh = {up_thresh}")
states = detectSWStates(model.output, threshold=threshold_per_node)
# for i, o in enumerate(model.output):
# smoothed = o # scipy.ndimage.gaussian_filter(o, sigma=500)
# s = detectSWStates(model.t, smoothed, **detectSWStates_kw)
# states[i, :] = s
if filter_long:
states = filter_long_states(model, states)
return states
def get_involvement(states, down=True):
"""Returns involvement in up- and down-states.
:param states: state array (NxT)
:type states: np.ndarray
:return: Involvement time series (1xT)
:rtype: np.ndarray
"""
up_involvement = np.sum(states, axis=0) / states.shape[0]
if down:
return 1 - up_involvement
else:
return up_involvement
def plot_states_timeseries(model, states, title=None, labels=True, cmap="plasma"):
figsize = (8, 2)
plt.figure(figsize=figsize)
plt.imshow(
states,
extent=[0, states.shape[1] * model.params.dt / 1000, 0, states.shape[0]],
aspect="auto",
cmap=plt.cm.get_cmap(cmap, 2),
)
if labels:
plt.xlabel("Time [s]")
plt.ylabel("Node")
else:
plt.xticks([])
plt.yticks([])
if title:
plt.title(title)
plt.autoscale(enable=True, axis="x", tight=True)
if labels:
cbar = plt.colorbar(pad=0.02)
cbar.set_ticks([0.25, 0.75])
cbar.ax.set_yticklabels(["Down", "Up"], rotation=90, va="center")
cbar.ax.tick_params(width=0, labelsize=14)
plt.tight_layout()
set_axis_size(*figsize)
def plot_involvement_timeseries(model, involvement):
fig, axs = plt.subplots(1, 2, figsize=(10, 4), gridspec_kw={"width_ratios": [4, 1]})
axs[0].set_title("Involvement of brain areas in SO events")
axs[0].plot(model.t / 1000, involvement * 100, c="C0")
axs[0].set_ylabel("Involvement [%]")
axs[0].set_xlabel("Time [s]")
axs[0].set_ylim([0, 100])
axs[0].set_aspect("auto")
axs[1].hist(involvement * 100, bins=10, orientation="horizontal", density=True, rwidth=0.8, edgecolor="k")
axs[1].set_yticks([])
axs[1].set_xlabel("KDE")
axs[1].set_ylim([0, 100])
plt.tight_layout()
def plot_degree_duration_scatterplot(model, states, ds, lingres=False, color_down="C0", color_up="C1"):
figsize = (2, 2)
plt.figure(figsize=figsize)
area_downtimes = np.sum(states == 0, axis=1) / model.output.shape[1] * 100
area_uptimes = np.sum(states == 1, axis=1) / model.output.shape[1] * 100
fig, ax = plt.subplots(1, 1, figsize=(3, 3))
degrees = [(np.sum(ds.Cmat, axis=1))[i] / np.max(np.sum(ds.Cmat, axis=1)) for i in range(ds.Cmat.shape[0])]
ax.scatter(
degrees,
area_uptimes,
s=14,
c=color_up,
edgecolor="black",
linewidth=0.5,
label="up-state",
)
ax.scatter(
degrees,
area_downtimes,
s=14,
c=color_down,
edgecolor="black",
linewidth=0.5,
label="down-state",
)
if lingres:
plot_linregress(degrees, area_downtimes, kwargs={"c": color_down, "zorder": -2})
if lingres:
plot_linregress(degrees, area_uptimes, kwargs={"c": color_up, "zorder": -2})
for i in range(ds.Cmat.shape[0]):
degree = (np.sum(ds.Cmat, axis=1))[i] / np.max(np.sum(ds.Cmat, axis=1))
plt.legend(fontsize=12, frameon=False, markerscale=1.8, handletextpad=-0.5)
ax.set_xlabel("Node degree")
ax.set_ylabel("Time spent [%]")
plt.tight_layout()
set_axis_size(*figsize)
def plot_transition_phases(node_mean_phases_down, node_mean_phases_up, atlas):
def hide_axis(ax):
ax.spines["top"].set_visible(False)
ax.spines["right"].set_visible(False)
ax.spines["bottom"].set_visible(False)
ax.spines["left"].set_visible(False)
names = []
phases_down = []
phases_up = []
ipsilateral_mean_down_phase = [
(i + k) / 2 for i, k in zip(node_mean_phases_down[0::2], node_mean_phases_down[1::2])
]
ipsilateral_mean_up_phase = [(i + k) / 2 for i, k in zip(node_mean_phases_up[0::2], node_mean_phases_up[1::2])]
# ipsilateral_names = [i[:-2] for i, k in zip(atlas.names()[0::2], atlas.names()[1::2])]
ipsilateral_names = [
f"{i[:-2]} ({nr*2}, {nr*2+1})" for nr, (i, k) in enumerate(zip(atlas.names()[0::2], atlas.names()[1::2]))
]
# clean up names
for i in range(len(ipsilateral_names)):
ipsilateral_names[i] = ipsilateral_names[i].replace("_", " ")
for i, ipsi_region in enumerate(np.argsort(ipsilateral_mean_down_phase)):
# print(i, region, node_mean_phases_down[region], atlas.names()[region], atlas.coords()[region][2])
# y_coord = (i%80)/30
names.append(ipsilateral_names[ipsi_region])
phases_down.append(ipsilateral_mean_down_phase[ipsi_region])
phases_up.append(ipsilateral_mean_up_phase[ipsi_region])
names = [n.replace("_", " ") for n in names]
fig, ax = plt.subplots(1, 1, figsize=(6, 3))
# left=-np.asarray(phases[::-1]),
ax.bar(names, phases_up, lw=1, ls="--", color="C0", label="up-transition")
ax.bar(names, phases_down, lw=1, ls="--", color="C1", label="down-transition")
# ax.tick_params(axis="both", which="major", labelsize=8)
# ax.yaxis.set_tick_params(width=1)
ax.autoscale(enable=True, axis="x", tight=True)
ax.legend(fontsize=8, loc=1, bbox_to_anchor=(0.98, 1.0))
ax.set_ylabel("Phase of transition", fontsize=12)
# ax.text(0.2, 80, "Up-state", fontsize=10)
# ax.text(-0.2, 80, "Down-state", fontsize=10, ha="right")
# ax.set_title("Mean transition phase")
hide_axis(ax)
plt.grid(alpha=0.5, lw=0.5)
ax.tick_params(axis="y", labelsize=10)
ax.tick_params(axis="x", which="major", labelsize=7, rotation=90)
plt.tight_layout(pad=0)
def plot_transition_phases_against_eachother(node_mean_phases_down, node_mean_phases_up):
figsize = (2, 2)
figsize = np.multiply(figsize, 0.75)
plt.figure(figsize=figsize)
plt.scatter(
node_mean_phases_down,
node_mean_phases_up,
s=8,
edgecolor="black",
linewidth=0.5,
c="lightgray",
)
plot_linregress(node_mean_phases_down, node_mean_phases_up, kwargs={"c": "k", "alpha": 0.5, "zorder": -2})
plt.xlabel("Mean down-phase")
plt.ylabel("Up-phase")
plt.tight_layout(pad=0)
set_axis_size(*figsize)
def plot_state_brain_areas(model, states, atlas, ds, color_down="C0", color_up="C1"):
fig, axs = plt.subplots(1, 1, figsize=(6, 3))
# axs.set_title("Time spent in up- and down-state per brain area", fontsize=12)
area_downtimes = np.sum(states == 0, axis=1) / model.output.shape[1] * 100
area_uptimes = np.sum(states == 1, axis=1) / model.output.shape[1] * 100
ipsilateral_downtimes = [(i + k) / 2 for i, k in zip(area_downtimes[0::2], area_downtimes[1::2])]
ipsilateral_uptimes = [(i + k) / 2 for i, k in zip(area_uptimes[0::2], area_uptimes[1::2])]
ipsilateral_uptimes_diff = [(i - k) for i, k in zip(area_uptimes[0::2], area_uptimes[1::2])]
ipsilateral_names = [
f"{i[:-2]} ({nr*2}, {nr*2+1})" for nr, (i, k) in enumerate(zip(atlas.names()[0::2], atlas.names()[1::2]))
]
# clean up names
for i in range(len(ipsilateral_names)):
ipsilateral_names[i] = ipsilateral_names[i].replace("_", " ")
axs.bar(
ipsilateral_names,
ipsilateral_uptimes,
bottom=ipsilateral_downtimes,
edgecolor="k",
color="C0",
linewidth="0.2",
zorder=-10,
label="up-state",
)
axs.bar(ipsilateral_names, ipsilateral_downtimes, edgecolor="k", color="C1", linewidth="0.2", label="down-state")
axs.legend(fontsize=8, loc=1, bbox_to_anchor=(0.98, 0.9))
axs.autoscale(enable=True, axis="x", tight=True)
axs.spines["right"].set_visible(False)
axs.spines["top"].set_visible(False)
axs.spines["left"].set_visible(False)
axs.spines["bottom"].set_visible(False)
axs.tick_params(axis="x", which="major", labelsize=7, rotation=90)
# axs[0].set_xlabel("Brain area")
axs.set_ylabel("Time spent [%]", fontsize=12)
axs.set_yticks([0, 25, 50, 75, 100])
axs.tick_params(axis="y", labelsize=10)
# for i in range(ds.Cmat.shape[0]):
# degree = (np.sum(ds.Cmat, axis=1))[i] / np.max(np.sum(ds.Cmat, axis=1))
# axs[1].scatter(degree, area_downtimes[i], s=5, c="C1", edgecolor="black", linewidth="0.2")
# axs[1].scatter(degree, area_uptimes[i], s=5, c="C0", edgecolor="black", linewidth="0.2")
# axs[1].set_xlabel("Node degree")
# axs[1].set_xticks([0, 1, 2, 3])
# axs[1].set_yticklabels([])
plt.tight_layout(pad=0)
return area_downtimes, area_uptimes
def plot_involvement_durations(model, states, involvement, nbins=6, legend=False):
invs = {0: [], 1: []}
lens = {0: [], 1: []}
for s in states[:]:
lengths = get_state_lengths(s)
current_idx = 0
for state, length in lengths:
state = int(state)
# compuite average involvement during this state
mean_involvement = np.mean(involvement[current_idx : current_idx + length])
lens[state].append(length * model.params.dt) # convert to seconds
invs[state].append(mean_involvement)
current_idx += length
from scipy.stats import binned_statistic
figsize = (3, 2)
figsize = np.multiply(figsize, 0.75)
plt.figure(figsize=figsize)
up_bin_means, bin_edges, _ = binned_statistic(invs[1], lens[1], bins=nbins, range=(0, 1))
plt.bar(bin_edges[:-1], up_bin_means[::-1], width=0.04, edgecolor="k", color="C0", label="up-state")
down_bin_means, bin_edges, _ = binned_statistic(invs[0], lens[0], bins=nbins, range=(0, 1))
plt.bar(bin_edges[:-1] + 0.05, down_bin_means, width=0.04, edgecolor="k", color="C1", label="down-state")
if legend:
plt.legend(fontsize=8)
plt.xticks([0, 0.5, 1], [0, 50, 100])
axs = plt.gca()
axs.spines["right"].set_visible(False)
axs.spines["top"].set_visible(False)
axs.spines["left"].set_visible(False)
plt.gca().tick_params(axis="both", direction="out", which="major", bottom=True, left=True)
plt.xlabel("Involvement [%]")
plt.ylabel("Duration [ms]")
plt.tight_layout()
set_axis_size(*figsize)
def get_state_durations_flat(model, states):
durations = get_state_lengths(states)
ups, downs = get_updown_lengths(durations)
dt_to_s = model.params.dt / 1000 # return seconds
flat_ups = [u * dt_to_s for up in ups for u in up]
flat_downs = [d * dt_to_s for down in downs for d in down]
return flat_ups, flat_downs
def plot_state_durations(model, states, legend=True, alpha=1.0):
durations = get_state_lengths(states)
ups, downs = get_updown_lengths(durations)
dt_to_s = model.params.dt / 1000
flat_ups = [u * dt_to_s for up in ups for u in up]
flat_downs = [d * dt_to_s for down in downs for d in down]
# figsize = (3, 2.0)
figsize = (2, 1.7)
# figsize = np.multiply(figsize, 0.75)
plt.figure(figsize=figsize)
plt.hist(flat_ups, color="C0", label="up", edgecolor="k", linewidth=0.75)
plt.hist(flat_downs, color="C1", label="down", edgecolor="k", linewidth=0.75, alpha=alpha)
if legend:
plt.legend(fontsize=12, frameon=False)
plt.gca().set_yscale("log")
plt.gca().xaxis.set_major_locator(plt.MaxNLocator(4))
plt.ylabel("Log-probability")
plt.yticks([])
plt.xlabel("Duration [s]")
plt.gca().tick_params(axis="x", direction="out", which="major", bottom=True, left=True)
ax = plt.gca()
ax.spines["right"].set_visible(False)
ax.spines["top"].set_visible(False)
ax.spines["left"].set_visible(False)
# ax.spines["bottom"].set_visible(False)
plt.tight_layout()
set_axis_size(*figsize)
def plot_involvement_distribution(model, involvement, remove_xticks=True, color_localglobal=False):
# figsize = (3, 2)
figsize = (2, 1.7)
# figsize = np.multiply(figsize, 0.75)
plt.figure(figsize=figsize)
N, bins, patches = plt.hist(involvement * 100, bins=12, density=True, rwidth=0.8, edgecolor="k", color="C1")
if color_localglobal:
for i in range(0, len(patches) // 2):
patches[i].set_facecolor("C0")
for i in range(len(patches) // 2, len(patches)):
patches[i].set_facecolor("C1")
plt.xticks([0, 50, 100])
if remove_xticks:
plt.yticks([])
else:
y_vals = plt.gca().get_yticks()
plt.gca().set_yticklabels(["{:3.0f}".format(x * 100) for x in y_vals])
plt.ylabel("Probability")
plt.xlabel("Involvement [%]")
plt.gca().tick_params(axis="x", direction="out", which="major", bottom=True, left=True)
plt.xlim([0, 100])
ax = plt.gca()
ax.spines["right"].set_visible(False)
ax.spines["top"].set_visible(False)
ax.spines["left"].set_visible(False)
# ax.spines["bottom"].set_visible(False)
max_y = plt.gca().get_ylim()[1] * 1.1
plt.ylim(0, max_y * 1.1)
# plt.vlines([50], 0, max_y, linestyles="--", colors="#363638", alpha=0.9)
plt.text(25, max_y * 0.95, "local", fontsize=14, color="C0", ha="center")
plt.text(75, max_y * 0.95, "global", fontsize=14, color="C1", ha="center")
plt.tight_layout()
set_axis_size(*figsize)
def plot_involvement_mean_amplitude(model, involvement, skip=300, lingress=True):
figsize = (3, 2)
figsize = np.multiply(figsize, 0.75)
plt.figure(figsize=figsize)
rates = np.mean(model.output, axis=0)[::skip]
plt.scatter(
involvement[::skip] * 100,
rates,
# scipy.stats.zscore(np.mean(model.output, axis=0)[::skip]),
s=10,
edgecolor="w",
linewidth=0.2,
c="C1",
alpha=0.7,
)
# plt.gca().axhline(0, linestyle="--", lw=1, color="#ABB2BF", zorder=-1)
plt.xlim(0, 100)
plt.xticks([0, 50, 100])
plt.xlabel("Involvement [%]")
plt.ylabel("Rate [Hz]")
if lingress:
slope, intercept, r_value, p_value, std_err = plot_linregress(
involvement[::skip] * 100, rates, kwargs={"c": "k", "alpha": 0.75}
)
plt.text(50, np.max(rates) * 0.75, f"$R^2={r_value**2:0.2f}$")
axs = plt.gca()
axs.spines["right"].set_visible(False)
axs.spines["top"].set_visible(False)
axs.spines["left"].set_visible(False)
axs.spines["bottom"].set_visible(False)
plt.gca().tick_params(axis="both", direction="out", which="major", bottom=True, left=True)
plt.tight_layout()
set_axis_size(*figsize)
def get_state_lengths(xs):
"""
Get's the length of successive elements in a list.
Useful for computing inter-spike-intervals (ISI) or the length
of states.
Example: get_state_lengths([0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 0])
Returns: [(0, 4), (1, 4), (0, 2), (1, 1), (0, 1)]
:param xs: Input list with successive states
:type xs: list
:return: List of (state, length) tuples
:rtype: list
"""
import itertools
if np.array(xs).ndim == 1:
durations = [(x, len(list(y))) for x, y in itertools.groupby(xs)]
elif np.array(xs).ndim > 1:
durations = [get_state_lengths(xss) for xss in xs]
return durations
def get_updown_lengths(durations):
"""Returns the length of all up- and down-states for each node"""
ups = []
downs = []
for i, l in enumerate(durations):
ups.append([u[1] for u in l if u[0] == 1.0])
downs.append([u[1] for u in l if u[0] == 0.0])
return ups, downs
def plot_linregress(x, y, plot=True, kwargs={}):
slope, intercept, r_value, p_value, std_err = stats.linregress(x, y)
print(f"slope = {slope}, intercept = {intercept}, r_value = {r_value}, p_value = {p_value}, std_err = {std_err}")
if plot:
plt.plot(x, intercept + x * slope, **kwargs)
return slope, intercept, r_value, p_value, std_err
def plot_down_up_durations(model, durations, ds, plot_regression=False):
import matplotlib.cm as cm
all_ups = []
all_downs = []
all_colors = []
for n, dur in enumerate(durations):
# make sure to start with a down-state
skip = 0 if dur[0][0] == 0.0 else 1
down_durations = [d[1] * model.params.dt / 1000 for d in dur[skip::2]]
up_durations = [d[1] * model.params.dt / 1000 for d in dur[skip + 1 :: 2]]
# normalized degree [0, 1]
degree = (np.sum(ds.Cmat, axis=1))[n] / np.max(np.sum(ds.Cmat, axis=1))
for d, u in zip(down_durations, up_durations):
all_ups.append(u)
all_downs.append(d)
all_colors.append(degree)
fig_scale = 1.2
plt.figure(figsize=(3 * fig_scale, 2.5 * fig_scale))
plt.scatter(all_downs, all_ups, s=2, c=all_colors, cmap="plasma", alpha=0.8)
plt.ylabel("Next up-state duration [s]")
plt.xlabel("Down-state duration [s]")
plot_linregress(all_downs, all_ups, plot=plot_regression)
cbar = plt.colorbar()
cbar.set_label(label="Node degree", size=10)
cbar.ax.tick_params(labelsize=10)
plt.show()
def get_transition_phases(states, phase):
transitions = np.diff(states)
node_mean_phases_down = []
node_mean_phases_up = []
for ni, trs in enumerate(transitions):
down_phases = []
up_phases = []
for i, t in enumerate(trs):
if t == -1:
down_phases.append(float(phase[i]))
if t == 1:
up_phases.append(float(phase[i]))
mean_down_phase = scipy.stats.circmean(down_phases, high=np.pi, low=-np.pi, nan_policy="raise")
mean_up_phase = scipy.stats.circmean(up_phases, high=np.pi, low=-np.pi, nan_policy="raise")
print(f"Node {ni}: mean_down_phase = {mean_down_phase}, mean_up_phase = {mean_up_phase}")
node_mean_phases_down.append(mean_down_phase)
node_mean_phases_up.append(mean_up_phase)
return node_mean_phases_down, node_mean_phases_up
def phase_transition_coordinate(node_mean_phases_down, node_mean_phases_up, atlas):
coords = atlas.coords()
minmax_coords = [int(np.min([c[1] for c in coords])), int(np.max([c[1] for c in coords]))]
figsize = (2, 2)
plt.figure(figsize=figsize)
# ATTENTION!!!! MULTIPLYING COORDINATES WITH -1 SO THE PLOT GOES ANTERIOR TO POSTERIOR
y_coords = np.array([c[1] for c in coords]) * -1
plt.scatter(y_coords, node_mean_phases_down, c="C1", s=14, edgecolor="k", linewidth=0.5, label="down")
plt.scatter(y_coords, node_mean_phases_up, c="C0", s=14, edgecolor="k", linewidth=0.5, label="up")
# plt.legend(fontsize=8)
down_slope, down_intercept, down_r_value, down_p_value, down_std_err = stats.linregress(
y_coords, node_mean_phases_down
)
print(f"Down transitions: slope: {down_slope} r: {down_r_value}, p: {down_p_value}")
plt.plot(y_coords, (lambda c: down_intercept + down_slope * c)(y_coords), c="C1", label="x", zorder=-5)
up_slope, up_intercept, up_r_value, up_p_value, up_std_err = stats.linregress(y_coords, node_mean_phases_up)
print(f"Up transitions: slope: {up_slope} r: {up_r_value}, p: {up_p_value}")
plt.plot(y_coords, (lambda c: up_intercept + up_slope * c)(y_coords), c="C0", label="x", zorder=-5)
plt.xlabel("Coordinate")
plt.xticks([np.min(y_coords) + 30, np.max(y_coords) - 30], [f"Anterior", f"Posterior"])
plt.ylabel("Transition phase $\phi$")
plt.tight_layout()
set_axis_size(*figsize)
return (
down_slope,
down_intercept,
down_r_value,
down_p_value,
down_std_err,
up_slope,
up_intercept,
up_r_value,
up_p_value,
up_std_err,
)
def kuramoto(events):
import tqdm
# fill in event at the end of the timeseries
events[:, -1] = True
phases = []
logging.info("Determining phases ...")
for n, ev in tqdm.tqdm(enumerate(events), total=len(events)):
maximalist = np.where(ev)[0]
phases.append([])
last_event = 0
for m in maximalist:
for t in range(last_event, m):
phi = 2 * np.pi * float(t - last_event) / float(m - last_event)
phases[n].append(phi)
last_event = m
phases[n].append(2 * np.pi)
logging.info("Computing Kuramoto order parameter ...")
# determine kuramoto order paramter
kuramoto = []
nTraces = events.shape[0]
for t in tqdm.tqdm(range(events.shape[1]), total=events.shape[1]):
R = 1j * 0
for n in range(nTraces):
R += np.exp(1j * phases[n][t])
R /= nTraces
kuramoto.append(np.absolute(R))
return kuramoto
def plot_phases_and_involvement(model, involvement, phases, states):
fig, axs = plt.subplots(2, 1, figsize=(4, 2), sharex=True)
up_transitions = np.diff(states) > 0
down_transitions = np.diff(states) < 0
for i, ups in enumerate(up_transitions):
axs[0].vlines(np.where(ups)[0] * model.params.dt / 1000, 0, 3, lw=0.2, alpha=1, color="C0")
for i, downs in enumerate(down_transitions):
axs[0].vlines(np.where(downs)[0] * model.params.dt / 1000, -3, 0, lw=0.2, alpha=1, color="C1")
# annotate vlines
axs[0].text(7.7, 7.0, "up-transitions", fontsize=8)
axs[0].vlines(7.6, 6.8, 9.0, lw=1, color="C0")
axs[0].text(7.7, 4.4, "down-transitions", fontsize=8)
axs[0].vlines(7.6, 4.0, 6.2, lw=1, color="C1")
# axs[0].fill_between(model.t/1000, phases, 0, where=phases<0, zorder=-2, color='C0', alpha=0.8, label='$\phi < 0$')
# axs[0].fill_between(model.t/1000, phases, 0, where=phases>0, zorder=-2, color='C1', alpha=0.8, label='$\phi > 0$')
axs[0].plot(model.t / 1000, phases, zorder=2, lw=1, label="Global phase $\phi$", c="fuchsia")
axs[0].set_yticks([])
axs[0].legend(fontsize=8, frameon=False, loc="upper center", bbox_to_anchor=(0.5, 1.1), ncol=1)
axs[1].plot(model.t / 1000, np.mean(model.output, axis=0), c="k", alpha=1, lw=1, label="Mean rate")
axs[1].plot(model.t / 1000, involvement * 30, lw=1, c="C3", label="Involvement")
axs[1].set_xlim(0, 10)
axs[1].set_yticks([])
axs[1].set_xticks([0, 5, 10])
axs[1].tick_params(labelsize=8)
axs[1].set_xlabel("Time [s]", fontsize=8)
axs[1].legend(fontsize=8, frameon=False, loc="upper center", bbox_to_anchor=(0.5, 1.25), ncol=2)
for ax in axs:
ax.spines["right"].set_visible(False)
ax.spines["top"].set_visible(False)
ax.spines["left"].set_visible(False)
ax.spines["bottom"].set_visible(False)
plt.tight_layout()
plt.subplots_adjust(wspace=0, hspace=0.2)
# used for RESULT-dynamical-regimes-EXP-5.ipynb
def plot_ts(
model,
plot_nodes=[0],
plot_alpha=1,
plot_mean_background=False,
mean_alpha=0.3,
shift_mean=False,
adaptation=False,
stimulus=False,
stimulus_scale=1.0,
log_power=False,
log_freq=False,
norm_power=True,
title_add="",
lw=1,
figsize=(4, 1.5),
labels=False,
crop_zero=None,
xlim=None,
savename=None,
fontsize=None,
n_ticks=2,
tick_width=1,
tick_length=3,
legend=False,
yticks=None,
):
_, axs = plt.subplots(1, 1, dpi=600, figsize=figsize)
title = " ".join([f"{p} = {model.params[p]}" for p in ["mue_ext_mean", "mui_ext_mean", "b", "sigma_ou"]])
title += " " + title_add
plot_col = "k"
if str(plot_nodes) == "all":
plot_output = model.output
plot_adaptation = model.outputs.IA
plot_col = None
elif str(plot_nodes) == "mean":
plot_output = np.mean(model.output, axis=0)
plot_adaptation = np.mean(model.outputs.IA, axis=0)
else:
plot_output = model.output[plot_nodes]
plot_adaptation = model.outputs.IA[plot_nodes]
plot_col = None if len(plot_nodes) > 1 else "k"
if plot_mean_background:
mean_signal = np.mean(model.output, axis=0)
# plot_adaptation = model.outputs.IA if str(plot_nodes) == "all" else model.outputs.IA[plot_nodes]
plot_t = model.t / 1000
plot_stimulus = model.params["ext_exc_current"] * stimulus_scale
if xlim:
plot_t = plot_t[xlim[0] : xlim[1]]
if plot_output.ndim == 2:
plot_output = plot_output[:, xlim[0] : xlim[1]]
if adaptation:
plot_adaptation = plot_adaptation[:, xlim[0] : xlim[1]]
else:
plot_output = plot_output[xlim[0] : xlim[1]]
if adaptation:
plot_adaptation = plot_adaptation[xlim[0] : xlim[1]]
if stimulus and model.params["ext_exc_current"].ndim > 0:
plot_stimulus = plot_stimulus[xlim[0] : xlim[1]]
if plot_mean_background:
mean_signal = mean_signal[xlim[0] : xlim[1]]
axs.plot(
plot_t,
plot_output.T,
alpha=plot_alpha,
lw=lw,
c=plot_col,
# label="Firing rate" if len(plot_nodes) == 1 else None,
)
# plot the mean signal in the background?
if plot_mean_background:
if shift_mean:
mean_signal /= np.max(mean_signal)
mean_signal *= np.abs(np.max(plot_output) - np.min(plot_output)) / 4
mean_signal = mean_signal + np.max(plot_output) * 1.1
axs.plot(plot_t, mean_signal, alpha=mean_alpha, lw=lw, c="k", zorder=10, label="Mean brain")
# if a stimulus was present
if legend and stimulus and model.params["ext_exc_current"].ndim > 0:
axs.plot(plot_t, plot_stimulus, lw=lw, c="C1", label="Stimulus", alpha=0.8)
# add a line for adaptation current in legend
if adaptation:
axs.plot([0], [0], lw=lw, c="C0", label="Adaptation")
leg = axs.legend(frameon=True, fontsize=14, framealpha=0.9)
# Get the bounding box of the original legend
bb = leg.get_bbox_to_anchor().inverse_transformed(axs.transAxes)
# Change to location of the legend.
yOffset = +0.0
bb.y0 += yOffset
bb.y1 += yOffset
leg.set_bbox_to_anchor(bb, transform=axs.transAxes)
if adaptation and not stimulus:
color = "C0"
ax_adapt = axs.twinx()
# ax_adapt.set_ylabel("$I_A$ [pA]", color=color)
ax_adapt.tick_params(
axis="y",
color=color,
labelcolor=color,
direction="out",
length=tick_length,
width=tick_width,
labelsize=fontsize,
right=False,
)
# plot_adaptation = model.outputs.IA if str(plot_nodes) == "all" else model.outputs.IA[plot_nodes]
ax_adapt.plot(plot_t, plot_adaptation.T, lw=lw, label="Adaptation", color=color)
# ax_adapt.legend(loc=4)
if legend and adaptation:
ax_adapt.legend(loc="lower right", frameon=True, fontsize=14, framealpha=0.9)
ax_adapt.spines["right"].set_visible(False)
ax_adapt.spines["top"].set_visible(False)
ax_adapt.spines["left"].set_visible(False)
ax_adapt.spines["bottom"].set_visible(False)
ax_adapt.yaxis.set_major_locator(plt.MaxNLocator(n_ticks))
if labels:
axs.set_xlabel("Time [s]")
axs.set_ylabel("Rate $r_E$ [Hz]")
if adaptation:
ax_adapt.set_ylabel("Adaptation $I_A$ [pA]", color=color)
axs.spines["right"].set_visible(False)
axs.spines["top"].set_visible(False)
axs.spines["left"].set_visible(False)
axs.spines["bottom"].set_visible(False)
# reduce number of ticks
axs.yaxis.set_major_locator(plt.MaxNLocator(n_ticks))
axs.xaxis.set_major_locator(MaxNLocator(integer=True))
if yticks is not None:
axs.set_yticks(yticks)
axs.tick_params(
axis="both",
direction="out",
length=tick_length,
width=tick_width,
colors="k",
labelsize=fontsize,
bottom=False,
left=False,
)
if crop_zero:
axs.set_xlim(crop_zero, model.t[-1] / 1000)
plt.tight_layout()
# set the axis size precisely
set_axis_size(figsize[0], figsize[1])
if savename:
save_fname = os.path.join(paths.FIGURES_DIR, f"{savename}")
plt.savefig(save_fname)
# helper function
def set_axis_size(w, h, ax=None):
""" w, h: width, height in inches """
if not ax:
ax = plt.gca()
l = ax.figure.subplotpars.left
r = ax.figure.subplotpars.right
t = ax.figure.subplotpars.top
b = ax.figure.subplotpars.bottom
figw = float(w) / (r - l)
figh = float(h) / (t - b)
ax.figure.set_size_inches(figw, figh)
def plot_matrix(mat, cbarlabel, cbar=True, ylabels=True, plotlog=False):
figsize = (2, 2)
fig = plt.figure(figsize=figsize)
# fc_fit = du.model_fit(model, ds, bold_transient=bold_transient, fc=True)["mean_fc_score"]
# plt.title(f"FC (corr: {fc_fit:0.2f})", fontsize=12)
if plotlog:
from matplotlib.colors import LogNorm
im = plt.imshow(mat, norm=LogNorm(vmin=10e-5, vmax=np.max(mat)), origin="upper")
else:
im = plt.imshow(mat, origin="upper")
plt.ylabel("Node")
plt.xlabel("Node")
plt.xticks([0, 20, 40, 60])
plt.yticks([0, 20, 40, 60])
if ylabels == False:
plt.ylabel("")
plt.yticks([])
if cbar:
# cbaxes = fig.add_axes([0.95, 0.36, 0.02, 0.52])
cbar = plt.colorbar(im, ax=plt.gca(), fraction=0.046, pad=0.04)
# cbar = plt.colorbar(im, cbaxes)
# cbar.set_ticks([0, 1])
# cbar.ax.tick_params(width=0, labelsize=10)
cbar.set_label(label=cbarlabel, size=10, labelpad=-1)
plt.tight_layout()
set_axis_size(*figsize)
################### plot fits
def plot_fc(bold, model=None, bold_transient=0, cbar=False, ylabels=True):
if bold_transient and model:
t_bold = model.outputs.BOLD.t_BOLD[model.outputs.BOLD.t_BOLD > bold_transient] / 1000
bold = model.outputs.BOLD.BOLD[:, model.outputs.BOLD.t_BOLD > bold_transient]
figsize = (2, 2)
fig = plt.figure(figsize=figsize)
# fc_fit = du.model_fit(model, ds, bold_transient=bold_transient, fc=True)["mean_fc_score"]
# plt.title(f"FC (corr: {fc_fit:0.2f})", fontsize=12)
im = plt.imshow(func.fc(bold), origin="upper", clim=(0, 1))
plt.ylabel("Node")
plt.xlabel("Node")
plt.xticks([0, 20, 40, 60])
plt.yticks([0, 20, 40, 60])
if ylabels == False:
plt.ylabel("")
plt.yticks([])
if cbar:
cbaxes = fig.add_axes([0.95, 0.36, 0.02, 0.52])
cbar = plt.colorbar(im, cbaxes)
cbar.set_ticks([0, 1])
cbar.ax.tick_params(width=0, labelsize=10)
cbar.set_label(label="Correlation", size=10, labelpad=-1)
plt.tight_layout()
set_axis_size(*figsize)
def plot_fcd(bold, model=None, bold_transient=0, cbar=False, ylabels=True):
if bold_transient and model:
t_bold = model.outputs.BOLD.t_BOLD[model.outputs.BOLD.t_BOLD > bold_transient] / 1000
bold = model.outputs.BOLD.BOLD[:, model.outputs.BOLD.t_BOLD > bold_transient]
figsize = (2, 2)
fig = plt.figure(figsize=figsize)
fcd_matrix = func.fcd(bold)
print(fcd_matrix.shape)
im = plt.imshow(fcd_matrix, origin="upper")
plt.xlabel("Time [min]")
plt.ylabel("Time [min]")
# nticks = 3
# plt.xticks(np.linspace(0, fcd_matrix.shape[0] - 1, nticks), np.linspace(0, bold.shape[1] * 2.0, nticks, dtype=int))
# plt.yticks(np.linspace(0, fcd_matrix.shape[0] - 1, nticks), np.linspace(0, bold.shape[1] * 2.0, nticks, dtype=int))
plt.xticks([0, 32, 64], [0, 6, 12])
plt.yticks([0, 32, 64], [0, 6, 12])
if ylabels == False:
plt.ylabel("")
plt.yticks([])
if cbar:
cbaxes = fig.add_axes([0.9, 0.36, 0.02, 0.52])
cbar = plt.colorbar(im, cbaxes)
# cbar.set_ticks([0.4, 1])
cbar.ax.locator_params(nbins=5)
cbar.ax.tick_params(width=0, labelsize=10)
cbar.set_label(label="Correlation", size=10)
plt.tight_layout(w_pad=4.5)
set_axis_size(*figsize)
def plot_fcd_distribution(model, ds, bold_transient=0):
if bold_transient and model:
t_bold = model.outputs.BOLD.t_BOLD[model.outputs.BOLD.t_BOLD > bold_transient] / 1000
bold = model.outputs.BOLD.BOLD[:, model.outputs.BOLD.t_BOLD > bold_transient]
figsize = (4, 3)
fig = plt.figure(figsize=figsize)
# plot distribution in fcd
# axs[2, 1].set_title(f"FCD distance {fcd_fit:0.2f}", fontsize=12)
plt.ylabel("Density")
plt.yticks([])
plt.xticks([0, 0.5, 1])
plt.xlabel("FCD$_{ij}$")
m1 = func.fcd(bold)
triu_m1_vals = m1[ | np.triu_indices(m1.shape[0], k=1) | numpy.triu_indices |
from __future__ import absolute_import
from __future__ import print_function
from keras import backend as K
import os
import argparse
import warnings
import numpy as np
import tensorflow as tf
import keras.backend as K
import keras
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten
from keras.layers import Conv2D, MaxPooling2D, BatchNormalization
K.set_image_data_format('channels_first')
from keras.models import load_model
import tensorflow.contrib.layers as layers
import dill as pickle
from third_party.lid_adversarial_subspace_detection.util import (get_data, get_model, cross_entropy) # , get_noisy_samples)
from third_party.lid_adversarial_subspace_detection.attacks \
import (fast_gradient_sign_method, basic_iterative_method,
saliency_map_method)
from third_party.lid_adversarial_subspace_detection.adaptive_attacks \
import adaptive_fast_gradient_sign_method
from third_party.lid_adversarial_subspace_detection.adaptive_attacks \
import adaptive_basic_iterative_method
from third_party.lid_adversarial_subspace_detection.cw_attacks import CarliniL2, CarliniFP, CarliniFP_2vars
from cleverhans.attacks import SPSA
from cleverhans.attacks import MadryEtAl
keras.layers.core.K.set_learning_phase(0)
# FGSM & BIM attack parameters that were chosen
ATTACK_PARAMS = {
'mnist': {'eps': 0.40, 'eps_iter': 0.010, 'image_size': 28, 'num_channels': 1, 'num_labels': 10},
'cifar': {'eps': 0.050, 'eps_iter': 0.005, 'image_size': 32, 'num_channels': 3, 'num_labels': 10},
'svhn': {'eps': 0.130, 'eps_iter': 0.010, 'image_size': 32, 'num_channels': 3, 'num_labels': 10}
}
# CLIP_MIN = 0.0
# CLIP_MAX = 1.0
# PATH_DATA = "../data/"
from cleverhans.model import Model, CallableModelWrapper
CLIP_MIN = -0.5
CLIP_MAX = 0.5
PATH_DATA = "./adv_examples/"
def craft_one_type(sess, model, X, Y, dataset, attack, batch_size, log_path=None,
fp_path = None, model_logits = None):
"""
TODO
:param sess:
:param model:
:param X:
:param Y:
:param dataset:
:param attack:
:param batch_size:
:return:
"""
print("entered")
if not log_path is None:
PATH_DATA = log_path
if attack == 'fgsm':
# FGSM attack
print('Crafting fgsm adversarial samples...')
X_adv = fast_gradient_sign_method(
sess, model, X, Y, eps=ATTACK_PARAMS[dataset]['eps'], clip_min=CLIP_MIN,
clip_max=CLIP_MAX, batch_size=batch_size
)
elif attack == 'adapt-fgsm':
# Adaptive FGSM attack
print('Crafting fgsm adversarial samples...')
X_adv = adaptive_fast_gradient_sign_method(
sess, model, X, Y, eps=ATTACK_PARAMS[dataset]['eps'], clip_min=CLIP_MIN,
clip_max=CLIP_MAX, batch_size=batch_size,
log_dir = fp_path,
model_logits = model_logits, dataset = dataset
)
elif attack == 'adapt-bim-b':
# BIM attack
print('Crafting %s adversarial samples...' % attack)
X_adv = adaptive_basic_iterative_method(
sess, model, X, Y, eps=ATTACK_PARAMS[dataset]['eps'],
eps_iter=ATTACK_PARAMS[dataset]['eps_iter'], clip_min=CLIP_MIN,
clip_max=CLIP_MAX, batch_size=batch_size,
log_dir = fp_path,
model_logits = model_logits, dataset = dataset)
elif attack in ['bim-a', 'bim-b']:
# BIM attack
print('Crafting %s adversarial samples...' % attack)
its, results = basic_iterative_method(
sess, model, X, Y, eps=ATTACK_PARAMS[dataset]['eps'],
eps_iter=ATTACK_PARAMS[dataset]['eps_iter'], clip_min=CLIP_MIN,
clip_max=CLIP_MAX, batch_size=batch_size
)
if attack == 'bim-a':
# BIM-A
# For each sample, select the time step where that sample first
# became misclassified
X_adv = np.asarray([results[its[i], i] for i in range(len(Y))])
else:
# BIM-B
# For each sample, select the very last time step
X_adv = results[-1]
elif attack == 'jsma':
# JSMA attack
print('Crafting jsma adversarial samples. This may take > 5 hours')
X_adv = saliency_map_method(
sess, model, X, Y, theta=1, gamma=0.1, clip_min=CLIP_MIN, clip_max=CLIP_MAX
)
elif attack == 'cw-l2':
# C&W attack
print('Crafting %s examples. This takes > 5 hours due to internal grid search' % attack)
image_size = ATTACK_PARAMS[dataset]['image_size']
num_channels = ATTACK_PARAMS[dataset]['num_channels']
num_labels = ATTACK_PARAMS[dataset]['num_labels']
cw_attack = CarliniL2(sess, model, image_size, num_channels, num_labels, batch_size=batch_size)
X_adv = cw_attack.attack(X, Y)
elif attack == 'cw-fp':
# C&W attack to break LID detector
print('Crafting %s examples. This takes > 5 hours due to internal grid search' % attack)
image_size = ATTACK_PARAMS[dataset]['image_size']
num_channels = ATTACK_PARAMS[dataset]['num_channels']
num_labels = ATTACK_PARAMS[dataset]['num_labels']
cw_attack = CarliniFP_2vars(sess, model, image_size, num_channels, num_labels, batch_size=batch_size,
fp_dir=fp_path)
X_adv = cw_attack.attack(X, Y)
elif attack == 'spsa':
binary_steps = 1
batch_shape = X.shape
X_input = tf.placeholder(tf.float32, shape=(1,) + batch_shape[1:])
Y_label = tf.placeholder(tf.int32, shape=(1,))
alpha = tf.placeholder(tf.float32, shape= (1,))
num_samples = np.shape(X)[0]
# X = (X - np.argmin(X))/(np.argmax(X)-np.argmin(X))
_min = np.min(X)
_max = np.max(X)
print(_max, _min)
print(tf.trainable_variables())
filters = sess.run('conv1/kernel:0')
biases = 0.0*sess.run('conv1/bias:0')
shift_model = Sequential()
if(dataset == 'mnist'):
shift_model.add(Conv2D(32, kernel_size=(3, 3),
activation=None,
input_shape=(1, 28, 28)))
else:
shift_model.add(Conv2D(32, kernel_size=(3, 3),
activation=None,
input_shape=(3, 32, 32)))
X_input_2 = tf.placeholder(tf.float32, shape=(None,) + batch_shape[1:])
correction_term = shift_model(X_input_2)
if(dataset == 'mnist'):
X_correction = -0.5*np.ones((1,1,28,28)) # We will shift the image up by 0.5, so this is the correction
else:
X_correction = -0.5*np.ones((1,3,32,32)) # We will shift the image up by 0.5, so this is the correction
# for PGD
shift_model.layers[0].set_weights([filters,biases])
bias_correction_terms =(sess.run(correction_term, feed_dict={X_input_2:X_correction}))
for i in range(32):
biases[i] = bias_correction_terms[0,i,0,0]
_, acc = model.evaluate(X, Y, batch_size=batch_size, verbose=0)
print("Model accuracy on the test set: %0.2f%%" % (100.0 * acc))
original_biases = model.layers[0].get_weights()[1]
original_weights = model.layers[0].get_weights()[0]
model.layers[0].set_weights([original_weights,original_biases+biases])
#Correct model for input shift
X = X + 0.5 #shift input to make it >=0
_, acc = model.evaluate(X, Y, batch_size=batch_size, verbose=0)
print("Model accuracy on the test set: %0.2f%%" % (100.0 * acc))
# check accuracy post correction of input and model
print('Crafting %s examples. Using Cleverhans' % attack)
image_size = ATTACK_PARAMS[dataset]['image_size']
num_channels = ATTACK_PARAMS[dataset]['num_channels']
num_labels = ATTACK_PARAMS[dataset]['num_labels']
from cleverhans.utils_keras import KerasModelWrapper
wrapped_model = KerasModelWrapper(model)
if dataset == "mnist":
wrapped_model.nb_classes = 10
elif dataset == "cifar":
wrapped_model.nb_classes = 10
else:
wrapped_model.nb_classes = 10
real_batch_size = X.shape[0]
X_adv = None
spsa = SPSA(wrapped_model, back='tf', sess=sess)
spsa_params = {
"epsilon": ATTACK_PARAMS[dataset]['eps'],
'num_steps': 100,
'spsa_iters': 1,
'early_stop_loss_threshold': None,
'is_targeted': False,
'is_debug': False
}
X_adv_spsa = spsa.generate(X_input, alpha=alpha, y=Y_label, fp_path=fp_path, **spsa_params)
for i in range(num_samples):
# rescale to format TF wants
#X_i_norm = (X[i] - _min)/(_max-_min)
X_i_norm = X[i]
# Run attack
best_res = None
ALPHA = np.ones(1)*0.1
lb = 1.0e-2
ub = 1.0e2
for j in range(binary_steps):
res = sess.run(X_adv_spsa,
feed_dict={X_input: np.expand_dims(X_i_norm, axis=0), Y_label: np.array([np.argmax(Y[i])]),
alpha: ALPHA})
if(dataset == 'mnist'):
X_place = tf.placeholder(tf.float32, shape=[1, 1, 28, 28])
else:
X_place = tf.placeholder(tf.float32, shape=[1, 3, 32, 32])
pred = model(X_place)
model_op = sess.run(pred,feed_dict={X_place:res
})
if(not np.argmax(model_op) == np.argmax(Y[i,:])):
lb = ALPHA[0]
else:
ub = ALPHA[0]
ALPHA[0] = 0.5*(lb+ub)
print(ALPHA)
if(best_res is None):
best_res = res
else:
if(not np.argmax(model_op) == np.argmax(Y[i,:])):
best_res = res
pass
# Rescale result back to our scale
if(i==0):
X_adv = best_res
else:
X_adv = np.concatenate((X_adv,best_res), axis=0)
_, acc = model.evaluate(X_adv, Y, batch_size=batch_size, verbose=0)
print("Model accuracy on the adversarial test set: %0.2f%%" % (100.0 * acc))
_, acc = model.evaluate(X, Y, batch_size=batch_size, verbose=0)
print("Model accuracy on the test set: %0.2f%%" % (100.0 * acc))
#Revert model to original
model.layers[0].set_weights([original_weights,original_biases])
#Revert adv shift
X_adv = X_adv - 0.5
X = X - 0.5 #Not used but just for logging purposes
elif attack=='adapt-pgd':
binary_steps = 1
rand_starts = 2
batch_shape = X.shape
X_input = tf.placeholder(tf.float32, shape=(1,) + batch_shape[1:])
Y_label = tf.placeholder(tf.int32, shape=(1,))
alpha = tf.placeholder(tf.float32, shape= (1,))
num_samples = np.shape(X)[0]
# X = (X - np.argmin(X))/(np.argmax(X)-np.argmin(X))
_min = np.min(X)
_max = np.max(X)
print(_max, _min)
print(tf.trainable_variables())
filters = sess.run('conv1/kernel:0')
biases = 0.0*sess.run('conv1/bias:0')
shift_model = Sequential()
if(dataset == 'mnist'):
shift_model.add(Conv2D(32, kernel_size=(3, 3),
activation=None,
input_shape=(1, 28, 28)))
else:
shift_model.add(Conv2D(32, kernel_size=(3, 3),
activation=None,
input_shape=(3, 32, 32)))
X_input_2 = tf.placeholder(tf.float32, shape=(None,) + batch_shape[1:])
correction_term = shift_model(X_input_2)
if(dataset == 'mnist'):
X_correction = -0.5* | np.ones((1,1,28,28)) | numpy.ones |
"""
This file warp around the nuscenes dataset => We only focus on what we want
"""
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
# insert system path for fast debugging
import sys
sys.path.insert(0, "../")
from nuscenes.nuscenes import NuScenes
from nuscenes.nuscenes import NuScenesExplorer
from nuscenes.utils.data_classes import LidarPointCloud, RadarPointCloud, PointCloud
from nuscenes.utils.geometry_utils import view_points, transform_matrix
from config.config_nuscenes import config_nuscenes as cfg
from nuscenes.utils.geometry_utils import view_points, box_in_image, BoxVisibility
from pyquaternion import Quaternion
from PIL import Image
from functools import reduce
import math
import os
import pickle
import numpy as np
from config.config_nuscenes import config_nuscenes as cfg
from misc.devkit.python.read_depth import depth_read
# Define the kitti dataset abstraction object
class Nuscenes_dataset(object):
# Initialize the dataset
def __init__(self, mode="mini") -> None:
# Check mode
if not mode in ["mini", "full"]:
raise ValueError("[Error] Unknow nuscene dataset mode. Consider using 'mini' or 'full'")
self.mode = mode
# Initialize nuscenes dataset API
print("[Info] Initializing Nuscenes official database...")
if self.mode == "mini":
dataroot = os.path.join(cfg.DATASET_ROOT, "v1.0-mini")
self.dataset = NuScenes(version="v1.0-mini", dataroot=dataroot)
elif self.mode == "full":
# dataroot = os.path.join(cfg.DATASET_ROOT, "v1.0-trainval")
dataroot = cfg.DATASET_ROOT
self.dataset = NuScenes(version="v1.0-trainval", dataroot=dataroot)
self.explorer = NuScenesExplorer(self.dataset)
print("[Info] Finished initializing Nuscenes official database!")
# ipdb.set_trace()
# Initialize some tables
self.samples = self.dataset.sample
self.scenes = self.dataset.scene
self.num_scenes = len(self.scenes)
self.num_samples = len(self.scenes)
self.train_val_table = self.get_train_val_table()
# Train related attributes
self.train_samples = self.train_val_table["train_samples"]
self.train_sample_tokens = self.train_val_table["train_sample_tokens"]
# Val related attributes
self.val_samples = self.train_val_table["val_samples"]
self.val_sample_tokens = self.train_val_table["val_sample_tokens"]
# Define camera keywords
self.camera_orientations = ["front", "front_right", "front_left", "back_right", "back_left", "back"]
self.orientation_to_camera = {
"front": "CAM_FRONT",
"front_right": "CAM_FRONT_RIGHT",
"front_left": "CAM_FRONT_LEFT",
"back_right": "CAM_BACK_RIGHT",
"back_left": "CAM_BACK_LEFT",
"back": "CAM_BACK"
}
# Define radar keywords
self.radar_orientations = ['front', 'front_right', 'front_left', 'back_right', 'back_left']
self.radar_keywords = ['RADAR_FRONT', 'RADAR_FRONT_RIGHT', 'RADAR_FRONT_LEFT',
'RADAR_BACK_RIGHT', 'RADAR_BACK_LEFT']
self.orientation_to_radar = {
"front": 'RADAR_FRONT',
"front_right": 'RADAR_FRONT_RIGHT',
"front_left": 'RADAR_FRONT_LEFT',
"back_right": 'RADAR_BACK_RIGHT',
"back_left": 'RADAR_BACK_LEFT'
}
# Now based on dataset version, we include different orientations
# print(cfg.version)
assert cfg.version in ["ver1", "ver2", "ver3"]
self.version = cfg.version
print("===============================")
print("[Info] Use dataset %s" % (self.version))
self.train_datapoints = self.get_datapoints("train")
self.val_datapoints = self.get_datapoints("val")
print("\t train datapoints: %d" % (len(self.train_datapoints)))
print("\t val datapoints: %d" % (len(self.val_datapoints)))
print("===============================")
# Initialize how many sweeps to use
self.lidar_sweeps = cfg.lidar_sweeps
self.radar_sweeps = cfg.radar_sweeps
####################################
## Some dataset manipulation APIs ##
####################################
# Easier call for get
def get(self, table_name, token):
return self.dataset.get(table_name, token)
# Easier call for get_sample_data
def get_sample_data(self, sample_data_token):
return self.dataset.get_sample_data(sample_data_token)
# Generate the train / val table based on the random seed
def get_train_val_table(self):
seed = cfg.TRAIN_VAL_SEED
val_num = int(cfg.VAL_RATIO * self.num_scenes)
# Get train / val scenes
all = set(list(range(self.num_scenes)))
np.random.seed(seed)
val = set(np.random.choice( | np.arange(0, self.num_scenes, 1) | numpy.arange |
from DartDeepRNN.rnn.RNNController import RNNController
from DartDeepRNN.util.Pose2d import Pose2d
from DartDeepRNN.util.Util import *
from OpenGL.GL import *
from OpenGL.GLU import *
from fltk import *
from PyCommon.modules.GUI.hpSimpleViewer import hpSimpleViewer as SimpleViewer
from PyCommon.modules.Renderer import ysRenderer as yr
from PyCommon.modules.Math import mmMath as mm
from PyCommon.modules.Motion import ysMotion as ym
from PyCommon.modules.Resource import ysMotionLoader as yf
from PyCommon.modules.dart.dart_ik import DartIk
import pydart2 as pydart
import numpy as np
MOTION_SCALE = .01
joint_point_list = [None, "Head_End", "LeftHand", "LeftFoot", "LeftToeBase", "RightHand", "RightFoot", "RightToeBase", "LeftArm",
"RightArm", "LeftForeArm", "LeftLeg", "RightForeArm", "RightLeg", "Spine", "LeftHandIndex1", "RightHandIndex1", "Neck1", "LeftUpLeg", "RightUpLeg"]
joint_list = ["Head", "Hips", "LHipJoint", "LeftArm", "LeftFoot", "LeftForeArm", "LeftHand",
"LeftLeg", "LeftShoulder", "LeftToeBase", "LeftUpLeg", "LowerBack", "Neck", "Neck1",
"RHipJoint", "RightArm", "RightFoot","RightForeArm","RightHand", "RightLeg","RightShoulder","RightToeBase","RightUpLeg",
"Spine","Spine1"]
class ModelViewer(object):
def __init__(self, folder):
pydart.init()
self.world = pydart.World(1./1200., "../data/cmu_with_ground.xml")
self.model = self.world.skeletons[1]
self.ik = DartIk(self.model)
self.controller = RNNController(folder)
self.all_angles = [[] for i in range(93)]
viewer = SimpleViewer(rect=[0, 0, 1280+300, 720+1+55], viewForceWnd=False)
self.viewer = viewer
# viewer.record(True)
viewer.record(False)
viewer.setMaxFrame(10000)
self.isFirst = True
self.lines = None
viewer.motionViewWnd.glWindow.set_mouse_pick(True)
def callback_btn(ptr):
self.controller.reset()
viewer.objectInfoWnd.addBtn('reset', callback_btn)
self.rc = yr.RenderContext()
self.rd_target_position = [None]
self.rd_frames = [None]
viewer.doc.addRenderer('contact', yr.PointsRenderer(self.rd_target_position, (0, 255, 0), save_state=False))
viewer.doc.addRenderer('MotionModel', yr.DartRenderer(self.world, (150,150,255), yr.POLYGON_FILL, save_state=False))
viewer.doc.addRenderer('rd_frames', yr.FramesRenderer(self.rd_frames))
def extraDrawCallback():
self.rd_target_position[0] = self.viewer.motionViewWnd.glWindow.pickPoint
self.step_model()
del self.rd_frames[:]
self.rd_frames.append(self.model.body(0).world_transform())
# for i in range(3):
# print(self.model.body(0).world_transform()[:3, i])
viewer.setExtraDrawCallback(extraDrawCallback)
viewer.startTimer(1. / 30.)
viewer.show()
# viewer.play()
Fl.run()
def get_target(self):
p = self.viewer.motionViewWnd.glWindow.pickPoint
target = Pose2d([p[0]/MOTION_SCALE, -p[2]/MOTION_SCALE])
target = self.controller.pose.relativePose(target)
target = target.p
t_len = v_len(target)
if t_len > 80:
ratio = 80/t_len
target[0] *= ratio
target[1] *= ratio
return target
def step_model(self):
contacts, points, angles, orientations, root_orientation = self.controller.step(self.get_target())
# pairs = [[0,11,3,4],
# [0,8,10,2],
# [0,13,6,7],
# [0,9,12,5],
# [0,1]]
pairs = [[0,18,11,3,4],
[0,14,8,10,2],
[0,19,13,6,7],
[0,14,9,12,5],
[0,14,17,1]]
self.lines = []
for pair in pairs:
for i in range(len(pair)-1):
self.lines.append([points[pair[i]], points[pair[i+1]]])
# print(len(orientations))
for i in range(len(angles)):
self.all_angles[i].append(angles[i])
for j in range(len(self.model.joints)):
if j == 0:
joint = self.model.joints[j] # type: pydart.FreeJoint
joint_idx = joint_list.index(joint.name)
hip_angles = mm.logSO3(np.dot(root_orientation, orientations[joint_idx]))
# hip_angles = mm.logSO3(root_orientation)
joint.set_position(np.array([hip_angles[0], hip_angles[1], hip_angles[2], points[0][0], points[0][1], points[0][2]]))
continue
joint = self.model.joints[j] # type: pydart.BallJoint
joint_idx = joint_list.index(joint.name)
joint.set_position(angles[joint_idx*3:joint_idx*3+3])
self.ik.clean_constraints()
self.ik.add_joint_pos_const('LeftForeArm', np.asarray(points[10]))
self.ik.add_joint_pos_const('LeftHand', | np.asarray(points[2]) | numpy.asarray |
# stdlib
from typing import Tuple, Union
# third party
import numpy as np
from sklearn.base import TransformerMixin
# Necessary packages
import torch
from torch import nn
EPS = 1e-8
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
def sample_Z(m: int, n: int) -> np.ndarray:
"""Random sample generator for Z.
Args:
m: number of rows
n: number of columns
Returns:
np.ndarray: generated random values
"""
res = np.random.uniform(0.0, 0.01, size=[m, n])
return torch.from_numpy(res).to(DEVICE)
def sample_M(m: int, n: int, p: float) -> np.ndarray:
"""Hint Vector Generation
Args:
m: number of rows
n: number of columns
p: hint rate
Returns:
np.ndarray: generated random values
"""
unif_prob = | np.random.uniform(0.0, 1.0, size=[m, n]) | numpy.random.uniform |
from functools import partial
import numpy as np
import pandas as pd
from sklearn.base import clone
from sklearn.model_selection import cross_val_score
from sklearn.metrics import make_scorer, mean_absolute_error, log_loss, accuracy_score
from dask import compute, delayed
| np.random.seed(42) | numpy.random.seed |
###################################################################################
## Main sampler
## Must provide data input 'data_input.pkl' to initiate the sampler.
## In 'data_input.pkl', one must include
## Y ........................................... censored observations on GEV scale
## cen ........................................................... indicator matrix
## initial.values ........ a dictionary: phi, tau_sqd, prob_below, prob_above, Dist,
## theta_c, X, X_s, R, Design_mat, beta_loc0,
## beta_loc1, Time, beta_scale, beta_shape
## n_updates .................................................... number of updates
## thinning ......................................... number of runs in each update
## experiment_name
## echo_interval ......................... echo process every echo_interval updates
## sigma_m
## prop_Sigma
## true_params ....................... a dictionary: phi, rho, tau_sqd, theta_gpd,
## prob_below, X_s, R
##
if __name__ == "__main__":
import os
from pickle import load
from pickle import dump
import nonstat_model_noXs.model_sim as utils
import nonstat_model_noXs.generic_samplers as sampler
import nonstat_model_noXs.priors as priors
import numpy as np
from scipy.spatial import distance
from scipy.stats import norm
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages
from scipy.linalg import lapack
# Check whether the 'mpi4py' is installed
test_mpi = os.system("python -c 'from mpi4py import *' &> /dev/null")
if test_mpi != 0:
import sys
sys.exit("mpi4py import is failing, aborting...")
# get rank and size
from mpi4py import MPI
comm = MPI.COMM_WORLD
rank = comm.Get_rank()
size = comm.Get_size()
## ---------------------------------------------------------------------------
## Automatically make a directory for the new simulation
## ---------------------------------------------------------------------------
run = 1
save_directory = "Simulation_"+str(run)
if rank==0:
dirs = os.listdir()
while save_directory in dirs:
run+=1
save_directory = "Simulation_"+str(run)
os.mkdir(save_directory)
run = comm.bcast(run,root=0)
save_directory = "Simulation_"+str(run)
## -------------------------------------------------------
## General setup
## -------------------------------------------------------
# size=64;rank=0
thinning = 10; echo_interval = 20; n_updates = 50001
# Generate multiple independent random streams
random_generator = np.random.RandomState()
# Constants to control adaptation of the Metropolis sampler
c_0 = 10
c_1 = 0.8
offset = 3 # the iteration offset
r_opt_1d = .41
r_opt_2d = .35
eps = 1e-6 # a small number
# Hyper parameters for the prior of the mixing distribution parameters and
hyper_params_phi = np.array([0.1,0.7])
hyper_params_tau_sqd = np.array([0.1,0.1])
hyper_params_theta_c = np.array([0, 20])
hyper_params_theta_gev = 25
# hyper_params_range = np.array([0.5,1.5]) # in case where roughness is not updated
# Load simulated data
data_filename = 'data_sim'+str(run)+'.pkl'
with open(data_filename, 'rb') as f:
Y_all = load(f)
cen_all = load(f)
cen_above_all = load(f)
data_all = load(f)
sigma_m = load(f)
prop_sigma = load(f)
f.close()
## -------------------------------------------------------
## Get the data for the local fit
## -------------------------------------------------------
local_fit_no = 0
radius = data_all['radius']
# Filename for storing the intermediate results
filename = './'+save_directory + '/local_' + str(local_fit_no) + '_progress_' + str(rank) + '.pkl'
# Subset the stations within radius of the knot_of_interest
knot_of_interest = data_all['Knots'][local_fit_no,:]
Dist_from_knot = distance.cdist(knot_of_interest.reshape((-1,2)),data_all['Stations'])
subset_indices = (Dist_from_knot[0,:] <= radius)
Stations_local = data_all['Stations'][subset_indices,:]
# import matplotlib.pyplot as plt
# circle = plt.Circle((knot_of_interest[0],knot_of_interest[1]), radius, color='r', fill=False)
# ax = plt.gca()
# ax.cla() # clear things for fresh plot
# ax.set_xlim((0, 10))
# ax.set_ylim((0, 10))
# ax.scatter(data_all['Stations'][:,0], data_all['Stations'][:,1], c='gray')
# ax.scatter(Stations_local[:,0], Stations_local[:,1], c='r')
# ax.add_patch(circle)
# Subset the observations
Y = Y_all[subset_indices,:]
# cen = cen_all[subset_indices,:]
# cen_above = cen_above_all[subset_indices,:]
# Bookkeeping
n_s = Y.shape[0]
n_t = Y.shape[1]
if n_t != size:
import sys
sys.exit("Make sure the number of cpus (N) = number of time replicates (n_t), i.e.\n srun -N python nonstat_sampler.py")
n_updates_thinned = np.int(np.ceil(n_updates/thinning))
wh_to_plot_Xs = n_s*np.array([0.25,0.5,0.75])
wh_to_plot_Xs = wh_to_plot_Xs.astype(int)
sigma_m['Z_onetime'] = sigma_m['Z_onetime'][:n_s]
# plt.scatter(data_all['Stations'][:,0], data_all['Stations'][:,1],c=data_all['phi_vec'], marker='o', alpha=0.5, cmap='jet')
# plt.colorbar()
# plt.scatter(data_all['Stations'][:,0], data_all['Stations'][:,1],c=data_all['range_vec'], marker='o', alpha=0.5, cmap='jet')
# plt.colorbar()
## -------------------------------------------------------
## Set initial values
## -------------------------------------------------------
phi = data_all['phi_at_knots'][local_fit_no]
gamma = data_all['gamma']
tau_sqd = data_all['tau_sqd']
prob_below = data_all['prob_below']
prob_above = data_all['prob_above']
range = data_all['range_at_knots'][local_fit_no]
nu = data_all['nu']
# 1. For current values of phi and gamma, obtain grids of survival probs and densities
grid = utils.density_interp_grid(phi, gamma, grid_size=800)
xp = grid[0]; den_p = grid[1]; surv_p = grid[2]
thresh_X = utils.qRW_me_interp(prob_below, xp, surv_p, tau_sqd, phi, gamma)
thresh_X_above = utils.qRW_me_interp(prob_above, xp, surv_p, tau_sqd, phi, gamma)
# 2. Marginal GEV parameters: per location x time
Design_mat = data_all['Design_mat'][subset_indices,:]
beta_loc0 = data_all['beta_loc0']
beta_loc1 = data_all['beta_loc1']
Time = data_all['Time']
beta_scale = data_all['beta_scale']
beta_shape = data_all['beta_shape']
loc0 = Design_mat @beta_loc0
loc1 = Design_mat @beta_loc1
Loc = np.tile(loc0, n_t) + np.tile(loc1, n_t)*np.repeat(Time,n_s)
Loc = Loc.reshape((n_s,n_t),order='F')
scale = Design_mat @beta_scale
Scale = np.tile(scale, n_t)
Scale = Scale.reshape((n_s,n_t),order='F')
# Design_mat1 = np.c_[np.repeat(1,n_s), np.log(Design_mat[:,1])]
shape = Design_mat @beta_shape
Shape = np.tile(shape, n_t)
Shape = Shape.reshape((n_s,n_t),order='F')
unifs = utils.pgev(Y, Loc, Scale, Shape)
cen = unifs < prob_below
cen_above = unifs > prob_above
# 3. Eigendecomposition of the correlation matrix
n_covariates = len(beta_loc0)
theta_c = np.array([range,nu])
Dist = distance.squareform(distance.pdist(Stations_local))
tmp_vec = np.ones(n_s)
Cor = utils.corr_fn(Dist, theta_c)
# eig_Cor = np.linalg.eigh(Cor) #For symmetric matrices
# V = eig_Cor[1]
# d = eig_Cor[0]
cholesky_inv = lapack.dposv(Cor,tmp_vec)
# 4. Process data given initial values
# X = data_all['X'][subset_indices,:]
# X_s = data_all['X_s'][subset_indices,:]
# Z = data_all['Z'][subset_indices,:]
X = utils.gev_2_RW_me(Y, xp, surv_p, tau_sqd, phi, gamma, Loc, Scale, Shape)
R = data_all['R_at_knots'][local_fit_no,:]
Z = np.empty((n_s,n_t))
Z[:] = np.nan
for idx in np.arange(n_t):
X_s_tmp = X[:,idx]-np.sqrt(tau_sqd)*norm.rvs(size=n_s)
lower_limit = R[idx]**phi
X_s_tmp[X_s_tmp<lower_limit] = lower_limit + 0.01
Z[:,idx] = norm.ppf(1-1/(X_s_tmp/(R[idx]**phi)))
# import matplotlib.pyplot as plt
# plt.scatter(Stations_local[:,0], Stations_local[:,1],c=Z[:,rank], marker='o', alpha=0.5, cmap='jet')
# plt.colorbar()
# plt.title("Z onetime");
v_q=np.repeat(2.4**2,n_s)
for idx in np.arange(n_t):
tmp = utils.Z_update_onetime(Y[:,idx], X[:,idx], R[idx], Z[:,idx], cen[:,idx], cen_above[:,idx], prob_below, prob_above,
tau_sqd, phi, gamma, Loc[:,idx], Scale[:,idx], Shape[:,idx], xp, surv_p, den_p,
thresh_X, thresh_X_above, Cor, cholesky_inv, v_q, random_generator)
Y_onetime = Y[:,rank]
X_onetime = X[:,rank]
R_onetime = R[rank]
X_s_onetime = (R_onetime**phi)*utils.norm_to_Pareto(Z[:,rank])
Z_onetime = Z[:,rank]
# Initial trace objects
Z_1t_accept = np.zeros(n_s)
R_accept = 0
Z_1t_trace = np.empty((n_s,n_updates_thinned)); Z_1t_trace[:] = np.nan
Z_1t_trace[:,0] = Z_onetime
R_1t_trace = np.empty(n_updates_thinned); R_1t_trace[:] = np.nan
R_1t_trace[0] = R_onetime
if rank == 0:
print("Number of time replicates = %d"%size)
X_s = np.empty((n_s,n_t))
phi_trace = np.empty(n_updates_thinned); phi_trace[:] = np.nan
phi_trace[0] = phi
tau_sqd_trace = np.empty(n_updates_thinned); tau_sqd_trace[:] = np.nan
tau_sqd_trace[0] = tau_sqd
theta_c_trace_within_thinning = np.empty((2,thinning)); theta_c_trace_within_thinning[:] = np.nan
theta_c_trace = np.empty((2,n_updates_thinned)); theta_c_trace[:] = np.nan
theta_c_trace[:,0] = theta_c
beta_loc0_trace_within_thinning = np.empty((n_covariates,thinning)); beta_loc0_trace_within_thinning[:] = np.nan
beta_loc0_trace = np.empty((n_covariates,n_updates_thinned)); beta_loc0_trace[:] = np.nan
beta_loc0_trace[:,0] = beta_loc0
beta_loc1_trace_within_thinning = np.empty((n_covariates,thinning)); beta_loc1_trace_within_thinning[:] = np.nan
beta_loc1_trace = np.empty((n_covariates,n_updates_thinned)); beta_loc1_trace[:] = np.nan
beta_loc1_trace[:,0] = beta_loc1
beta_scale_trace_within_thinning = np.empty((n_covariates,thinning)); beta_scale_trace_within_thinning[:] = np.nan
beta_scale_trace = np.empty((n_covariates,n_updates_thinned)); beta_scale_trace[:] = np.nan
beta_scale_trace[:,0] = beta_scale
beta_shape_trace_within_thinning = np.empty((n_covariates,thinning)); beta_shape_trace_within_thinning[:] = np.nan
beta_shape_trace = np.empty((n_covariates,n_updates_thinned)); beta_shape_trace[:] = np.nan
beta_shape_trace[:,0] = beta_shape
phi_accept = 0
tau_sqd_accept = 0
theta_c_accept = 0
beta_loc0_accept = 0
beta_loc1_accept = 0
beta_scale_accept = 0
beta_shape_accept = 0
# -----------------------------------------------------------------------------------
# -----------------------------------------------------------------------------------
# --------------------------- Start Metropolis Updates ------------------------------
# -----------------------------------------------------------------------------------
# -----------------------------------------------------------------------------------
for iter in np.arange(1,n_updates):
# Update X
# print(str(rank)+" "+str(iter)+" Gathered? "+str(np.where(~cen)))
X_onetime = utils.X_update(Y_onetime, cen[:,rank], cen_above[:,rank], xp, surv_p, tau_sqd, phi, gamma, Loc[:,rank], Scale[:,rank], Shape[:,rank])
# Update Z
tmp = utils.Z_update_onetime(Y_onetime, X_onetime, R_onetime, Z_onetime, cen[:,rank], cen_above[:,rank], prob_below, prob_above,
tau_sqd, phi, gamma, Loc[:,rank], Scale[:,rank], Shape[:,rank], xp, surv_p, den_p,
thresh_X, thresh_X_above, Cor, cholesky_inv, sigma_m['Z_onetime'], random_generator)
Z_1t_accept = Z_1t_accept + tmp
# Update R
Metr_R = sampler.static_metr(Y_onetime, R_onetime, utils.Rt_update_mixture_me_likelihood,
priors.R_prior, gamma, 2,
random_generator,
np.nan, sigma_m['R_1t'], False,
X_onetime, Z_onetime, cen[:,rank], cen_above[:,rank],
prob_below, prob_above, Loc[:,rank], Scale[:,rank], Shape[:,rank], tau_sqd, phi, gamma,
xp, surv_p, den_p, thresh_X, thresh_X_above)
R_accept = R_accept + Metr_R['acc_prob']
R_onetime = Metr_R['trace'][0,1]
X_s_onetime = (R_onetime**phi)*utils.norm_to_Pareto(Z_onetime)
# *** Gather items ***
X_s_recv = comm.gather(X_s_onetime,root=0)
X_recv = comm.gather(X_onetime, root=0)
Z_recv = comm.gather(Z_onetime, root=0)
R_recv = comm.gather(R_onetime, root=0)
if rank==0:
X_s[:] = np.vstack(X_s_recv).T
X[:] = np.vstack(X_recv).T
# Check whether X is negative
if np.any(X[~cen & ~cen_above]<0):
sys.exit("X value abnormalty "+str(phi)+" "+str(tau_sqd))
Z[:] = np.vstack(Z_recv).T
R[:] = R_recv
index_within = (iter-1)%thinning
# print('beta_shape_accept=',beta_shape_accept, ', iter=', iter)
# Update phi
Metr_phi = sampler.static_metr(Y, phi, utils.phi_update_mixture_me_likelihood, priors.interval_unif,
hyper_params_phi, 2,
random_generator,
np.nan, sigma_m['phi'], False,
R, Z, cen, cen_above,
prob_below, prob_above, Loc, Scale, Shape, tau_sqd, gamma)
phi_accept = phi_accept + Metr_phi['acc_prob']
phi = Metr_phi['trace'][0,1]
# Update gamma (TBD)
#
grid = utils.density_interp_grid(phi, gamma, grid_size=800)
xp = grid[0]; den_p = grid[1]; surv_p = grid[2]
X_s = (R**phi)*utils.norm_to_Pareto(Z)
# Update tau_sqd
Metr_tau_sqd = sampler.static_metr(Y, tau_sqd, utils.tau_update_mixture_me_likelihood, priors.invGamma_prior,
hyper_params_tau_sqd, 2,
random_generator,
np.nan, sigma_m['tau_sqd'], False,
X_s, cen, cen_above,
prob_below, prob_above, Loc, Scale, Shape,
phi, gamma, xp, surv_p, den_p)
tau_sqd_accept = tau_sqd_accept + Metr_tau_sqd['acc_prob']
tau_sqd = Metr_tau_sqd['trace'][0,1]
thresh_X = utils.qRW_me_interp(prob_below, xp, surv_p, tau_sqd, phi, gamma)
thresh_X_above = utils.qRW_me_interp(prob_above, xp, surv_p, tau_sqd, phi, gamma)
# Update theta_c
# Metr_theta_c = sampler.static_metr(Z, theta_c, utils.theta_c_update_mixture_me_likelihood,
# priors.interval_unif_multi, hyper_params_theta_c, 2,
# random_generator,
# prop_sigma['theta_c'], sigma_m['theta_c'], False,
# Dist)
# theta_c_accept = theta_c_accept + Metr_theta_c['acc_prob']
# theta_c = Metr_theta_c['trace'][:,1]
# theta_c_trace_within_thinning[:,index_within] = theta_c
Metr_theta_c = sampler.static_metr(Z, theta_c[0], utils.range_update_mixture_me_likelihood,
priors.interval_unif, hyper_params_theta_c, 2,
random_generator,
np.nan, sigma_m['range'], False,
theta_c[1],Dist)
theta_c_accept = theta_c_accept + Metr_theta_c['acc_prob']
theta_c = np.array([Metr_theta_c['trace'][0,1],theta_c[1]])
theta_c_trace_within_thinning[:,index_within] = theta_c
if Metr_theta_c['acc_prob']>0:
Cor = utils.corr_fn(Dist, theta_c)
# eig_Cor = np.linalg.eigh(Cor) #For symmetric matrices
# V = eig_Cor[1]
# d = eig_Cor[0]
cholesky_inv = lapack.dposv(Cor,tmp_vec)
# Update beta_loc0
# Metr_beta_loc0 = sampler.static_metr(Design_mat, beta_loc0, utils.loc0_gev_update_mixture_me_likelihood,
# priors.unif_prior, hyper_params_theta_gev, 2,
# random_generator,
# prop_sigma['beta_loc0'], sigma_m['beta_loc0'], False,
# Y, X_s, cen, cen_above, prob_below, prob_above,
# tau_sqd, phi, gamma, loc1, Scale, Shape, Time, xp, surv_p, den_p,
# thresh_X, thresh_X_above)
# beta_loc0_accept = beta_loc0_accept + Metr_beta_loc0['acc_prob']
# beta_loc0 = Metr_beta_loc0['trace'][:,1]
# beta_loc0_trace_within_thinning[:,index_within] = beta_loc0
# loc0 = Design_mat @beta_loc0
Metr_beta_loc0 = sampler.static_metr(Design_mat, beta_loc0[0], utils.loc0_interc_gev_update_mixture_me_likelihood,
priors.unif_prior_1dim, hyper_params_theta_gev, 2,
random_generator,
np.nan, sigma_m['beta_loc0'], False,
beta_loc0[1], Y, X_s, cen, cen_above, prob_below, prob_above,
tau_sqd, phi, gamma, loc1, Scale, Shape, Time, xp, surv_p, den_p,
thresh_X, thresh_X_above)
beta_loc0_accept = beta_loc0_accept + Metr_beta_loc0['acc_prob']
beta_loc0 = np.array([Metr_beta_loc0['trace'][0,1],beta_loc0[1]])
beta_loc0_trace_within_thinning[:,index_within] = beta_loc0
loc0 = Design_mat @beta_loc0
# Update beta_loc1
# Metr_beta_loc1 = sampler.static_metr(Design_mat, beta_loc1, utils.loc1_gev_update_mixture_me_likelihood,
# priors.unif_prior, hyper_params_theta_gev, 2,
# random_generator,
# prop_sigma['beta_loc1'], sigma_m['beta_loc1'], False,
# Y, X_s, cen, cen_above, prob_below, prob_above,
# tau_sqd, phi, gamma, loc0, Scale, Shape, Time, xp, surv_p, den_p,
# thresh_X, thresh_X_above)
# beta_loc1_accept = beta_loc1_accept + Metr_beta_loc1['acc_prob']
# beta_loc1 = Metr_beta_loc1['trace'][:,1]
# beta_loc1_trace_within_thinning[:,index_within] = beta_loc1
# loc1 = Design_mat @beta_loc1
Loc = | np.tile(loc0, n_t) | numpy.tile |
"""Unit tests for utils functions."""
import numpy as np
from tsepy.utils import brainsync, find_central_scan, rotate_data
def test_brainsync():
"""Tests whether the outputs of tsepy.utils.brainsync have te correct shape
and whether the within-matrix correlations of the input and output matrix
remain identical."""
x1 = np.random.rand(10, 5, 3)
y1, rotations = brainsync(x1)
y2, _ = brainsync(x1[:, :, 1:], x1[:, :, 0])
for i in range(x1.shape[2]):
assert np.allclose(np.corrcoef(x1[:, :, i]), np.corrcoef(y1[:, :, i]))
if i != 0:
assert np.allclose(np.corrcoef(x1[:, :, i]), np.corrcoef(y2[:, :, i - 1]))
assert rotations.shape == (x1.shape[1], x1.shape[1], x1.shape[2])
def test_find_central_scan():
"""Tests whether the output of tsepy.utils.find_central_scan is less than
its length."""
x = np.random.rand(10, 10, 3)
idx = find_central_scan(x)
assert idx < x.shape[2]
def test_rotate_data():
"""Tests whether the within-matrix correlation before and after rotation
with tsepy.utils.rotate_data remain identical"""
data = np.random.rand(10, 5)
reference = | np.random.rand(10, 5) | numpy.random.rand |
import os
import librosa
import numpy as np
from logging import log, info, debug, basicConfig, DEBUG, INFO, error
from google.cloud import storage
from google.api_core.exceptions import NotFound
import matplotlib
matplotlib.use('agg')
import matplotlib.pyplot as plt
def plot_spectrum(gen_spectrum, image_name):
plt.figure(figsize=(5, 5))
# we then use the 2nd column.
plt.subplot(1, 1, 1)
plt.title("CNN Voice Transfer Result")
plt.imsave(image_name, gen_spectrum[:400, :])
def wav2spect(filename, N_FFT):
x, sr = librosa.load(filename)
S = librosa.stft(x, N_FFT)
p = np.angle(S)
S = np.log1p( | np.abs(S) | numpy.abs |
# Written by <NAME>
#
# Based on:
# --------------------------------------------------------
# Copyright (c) 2017-present, Facebook, Inc.
#
# 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.
##############################################################################
#
# Based on:
# --------------------------------------------------------
# Fast R-CNN
# Copyright (c) 2015 Microsoft
# Licensed under The MIT License [see LICENSE for details]
# Written by <NAME>
# --------------------------------------------------------
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from collections import defaultdict
import cv2
import numpy as np
import pycocotools.mask as mask_util
from torch.autograd import Variable
import torch
import ipdb
import math
from core.config import cfg
from utils.timer import Timer
import utils.boxes as box_utils
import utils.blob as blob_utils
import utils.fpn as fpn_utils
import utils.image as image_utils
import utils.keypoints as keypoint_utils
from roi_data.hoi_data import get_hoi_blob_names
from roi_data.hoi_data_union import get_hoi_union_blob_names, generate_union_mask, generate_joints_heatmap
from roi_data.hoi_data_union import generate_pose_configmap, generate_part_box_from_kp, generate_part_box_from_kp17
from datasets import json_dataset
import torch.nn.functional as F
import time
def im_detect_all(model, im, box_proposals=None, timers=None, entry=None):
"""Process the outputs of model for testing
Args:
model: the network module
im_data: Pytorch variable. Input batch to the model.
im_info: Pytorch variable. Input batch to the model.
gt_boxes: Pytorch variable. Input batch to the model.
num_boxes: Pytorch variable. Input batch to the model.
args: arguments from command line.
timer: record the cost of time for different steps
The rest of inputs are of type pytorch Variables and either input to or output from the model.
"""
if timers is None:
timers = defaultdict(Timer)
timers['im_detect_bbox'].tic()
if cfg.TEST.BBOX_AUG.ENABLED:
# boxes is in origin img size
scores, boxes, im_scale, blob_conv = im_detect_bbox_aug(
model, im, box_proposals)
else:
scores, boxes, im_scale, blob_conv = im_detect_bbox(
model, im, cfg.TEST.SCALE, cfg.TEST.MAX_SIZE, box_proposals)
timers['im_detect_bbox'].toc()
im_info = np.array([im.shape[:2]+(im_scale[0],)])
# score and boxes are from the whole image after score thresholding and nms
# (they are not separated by class) (numpy.ndarray)
# cls_boxes boxes and scores are separated by class and in the format used
# for evaluating results
timers['misc_bbox'].tic()
scores, boxes, cls_boxes = box_results_with_nms_and_limit(scores, boxes)
timers['misc_bbox'].toc()
if cfg.MODEL.MASK_ON and boxes.shape[0] > 0:
timers['im_detect_mask'].tic()
if cfg.TEST.MASK_AUG.ENABLED:
masks = im_detect_mask_aug(model, im, boxes, im_scale, blob_conv)
else:
masks = im_detect_mask(model, im_scale, boxes, blob_conv)
timers['im_detect_mask'].toc()
timers['misc_mask'].tic()
cls_segms = segm_results(cls_boxes, masks, boxes, im.shape[0], im.shape[1])
timers['misc_mask'].toc()
else:
cls_segms = None
if cfg.MODEL.KEYPOINTS_ON and boxes.shape[0] > 0:
timers['im_detect_keypoints'].tic()
if cfg.TEST.KPS_AUG.ENABLED:
heatmaps = im_detect_keypoints_aug(model, im, boxes, im_scale, blob_conv)
else:
heatmaps = im_detect_keypoints(model, im_scale, boxes, blob_conv)
timers['im_detect_keypoints'].toc()
timers['misc_keypoints'].tic()
cls_keyps = keypoint_results(cls_boxes, heatmaps, boxes)
timers['misc_keypoints'].toc()
else:
cls_keyps = None
vcoco_heatmaps = None
if cfg.MODEL.VCOCO_ON:
if cfg.VCOCO.KEYPOINTS_ON:
# ipdb.set_trace()
vcoco_heatmaps, vcoco_heatmaps_np = im_detect_keypoints_vcoco(model, im_scale[0], cls_boxes[1][:, :4], blob_conv)
vcoco_cls_keyps = keypoint_results_vcoco(cls_boxes, vcoco_heatmaps_np)
else:
vcoco_cls_keyps = None
hoi_res = im_detect_hoi_union(model, boxes, scores, cls_boxes[1].shape[0],
im_info, blob_conv, entry,
vcoco_heatmaps)
else:
hoi_res = None
vcoco_cls_keyps = None
return cls_boxes, cls_segms, cls_keyps, hoi_res, vcoco_cls_keyps
def im_detect_all_precomp_box(model, im, timers=None, entry=None, mode='val', category_id_to_contiguous_id=None):
"""Process the outputs of model for testing
Args:
model: the network module
im_data: Pytorch variable. Input batch to the model.
im_info: Pytorch variable. Input batch to the model.
gt_boxes: Pytorch variable. Input batch to the model.
num_boxes: Pytorch variable. Input batch to the model.
args: arguments from command line.
timer: record the cost of time for different steps
The rest of inputs are of type pytorch Variables and either input to or output from the model.
"""
if timers is None:
timers = defaultdict(Timer)
blob_conv, im_scale = im_conv_body_only(model, im, cfg.TEST.SCALE, cfg.TEST.MAX_SIZE)
im_info = np.array([im.shape[:2] + (im_scale[0],)])
scores, boxes, cates, cls_boxes = im_detect_bbox_precomp_box(entry, category_id_to_contiguous_id)
if cfg.MODEL.MASK_ON and boxes.shape[0] > 0:
timers['im_detect_mask'].tic()
if cfg.TEST.MASK_AUG.ENABLED:
masks = im_detect_mask_aug(model, im, boxes, im_scale, blob_conv)
else:
masks = im_detect_mask(model, im_scale, boxes, blob_conv)
timers['im_detect_mask'].toc()
timers['misc_mask'].tic()
cls_segms = segm_results(cls_boxes, masks, boxes, im.shape[0], im.shape[1])
timers['misc_mask'].toc()
else:
cls_segms = None
if cfg.MODEL.KEYPOINTS_ON and boxes.shape[0] > 0:
timers['im_detect_keypoints'].tic()
if cfg.TEST.KPS_AUG.ENABLED:
heatmaps = im_detect_keypoints_aug(model, im, boxes, im_scale, blob_conv)
else:
heatmaps = im_detect_keypoints(model, im_scale, boxes, blob_conv)
timers['im_detect_keypoints'].toc()
timers['misc_keypoints'].tic()
cls_keyps = keypoint_results(cls_boxes, heatmaps, boxes)
timers['misc_keypoints'].toc()
else:
cls_keyps = None
vcoco_heatmaps = None
vcoco_cls_keyps = None
loss = None
if cfg.MODEL.VCOCO_ON:
hoi_res, loss = im_detect_hoi_union(model, boxes, scores, cates, cls_boxes[1].shape[0],
im_info, blob_conv, entry, mode,
vcoco_heatmaps)
else:
hoi_res = None
vcoco_cls_keyps = None
return cls_boxes, cls_segms, cls_keyps, hoi_res, vcoco_cls_keyps, loss
def im_conv_body_only(model, im, target_scale, target_max_size):
inputs, im_scale = _get_blobs(im, None, target_scale, target_max_size)
if cfg.PYTORCH_VERSION_LESS_THAN_040:
inputs['data'] = Variable(torch.from_numpy(inputs['data']), volatile=True).cuda()
else:
inputs['data'] = torch.from_numpy(inputs['data']).cuda()
inputs.pop('im_info')
blob_conv = model.module.convbody_net(**inputs)
return blob_conv, im_scale
def im_detect_bbox(model, im, target_scale, target_max_size, boxes=None):
"""Prepare the bbox for testing"""
inputs, im_scale = _get_blobs(im, boxes, target_scale, target_max_size)
if cfg.DEDUP_BOXES > 0 and not cfg.MODEL.FASTER_RCNN:
v = np.array([1, 1e3, 1e6, 1e9, 1e12])
hashes = np.round(inputs['rois'] * cfg.DEDUP_BOXES).dot(v)
_, index, inv_index = np.unique(
hashes, return_index=True, return_inverse=True
)
inputs['rois'] = inputs['rois'][index, :]
boxes = boxes[index, :]
# Add multi-level rois for FPN
if cfg.FPN.MULTILEVEL_ROIS and not cfg.MODEL.FASTER_RCNN:
_add_multilevel_rois_for_test(inputs, 'rois')
if cfg.PYTORCH_VERSION_LESS_THAN_040:
inputs['data'] = [Variable(torch.from_numpy(inputs['data']), volatile=True)]
inputs['im_info'] = [Variable(torch.from_numpy(inputs['im_info']), volatile=True)]
else:
inputs['data'] = [torch.from_numpy(inputs['data'])]
inputs['im_info'] = [torch.from_numpy(inputs['im_info'])]
time1 = time.time()
return_dict = model(**inputs)
time2 = time.time()
print('model_time:', time2-time1)
if cfg.MODEL.FASTER_RCNN:
rois = return_dict['rois'].data.cpu().numpy()
# unscale back to raw image space
boxes = rois[:, 1:5] / im_scale
# cls prob (activations after softmax)
scores = return_dict['cls_score'].data.cpu().numpy().squeeze()
# In case there is 1 proposal
scores = scores.reshape([-1, scores.shape[-1]])
if cfg.TEST.BBOX_REG:
# Apply bounding-box regression deltas
box_deltas = return_dict['bbox_pred'].data.cpu().numpy().squeeze()
# In case there is 1 proposal
box_deltas = box_deltas.reshape([-1, box_deltas.shape[-1]])
if cfg.MODEL.CLS_AGNOSTIC_BBOX_REG:
# Remove predictions for bg class (compat with MSRA code)
box_deltas = box_deltas[:, -4:]
if cfg.TRAIN.BBOX_NORMALIZE_TARGETS_PRECOMPUTED:
# (legacy) Optionally normalize targets by a precomputed mean and stdev
box_deltas = box_deltas.view(-1, 4) * cfg.TRAIN.BBOX_NORMALIZE_STDS \
+ cfg.TRAIN.BBOX_NORMALIZE_MEANS
pred_boxes = box_utils.bbox_transform(boxes, box_deltas, cfg.MODEL.BBOX_REG_WEIGHTS)
pred_boxes = box_utils.clip_tiled_boxes(pred_boxes, im.shape)
if cfg.MODEL.CLS_AGNOSTIC_BBOX_REG:
pred_boxes = np.tile(pred_boxes, (1, scores.shape[1]))
else:
# Simply repeat the boxes, once for each class
pred_boxes = np.tile(boxes, (1, scores.shape[1]))
if cfg.DEDUP_BOXES > 0 and not cfg.MODEL.FASTER_RCNN:
# Map scores and predictions back to the original set of boxes
scores = scores[inv_index, :]
pred_boxes = pred_boxes[inv_index, :]
return scores, pred_boxes, im_scale, return_dict['blob_conv']
def im_detect_bbox_precomp_box(entry, category_id_to_contiguous_id):
"""Prepare the bbox for testing"""
# box in origin image
pred_boxes = entry['precomp_boxes']
scores = entry['precomp_score']
cates = entry['precomp_cate'].astype(np.int32)
contiguous_cate = list()
for cls in cates:
# ipdb.set_trace()
if category_id_to_contiguous_id.get(cls) is None:
contiguous_cate.append(80)
else:
contiguous_cate.append(category_id_to_contiguous_id[cls])
cates = np.array(contiguous_cate, dtype=cates.dtype)
num_classes = cfg.MODEL.NUM_CLASSES
cls_boxes = [[] for _ in range(num_classes)]
box_sc = np.concatenate([pred_boxes, scores[:, None]], 1)
unique_cates = np.unique(cates)
for c in unique_cates:
if category_id_to_contiguous_id.get(c) is not None:
inds = np.where(cates == c)
cls_boxes[category_id_to_contiguous_id[c]] = box_sc[inds]
if len(cls_boxes[1]) == 0:
cls_boxes[1] = np.empty((0,5), dtype=np.float32)
return scores, pred_boxes, cates, cls_boxes
def im_detect_bbox_aug(model, im, box_proposals=None):
"""Performs bbox detection with test-time augmentations.
Function signature is the same as for im_detect_bbox.
"""
assert not cfg.TEST.BBOX_AUG.SCALE_SIZE_DEP, \
'Size dependent scaling not implemented'
assert not cfg.TEST.BBOX_AUG.SCORE_HEUR == 'UNION' or \
cfg.TEST.BBOX_AUG.COORD_HEUR == 'UNION', \
'Coord heuristic must be union whenever score heuristic is union'
assert not cfg.TEST.BBOX_AUG.COORD_HEUR == 'UNION' or \
cfg.TEST.BBOX_AUG.SCORE_HEUR == 'UNION', \
'Score heuristic must be union whenever coord heuristic is union'
assert not cfg.MODEL.FASTER_RCNN or \
cfg.TEST.BBOX_AUG.SCORE_HEUR == 'UNION', \
'Union heuristic must be used to combine Faster RCNN predictions'
# Collect detections computed under different transformations
scores_ts = []
boxes_ts = []
def add_preds_t(scores_t, boxes_t):
scores_ts.append(scores_t)
boxes_ts.append(boxes_t)
# Perform detection on the horizontally flipped image
if cfg.TEST.BBOX_AUG.H_FLIP:
scores_hf, boxes_hf, _ = im_detect_bbox_hflip(
model,
im,
cfg.TEST.SCALE,
cfg.TEST.MAX_SIZE,
box_proposals=box_proposals
)
add_preds_t(scores_hf, boxes_hf)
# Compute detections at different scales
for scale in cfg.TEST.BBOX_AUG.SCALES:
max_size = cfg.TEST.BBOX_AUG.MAX_SIZE
scores_scl, boxes_scl = im_detect_bbox_scale(
model, im, scale, max_size, box_proposals
)
add_preds_t(scores_scl, boxes_scl)
if cfg.TEST.BBOX_AUG.SCALE_H_FLIP:
scores_scl_hf, boxes_scl_hf = im_detect_bbox_scale(
model, im, scale, max_size, box_proposals, hflip=True
)
add_preds_t(scores_scl_hf, boxes_scl_hf)
# Perform detection at different aspect ratios
for aspect_ratio in cfg.TEST.BBOX_AUG.ASPECT_RATIOS:
scores_ar, boxes_ar = im_detect_bbox_aspect_ratio(
model, im, aspect_ratio, box_proposals
)
add_preds_t(scores_ar, boxes_ar)
if cfg.TEST.BBOX_AUG.ASPECT_RATIO_H_FLIP:
scores_ar_hf, boxes_ar_hf = im_detect_bbox_aspect_ratio(
model, im, aspect_ratio, box_proposals, hflip=True
)
add_preds_t(scores_ar_hf, boxes_ar_hf)
# Compute detections for the original image (identity transform) last to
# ensure that the Caffe2 workspace is populated with blobs corresponding
# to the original image on return (postcondition of im_detect_bbox)
scores_i, boxes_i, im_scale_i, blob_conv_i = im_detect_bbox(
model, im, cfg.TEST.SCALE, cfg.TEST.MAX_SIZE, boxes=box_proposals
)
add_preds_t(scores_i, boxes_i)
# Combine the predicted scores
if cfg.TEST.BBOX_AUG.SCORE_HEUR == 'ID':
scores_c = scores_i
elif cfg.TEST.BBOX_AUG.SCORE_HEUR == 'AVG':
scores_c = np.mean(scores_ts, axis=0)
elif cfg.TEST.BBOX_AUG.SCORE_HEUR == 'UNION':
scores_c = np.vstack(scores_ts)
else:
raise NotImplementedError(
'Score heur {} not supported'.format(cfg.TEST.BBOX_AUG.SCORE_HEUR)
)
# Combine the predicted boxes
if cfg.TEST.BBOX_AUG.COORD_HEUR == 'ID':
boxes_c = boxes_i
elif cfg.TEST.BBOX_AUG.COORD_HEUR == 'AVG':
boxes_c = np.mean(boxes_ts, axis=0)
elif cfg.TEST.BBOX_AUG.COORD_HEUR == 'UNION':
boxes_c = np.vstack(boxes_ts)
else:
raise NotImplementedError(
'Coord heur {} not supported'.format(cfg.TEST.BBOX_AUG.COORD_HEUR)
)
return scores_c, boxes_c, im_scale_i, blob_conv_i
def im_detect_bbox_hflip(
model, im, target_scale, target_max_size, box_proposals=None):
"""Performs bbox detection on the horizontally flipped image.
Function signature is the same as for im_detect_bbox.
"""
# Compute predictions on the flipped image
im_hf = im[:, ::-1, :]
im_width = im.shape[1]
if not cfg.MODEL.FASTER_RCNN:
box_proposals_hf = box_utils.flip_boxes(box_proposals, im_width)
else:
box_proposals_hf = None
scores_hf, boxes_hf, im_scale, _ = im_detect_bbox(
model, im_hf, target_scale, target_max_size, boxes=box_proposals_hf
)
# Invert the detections computed on the flipped image
boxes_inv = box_utils.flip_boxes(boxes_hf, im_width)
return scores_hf, boxes_inv, im_scale
def im_detect_bbox_scale(
model, im, target_scale, target_max_size, box_proposals=None, hflip=False):
"""Computes bbox detections at the given scale.
Returns predictions in the original image space.
"""
if hflip:
scores_scl, boxes_scl, _ = im_detect_bbox_hflip(
model, im, target_scale, target_max_size, box_proposals=box_proposals
)
else:
scores_scl, boxes_scl, _, _ = im_detect_bbox(
model, im, target_scale, target_max_size, boxes=box_proposals
)
return scores_scl, boxes_scl
def im_detect_bbox_aspect_ratio(
model, im, aspect_ratio, box_proposals=None, hflip=False):
"""Computes bbox detections at the given width-relative aspect ratio.
Returns predictions in the original image space.
"""
# Compute predictions on the transformed image
im_ar = image_utils.aspect_ratio_rel(im, aspect_ratio)
if not cfg.MODEL.FASTER_RCNN:
box_proposals_ar = box_utils.aspect_ratio(box_proposals, aspect_ratio)
else:
box_proposals_ar = None
if hflip:
scores_ar, boxes_ar, _ = im_detect_bbox_hflip(
model,
im_ar,
cfg.TEST.SCALE,
cfg.TEST.MAX_SIZE,
box_proposals=box_proposals_ar
)
else:
scores_ar, boxes_ar, _, _ = im_detect_bbox(
model,
im_ar,
cfg.TEST.SCALE,
cfg.TEST.MAX_SIZE,
boxes=box_proposals_ar
)
# Invert the detected boxes
boxes_inv = box_utils.aspect_ratio(boxes_ar, 1.0 / aspect_ratio)
return scores_ar, boxes_inv
def im_detect_mask(model, im_scale, boxes, blob_conv):
"""Infer instance segmentation masks. This function must be called after
im_detect_bbox as it assumes that the Caffe2 workspace is already populated
with the necessary blobs.
Arguments:
model (DetectionModelHelper): the detection model to use
im_scale (list): image blob scales as returned by im_detect_bbox
boxes (ndarray): R x 4 array of bounding box detections (e.g., as
returned by im_detect_bbox)
blob_conv (Variable): base features from the backbone network.
Returns:
pred_masks (ndarray): R x K x M x M array of class specific soft masks
output by the network (must be processed by segm_results to convert
into hard masks in the original image coordinate space)
"""
M = cfg.MRCNN.RESOLUTION
if boxes.shape[0] == 0:
pred_masks = np.zeros((0, M, M), np.float32)
return pred_masks
inputs = {'mask_rois': _get_rois_blob(boxes, im_scale)}
# Add multi-level rois for FPN
if cfg.FPN.MULTILEVEL_ROIS:
_add_multilevel_rois_for_test(inputs, 'mask_rois')
pred_masks = model.module.mask_net(blob_conv, inputs)
pred_masks = pred_masks.data.cpu().numpy().squeeze()
if cfg.MRCNN.CLS_SPECIFIC_MASK:
pred_masks = pred_masks.reshape([-1, cfg.MODEL.NUM_CLASSES, M, M])
else:
pred_masks = pred_masks.reshape([-1, 1, M, M])
return pred_masks
def im_detect_mask_aug(model, im, boxes, im_scale, blob_conv):
"""Performs mask detection with test-time augmentations.
Arguments:
model (DetectionModelHelper): the detection model to use
im (ndarray): BGR image to test
boxes (ndarray): R x 4 array of bounding boxes
im_scale (list): image blob scales as returned by im_detect_bbox
blob_conv (Tensor): base features from the backbone network.
Returns:
masks (ndarray): R x K x M x M array of class specific soft masks
"""
assert not cfg.TEST.MASK_AUG.SCALE_SIZE_DEP, \
'Size dependent scaling not implemented'
# Collect masks computed under different transformations
masks_ts = []
# Compute masks for the original image (identity transform)
masks_i = im_detect_mask(model, im_scale, boxes, blob_conv)
masks_ts.append(masks_i)
# Perform mask detection on the horizontally flipped image
if cfg.TEST.MASK_AUG.H_FLIP:
masks_hf = im_detect_mask_hflip(
model, im, cfg.TEST.SCALE, cfg.TEST.MAX_SIZE, boxes
)
masks_ts.append(masks_hf)
# Compute detections at different scales
for scale in cfg.TEST.MASK_AUG.SCALES:
max_size = cfg.TEST.MASK_AUG.MAX_SIZE
masks_scl = im_detect_mask_scale(model, im, scale, max_size, boxes)
masks_ts.append(masks_scl)
if cfg.TEST.MASK_AUG.SCALE_H_FLIP:
masks_scl_hf = im_detect_mask_scale(
model, im, scale, max_size, boxes, hflip=True
)
masks_ts.append(masks_scl_hf)
# Compute masks at different aspect ratios
for aspect_ratio in cfg.TEST.MASK_AUG.ASPECT_RATIOS:
masks_ar = im_detect_mask_aspect_ratio(model, im, aspect_ratio, boxes)
masks_ts.append(masks_ar)
if cfg.TEST.MASK_AUG.ASPECT_RATIO_H_FLIP:
masks_ar_hf = im_detect_mask_aspect_ratio(
model, im, aspect_ratio, boxes, hflip=True
)
masks_ts.append(masks_ar_hf)
# Combine the predicted soft masks
if cfg.TEST.MASK_AUG.HEUR == 'SOFT_AVG':
masks_c = np.mean(masks_ts, axis=0)
elif cfg.TEST.MASK_AUG.HEUR == 'SOFT_MAX':
masks_c = np.amax(masks_ts, axis=0)
elif cfg.TEST.MASK_AUG.HEUR == 'LOGIT_AVG':
def logit(y):
return -1.0 * np.log((1.0 - y) / np.maximum(y, 1e-20))
logit_masks = [logit(y) for y in masks_ts]
logit_masks = np.mean(logit_masks, axis=0)
masks_c = 1.0 / (1.0 + np.exp(-logit_masks))
else:
raise NotImplementedError(
'Heuristic {} not supported'.format(cfg.TEST.MASK_AUG.HEUR)
)
return masks_c
def im_detect_mask_hflip(model, im, target_scale, target_max_size, boxes):
"""Performs mask detection on the horizontally flipped image.
Function signature is the same as for im_detect_mask_aug.
"""
# Compute the masks for the flipped image
im_hf = im[:, ::-1, :]
boxes_hf = box_utils.flip_boxes(boxes, im.shape[1])
blob_conv, im_scale = im_conv_body_only(model, im_hf, target_scale, target_max_size)
masks_hf = im_detect_mask(model, im_scale, boxes_hf, blob_conv)
# Invert the predicted soft masks
masks_inv = masks_hf[:, :, :, ::-1]
return masks_inv
def im_detect_mask_scale(
model, im, target_scale, target_max_size, boxes, hflip=False):
"""Computes masks at the given scale."""
if hflip:
masks_scl = im_detect_mask_hflip(
model, im, target_scale, target_max_size, boxes
)
else:
blob_conv, im_scale = im_conv_body_only(model, im, target_scale, target_max_size)
masks_scl = im_detect_mask(model, im_scale, boxes, blob_conv)
return masks_scl
def im_detect_mask_aspect_ratio(model, im, aspect_ratio, boxes, hflip=False):
"""Computes mask detections at the given width-relative aspect ratio."""
# Perform mask detection on the transformed image
im_ar = image_utils.aspect_ratio_rel(im, aspect_ratio)
boxes_ar = box_utils.aspect_ratio(boxes, aspect_ratio)
if hflip:
masks_ar = im_detect_mask_hflip(
model, im_ar, cfg.TEST.SCALE, cfg.TEST.MAX_SIZE, boxes_ar
)
else:
blob_conv, im_scale = im_conv_body_only(
model, im_ar, cfg.TEST.SCALE, cfg.TEST.MAX_SIZE
)
masks_ar = im_detect_mask(model, im_scale, boxes_ar, blob_conv)
return masks_ar
def im_detect_keypoints_vcoco(model, im_scale, human_boxes, blob_conv):
"""Infer instance keypoint poses. This function must be called after
im_detect_bbox as it assumes that the Caffe2 workspace is already populated
with the necessary blobs.
Arguments:
model (DetectionModelHelper): the detection model to use
im_scale (list): image blob scales as returned by im_detect_bbox
boxes (ndarray): R x 4 array of bounding box detections (e.g., as
returned by im_detect_bbox)
Returns:
pred_heatmaps (ndarray): R x J x M x M array of keypoint location
logits (softmax inputs) for each of the J keypoint types output
by the network (must be processed by keypoint_results to convert
into point predictions in the original image coordinate space)
"""
M = cfg.KRCNN.HEATMAP_SIZE
if human_boxes.shape[0] == 0:
pred_heatmaps = np.zeros((0, cfg.KRCNN.NUM_KEYPOINTS, M, M), np.float32)
return None, pred_heatmaps
# project boxes to re-sized image size
human_boxes = np.hstack((np.zeros((human_boxes.shape[0], 1), dtype=human_boxes.dtype),
human_boxes * im_scale))
inputs = {'human_boxes': human_boxes}
# Add multi-level rois for FPN
if cfg.FPN.MULTILEVEL_ROIS:
_add_multilevel_rois_for_test(inputs, 'human_boxes')
pred_heatmaps = model.module.vcoco_keypoint_net(blob_conv, inputs)
np_pred_heatmaps = pred_heatmaps.data.cpu().numpy().squeeze()
# In case of 1
if np_pred_heatmaps.ndim == 3:
np_pred_heatmaps = np.expand_dims(np_pred_heatmaps, axis=0)
return pred_heatmaps, np_pred_heatmaps
def keypoint_results_vcoco(cls_boxes, pred_heatmaps):
num_classes = cfg.MODEL.NUM_CLASSES
cls_keyps = [[] for _ in range(num_classes)]
person_idx = keypoint_utils.get_person_class_index()
xy_preds = keypoint_utils.heatmaps_to_keypoints(pred_heatmaps, cls_boxes[person_idx])
# NMS OKS
if cfg.KRCNN.NMS_OKS:
keep = keypoint_utils.nms_oks(xy_preds, cls_boxes[person_idx], 0.3)
xy_preds = xy_preds[keep, :, :]
# ref_boxes = ref_boxes[keep, :]
# pred_heatmaps = pred_heatmaps[keep, :, :, :]
cls_boxes[person_idx] = cls_boxes[person_idx][keep, :]
kps = [xy_preds[i] for i in range(xy_preds.shape[0])]
cls_keyps[person_idx] = kps
return cls_keyps
def im_detect_keypoints(model, im_scale, boxes, blob_conv):
"""Infer instance keypoint poses. This function must be called after
im_detect_bbox as it assumes that the Caffe2 workspace is already populated
with the necessary blobs.
Arguments:
model (DetectionModelHelper): the detection model to use
im_scale (list): image blob scales as returned by im_detect_bbox
boxes (ndarray): R x 4 array of bounding box detections (e.g., as
returned by im_detect_bbox)
Returns:
pred_heatmaps (ndarray): R x J x M x M array of keypoint location
logits (softmax inputs) for each of the J keypoint types output
by the network (must be processed by keypoint_results to convert
into point predictions in the original image coordinate space)
"""
M = cfg.KRCNN.HEATMAP_SIZE
if boxes.shape[0] == 0:
pred_heatmaps = np.zeros((0, cfg.KRCNN.NUM_KEYPOINTS, M, M), np.float32)
return pred_heatmaps
inputs = {'keypoint_rois': _get_rois_blob(boxes, im_scale)}
# Add multi-level rois for FPN
if cfg.FPN.MULTILEVEL_ROIS:
_add_multilevel_rois_for_test(inputs, 'keypoint_rois')
pred_heatmaps = model.module.keypoint_net(blob_conv, inputs)
pred_heatmaps = pred_heatmaps.data.cpu().numpy().squeeze()
# In case of 1
if pred_heatmaps.ndim == 3:
pred_heatmaps = np.expand_dims(pred_heatmaps, axis=0)
return pred_heatmaps
def im_detect_keypoints_aug(model, im, boxes, im_scale, blob_conv):
"""Computes keypoint predictions with test-time augmentations.
Arguments:
model (DetectionModelHelper): the detection model to use
im (ndarray): BGR image to test
boxes (ndarray): R x 4 array of bounding boxes
im_scale (list): image blob scales as returned by im_detect_bbox
blob_conv (Tensor): base features from the backbone network.
Returns:
heatmaps (ndarray): R x J x M x M array of keypoint location logits
"""
# Collect heatmaps predicted under different transformations
heatmaps_ts = []
# Tag predictions computed under downscaling and upscaling transformations
ds_ts = []
us_ts = []
def add_heatmaps_t(heatmaps_t, ds_t=False, us_t=False):
heatmaps_ts.append(heatmaps_t)
ds_ts.append(ds_t)
us_ts.append(us_t)
# Compute the heatmaps for the original image (identity transform)
heatmaps_i = im_detect_keypoints(model, im_scale, boxes, blob_conv)
add_heatmaps_t(heatmaps_i)
# Perform keypoints detection on the horizontally flipped image
if cfg.TEST.KPS_AUG.H_FLIP:
heatmaps_hf = im_detect_keypoints_hflip(
model, im, cfg.TEST.SCALE, cfg.TEST.MAX_SIZE, boxes
)
add_heatmaps_t(heatmaps_hf)
# Compute detections at different scales
for scale in cfg.TEST.KPS_AUG.SCALES:
ds_scl = scale < cfg.TEST.SCALE
us_scl = scale > cfg.TEST.SCALE
heatmaps_scl = im_detect_keypoints_scale(
model, im, scale, cfg.TEST.KPS_AUG.MAX_SIZE, boxes
)
add_heatmaps_t(heatmaps_scl, ds_scl, us_scl)
if cfg.TEST.KPS_AUG.SCALE_H_FLIP:
heatmaps_scl_hf = im_detect_keypoints_scale(
model, im, scale, cfg.TEST.KPS_AUG.MAX_SIZE, boxes, hflip=True
)
add_heatmaps_t(heatmaps_scl_hf, ds_scl, us_scl)
# Compute keypoints at different aspect ratios
for aspect_ratio in cfg.TEST.KPS_AUG.ASPECT_RATIOS:
heatmaps_ar = im_detect_keypoints_aspect_ratio(
model, im, aspect_ratio, boxes
)
add_heatmaps_t(heatmaps_ar)
if cfg.TEST.KPS_AUG.ASPECT_RATIO_H_FLIP:
heatmaps_ar_hf = im_detect_keypoints_aspect_ratio(
model, im, aspect_ratio, boxes, hflip=True
)
add_heatmaps_t(heatmaps_ar_hf)
# Select the heuristic function for combining the heatmaps
if cfg.TEST.KPS_AUG.HEUR == 'HM_AVG':
np_f = np.mean
elif cfg.TEST.KPS_AUG.HEUR == 'HM_MAX':
np_f = np.amax
else:
raise NotImplementedError(
'Heuristic {} not supported'.format(cfg.TEST.KPS_AUG.HEUR)
)
def heur_f(hms_ts):
return np_f(hms_ts, axis=0)
# Combine the heatmaps
if cfg.TEST.KPS_AUG.SCALE_SIZE_DEP:
heatmaps_c = combine_heatmaps_size_dep(
heatmaps_ts, ds_ts, us_ts, boxes, heur_f
)
else:
heatmaps_c = heur_f(heatmaps_ts)
return heatmaps_c
def im_detect_keypoints_hflip(model, im, target_scale, target_max_size, boxes):
"""Computes keypoint predictions on the horizontally flipped image.
Function signature is the same as for im_detect_keypoints_aug.
"""
# Compute keypoints for the flipped image
im_hf = im[:, ::-1, :]
boxes_hf = box_utils.flip_boxes(boxes, im.shape[1])
blob_conv, im_scale = im_conv_body_only(model, im_hf, target_scale, target_max_size)
heatmaps_hf = im_detect_keypoints(model, im_scale, boxes_hf, blob_conv)
# Invert the predicted keypoints
heatmaps_inv = keypoint_utils.flip_heatmaps(heatmaps_hf)
return heatmaps_inv
def im_detect_keypoints_scale(
model, im, target_scale, target_max_size, boxes, hflip=False):
"""Computes keypoint predictions at the given scale."""
if hflip:
heatmaps_scl = im_detect_keypoints_hflip(
model, im, target_scale, target_max_size, boxes
)
else:
blob_conv, im_scale = im_conv_body_only(model, im, target_scale, target_max_size)
heatmaps_scl = im_detect_keypoints(model, im_scale, boxes, blob_conv)
return heatmaps_scl
def im_detect_keypoints_aspect_ratio(
model, im, aspect_ratio, boxes, hflip=False):
"""Detects keypoints at the given width-relative aspect ratio."""
# Perform keypoint detectionon the transformed image
im_ar = image_utils.aspect_ratio_rel(im, aspect_ratio)
boxes_ar = box_utils.aspect_ratio(boxes, aspect_ratio)
if hflip:
heatmaps_ar = im_detect_keypoints_hflip(
model, im_ar, cfg.TEST.SCALE, cfg.TEST.MAX_SIZE, boxes_ar
)
else:
blob_conv, im_scale = im_conv_body_only(
model, im_ar, cfg.TEST.SCALE, cfg.TEST.MAX_SIZE
)
heatmaps_ar = im_detect_keypoints(model, im_scale, boxes_ar, blob_conv)
return heatmaps_ar
def combine_heatmaps_size_dep(hms_ts, ds_ts, us_ts, boxes, heur_f):
"""Combines heatmaps while taking object sizes into account."""
assert len(hms_ts) == len(ds_ts) and len(ds_ts) == len(us_ts), \
'All sets of hms must be tagged with downscaling and upscaling flags'
# Classify objects into small+medium and large based on their box areas
areas = box_utils.boxes_area(boxes)
sm_objs = areas < cfg.TEST.KPS_AUG.AREA_TH
l_objs = areas >= cfg.TEST.KPS_AUG.AREA_TH
# Combine heatmaps computed under different transformations for each object
hms_c = np.zeros_like(hms_ts[0])
for i in range(hms_c.shape[0]):
hms_to_combine = []
for hms_t, ds_t, us_t in zip(hms_ts, ds_ts, us_ts):
# Discard downscaling predictions for small and medium objects
if sm_objs[i] and ds_t:
continue
# Discard upscaling predictions for large objects
if l_objs[i] and us_t:
continue
hms_to_combine.append(hms_t[i])
hms_c[i] = heur_f(hms_to_combine)
return hms_c
def box_results_with_nms_and_limit(scores, boxes): # NOTE: support single-batch
"""Returns bounding-box detection results by thresholding on scores and
applying non-maximum suppression (NMS).
`boxes` has shape (#detections, 4 * #classes), where each row represents
a list of predicted bounding boxes for each of the object classes in the
dataset (including the background class). The detections in each row
originate from the same object proposal.
`scores` has shape (#detection, #classes), where each row represents a list
of object detection confidence scores for each of the object classes in the
dataset (including the background class). `scores[i, j]`` corresponds to the
box at `boxes[i, j * 4:(j + 1) * 4]`.
"""
num_classes = cfg.MODEL.NUM_CLASSES
cls_boxes = [[] for _ in range(num_classes)]
# Apply threshold on detection probabilities and apply NMS
# Skip j = 0, because it's the background class
for j in range(1, num_classes):
inds = np.where(scores[:, j] > cfg.TEST.SCORE_THRESH)[0]
scores_j = scores[inds, j]
boxes_j = boxes[inds, j * 4:(j + 1) * 4]
dets_j = np.hstack((boxes_j, scores_j[:, np.newaxis])).astype(np.float32, copy=False)
if cfg.TEST.SOFT_NMS.ENABLED:
nms_dets, _ = box_utils.soft_nms(
dets_j,
sigma=cfg.TEST.SOFT_NMS.SIGMA,
overlap_thresh=cfg.TEST.NMS,
score_thresh=0.05,
# score_thresh=0.0001,
method=cfg.TEST.SOFT_NMS.METHOD
)
else:
keep = box_utils.nms(dets_j, cfg.TEST.NMS)
nms_dets = dets_j[keep, :]
# Refine the post-NMS boxes using bounding-box voting
if cfg.TEST.BBOX_VOTE.ENABLED:
nms_dets = box_utils.box_voting(
nms_dets,
dets_j,
cfg.TEST.BBOX_VOTE.VOTE_TH,
scoring_method=cfg.TEST.BBOX_VOTE.SCORING_METHOD
)
cls_boxes[j] = nms_dets
# Limit to max_per_image detections **over all classes**
if cfg.TEST.DETECTIONS_PER_IM > 0:
image_scores = np.hstack(
[cls_boxes[j][:, -1] for j in range(1, num_classes)]
)
if len(image_scores) > cfg.TEST.DETECTIONS_PER_IM:
image_thresh = np.sort(image_scores)[-cfg.TEST.DETECTIONS_PER_IM]
for j in range(1, num_classes):
keep = np.where(cls_boxes[j][:, -1] >= image_thresh)[0]
cls_boxes[j] = cls_boxes[j][keep, :]
im_results = np.vstack([cls_boxes[j] for j in range(1, num_classes)])
boxes = im_results[:, :-1]
scores = im_results[:, -1]
return scores, boxes, cls_boxes
def segm_results(cls_boxes, masks, ref_boxes, im_h, im_w):
num_classes = cfg.MODEL.NUM_CLASSES
cls_segms = [[] for _ in range(num_classes)]
mask_ind = 0
# To work around an issue with cv2.resize (it seems to automatically pad
# with repeated border values), we manually zero-pad the masks by 1 pixel
# prior to resizing back to the original image resolution. This prevents
# "top hat" artifacts. We therefore need to expand the reference boxes by an
# appropriate factor.
M = cfg.MRCNN.RESOLUTION
scale = (M + 2.0) / M
ref_boxes = box_utils.expand_boxes(ref_boxes, scale)
ref_boxes = ref_boxes.astype(np.int32)
padded_mask = np.zeros((M + 2, M + 2), dtype=np.float32)
# skip j = 0, because it's the background class
for j in range(1, num_classes):
segms = []
for _ in range(cls_boxes[j].shape[0]):
if cfg.MRCNN.CLS_SPECIFIC_MASK:
padded_mask[1:-1, 1:-1] = masks[mask_ind, j, :, :]
else:
padded_mask[1:-1, 1:-1] = masks[mask_ind, 0, :, :]
ref_box = ref_boxes[mask_ind, :]
w = (ref_box[2] - ref_box[0] + 1)
h = (ref_box[3] - ref_box[1] + 1)
w = np.maximum(w, 1)
h = np.maximum(h, 1)
mask = cv2.resize(padded_mask, (w, h))
mask = np.array(mask > cfg.MRCNN.THRESH_BINARIZE, dtype=np.uint8)
im_mask = np.zeros((im_h, im_w), dtype=np.uint8)
x_0 = max(ref_box[0], 0)
x_1 = min(ref_box[2] + 1, im_w)
y_0 = max(ref_box[1], 0)
y_1 = min(ref_box[3] + 1, im_h)
im_mask[y_0:y_1, x_0:x_1] = mask[
(y_0 - ref_box[1]):(y_1 - ref_box[1]), (x_0 - ref_box[0]):(x_1 - ref_box[0])]
# Get RLE encoding used by the COCO evaluation API
rle = mask_util.encode(np.array(im_mask[:, :, np.newaxis], order='F'))[0]
# For dumping to json, need to decode the byte string.
# https://github.com/cocodataset/cocoapi/issues/70
rle['counts'] = rle['counts'].decode('ascii')
segms.append(rle)
mask_ind += 1
cls_segms[j] = segms
assert mask_ind == masks.shape[0]
return cls_segms
def keypoint_results(cls_boxes, pred_heatmaps, ref_boxes):
num_classes = cfg.MODEL.NUM_CLASSES
cls_keyps = [[] for _ in range(num_classes)]
person_idx = keypoint_utils.get_person_class_index()
xy_preds = keypoint_utils.heatmaps_to_keypoints(pred_heatmaps, ref_boxes)
# NMS OKS
if cfg.KRCNN.NMS_OKS:
keep = keypoint_utils.nms_oks(xy_preds, ref_boxes, 0.3)
xy_preds = xy_preds[keep, :, :]
ref_boxes = ref_boxes[keep, :]
pred_heatmaps = pred_heatmaps[keep, :, :, :]
cls_boxes[person_idx] = cls_boxes[person_idx][keep, :]
kps = [xy_preds[i] for i in range(xy_preds.shape[0])]
cls_keyps[person_idx] = kps
return cls_keyps
def _get_rois_blob(im_rois, im_scale):
"""Converts RoIs into network inputs.
Arguments:
im_rois (ndarray): R x 4 matrix of RoIs in original image coordinates
im_scale_factors (list): scale factors as returned by _get_image_blob
Returns:
blob (ndarray): R x 5 matrix of RoIs in the image pyramid with columns
[level, x1, y1, x2, y2]
"""
rois, levels = _project_im_rois(im_rois, im_scale)
rois_blob = np.hstack((levels, rois))
return rois_blob.astype(np.float32, copy=False)
def _project_im_rois(im_rois, scales):
"""Project image RoIs into the image pyramid built by _get_image_blob.
Arguments:
im_rois (ndarray): R x 4 matrix of RoIs in original image coordinates
scales (list): scale factors as returned by _get_image_blob
Returns:
rois (ndarray): R x 4 matrix of projected RoI coordinates
levels (ndarray): image pyramid levels used by each projected RoI
"""
rois = im_rois.astype(np.float, copy=False) * scales
levels = np.zeros((im_rois.shape[0], 1), dtype=np.int)
return rois, levels
def _add_multilevel_rois_for_test(blobs, name):
"""Distributes a set of RoIs across FPN pyramid levels by creating new level
specific RoI blobs.
Arguments:
blobs (dict): dictionary of blobs
name (str): a key in 'blobs' identifying the source RoI blob
Returns:
[by ref] blobs (dict): new keys named by `name + 'fpn' + level`
are added to dict each with a value that's an R_level x 5 ndarray of
RoIs (see _get_rois_blob for format)
"""
lvl_min = cfg.FPN.ROI_MIN_LEVEL
lvl_max = cfg.FPN.ROI_MAX_LEVEL
lvls = fpn_utils.map_rois_to_fpn_levels(blobs[name][:, 1:5], lvl_min, lvl_max)
fpn_utils.add_multilevel_roi_blobs(
blobs, name, blobs[name], lvls, lvl_min, lvl_max
)
def _get_blobs(im, rois, target_scale, target_max_size):
"""Convert an image and RoIs within that image into network inputs."""
blobs = {}
blobs['data'], im_scale, blobs['im_info'] = \
blob_utils.get_image_blob(im, target_scale, target_max_size)
if rois is not None:
blobs['rois'] = _get_rois_blob(rois, im_scale)
return blobs, im_scale
# -------------------------- HOI ----------------------------
def im_detect_hoi(model, boxes, scores, human_count, im_info, blob_conv, entry=None, vcoco_heatmaps=None):
hoi_blob_in = get_hoi_blob_names(is_training=False)
# im_info.shape = (1, 3) h, w, scale
im_scale = im_info[0, 2]
# project boxes to re-sized image size
hoi_blob_in['boxes'] = np.hstack((np.zeros((boxes.shape[0], 1), dtype=boxes.dtype),
boxes * im_scale))
hoi_blob_in['scores'] = scores
human_index = np.arange(boxes.shape[0])[:human_count]
object_index = np.arange(boxes.shape[0])[human_count:]
interaction_human_inds, interaction_target_object_inds \
= np.repeat(human_index, object_index.size), np.tile(object_index - human_count, human_index.size)
hoi_blob_in['human_index'] = human_index
hoi_blob_in['target_object_index'] = object_index
hoi_blob_in['interaction_human_inds'] = interaction_human_inds
hoi_blob_in['interaction_target_object_inds'] = interaction_target_object_inds
# Add multi-level rois for FPN
if cfg.FPN.MULTILEVEL_ROIS:
_add_multilevel_rois_for_test(hoi_blob_in, 'boxes')
# if no human box is detected, not use hoi_head, just return nan
if human_index.size > 0:
hoi_blob_out = model.module.hoi_net(blob_conv, hoi_blob_in, im_info, vcoco_heatmaps)
# ipdb.set_trace()
# if entry:
# test_hoi_fill_hoi_blob_from_gt(hoi_blob_out, entry, im_scale)
hoi_res = hoi_res_gather(hoi_blob_out, im_scale, entry)
else:
# ToDo: any problem here?
hoi_res = dict(
agents=np.full((1, 4 + cfg.VCOCO.NUM_ACTION_CLASSES), np.nan),
roles=np.full((1, 5 * cfg.VCOCO.NUM_ACTION_CLASSES, cfg.VCOCO.NUM_TARGET_OBJECT_TYPES), np.nan),
)
return hoi_res
def hoi_res_gather(hoi_blob, im_scale, entry=None):
'''
Convert predicted score and location to triplets
:param hoi_blob:
:param im_scale:
:param entry:
:return:
'''
# ToDo: modify comments
num_action_classes = cfg.VCOCO.NUM_ACTION_CLASSES
num_target_object_types = cfg.VCOCO.NUM_TARGET_OBJECT_TYPES
human_action_score = F.sigmoid(hoi_blob['human_action_score']).cpu().numpy()
human_action_bbox_pred = hoi_blob['human_action_bbox_pred'].cpu().numpy()
interaction_action_score = F.sigmoid(hoi_blob['interaction_action_score']).cpu().numpy()
human_score = hoi_blob['scores'][hoi_blob['human_index']]
object_score = hoi_blob['scores'][hoi_blob['target_object_index']]
# scale to original image size when testing
boxes = hoi_blob['boxes'][:, 1:] / im_scale
# For actions don't interact with object, action_score is s_h * s^a_h
# For triplets(interact with objects), action_score is s_h * s_o * s^a_h * g^a_h,o
# we use mask to choose appropriate score
action_mask = np.array(cfg.VCOCO.ACTION_MASK)
triplet_action_mask = np.tile(action_mask.transpose((1, 0)), (human_action_score.shape[0], 1, 1))
# For actions that that do not interact with any object (e.g., smile, run),
# we rely on s^a_h and the interaction output s^a_h_o is not used,
human_action_pair_score = human_score[:, np.newaxis] * human_action_score
# in case there is no role-objects
if hoi_blob['target_object_index'].size > 0:
# transform from (human num, object num, action_num) to
# (human_num*action_num*num_target_object_types, object_num)
interaction_action_score = \
interaction_action_score.reshape(human_score.size, object_score.size, -1).transpose(0, 2, 1)
interaction_action_score = np.repeat(interaction_action_score, num_target_object_types, axis=1
).reshape(-1, object_score.size)
# get target localization term g^a_h,o
target_localization_term = target_localization(boxes, hoi_blob['human_index'],
hoi_blob['target_object_index'], human_action_bbox_pred)
# find the object box that maximizes S^a_h,o
# `for each human / action pair we find the object box that maximizes S_h_o^a`
object_action_score = object_score * interaction_action_score * target_localization_term
choosed_object_inds = np.argmax(object_action_score, axis=-1)
# choose corresponding target_localization_term
target_localization_term = target_localization_term[np.arange(choosed_object_inds.size), choosed_object_inds]
# ToDo: choose top-50
# triplet score S^a_h,o
triplet_action_score = \
np.repeat(human_score, num_action_classes * num_target_object_types) * \
object_score[choosed_object_inds] * \
np.repeat(human_action_score, num_target_object_types, axis=1).ravel() * \
target_localization_term
# transform to (human_num, action_num, num_target_object_types)
triplet_action_score = triplet_action_score.reshape(human_action_score.shape[0], num_action_classes,
num_target_object_types)
# ToDo: thresh
# triplet_action_score[triplet_action_mask <= cfg.TEST.SCORE_THRESH] = np.nan
if entry:
# assert triplet_action_score.shape == entry['gt_role_id'][hoi_blob['human_index']].shape
for i in range(len(triplet_action_score.shape)):
pass
# assert np.all(np.where(triplet_action_score > 0.9)[i] ==
# np.where(entry['gt_role_id'][hoi_blob['human_index']] > -1)[i])
# choose appropriate score
# ToDo: any problem here?
# As not every action that defined interacts with objects will have
# corresponding objects in one image, and triplet_action_score always
# have a object box, should I set a thresh or some method to choose
# score between human_action_pair_score and triplet score???
# OR wrong result will be excluded when calculate AP??
# action_score = np.zeros(human_action_score.shape)
# action_score[human_action_mask == 0] = human_action_pair_score[human_action_mask == 0]
# action_score[human_action_mask == 1] = np.amax(triplet_action_score, axis=-1)[human_action_mask == 1]
# set triplet action score don't interact with object to zero
# triplet_action_score[triplet_action_mask == 0] = np.nan
triplet_action_score[triplet_action_mask == 0] = -1
top_k_value = triplet_action_score.flatten()[
np.argpartition(triplet_action_score, -cfg.VCOCO.KEEP_TOP_NUM, axis=None)[-cfg.VCOCO.KEEP_TOP_NUM]]
triplet_action_score[triplet_action_score <= top_k_value] = np.nan
# get corresponding box of role-objects
choosed_object_inds = choosed_object_inds.reshape(human_action_score.shape[0], num_action_classes,
num_target_object_types)
choosed_objects = boxes[hoi_blob['target_object_index']][choosed_object_inds]
else:
# if there is no object predicted, triplet action score won't used
triplet_action_score = np.full((1, num_action_classes, num_target_object_types), np.nan)
choosed_objects = | np.zeros((1, num_action_classes, num_target_object_types, 4)) | numpy.zeros |
"""
@Project : MachineLearningNoteBooks
@Module : ml_model.py
@Author : HjwGivenLyy [<EMAIL>]
@Created : 1/17/19 1:43 PM
@Desc : LSTM algorithm
"""
import time
import typing
from math import sqrt
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from keras.layers import Dense, LSTM
from keras.models import Sequential
from sklearn.metrics import mean_squared_error
from sklearn.preprocessing import MinMaxScaler
from base import FILE_PATH
from base import evaluation_criteria_model, split_train_test_data
DATA_PATH = FILE_PATH + "data.csv"
np.random.seed(5)
def load_data():
"""get date from file library"""
data = pd.read_csv(DATA_PATH)
rtn = data.values.astype('float32')
return rtn
def get_key_lst_by_value(aim_value, data_dct: dict) -> list:
"""根据字典value值获取key值"""
key_lst = []
for key, value in data_dct.items():
if value == aim_value:
key_lst.append(key)
return key_lst
def load_data_feature_lstm():
"""get date from file library"""
data = pd.read_csv(FILE_PATH)
data.set_index(["year_month"], inplace=True)
data.index.name = 'year_month'
rtn = data.values.astype('float32')
return rtn
def deal_data(data: np.array,
look_back: int = 1) -> typing.Tuple[np.array, np.array]:
"""convert an array of values into a data set matrix"""
data_x, data_y = [], []
for i in range(len(data) - look_back):
data_x.append(data[i:(i + look_back), 0])
data_y.append(data[i + look_back, 0])
return np.array(data_x), | np.array(data_y) | numpy.array |
import numpy as np
import utils.gen_cutouts as gc
from sklearn import metrics
import pandas as pd
import ipdb
import matplotlib
from matplotlib import pyplot as plt
matplotlib.rcParams['mathtext.fontset'] = 'stixsans'
matplotlib.rcParams['font.family'] = 'STIXGeneral'
MEAN_TEMP = 2.726 * (10**6)
DEFAULT_FONT = 24
import os
from global_settings import DATA_PATH, FULL_DATA_PATH, FULL_DATA_LABEL_PATH, CNN_MODEL_OUTPUT_DIR, CACHE_FULLDF, CACHE_MAPPED_HALOS, CACHE_FULLDF_DIST2EDGE_CAL
import os
def prepare_data_class(dir_test, num_frequency=3, get_all_components=False, label_fname="1025_hashalo_freq%03i.npy" % 148,
balanced=False,
suffix=""):
"""
read data from dir_test, and prepare data with different noise level (components)
"""
freqs=[90,148,219]
def _load_help(name_format):
paths = [os.path.join(dir_test, name_format%freq) for freq in freqs]
ret = [np.load(p) for p in paths]
#print(paths)
return ret
# set file names for data
#y_data = np.load(dir_test + "1025_hashalo_freq%03i.npy"%148) # y data (labels)
y_data = np.load(os.path.join(dir_test, label_fname))
y_data[y_data > 1] = 1
y_data = y_data.astype(float)
nsamples = len(y_data)
#load data into dictionary
x_data_all = {}
# load data
k2uk = 1.0e6
Tcmb = 2.726
#load noise (for SPT-3G 1500 sq deg patch, it's [2.8,2.6,6.6]uK-arcmin)
noises = [np.load(os.path.join(dir_test, "noise_1uK-arcmin{}{}.npy".format(s, suffix))) for s in ["_90","_150", "_220"]]
noises = [noises[0]*2.8, noises[1]*2.6, noises[2]*6.6]
#samples has CMB+TSZ
try:
com = ['samples','ksz','ir_pts','rad_pts','dust']
x_data_all['base'] = _load_help("1025_samples_freq%03i{}.npy".format(suffix))
ksz_comp = _load_help("1025_ksz_freq%03i{}.npy".format(suffix))
x_data_all['ksz'] = [x_data_all['base'][i] + ksz_comp[i] for i in range(3)]
ir_comp = _load_help("1025_ir_pts_freq%03i{}.npy".format(suffix))
x_data_all['ir'] = [x_data_all['ksz'][i] + ir_comp[i] for i in range(3)]
rad_comp = _load_help("1025_rad_pts_freq%03i{}.npy".format(suffix))
x_data_all['rad'] = [x_data_all['ir'][i] + rad_comp[i] for i in range(3)]
dust_comp = _load_help("1025_dust_freq%03i{}.npy".format(suffix))
x_data_all['dust'] = [x_data_all['rad'][i] + dust_comp[i] for i in range(3)]
except Exception as err:
print("error: ", err)
print("reading only the composite")
x_data_all['dust'] = _load_help("1025_skymap_freq%03i{}.npy".format(suffix))
#return x_data_all['dust'], y_data
x_data = {}
for com1 in x_data_all.keys():
# add noise
x_data[com1] = np.empty((nsamples,num_frequency,10,10),dtype=np.float64)
if num_frequency == 3:
for i in range(3):
x_data[com1][:,i,:,:] = np.squeeze(x_data_all[com1][i]*k2uk*Tcmb) + noises[i]
else:
x_data[com1][:,0,:,:] = -np.squeeze(x_data_all[com1][2]*k2uk*Tcmb) - noises[2]
x_data[com1][:,0,:,:] += np.squeeze(x_data_all[com1][1]*k2uk*Tcmb) + noises[1]
if num_frequency > 1:
x_data[com1][:,1,:,:] = -np.squeeze(x_data_all[com1][2]*k2uk*Tcmb) - noises[2]
x_data[com1][:,1,:,:] += np.squeeze(x_data_all[com1][0]*k2uk*Tcmb) + noises[0]
if balanced:
n_pos = int(y_data.sum())
idx = np.arange(nsamples)
idx = np.concatenate([idx[y_data==0.0][:n_pos], idx[y_data==1.0]])
x_data = {k: x_data[k][idx] for k in x_data.keys()}
return x_data if get_all_components else x_data['dust'], y_data[idx], idx
return x_data if get_all_components else x_data['dust'], y_data
def prepare_data_class2(dir_test, num_frequency=3, component="skymap", label_fname="1025_hashalo_freq%03i.npy" % 148,
balanced=False,
use_noise=True,
get_test_idx=False,
suffix=""):
"""
read data from dir_test, and prepare data with different noise level (components)
"""
freqs=[90,148,219]
def _load_help(name_format):
paths = [os.path.join(dir_test, name_format%freq) for freq in freqs]
ret = [np.load(p) for p in paths]
#print(paths)
return ret
# set file names for data
y_data = np.load(os.path.join(dir_test, label_fname))
y_data[y_data > 1] = 1
y_data = y_data.astype(float)
nsamples = len(y_data)
#load data into dictionary
x_data_all = {}
# load data
k2uk = 1.0e6
Tcmb = 2.726
#load noise (for SPT-3G 1500 sq deg patch, it's [2.8,2.6,6.6]uK-arcmin)
if use_noise:
noises = [np.load(os.path.join(dir_test, "noise_1uK-arcmin{}{}.npy".format(s, suffix))) for s in ["_90","_150", "_220"]]
noises = [noises[0]*2.8, noises[1]*2.6, noises[2]*6.6]
else:
noises = [0., 0., 0.]
#samples has CMB+TSZ
x_data_all[component] = _load_help("1025_{}_freq%03i{}.npy".format(component, suffix))
x_data = {}
for com1 in x_data_all.keys():
# add noise
x_data[com1] = np.empty((nsamples,num_frequency,10,10),dtype=np.float64)
if num_frequency == 3:
for i in range(3):
x_data[com1][:,i,:,:] = np.squeeze(x_data_all[com1][i]*k2uk*Tcmb) + noises[i]
else:
x_data[com1][:,0,:,:] = -np.squeeze(x_data_all[com1][2]*k2uk*Tcmb) - noises[2]
x_data[com1][:,0,:,:] += np.squeeze(x_data_all[com1][1]*k2uk*Tcmb) + noises[1]
if num_frequency > 1:
x_data[com1][:,1,:,:] = -np.squeeze(x_data_all[com1][2]*k2uk*Tcmb) - noises[2]
x_data[com1][:,1,:,:] += np.squeeze(x_data_all[com1][0]*k2uk*Tcmb) + noises[0]
splits = np.asarray([0.8, 0.2])
splits = np.round(splits / splits.sum() * nsamples).astype(int).cumsum()
split_idx = np.split(np.arange(nsamples),splits[:-1])
x_data, x_test = {k: x_data[k][split_idx[0]] for k in x_data.keys()}, {k: x_data[k][split_idx[-1]] for k in x_data.keys()}
y_data, y_test = y_data[split_idx[0]], y_data[split_idx[-1]]
nsamples = len(y_data)
if balanced:
n_pos = int(y_data.sum())
idx = np.arange(nsamples)
idx = np.concatenate([idx[y_data==0.0][:n_pos], idx[y_data==1.0]])
x_data = {k: x_data[k][idx] for k in x_data.keys()}
if get_test_idx: return x_data[component], y_data[idx], x_test[component], y_test, idx, split_idx[-1]
return x_data[component], y_data[idx], x_test[component], y_test, idx
if get_test_idx:
return x_data[component], y_data, x_test[component], y_test, split_idx[-1]
return x_data[component], y_data, x_test[component], y_test
class DataHolder:
def __init__(self, data, label, idx):
self.data = data
self.label = label
self.idx = idx
def get(self, which, ratio=None, incl_idx=False):
curr_idx = self.idx[which]
y_data = self.label[curr_idx]
if ratio is not None:
n_pos = int(y_data.sum())
idx = np.arange(len(y_data))
idx = np.concatenate([idx[y_data == 0.0][:int(ratio * n_pos)], idx[y_data == 1.0]])
curr_idx = curr_idx[idx]
if incl_idx:
return self.data[curr_idx], self.label[curr_idx], curr_idx
return self.data[curr_idx], self.label[curr_idx]
class DataGetter:
WO_DUST_MAPPING = ("dust", ['samples', 'ksz', 'ir_pts', 'rad_pts'])
def __init__(self, dir_test, overlap=False):
self.dir_test = dir_test
self.overlap = overlap
self.halocounter = gc.HalosCounter(overlap=overlap)
df = self.halocounter.get_complete_df()
if overlap:
df = df.reset_index().rename(columns={"index": "cutout_id"})
test_idx = df[(df['cutout_ra'] >= 0.5 * 90) & (df['cutout_dec'] > 0.5 * 90)].index
train_idx = df[~df.index.isin(test_idx)].index
n_samples = len(train_idx)
splits = np.asarray([0.65, 0.1])
splits = np.round(splits / splits.sum() * n_samples).astype(int).cumsum()
#print(splits)
#print(train_idx, len(train_idx))
split_idx = np.split(train_idx, splits[:-1])
split_idx = [split_idx[0], split_idx[1], test_idx]
#print(len(split_idx[0]), len(split_idx[1]), len(split_idx[2]))
#print(split_idx[0], split_idx[1], split_idx[2])
else:
n_samples = df.shape[0]
splits = np.asarray([0.7, 0.1, 0.2]) # (train ratio, valid ratio, test ratio)
splits = np.round(splits / splits.sum() * n_samples).astype(int).cumsum()
split_idx = np.split(np.arange(n_samples), splits[:-1])
#print(list(map(len, split_idx)), df.shape)
self.split_idx = {"train":split_idx[0], 'valid':split_idx[1], 'test':split_idx[2]}
pass
def get_labels(self, thres=5e13, which='full'):
if isinstance(thres, float) or isinstance(thres, int):
thres = ("%0.0e"%(thres)).replace("+", "")
label_fname = {"5e13": "m5e13_z0.25_y.npy", "2e14":"m2e14_z0.5_y.npy"}[thres]
y_data = np.load(os.path.join(self.dir_test, label_fname))
y_data[y_data > 1] = 1
y_data = y_data.astype(float)
if which == 'full': return y_data
return y_data[self.split_idx[which]]
def get_data(self, component, thres=5e13, use_noise=False, num_frequency=3):
suffix = "_overlap" if self.overlap else ""
freqs = [90, 148, 219]
def _load_help(name_format):
paths = [os.path.join(self.dir_test, name_format % freq) for freq in freqs]
return [np.load(p) for p in paths]
y_data = self.get_labels(thres, which='full')
nsamples = len(y_data)
x_data_all = {}
# load data
k2uk = 1.0e6
Tcmb = 2.726
# load noise (for SPT-3G 1500 sq deg patch, it's [2.8,2.6,6.6]uK-arcmin)
if use_noise:
noises = [np.load(os.path.join(self.dir_test, "noise_1uK-arcmin{}{}.npy".format(s, suffix))) for s in
["_90", "_150", "_220"]]
noises = [noises[0] * 2.8, noises[1] * 2.6, noises[2] * 6.6]
else:
noises = [0., 0., 0.]
# samples has CMB+TSZ
if isinstance(component, str):
x_data_all[component] = _load_help("1025_{}_freq%03i{}.npy".format(component, suffix))
elif isinstance(component,tuple):
component, lc = component
x_data_all[component] = _load_help("1025_{}_freq%03i{}.npy".format(lc[0], suffix))
for cc in lc[1:]:
tx = _load_help("1025_{}_freq%03i{}.npy".format(cc, suffix))
assert len(tx) == len(x_data_all[component])
x_data_all[component] = [x_data_all[component][i] + tx[i] for i in range(len(tx))]
x_data = {}
for com1 in x_data_all.keys():
# add noise
x_data[com1] = np.empty((nsamples, num_frequency, 10, 10), dtype=np.float64)
if num_frequency == 3:
for i in range(3):
x_data[com1][:, i, :, :] = np.squeeze(x_data_all[com1][i] * k2uk * Tcmb) + noises[i]
else:
x_data[com1][:, 0, :, :] = -np.squeeze(x_data_all[com1][2] * k2uk * Tcmb) - noises[2]
x_data[com1][:, 0, :, :] += np.squeeze(x_data_all[com1][1] * k2uk * Tcmb) + noises[1]
if num_frequency > 1:
x_data[com1][:, 1, :, :] = -np.squeeze(x_data_all[com1][2] * k2uk * Tcmb) - noises[2]
x_data[com1][:, 1, :, :] += np.squeeze(x_data_all[com1][0] * k2uk * Tcmb) + noises[0]
return DataHolder(x_data[component], y_data, self.split_idx)
def get_full_df(self):
df = self.halocounter.get_complete_df().reset_index().rename(columns={"index":"cutout_id"})
for k, idx in self.split_idx.items():
df.loc[idx, "which_set"] = k
return df
class IndexMapper:
#map cutout_id to the index location
def __init__(self, overlap=False):
self.overlap = overlap
o = DataGetter(overlap)
self.split_idx = o.split_idx
self.full_idx = gc.HalosCounter(overlap=overlap).get_complete_df().index
self.split_idx = {"train":self.full_idx[self.split_idx['train']],
"valid":self.full_idx[self.split_idx['valid']],
"test":self.full_idx[self.split_idx['test']],
"full":self.full_idx}
self.reverse_idx = {'train':{}, 'valid':{}, 'test':{}, 'full':{}}
for k in self.split_idx.keys():
idx = self.split_idx[k]
for i, d in enumerate(idx):
self.reverse_idx[k][d] = i
def get(self, i, which='test'):
return self.reverse_idx[which][i]
def eval(models, get_test_func, model_weight_paths=None, pred_only=False):
y_prob_avg = None
y_probs = []
x_test, y_test = get_test_func()
num_nets = len(models)
for i in range(num_nets):
model = models[i]
if model_weight_paths is not None:
model.load_weights(model_weight_paths[i])
y_prob = model.predict(x_test)
y_probs.append(y_prob.squeeze())
y_prob_avg = y_prob if y_prob_avg is None else y_prob + y_prob_avg
y_probs = np.stack(y_probs, 0)
y_prob_avg /= float(num_nets)
y_pred = (y_prob_avg > 0.5).astype('int32').squeeze() # binary classification
if pred_only:
return y_prob_avg
return summary_results_class(y_probs, y_test), y_pred, y_prob_avg, y_test, x_test, models
def summary_results_class(y_probs, y_test, threshold=0.5, log_roc=False, show_f1=True):
"""
y_probs: a list of independent predictions
y_test: true label
threshold: predict the image to be positive when the prediction > threshold
"""
# measure confusion matrix
if show_f1:
threshold, maxf1 = get_F1(y_probs.mean(0),y_test)
threshold = threshold - 1e-7
cm = pd.DataFrame(0, index=['pred0','pred1'], columns=['actual0','actual1'])
cm_std = pd.DataFrame(0, index=['pred0', 'pred1'], columns=['actual0', 'actual1'])
#memorizing the number of samples in each case (true positive, false positive, etc.)
tp_rate, tn_rate = np.zeros(len(y_probs)), np.zeros(len(y_probs))
for actual_label in range(2):
for pred_label in range(2):
cnt = np.zeros(len(y_probs))
for i in range(len(y_probs)):
cnt[i] = np.sum(np.logical_and(y_test == actual_label, (y_probs[i] > threshold) == pred_label))
cm.loc["pred%d"%pred_label,"actual%d"%actual_label] = cnt.mean()
cm_std.loc["pred%d" % pred_label, "actual%d" % actual_label] = cnt.std()
print("Confusion matrix (cnts)",cm)
print("Confusion matrix (stdev of cnts)", cm_std)
#Measuring the true positive and negative rates,
#since the false positive/negative rates are always 1 minus these,
#they are not printed and have the same standard deviation
for i in range(len(y_probs)):
pred_i = y_probs[i] > threshold
tp_rate[i] = np.sum(np.logical_and(y_test==1, pred_i==1)) / np.sum(pred_i==1)
tn_rate[i] = np.sum(np.logical_and(y_test==0, pred_i==0)) / np.sum(pred_i == 0)
print("True Positive (rate): {0:0.4f} ({1:0.4f})".format(tp_rate.mean(), tp_rate.std()))
print("True Negative (rate): {0:0.4f} ({1:0.4f})".format(tn_rate.mean(), tn_rate.std()))
def vertical_averaging_help(xs, ys, xlen=101):
"""
Interpolate the ROC curves to the same grid on x-axis
"""
numnets = len(xs)
xvals = np.linspace(0,1,xlen)
yinterp = np.zeros((len(ys),len(xvals)))
for i in range(numnets):
yinterp[i,:] = np.interp(xvals, xs[i], ys[i])
return xvals, yinterp
fprs, tprs = [], []
for i in range(len(y_probs)):
fpr, tpr, _ = metrics.roc_curve(y_test, y_probs[i], pos_label=1)
fprs.append(fpr)
tprs.append(tpr)
new_fprs, new_tprs = vertical_averaging_help(fprs, tprs)
# measure Area Under Curve (AUC)
y_prob_mean = y_probs.mean(0)
auc = metrics.roc_auc_score(y_test, y_prob_mean)
try:
auc = metrics.roc_auc_score(y_test, y_prob_mean)
print()
print("AUC:", auc)
except Exception as err:
print(err)
auc = np.nan
#Take the percentiles for of the ROC curves at each point
new_tpr_mean, new_tpr_5, new_tpr_95 = new_tprs.mean(0), np.percentile(new_tprs, 95, 0), np.percentile(new_tprs, 5, 0)
# plot ROC curve
plt.figure(figsize=[12,8])
lw = 2
plt.plot(new_fprs, new_tpr_mean, color='darkorange',
lw=lw, label='ROC curve (area = %0.4f)' % metrics.auc(new_fprs, new_tpr_mean))
if len(y_probs) > 1:
plt.plot(new_fprs, new_tpr_95, color='yellow',
lw=lw, label='ROC curve 5%s (area = %0.4f)' % ("%", metrics.auc(new_fprs, new_tpr_95)))
plt.plot(new_fprs, new_tpr_5, color='yellow',
lw=lw, label='ROC curve 95%s (area = %0.4f)' % ("%", metrics.auc(new_fprs, new_tpr_5)))
plt.plot([0, 1], [0, 1], color='navy', lw=lw, linestyle='--')
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.05])
plt.xlabel('False Positive Rate', fontsize=16)
plt.ylabel('True Positive Rate', fontsize=16)
plt.title('Receiver operating characteristic')
plt.legend(loc="lower right", fontsize=16)
plt.grid()
plt.show()
#If log flag is set, plot also the log of the ROC curves within some reasonable range
if log_roc:
# plot ROC curve
plt.figure(figsize=[12,8])
lw = 2
plt.plot(np.log(new_fprs), np.log(new_tpr_mean), color='darkorange',
lw=lw, label='ROC curve (area = %0.4f)' % metrics.auc(new_fprs, new_tpr_mean))
if len(y_probs) > 1:
plt.plot(np.log(new_fprs), np.log(new_tpr_95), color='yellow',
lw=lw, label='ROC curve 5%s (area = %0.4f)' % ("%", metrics.auc(new_fprs, new_tpr_95)))
plt.plot(np.log(new_fprs), np.log(new_tpr_5), color='yellow',
lw=lw, label='ROC curve 95%s (area = %0.4f)' % ("%", metrics.auc(new_fprs, new_tpr_5)))
#plt.plot([0, 1], [0, 1], color='navy', lw=lw, linestyle='--')
plt.xlim([-5, -3])
plt.ylim([-1, 0.2])
plt.xlabel('Log False Positive Rate', fontsize=16)
plt.ylabel('Log True Positive Rate', fontsize=16)
plt.title('Receiver operating characteristic')
plt.legend(loc="lower right", fontsize=16)
plt.grid()
plt.show()
return (auc,maxf1) if show_f1 else auc, (tp_rate.mean(),tn_rate.mean()), new_fprs, new_tprs
#=======================================================Prediction criteria here
import numpy as np
import pickle
import pandas as pd
from scipy.optimize import minimize
def _get_Fbeta(y, yhat, beta=1., debug=False, get_raw=False):
TP = ((y == 1) & (yhat == 1)).sum()
FP = ((y == 0) & (yhat == 1)).sum()
TN = ((y == 0) & (yhat == 0)).sum()
FN = ((y == 1) & (yhat == 0)).sum()
if debug: print("TP: {}, FP:{}, TN:{}, FN:{}".format(TP, FP, TN, FN))
if FP+TP == 0 or TP + FN==0 or TP == 0: return -1.
precision = (TP) / (FP + TP).astype(float)
recall = (TP) / (TP + FN).astype(float)
if debug:
print("TP={}; FP={}; TN={}; FN={}; precision={};recall={}".format(((y == 1) & (yhat == 1)).sum(),
((y == 0) & (yhat == 1)).sum(),
((y == 0) & (yhat == 0)).sum(),
((y == 1) & (yhat == 0)).sum(), precision,
recall))
if get_raw: return precision, recall, (1 + beta ** 2) * (precision * recall) / (beta * precision + recall)
return (1 + beta ** 2) * (precision * recall) / (beta * precision + recall)
def get_F1(y_pred, y, xlim=None, method='cnn', mass_thresh='5e13', plot=True,
save_path=None, xlabel=None, get_raw=False, font=DEFAULT_FONT):
plt.rcParams.update({'font.size': font})
if xlim is None:
xlim = (0, 0.997)
x = np.linspace(xlim[0], xlim[1])
elif isinstance(xlim, tuple):
x = np.linspace(xlim[0], xlim[1])
else:
x = xlim
Fscore = lambda x: _get_Fbeta(y, (y_pred > x).astype(int))
y = np.asarray([Fscore(xx) for xx in x]).clip(0.)
if plot:
f = plt.figure(figsize=(8, 5))
plt.plot(x, y)
plt.xlim(x[0], x[-1])
if xlabel:
plt.xlabel(xlabel)
else:
plt.xlabel('%s Threshold' % ("CNN Prob" if method == 'cnn' else "MF S/N"))
plt.ylabel('F1 Score', fontsize=font)
if save_path is not None: plt.savefig(save_path, dpi=500, bbox_inches='tight')
plt.show(block=True)
if get_raw: return x, y
return x[np.argmax(y)], np.max(y)
def stack_F1(xmf, ymf, xcnn, ycnn, save_path=None, font=DEFAULT_FONT, title="", hist={}, nxbins=20):
lns = []
fig = plt.figure(figsize=(8,5))
ax1 = fig.add_subplot(111)
ax2 = ax1.twiny()
plt.rcParams.update({'font.size': font})
lns.extend(ax1.plot(xmf, ymf, label='MF', color='purple'))
ax1.set_xlabel("MF S/N Ratio")
ax1.set_ylabel("F1 Score")
lns.extend(ax2.plot(xcnn, ycnn, label='CNN', color='black'))
ax2.set_xlabel("CNN Prob")
import matplotlib.patches as mpatches
if 'MF' in hist:
assert 'CNN' in hist
ax12 = ax1.twinx()
bins = np.linspace(*ax1.get_xlim(), num=nxbins)
#ax12.set_ylim(0, 100000)
ax12.hist(hist['MF'][~pd.isnull(hist['MF'])], alpha=0.3, bins=bins, color='purple',
#weights=np.ones(len(hist['MF']))/len(hist['MF'])
)
lns.append(mpatches.Patch(color='purple', label='MF Score Dist.', alpha=0.3))
ax12.set_yscale('log')
ax22 = ax2.twinx()
bins = np.linspace(*ax2.get_xlim(), num=nxbins)
#ax22.set_ylim(0, 100000)
ax22.hist(hist['CNN'], alpha=0.3, bins=bins, color='black',
#weights=np.ones(len(hist['CNN']))/len(hist['CNN'])
)
lns.append(mpatches.Patch(color='black', label='CNN Score Dist.', alpha=0.3))
ax22.set_yscale('log')
if ax12.get_ylim()[1] > ax22.get_ylim()[1]:
ax22.set_ylim(ax12.get_ylim())
else:
ax12.set_ylim(ax22.get_ylim())
#ylim1 = ax12.get_ylim()
#ylim2 = ax22.get_ylim()
#ylim = (min(ylim1[0], ylim2[0]), max(ylim1[1], ylim2[1]))
#print(ylim)
#for _temp in [ax12, ax22]:
#_temp.set_ylim(ylim)
#_temp.set_yscale('log')
ax12.set_ylabel("Counts", fontsize=font)
#ax12.set_yscale('log')
labs = [l.get_label() for l in lns]
plt.title(title)
plt.legend(lns, labs, loc='lower center', prop={"size":font-8})
if save_path is not None: plt.savefig(save_path, dpi=500, bbox_inches="tight")
return
def get_F1_CNN_and_MF(vdf, col_cnn='score_wdust (trained>%s)', col_mf ='mf_peaksig', col_label='Truth(>%s)',
mass_thresh='5e13', method='and', save_path=None, font=DEFAULT_FONT):
plt.rcParams.update({'font.size': font})
import itertools
if mass_thresh == '5e13':
cnn_range = (0, 0.997)
mf_range = (3, 15)
else:
#cnn_range = (0.4, 0.8)
#mf_range = (3, 15)
cnn_range = (0.2, 0.9)
mf_range = (3, 25)
cnn_range = np.linspace(cnn_range[0], cnn_range[1])
mf_range = np.linspace(mf_range[0], mf_range[1])
#criteria = itertools.product(cnn_range, mf_range)
criteria = [(c,m) for c in cnn_range for m in mf_range]
if method == 'or':
Fscore = lambda cc, mc: _get_Fbeta(vdf[col_label], ((vdf[col_cnn] > cc) | (vdf[col_mf] > mc)).astype(int))
elif method == 'and':
Fscore = lambda cc, mc: _get_Fbeta(vdf[col_label], ((vdf[col_cnn] > cc) & (vdf[col_mf] > mc)).astype(int))
elif method == 'rankproduct':
rnk_cnn = vdf[col_cnn].rank() / len(vdf)
rnk_mf = vdf[col_mf].rank() / float(vdf[col_mf].count())
return get_F1(rnk_cnn * rnk_mf, vdf[col_label], xlim=(0.7, .985), xlabel='rank product', save_path=save_path, font=font)
cnn_x = np.asarray([c[0] for c in criteria])
mf_y = np.asarray([c[1] for c in criteria])
vals = np.asarray([Fscore(cc,mc) for cc,mc in criteria])
cm = plt.cm.get_cmap('YlGn')
sc = plt.scatter(cnn_x, mf_y, c=vals, cmap=cm)
plt.scatter(*criteria[np.argmax(vals)], s=100, c='black', marker='x', linewidth=3)
cbar = plt.colorbar(sc)
cbar.set_label("F1 Score", rotation=270, labelpad=20)
plt.xlabel("CNN Threshold")
plt.ylabel("MF Threshold")
if save_path is not None: plt.savefig(save_path, dpi=500, bbox_inches="tight")
return criteria[np.argmax(vals)], | np.max(vals) | numpy.max |
import cv2
import os
from facenet_pytorch import InceptionResnetV1, fixed_image_standardization
import torch
from PIL import Image
from torchvision import transforms,get_image_backend
import numpy as np
import math
size_m = 30
size_n = 30
os.environ["CUDA_VISIBLE_DEVICES"] = '1'
workers = 0 if os.name == 'nt' else 8
device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
print('Running on device: {}'.format(device))
resnet = InceptionResnetV1(pretrained='vggface2').eval().to(device)
trans = transforms.Compose([
transforms.Resize((160,160)),
np.float32,
transforms.ToTensor(),
fixed_image_standardization
])
def detect(img, cascade):
rects = cascade.detectMultiScale(img, scaleFactor=1.3, minNeighbors=4, minSize=(30, 30),
flags=cv2.CASCADE_SCALE_IMAGE)
if len(rects) == 0:
return []
rects[:, 2:] += rects[:, :2]
return rects
def pil_loader(path):
with open(path, 'rb') as f:
with Image.open(f) as img:
return img.convert('RGB')
def distance(embeddings1, embeddings2, distance_metric=1):
if distance_metric==0:
# Euclidian distance
diff = np.subtract(embeddings1, embeddings2)
dist = np.sum(np.square(diff),1)
elif distance_metric==1:
# Distance based on cosine similarity
dot = np.sum(np.multiply(embeddings1, embeddings2), axis=1)
norm = | np.linalg.norm(embeddings1, axis=1) | numpy.linalg.norm |
"""Model wrapper class for performing GradCam visualization with a ShowAndTellModel."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from im2txt import show_and_tell_model
from im2txt.inference_utils import inference_wrapper_base
import numpy as np
import matplotlib
# Fix to run remotely (with no display)
# matplotlib.use('agg')
import tensorflow as tf
import PIL.Image
from matplotlib import pylab as P
import pickle
import matplotlib.pyplot as plt
plt.switch_backend('agg')
import matplotlib.colors as mcolors
import os
import os.path as osp
slim=tf.contrib.slim
import scipy
import sys
sys.path.append('gradcam')
def transparent_cmap(cmap, N=255):
"Copy colormap and set alpha values"
mycmap = cmap
mycmap._init()
mycmap._lut[:,-1] = np.linspace(0, 0.8, N+4)
return mycmap
class GradCamWrapper(inference_wrapper_base.InferenceWrapperBase):
"""Model wrapper class for performing inference with a ShowAndTellModel."""
def __init__(self):
super(GradCamWrapper, self).__init__()
def build_model(self, model_config):
model = show_and_tell_model.ShowAndTellModel(model_config, mode="gradcam")
model.build()
return model
def process_image(self, sess, encoded_image, input_feed, filename, vocab, word_index=1, word_id=None, save_path=None):
graph = tf.get_default_graph()
softmax = sess.run(fetches=["softmax:0"], feed_dict={"image_feed:0": encoded_image, "input_feed:0": input_feed})
logits = graph.get_tensor_by_name('softmax:0')
neuron_selector = tf.placeholder(tf.int32)
neuron_pred = logits[0,word_index][neuron_selector]
pred_max = np.argmax(softmax[0][0][word_index])
if word_id != None:
print('%s\tpredicted: %s with prob %f , given: %s with prob %.10f' % (filename, vocab.id_to_word(pred_max), np.max(softmax[0][0][word_index]), vocab.id_to_word(word_id), softmax[0][0][word_index][word_id]))
pred_max = word_id
from grad_cam import GradCam
grad_cam = GradCam(graph, sess, neuron_pred, graph.get_tensor_by_name('concat:0'), conv_layer = graph.get_tensor_by_name('InceptionV3/InceptionV3/Mixed_7c/concat:0'))
input_image = PIL.Image.open(filename)
input_image = input_image.convert('RGB')
im = | np.asarray(input_image) | numpy.asarray |
# Copyright 2019 The TensorNetwork 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.
import math
import numpy as np
import torch
from tensornetwork.backends.pytorch import decompositions
def test_expected_shapes():
val = torch.zeros((2, 3, 4, 5))
u, s, vh, _ = decompositions.svd(torch, val, 2)
assert u.shape == (2, 3, 6)
assert s.shape == (6,)
np.testing.assert_allclose(s, np.zeros(6))
assert vh.shape == (6, 4, 5)
def test_expected_shapes_qr():
val = torch.zeros((2, 3, 4, 5))
for non_negative_diagonal in [True, False]:
q, r = decompositions.qr(torch, val, 2, non_negative_diagonal)
assert q.shape == (2, 3, 6)
assert r.shape == (6, 4, 5)
def test_expected_shapes_rq():
val = torch.zeros((2, 3, 4, 5))
for non_negative_diagonal in [True, False]:
r, q = decompositions.rq(torch, val, 2, non_negative_diagonal)
assert r.shape == (2, 3, 6)
assert q.shape == (6, 4, 5)
def test_rq():
random_matrix = torch.rand([10, 10], dtype=torch.float64)
for non_negative_diagonal in [True, False]:
r, q = decompositions.rq(torch, random_matrix, 1, non_negative_diagonal)
np.testing.assert_allclose(r.mm(q), random_matrix)
def test_qr():
random_matrix = torch.rand([10, 10], dtype=torch.float64)
for non_negative_diagonal in [True, False]:
q, r = decompositions.rq(torch, random_matrix, 1, non_negative_diagonal)
np.testing.assert_allclose(q.mm(r), random_matrix)
def test_max_singular_values():
np.random.seed(2018)
random_matrix = np.random.rand(10, 10)
unitary1, _, unitary2 = np.linalg.svd(random_matrix)
singular_values = np.array(range(10))
val = unitary1.dot(np.diag(singular_values).dot(unitary2.T))
u, s, vh, trun = decompositions.svd(
torch, torch.tensor(val), 1, max_singular_values=7)
assert u.shape == (10, 7)
assert s.shape == (7,)
np.testing.assert_array_almost_equal(s, np.arange(9, 2, -1))
assert vh.shape == (7, 10)
np.testing.assert_array_almost_equal(trun, np.arange(2, -1, -1))
def test_max_truncation_error():
np.random.seed(2019)
random_matrix = np.random.rand(10, 10)
unitary1, _, unitary2 = | np.linalg.svd(random_matrix) | numpy.linalg.svd |
import numpy as np
import pandas as pd
import xarray as xr
import Grid
from timeit import default_timer as timer
err = 1e-5
limit = 1e5
alpha = 0.005
# ---- BASIC FUNCTIONS ----
def ur(mI, mB):
return (mB * mI) / (mB + mI)
def nu(gBB):
return np.sqrt(gBB)
def epsilon(kx, ky, kz, mB):
return (kx**2 + ky**2 + kz**2) / (2 * mB)
def omegak(kx, ky, kz, mB, n0, gBB):
ep = epsilon(kx, ky, kz, mB)
return np.sqrt(ep * (ep + 2 * gBB * n0))
def Omega(kx, ky, kz, DP, mI, mB, n0, gBB):
return omegak(kx, ky, kz, mB, n0, gBB) + (kx**2 + ky**2 + kz**2) / (2 * mI) - kz * DP / mI
def Wk(kx, ky, kz, mB, n0, gBB):
# old_settings = np.seterr(); np.seterr(all='ignore')
output = np.sqrt(epsilon(kx, ky, kz, mB) / omegak(kx, ky, kz, mB, n0, gBB))
# np.seterr(**old_settings)
return output
def g(kxg, kyg, kzg, dVk, aIBi, mI, mB, n0, gBB):
# gives bare interaction strength constant
old_settings = np.seterr(); np.seterr(all='ignore')
mR = ur(mI, mB)
integrand = 2 * mR / (kxg**2 + kyg**2 + kzg**2)
mask = np.isinf(integrand); integrand[mask] = 0
np.seterr(**old_settings)
return 1 / ((mR / (2 * np.pi)) * aIBi - np.sum(integrand) * dVk)
# ---- CALCULATION HELPER FUNCTIONS ----
def ImpMomGrid_from_PhononMomGrid(kgrid, P):
kx = kgrid.getArray('kx'); ky = kgrid.getArray('ky'); kz = kgrid.getArray('kz')
PI_x = -1 * kx; PI_y = -1 * ky; PI_z = P - kz
PI_x_ord = np.flip(PI_x, 0); PI_y_ord = np.flip(PI_y, 0); PI_z_ord = np.flip(PI_z, 0)
PIgrid = Grid.Grid('CARTESIAN_3D')
PIgrid.initArray_premade('kx', PI_x_ord); PIgrid.initArray_premade('ky', PI_y_ord); PIgrid.initArray_premade('kz', PI_z_ord)
return PIgrid
def FWHM(x, f):
# f is function of x -> f(x)
if np.abs(np.max(f) - np.min(f)) < 1e-2:
return 0
else:
D = f - np.max(f) / 2
indices = np.where(D > 0)[0]
return x[indices[-1]] - x[indices[0]]
def xyzDist_ProjSlices(phonon_pos_dist, phonon_mom_dist, grid_size_args, grid_diff_args):
nxyz = phonon_pos_dist
nPB = phonon_mom_dist
Nx, Ny, Nz = grid_size_args
dx, dy, dz, dkx, dky, dkz = grid_diff_args
# slice directions
nPB_x_slice = nPB[:, Ny // 2, Nz // 2]
nPB_y_slice = nPB[Nx // 2, :, Nz // 2]
nPB_z_slice = nPB[Nx // 2, Ny // 2, :]
nPB_xz_slice = nPB[:, Ny // 2, :]
nPB_xy_slice = nPB[:, :, Nz // 2]
nxyz_x_slice = nxyz[:, Ny // 2, Nz // 2]
nxyz_y_slice = nxyz[Nx // 2, :, Nz // 2]
nxyz_z_slice = nxyz[Nx // 2, Ny // 2, :]
nxyz_xz_slice = nxyz[:, Ny // 2, :]
nxyz_xy_slice = nxyz[:, :, Nz // 2]
nPI_x_slice = np.flip(nPB_x_slice, 0)
nPI_y_slice = np.flip(nPB_y_slice, 0)
nPI_z_slice = np.flip(nPB_z_slice, 0)
nPI_xz_slice = np.flip(np.flip(nPB_xz_slice, 0), 1)
nPI_xy_slice = np.flip(np.flip(nPB_xy_slice, 0), 1)
pos_slices = nxyz_x_slice, nxyz_y_slice, nxyz_z_slice
mom_slices = nPB_x_slice, nPB_y_slice, nPB_z_slice, nPI_x_slice, nPI_y_slice, nPI_z_slice
cont_slices = nxyz_xz_slice, nxyz_xy_slice, nPB_xz_slice, nPB_xy_slice, nPI_xz_slice, nPI_xy_slice
# integrate directions
nPB_x = np.sum(nPB, axis=(1, 2)) * dky * dkz
nPB_y = np.sum(nPB, axis=(0, 2)) * dkx * dkz
nPB_z = np.sum(nPB, axis=(0, 1)) * dkx * dky
nxyz_x = np.sum(nxyz, axis=(1, 2)) * dy * dz
nxyz_y = np.sum(nxyz, axis=(0, 2)) * dx * dz
nxyz_z = np.sum(nxyz, axis=(0, 1)) * dx * dy
nPI_x = np.flip(nPB_x, 0)
nPI_y = np.flip(nPB_y, 0)
nPI_z = np.flip(nPB_z, 0)
pos_integration = nxyz_x, nxyz_y, nxyz_z
mom_integration = nPB_x, nPB_y, nPB_z, nPI_x, nPI_y, nPI_z
return pos_slices, mom_slices, cont_slices, pos_integration, mom_integration
# @profile
def xyzDist_To_magDist(kgrid, phonon_mom_dist, P):
nPB = phonon_mom_dist
# kgrid is the Cartesian grid upon which the 3D matrix nPB is defined -> nPB is the phonon momentum distribution in kx,ky,kz
kxg, kyg, kzg = np.meshgrid(kgrid.getArray('kx'), kgrid.getArray('ky'), kgrid.getArray('kz'), indexing='ij', sparse=True) # can optimize speed by taking this from the coherent_state precalculation
dVk_const = kgrid.dV()[0] * (2 * np.pi)**(3)
PB = np.sqrt(kxg**2 + kyg**2 + kzg**2)
PI = np.sqrt((-kxg)**2 + (-kyg)**2 + (P - kzg)**2)
PB_flat = PB.reshape(PB.size)
PI_flat = PI.reshape(PI.size)
nPB_flat = nPB.reshape(nPB.size)
PB_series = pd.Series(nPB_flat, index=PB_flat)
PI_series = pd.Series(nPB_flat, index=PI_flat)
nPBm_unique = PB_series.groupby(PB_series.index).sum() * dVk_const
nPIm_unique = PI_series.groupby(PI_series.index).sum() * dVk_const
PB_unique = nPBm_unique.keys().values
PI_unique = nPIm_unique.keys().values
nPBm_cum = nPBm_unique.cumsum()
nPIm_cum = nPIm_unique.cumsum()
# CDF and PDF pre-processing
PBm_Vec, dPBm = np.linspace(0, np.max(PB_unique), 200, retstep=True)
PIm_Vec, dPIm = np.linspace(0, np.max(PI_unique), 200, retstep=True)
nPBm_cum_smooth = nPBm_cum.groupby(pd.cut(x=nPBm_cum.index, bins=PBm_Vec, right=True, include_lowest=True)).mean()
nPIm_cum_smooth = nPIm_cum.groupby(pd.cut(x=nPIm_cum.index, bins=PIm_Vec, right=True, include_lowest=True)).mean()
# one less bin than bin edge so consider each bin average to correspond to left bin edge and throw out last (rightmost) edge
PBm_Vec = PBm_Vec[0:-1]
PIm_Vec = PIm_Vec[0:-1]
# smooth data has NaNs in it from bins that don't contain any points - forward fill these holes
PBmapping = dict(zip(nPBm_cum_smooth.keys(), PBm_Vec))
PImapping = dict(zip(nPIm_cum_smooth.keys(), PIm_Vec))
# PBmapping = pd.Series(PBm_Vec, index=nPBm_cum_smooth.keys())
# PImapping = pd.Series(PIm_Vec, index=nPIm_cum_smooth.keys())
nPBm_cum_smooth = nPBm_cum_smooth.rename(PBmapping).fillna(method='ffill')
nPIm_cum_smooth = nPIm_cum_smooth.rename(PImapping).fillna(method='ffill')
nPBm_Vec = np.gradient(nPBm_cum_smooth, dPBm)
nPIm_Vec = np.gradient(nPIm_cum_smooth, dPIm)
mag_dist_List = [PBm_Vec, nPBm_Vec, PIm_Vec, nPIm_Vec]
return mag_dist_List
# ---- DATA GENERATION ----
# @profile
def quenchDynamics_DataGeneration(cParams, gParams, sParams, toggleDict):
#
# do not run this inside CoherentState or PolaronHamiltonian
import CoherentState
import PolaronHamiltonian
# takes parameters, performs dynamics, and outputs desired observables
[P, aIBi] = cParams
[xgrid, kgrid, tgrid] = gParams
[mI, mB, n0, gBB] = sParams
# grid unpacking
x = xgrid.getArray('x'); y = xgrid.getArray('y'); z = xgrid.getArray('z')
dx = xgrid.arrays_diff['x']; dy = xgrid.arrays_diff['y']; dz = xgrid.arrays_diff['z']
Nx, Ny, Nz = len(xgrid.getArray('x')), len(xgrid.getArray('y')), len(xgrid.getArray('z'))
kx = kgrid.getArray('kx'); ky = kgrid.getArray('ky'); kz = kgrid.getArray('kz')
dkx = kgrid.arrays_diff['kx']; dky = kgrid.arrays_diff['ky']; dkz = kgrid.arrays_diff['kz']
grid_size_args = Nx, Ny, Nz
grid_diff_args = dx, dy, dz, dkx, dky, dkz
NGridPoints = xgrid.size()
k_max = np.sqrt(np.max(kx)**2 + np.max(ky)**2 + np.max(kz)**2)
# Initialization CoherentState
cs = CoherentState.CoherentState(kgrid, xgrid)
# Initialization PolaronHamiltonian
Params = [P, aIBi, mI, mB, n0, gBB]
ham = PolaronHamiltonian.PolaronHamiltonian(cs, Params, toggleDict)
# calculate some parameters
nu_const = nu(gBB)
gIB = g(cs.kxg, cs.kyg, cs.kzg, cs.dVk[0], aIBi, mI, mB, n0, gBB)
# Other book-keeping
PIgrid = ImpMomGrid_from_PhononMomGrid(kgrid, P)
PB_x = kx; PB_y = ky; PB_z = kz
PI_x = PIgrid.getArray('kx'); PI_y = PIgrid.getArray('ky'); PI_z = PIgrid.getArray('kz')
# Time evolution
# Choose coarsegrain step size
maxfac = 1
largest_coarsegrain = 1
for f in range(1, largest_coarsegrain + 1, 1):
if tgrid.size % f == 0:
maxfac = f
tgrid_coarse = np.zeros(int(tgrid.size / maxfac), dtype=float)
cind = 0
print('Time grid size: {0}, Coarse grain step: {1}'.format(tgrid.size, maxfac))
# Initialize observable Data Arrays
PB_da = xr.DataArray(np.full(tgrid.size, np.nan, dtype=float), coords=[tgrid], dims=['t'])
NB_da = xr.DataArray(np.full(tgrid.size, np.nan, dtype=float), coords=[tgrid], dims=['t'])
ReDynOv_da = xr.DataArray(np.full(tgrid.size, np.nan, dtype=float), coords=[tgrid], dims=['t'])
ImDynOv_da = xr.DataArray(np.full(tgrid.size, np.nan, dtype=float), coords=[tgrid], dims=['t'])
Phase_da = xr.DataArray(np.full(tgrid.size, np.nan, dtype=float), coords=[tgrid], dims=['t'])
phonon_mom_k0deltapeak_da = xr.DataArray(np.full(tgrid.size, np.nan, dtype=float), coords=[tgrid], dims=['t'])
# Initialize distribution Data Arrays
nxyz_x_slice_da = xr.DataArray(np.full((tgrid.size, x.size), np.nan, dtype=float), coords=[tgrid, x], dims=['t', 'x']); nxyz_y_slice_da = xr.DataArray(np.full((tgrid.size, y.size), np.nan, dtype=float), coords=[tgrid, y], dims=['t', 'y']); nxyz_z_slice_da = xr.DataArray(np.full((tgrid.size, z.size), np.nan, dtype=float), coords=[tgrid, z], dims=['t', 'z'])
nxyz_xz_slice_da = xr.DataArray(np.full((tgrid.size, x.size, z.size), np.nan, dtype=float), coords=[tgrid, x, z], dims=['t', 'x', 'z']); nxyz_xy_slice_da = xr.DataArray(np.full((tgrid.size, x.size, y.size), np.nan, dtype=float), coords=[tgrid, x, y], dims=['t', 'x', 'y'])
nxyz_x_da = xr.DataArray(np.full((tgrid.size, x.size), np.nan, dtype=float), coords=[tgrid, x], dims=['t', 'x']); nxyz_y_da = xr.DataArray(np.full((tgrid.size, y.size), np.nan, dtype=float), coords=[tgrid, y], dims=['t', 'y']); nxyz_z_da = xr.DataArray(np.full((tgrid.size, z.size), np.nan, dtype=float), coords=[tgrid, z], dims=['t', 'z'])
nPB_x_slice_da = xr.DataArray(np.full((tgrid.size, PB_x.size), np.nan, dtype=float), coords=[tgrid, PB_x], dims=['t', 'PB_x']); nPB_y_slice_da = xr.DataArray(np.full((tgrid.size, PB_y.size), np.nan, dtype=float), coords=[tgrid, PB_y], dims=['t', 'PB_y']); nPB_z_slice_da = xr.DataArray(np.full((tgrid.size, PB_z.size), np.nan, dtype=float), coords=[tgrid, PB_z], dims=['t', 'PB_z'])
nPB_xz_slice_da = xr.DataArray(np.full((tgrid.size, PB_x.size, PB_z.size), np.nan, dtype=float), coords=[tgrid, PB_x, PB_z], dims=['t', 'PB_x', 'PB_z']); nPB_xy_slice_da = xr.DataArray(np.full((tgrid.size, PB_x.size, PB_y.size), np.nan, dtype=float), coords=[tgrid, PB_x, PB_y], dims=['t', 'PB_x', 'PB_y'])
nPB_x_da = xr.DataArray(np.full((tgrid.size, PB_x.size), np.nan, dtype=float), coords=[tgrid, PB_x], dims=['t', 'PB_x']); nPB_y_da = xr.DataArray(np.full((tgrid.size, PB_y.size), np.nan, dtype=float), coords=[tgrid, PB_y], dims=['t', 'PB_y']); nPB_z_da = xr.DataArray(np.full((tgrid.size, PB_z.size), np.nan, dtype=float), coords=[tgrid, PB_z], dims=['t', 'PB_z'])
nPI_x_slice_da = xr.DataArray(np.full((tgrid.size, PI_x.size), np.nan, dtype=float), coords=[tgrid, PI_x], dims=['t', 'PI_x']); nPI_y_slice_da = xr.DataArray( | np.full((tgrid.size, PI_y.size), np.nan, dtype=float) | numpy.full |
# -*- coding: utf-8 -*-
"""
Created on Tue Nov 17 19:37:53 2020
@author: <NAME>
"""
import numpy as np
from stereo_calibration import StereoCalibration
chess_size = (8,6)
square_size = 2.5 # cm
camera_model = StereoCalibration(chess_size, square_size)
Camera_L_Matrix = np.array(camera_model['M_L'])
Camera_R_Matrix = np.array(camera_model['M_R'])
distorsionL = np.array(camera_model['distL'])
distorsionR = np.array(camera_model['distR'])
R = np.array(camera_model['R'])
T = np.array(camera_model['T'])
Proj_L = np.array(camera_model['Proj_L'])
Proj_R = np.array(camera_model['Proj_R'])
Rotation_L = np.array(camera_model['rotation_vec_L'])
Rotation_R = np.array(camera_model['rotation_vec_R'])
np.save("SmartCar/Calibration/matrices/Camera_L_Matrix.npy", Camera_L_Matrix)
np.save("SmartCar/Calibration/matrices/Camera_R_Matrix.npy", Camera_R_Matrix)
np.save("SmartCar/Calibration/matrices/distorsionL.npy", distorsionL)
np.save("SmartCar/Calibration/matrices/distorsionR.npy", distorsionR)
np.save("SmartCar/Calibration/matrices/R.npy", R)
np.save("SmartCar/Calibration/matrices/T.npy", T)
np.save("SmartCar/Calibration/matrices/Proj_L.npy", Proj_L)
| np.save("SmartCar/Calibration/matrices/Proj_R.npy", Proj_R) | numpy.save |
# coding: utf-8
# In[1]:
#get_ipython().magic(u'matplotlib inline')
# In[2]:
import os
import numpy as np
np.set_printoptions(precision=3, linewidth=250)
import scipy as sp
from scipy import signal, io
import pandas as pd
import statsmodels.formula.api as smf
import matplotlib.pyplot as plt
import matplotlib.cm as cm
from sklearn.manifold import MDS
from sklearn import svm, cross_validation, metrics
from sklearn import discriminant_analysis
import sys
sys.path.append('/mnt/Other/DEAP/tmp/')
from dyconnmap.fc import PLI, PAC
from dyconnmap import bands
from dyconnmap import tvfcg_cfc
from dyconnmap import analytic_signal
# ### Process subject
# In[3]:
subject_id = 1
basedir = "/mnt/Other/DEAP/data/data_preprocessed_python/"
data = np.load(basedir + "/s01.dat")
eeg = data['data']
n_trials, n_channels, n_samples = eeg.shape
# In[4]:
fname = ("/mnt/Other/DEAP/data/data_preprocessed_python/s%02d.dat" % (subject_id))
data = np.load(fname)
eeg = data['data'][:, 0:32, :]
# In[5]:
n_trials, n_channels, n_samples = np.shape(eeg)
print(n_trials, n_channels, n_samples)
# In[7]:
trial1 = eeg[0, :]
# In[91]:
p_range = (1, 20)
a_range = (1, 60)
dp = 0.5
da = 0.5
f_phases = np.arange(p_range[0], p_range[1], dp)
f_amps = np.arange(a_range[0], a_range[1], da)
P = len(f_phases)
A = len(f_amps)
# In[92]:
print(f_phases)
print(f_amps)
# In[ ]:
comodu = np.zeros((P, A))
estimator = PLI(0, 0)
for p in range(P):
f_lo = (f_phases[p], f_phases[p] + dp)
_, hilberted_lo, _ = analytic_signal(trial1, f_lo)
phase = np.angle(hilberted_lo)
for a in range(A):
f_hi = (f_amps[a], f_amps[a] + da)
_, hilberted_hi, _ = analytic_signal(trial1, f_hi)
amp = np.abs(hilberted_hi)
_, hilberted_lohi, _ = analytic_signal(amp, f_lo)
phase_lohi = np.angle(hilberted_lohi)
ts, avg = estimator.estimate_pair(phase, phase_lohi)
comodu[p, a] = avg
# In[ ]:
np.shape(comodu)
# In[ ]:
np.shape(f_phases)
# In[ ]:
| np.shape(f_amps) | numpy.shape |
# -*- coding: utf-8 -*-
__author__ = '<NAME>'
import os, itertools,copy
import numpy as np
from scipy import sparse
from scipy.spatial.distance import cdist
from ase.neighborlist import NeighborList,natural_cutoffs
from ase.data import atomic_masses_iupac2016,atomic_numbers
from pymatgen.symmetry.analyzer import PointGroupAnalyzer as pga
from pymove import Structure
from pymove.io import read,write,output_geo
"""
It will be better overall to break these complex operations into classes
which will be easier to use and have a more intuitive API.
"""
def get_molecules(struct, mult=1.05):
"""
Arguments
---------
mult: float
Multiplicative factor to use for natural_cutoffs
Returns
-------
List of Structure objects for each molecule identified using the smallest
molecule representation.
"""
molecule_list = find_molecules(struct, mult=mult)
molecule_struct_list = extract_molecules(struct, molecule_list,
mult=mult)
if len(molecule_struct_list) == 0:
raise Exception("No molecules found for structure {}."
.format(struct.struct_id))
return molecule_struct_list
def find_molecules(struct, mult=1.05):
"""
Identify molecular fragments in struct
Returns
-------
List of lists for atom index of each molecule
"""
atoms = struct.get_ase_atoms()
cutOff = natural_cutoffs(atoms, mult=mult)
## Skin=0.3 is not a great parameter, but it seems to work pretty well
## for mulicule identification. In addition, it's not the same affect as
## change the mult value because it's a constant addition to all
## covalent bonds.
neighborList = NeighborList(cutOff, skin=0.0)
neighborList.update(atoms)
matrix = neighborList.get_connectivity_matrix()
n_components, component_list = sparse.csgraph.connected_components(matrix)
molecule_list = [np.where(component_list == x)[0]
for x in range(n_components)]
return molecule_list
def extract_molecules(struct, molecule_list, whole_molecules=True,
mult=1.05):
""" Converts list of list of coordinates to Structures """
# Information from original structure
geo = struct.get_geo_array()
elements = struct.geometry['element']
# Extract molecule geometries from original
molecule_geo_list = [geo[x,:] for x in molecule_list]
molecule_ele_list = [elements[x] for x in molecule_list]
# Convert geometry to Structure
molecule_struct_list = [Structure() for x in range(len(molecule_list))]
[x.from_geo_array(molecule_geo_list[i],molecule_ele_list[i])
for i,x in enumerate(molecule_struct_list)]
# Construct whole molecule representations
if whole_molecules:
molecule_struct_list = [construct_smallest_molecule(struct,x,mult=mult)
for x in molecule_struct_list]
return molecule_struct_list
def construct_smallest_molecule(struct,molecule_struct,mult=1.05):
""" Make molecule smallest possible w.r.t. structure pbc
Purpose
-------
Sometimes structures are given where molecules are not fully connected
because all atomic coordinates have been brought into the cell. This
function minimizes the distance between coordinates in the molecule
w.r.t. the pbc of the input structure such that the molecule's final
geometric coordinates are fully connected.
"""
# Check if molecule is fully connected
mol_index_list = find_molecules(molecule_struct,mult=mult)
if len(mol_index_list) == 1:
return molecule_struct
# New method: construct supercell and pick molecule fragment with the same
# length as the input. Doesn't matter which one is chosen because they are
# all images of the same molecule. The final positions will be augmented
# to have COM inside the cell.
temp = copy.deepcopy(molecule_struct)
temp.set_lattice_vectors(struct.get_lattice_vectors())
# Loop through creating supercells of increasing size to find smallest
# molecule representation efficiently.
success = False
for i in range(2,9):
# Construct ixixi supercell about the origin
supercell = construct_supercell_by_molecule(temp, supercell=i,
include_negative=False)
# Get atom index for molecules from supercell
result = find_molecules(supercell, mult=mult)
# Get molecule structure
molecule_list = extract_molecules(supercell, result,
mult=mult,
whole_molecules=False)
# Identify whole molecule in non-periodic cell
frag_list = [len(find_molecules(x, mult=mult)) for x in molecule_list]
try:
whole_molecule_idx = frag_list.index(1)
success = True
break
except:
pass
if success == False:
raise Exception('No whole represenation was found for the molecule '+
'without periodic boundary conditions. Please check the ' +
'structure for any irregularities. If none are found, then '+
'improvements probably need to be made to the source code to '+
'work for this structure.')
whole_molecule = molecule_list[whole_molecule_idx]
geo = whole_molecule.get_geo_array()
# Ensure COM of final molecule is inside cell and smallest possibe
# w.r.t. lattice sites.
COM = com(whole_molecule)
# Lattice vector array as columns
lattice_vectors = np.array(struct.get_lattice_vectors()).T
lattice_vectors_i = np.linalg.inv(lattice_vectors)
relative_COM = np.dot(lattice_vectors_i, COM)
# First make COM all positive w.r.t. lattice vectors
trans_idx = relative_COM < -0.0001
trans_vector = np.dot(lattice_vectors, trans_idx[:,None])
geo = geo + trans_vector.T
# Recompute COM then move inside of cell
temp_molecule = Structure()
temp_molecule.from_geo_array(geo, whole_molecule.geometry['element'])
COM = com(temp_molecule)
relative_COM = np.dot(lattice_vectors_i, COM)
trans_idx = relative_COM > 0.99
trans_vector = np.dot(lattice_vectors, trans_idx[:,None])
geo = geo - trans_vector.T
# Set final molecule
final_molecule = Structure()
final_molecule.from_geo_array(geo, whole_molecule.geometry['element'])
final_molecule.struct_id = molecule_struct.struct_id
return final_molecule
def reconstruct_with_whole_molecules(struct):
""" Build smallest molecule representation of struct.
"""
rstruct = Structure()
rstruct.set_lattice_vectors(struct.get_lattice_vectors())
molecule_struct_list = get_molecules(struct)
for molecule_struct in molecule_struct_list:
geo_array = molecule_struct.get_geo_array()
ele = molecule_struct.geometry['element']
for i,coord in enumerate(geo_array):
rstruct.append(coord[0],coord[1],coord[2],ele[i])
return rstruct
def com(struct):
"""
Calculates center of mass of the system.
"""
geo_array = struct.get_geo_array()
element_list = struct.geometry['element']
mass = np.array([atomic_masses_iupac2016[atomic_numbers[x]]
for x in element_list]).reshape(-1)
total = np.sum(mass)
com = np.sum(geo_array*mass[:,None], axis=0)
com = com / total
return com
def find_translation_vector(f1, f2, lattice_vectors):
"""
From a set of a lattice vectors, find the lattice vector that minimizes the
distance between fragment 1, f1, and fragment 2, f2.
"""
base_atom = len(f1)
full_geo = np.concatenate([f1, f2], axis=0)
x_dist = np.min(calc_euclidean_dist_vectorized(full_geo[:,0][:,None]
)[0:base_atom,base_atom:])
y_dist = np.min(calc_euclidean_dist_vectorized(full_geo[:,1][:,None]
)[0:base_atom,base_atom:])
z_dist = np.min(calc_euclidean_dist_vectorized(full_geo[:,2][:,None]
)[0:base_atom,base_atom:])
min_dist = np.array([[x_dist,y_dist,z_dist]])
closest_vector = np.argmin(cdist(min_dist, lattice_vectors))
# Decide to add or subtract lattice vector
sign = 1
f1_mean = np.mean(f1,axis=0)
f2_mean = np.mean(f2,axis=0)
mean_dist = f2_mean - f1_mean
plus = mean_dist + lattice_vectors[closest_vector,:]
minus = mean_dist - lattice_vectors[closest_vector,:]
if np.sum(np.abs(plus)) > np.sum(np.abs(minus)):
sign = -1
return closest_vector,sign
def get_molecule_orientation(molecule_struct):
"""
Not quite sure what this function needs to do yet, but the indexing for
pymatgen principal axes is shown correctly
Arguments
---------
Pymatgen molecule object
"""
molp = molecule_struct.get_pymatgen_structure()
PGA = pga(molp)
pa = PGA.principal_axes
# axes = np.zeros(3,3)
# for i,row in enumerate(pa):
# axes[i,:] = row
return pa
def get_orr_tensor(struct):
""" Gets orientation of all molecules in the struct """
molecule_list = get_molecules(struct)
orr_tensor = np.zeros((len(molecule_list),3,3))
for i,molecule_struct in enumerate(molecule_list):
orr_tensor[i,:,:] = get_molecule_orientation(molecule_struct)
return orr_tensor
def get_COM(struct):
""" Gets COM positions for all molecules in the structure
Returns
-------
List of all COM positions in the structure
"""
molecule_list = get_molecules(struct)
COM_array = np.zeros((len(molecule_list),3))
for i,molecule_struct in enumerate(molecule_list):
COM_array[i,:] = calc_COM(molecule_struct)
return COM_array
def calc_COM(molecule_struct):
""" COM calculation for Molecule Structure """
geometry = molecule_struct.get_geo_array()
elements = molecule_struct.geometry['element']
element_numbers = [atomic_numbers[x] for x in elements]
element_masses = np.array([atomic_masses_iupac2016[x]
for x in element_numbers])[:,None]
weighted_geometry = geometry*element_masses
return np.sum(weighted_geometry,axis=0) / np.sum(element_masses)
def construct_supercell_by_molecule(struct,supercell=3,include_negative=False):
""" Construct supercell w.r.t. the molecules in the current structure
Arguments
---------
struct: Structure
Structure object that was used to construct the molecules argument,
Must have lattice parameters.
supercell: int
Dimension of supercell (int x int x int)
"""
if supercell <= 0:
raise Exception('Input to construct_supercell must be larger than 0')
lattice_vectors = struct.get_lattice_vectors()
if lattice_vectors == False:
raise Exception('Input Structure object to function '+
'construct_supercell must have lattice parameters.')
lattice_vectors = np.array(lattice_vectors)
# Array for translations to construct supercell
translation_vectors = get_translation_vectors(supercell, lattice_vectors,
include_negative=include_negative)
# Initialize supercell
supercell_struct = Structure()
supercell_struct.set_lattice_vectors(lattice_vectors*supercell)
geo_array = struct.get_geo_array()
# Broadcast geometry with translation vectors
supercell_geo = geo_array[:,None,:] + translation_vectors
num_atoms,num_tr,dim = supercell_geo.shape
# Getting correct indexing for supercell tensor
# Indexing scheme for molecules in first unit cell
depth_index = num_tr*dim*np.arange(num_atoms)
# Broadcast across three dimensions
column_values = np.arange(3)
unit_cell_index = depth_index[:,None] + column_values
# Index scheme for the next unit cells in supercell
molecule_index = np.arange(num_tr)*3
# Broadcast initial molecule across next moleculess
supercell_index = molecule_index[:,None,None] + unit_cell_index
supercell_index = supercell_index.reshape(num_tr*num_atoms, 3)
supercell_geo = np.take(supercell_geo, supercell_index)
###########################################################################
# For example, this gets the original geometry #
###########################################################################
# depth_index = num_tr*dim*np.arange(num_atoms)
# column_values = np.arange(3)
# broadcasted_index = depth_index[:,None] + column_values
###########################################################################
num_ele = translation_vectors.shape[0]
supercell_elements = np.tile(struct.geometry['element'],num_ele)
supercell_struct.from_geo_array(supercell_geo, supercell_elements)
return supercell_struct
def construct_molecular_index_for_supercell(num_atoms, num_tr,
combine_mol=True):
'''
Arguments
---------
num_atoms: int
Number of atoms in the original structure
num_tr: int
Number of translation vectors applied to construct supercell
combine_mol: bool
True: molecules should be combined, such is the case when the desired
output is a single supercell strcutre
False: molecules should not be combined, such is the case when trying
to identify the smallest representation of the molecule w/o
pbc
'''
# Cartesian space
dim = 3
# Getting correct indexing for supercell tensor
# Indexing scheme for molecules in first unit cell
depth_index = num_tr*dim*np.arange(num_atoms)
# Broadcast across three dimensions
column_values = np.arange(3)
unit_cell_index = depth_index[:,None] + column_values
# Index scheme for the next unit cells in supercell
molecule_index = np.arange(num_tr)*3
# Broadcast initial molecule across next moleculess
supercell_index = molecule_index[:,None,None] + unit_cell_index
if combine_mol == True:
return supercell_index.reshape(num_tr*num_atoms, 3)
return supercell_index
def construct_orientation_supercell(struct,supercell,include_negative=False,
molecule_list=[]):
""" Construct supercell of only molecular orientations
Arguments
---------
struct: Structure
Structure object that was used to construct the molecules argument,
Must have lattice parameters.
supercell: int
Dimension of supercell (int x int x int)
molecule_lsit: list of Structures
Can pass in argument if molecule_list was pre-computed
"""
if supercell <= 0:
raise Exception('Input to construct_supercell must be larger than 0')
lattice_vectors = struct.get_lattice_vectors()
if lattice_vectors == False:
raise Exception('Input Structure object to function '+
'construct_supercell must have lattice parameters.')
lattice_vectors = np.array(lattice_vectors)
translation_vectors = get_translation_vectors(supercell, lattice_vectors,
include_negative)
if len(molecule_list) == 0:
molecule_list = get_molecules(struct)
num_atoms = struct.get_geo_array().shape[0]
num_molecules = len(molecule_list)
num_tr = len(translation_vectors)
COM_array = np.array([calc_COM(molecule_struct)
for molecule_struct in molecule_list])
orientation_tensor = np.array([get_molecule_orientation(mol)
for mol in molecule_list])
orientation_tensor = orientation_tensor + COM_array[:,None,:]
orientation_tensor = orientation_tensor[:,None,:] + \
translation_vectors[:,None,:]
orientation_tensor = orientation_tensor.reshape(num_molecules*num_tr,3,3)
COM_tensor = COM_array[:,None,:] + translation_vectors
COM_tensor = COM_tensor.reshape(num_molecules*num_tr,3)
return orientation_tensor,COM_tensor
def get_translation_vectors(supercell, lattice_vectors, include_negative=False):
''' Returns all translation vectors for a given supercell size
Arguments
---------
supercell: int
Value of the supercell dimension. Example 3x3x3
lattice_vectors: Numpy array
Lattice vectors in row format where each lattice vector is one row.
include_negative: bool
False: Only supercells in the positive direction will be constructed
True: Supercells in the positive and negative direction will be
constructed.
If true, constructs the supercell about the origin of the original
Returns: Numpy array of all translation vectors in row format.
'''
if include_negative:
list_range = [x for x in range(-supercell+1,supercell,1)]
else:
list_range = [x for x in range(supercell)]
tr = list(itertools.product(list_range,list_range,list_range))
translation_vectors = np.dot(tr,lattice_vectors)
return translation_vectors
def compute_motif(struct, supercell=3, include_negative=True, num_mol=12):
""" Computes deg_array which is translated into specific packing motifs
Arguments
---------
supercell: int
Value of the supercell dimension. Example 3x3x3
include_negative: bool
False: Only supercells in the positive direction will be constructed
True: Supercells in the positive and negative direction will be
constructed. This will double the number constructed.
num_mol: int >= 4
Number of nearest neighbor molecules to be used for motif
identification. Should be at least four.
"""
deg_array,plane_deg_min = compute_deg_array(struct, supercell,
include_negative, num_mol=num_mol)
return motif_definitions(deg_array,plane_deg_min)
def compute_deg_array(struct, supercell=3, include_negative=True, num_mol=12):
molecule_list = get_molecules(struct)
orientation_tensor,COM_array = construct_orientation_supercell(struct,
supercell,include_negative,
molecule_list)
deg_array,plane_deg_min = compute_orientation_difference(orientation_tensor,COM_array,
molecule_list,num_mol=num_mol)
return deg_array,plane_deg_min
def motif_definitions(deg_array,plane_deg_min):
""" Defines how motifs are identified from the deg_array
Arguments
---------
deg_array: np.array (n,)
Vector of orientation differences found
plane_deg_min: np.array
Vector of orientation differences found for molecules that were
co-planar to the reference molecule
"""
num_mol = 4
if len(deg_array) < num_mol:
raise Exception("For proper motif identification, the input array "+
"must have a length of at least 6. "+
"Input was {}.".format(deg_array))
# Only use first for neighbors
def_deg = deg_array[0:num_mol]
sheet_like = def_deg < 9
# Be more stringent for sheet classification
if np.sum(deg_array < 9) == len(deg_array):
return 'Sheet'
else:
if sheet_like[0] == True:
if sheet_like[1] != True:
if np.sum(plane_deg_min < 9) == len(plane_deg_min):
return 'Sheet'
return 'Sandwich'
else:
# if np.sum(plane_deg_min < 9) == len(plane_deg_min):
# return 'Gamma'
return 'Gamma'
else:
# Have at least 1 co-planar in first 4 neighbors
if np.sum(sheet_like) == 1:
if np.sum(plane_deg_min < 9) == len(plane_deg_min):
return 'Sheet'
return 'Herringbone'
def compute_orientation_difference(orientation_tensor,COM_array,molecule_list,
num_mol=12):
"""
Computes difference between molecular orientation bewteen the molecular
plane and the principal axes of num_mol from the supercell closest to
the molecule in molecule_list closest to the origin.
Arguments
---------
num_mol: int
Should be approximately equal to the number of molecules per unit cell
multiplied by supercell
"""
centerd_orientation_tensor = orientation_tensor - COM_array[:,None]
index_min,index_dist_min = find_nearest_COM(COM_array,
reference=molecule_list, num_mol=num_mol)
molecule_struct_min = molecule_list[index_min]
origin_orientation = centerd_orientation_tensor[index_dist_min]
# Compute norm to molecular plane of original molecule
plane_norm = get_molecule_orientation(molecule_struct_min)[0,:]
original_COM_array = np.array([calc_COM(x) for x in molecule_list])
COM_test = original_COM_array[index_min,:]
origin_COM = COM_array[index_dist_min]
dist_vector = COM_test - origin_COM
dist_vector = dist_vector / np.linalg.norm(dist_vector,axis=1)[:,None]
COM_test = COM_test/np.linalg.norm(COM_test)
COM_angles = | np.dot(dist_vector, COM_test) | numpy.dot |
# Copyright 2021 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# =============================================================================
import numpy as np
from tensorflow.python.ipu.config import IPUConfig
from tensorflow.compiler.plugin.poplar.tests import test_utils as tu
from tensorflow.compiler.plugin.poplar.ops import gen_popops_ops
from tensorflow.compiler.plugin.poplar.ops import gen_poputil_ops
from tensorflow.python import ipu
from tensorflow.python.framework import ops
from tensorflow.python.framework import test_util
from tensorflow.python.platform import googletest
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import variables
class TestAllGather(test_util.TensorFlowTestCase):
@tu.test_uses_ipus(num_ipus=8)
@test_util.deprecated_graph_mode_only
def testAllGather(self):
with ops.device('cpu'):
x = array_ops.placeholder(np.float32, shape=[8])
outfeed_queue = ipu.ipu_outfeed_queue.IPUOutfeedQueue()
def my_graph(x):
with ops.device("/device:IPU:0"):
rep_id = ipu.replication_ops.replication_index()
x = x + math_ops.cast(rep_id, dtype=np.float32)
y = gen_popops_ops.ipu_all_gather(x, replication_factor=8)
outfeed = outfeed_queue.enqueue(y)
return y, outfeed
out = ipu.ipu_compiler.compile(my_graph, [x])
config = IPUConfig()
config.auto_select_ipus = [8]
tu.add_hw_ci_connection_options(config)
config.configure_ipu_system()
outfeed = outfeed_queue.dequeue()
with tu.ipu_session() as sess:
sess.run(variables.global_variables_initializer())
sess.run(out, {x: np.zeros([8])})
result = sess.run(outfeed)[0]
for replica in range(0, 8):
self.assertAllEqual(result[replica][0], [0] * 8)
self.assertAllEqual(result[replica][1], [1] * 8)
self.assertAllEqual(result[replica][2], [2] * 8)
self.assertAllEqual(result[replica][3], [3] * 8)
self.assertAllEqual(result[replica][4], [4] * 8)
self.assertAllEqual(result[replica][5], [5] * 8)
self.assertAllEqual(result[replica][6], [6] * 8)
self.assertAllEqual(result[replica][7], [7] * 8)
@test_util.deprecated_graph_mode_only
def testAllGatherShapeInference(self):
x = array_ops.placeholder(np.float32, shape=(2, 4))
y = gen_popops_ops.ipu_all_gather(x, replication_factor=8)
self.assertAllEqual((8, 2, 4), y.shape)
@tu.test_uses_ipus(num_ipus=8)
@test_util.deprecated_graph_mode_only
def testSerializedMultiUpdateAdd(self):
with ops.device('cpu'):
idx = array_ops.placeholder(np.int32, shape=[16, 1])
updates = array_ops.placeholder(np.float32, shape=[16, 128])
scale = array_ops.placeholder(np.float32, shape=[])
outfeed_queue = ipu.ipu_outfeed_queue.IPUOutfeedQueue()
def my_graph(idx, updates, scale):
zero = 0.0
zeros = array_ops.broadcast_to(zero, shape=[1000, 128])
out = gen_popops_ops.ipu_multi_update_add(zeros,
updates=updates,
indices=idx,
scale=scale)
out = gen_popops_ops.ipu_cross_replica_sum(out)
out = gen_poputil_ops.ipu_replication_normalise(out)
outfeed = outfeed_queue.enqueue(out)
return out, outfeed
with ops.device("/device:IPU:0"):
out = ipu.ipu_compiler.compile(my_graph, [idx, updates, scale])
config = IPUConfig()
config.auto_select_ipus = [8]
tu.add_hw_ci_connection_options(config)
config.configure_ipu_system()
outfeed = outfeed_queue.dequeue()
with tu.ipu_session() as sess:
sess.run(variables.global_variables_initializer())
sess.run(
out, {
idx: [[1], [2], [3], [4], [1], [2], [3], [4], [10], [20], [30],
[40], [100], [200], [300], [400]],
updates:
np.ones(updates.shape),
scale:
2,
})
result = sess.run(outfeed)
for replica in range(0, 8):
t = result[0][replica]
self.assertAllEqual(t[1], np.full([128], 4.0))
self.assertAllEqual(t[2], np.full([128], 4.0))
self.assertAllEqual(t[3], np.full([128], 4.0))
self.assertAllEqual(t[4], np.full([128], 4.0))
self.assertAllEqual(t[10], np.full([128], 2.0))
self.assertAllEqual(t[20], np.full([128], 2.0))
self.assertAllEqual(t[30], np.full([128], 2.0))
self.assertAllEqual(t[40], np.full([128], 2.0))
self.assertAllEqual(t[100], np.full([128], 2.0))
self.assertAllEqual(t[200], | np.full([128], 2.0) | numpy.full |
# -*- coding: utf-8 -*-
"""F
Created on Wed Feb 26 10:24:21 2020
@author: <NAME>
"""
import sys
import math
import random
import numpy as np
import pandas as pd
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import seaborn as sns
from matplotlib import cbook
from matplotlib import cm
from matplotlib.colors import LightSource
from matplotlib.colors import Normalize
from scipy import signal
from scipy import stats
from sklearn.cross_decomposition import PLSRegression
#from pls import PLSRegression #own SIMPLS based alternative to sklearn
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import KFold
from sklearn.model_selection import LeaveOneGroupOut
from sklearn.model_selection import GridSearchCV
from sklearn import metrics
from sklearn.svm import SVR
from sklearn.pipeline import Pipeline
import warnings
from fssreg import FSSRegression
from ipls import IntervalPLSRegression
from class_mcw_pls import mcw_pls_sklearn
from osc import OSC
warnings.filterwarnings('ignore')
class InputError(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
class NIRData:
def __init__(self, df, y_name="value",date_name="refdate",
cval="MD",cval_param=None):
# The class takes input dataframe in the following format:
# -it needs to be a pandas dataframe
# -it can only have the following columns: spectra variables,
# measurement date, single dependent variable
# -the measurement date and dpeendent variable column's name needs to be specified
# -the CV method needs to be defined, it supports MD and kfold, for kfold
# the number of folds needs to be defined with cval_param
self.df0=df.copy()
self.df=df.copy()
#Column with dependent variable
self.y_name=y_name
#Date column
self.date_name=date_name
#Columns with predictors
self.freqs = [col for col in df.columns if col not in [date_name, y_name]]
#If frequency columns are not all numeric, convert them
if len([x for x in self.freqs if isinstance(x, float)])<len(self.freqs):
self.freqs=[float(freq) for freq in self.freqs]
self.df0.columns=[float(col) if col not in [date_name, y_name] else col for col in df.columns]
self.df.columns=[float(col) if col not in [date_name, y_name] else col for col in df.columns]
self.cval=cval
if cval!="MD":
if cval_param==None:
raise InputError("Missing cross validation parameter!")
self.cval_param=cval_param
#Changing the cross validation method without reinstantiating the class
def set_cval(self,cval_new):
self.cval=cval_new
################# Preprocessing techniques
# Resetting the pre-processing to the raw spectra
def reset(self):
self.df=self.df0.copy()
# Preprocessing methods (detrending, SG filter, SNV, MSC)
def to_percent(self):
f = lambda x: x/100
a=np.vectorize(f)(self.df[self.freqs].to_numpy())
self.df.loc[:, self.freqs]=a
# Convert transmittance/reflectance to absorbance
def to_absorb(self,mode="R",percent=False):
# If source is transmittance, use mode="T", if reflectance mode="R"
# Functions only valid if data is between 0-1 (percent=True)
# otherwise convert the T/R values to percent
if not percent:
self.to_percent()
if mode=="T":
f = lambda x: math.log10(1/x)
elif mode=="R":
f = lambda x: ((1-x)**2)/x
else:
raise Exception("Invalid mode, has to be either T or R")
a=np.vectorize(f)(self.df[self.freqs].to_numpy())
self.df.loc[:, self.freqs]=a
# Detrending
def detrend(self, degree=1):
# Calculates a linear trend or a constant (the mean) for every
# spectral line and subtracts it
# Result is slightly different from manually implementing it!!!
x=np.array([self.freqs]).reshape(-1,)
Y=self.df[self.freqs].to_numpy()
for i in range(Y.shape[0]):
y=Y[i,:]
fit = np.polyfit(x, y, degree)
trend=np.polyval(fit, x)
y=y-trend
Y[i,:]=y
self.df.loc[:, self.freqs]=Y
# Savitzky-Golay filter
def sgfilter(self,window_length=13,polyorder=2,deriv=1):
a=signal.savgol_filter(self.df[self.freqs]
,window_length, polyorder, deriv, delta=1.0,axis=-1, mode='interp', cval=0.0)
self.df[self.freqs]=a
# SNV
def snv(self):
scaler = StandardScaler(with_mean=True, with_std=True)
scaler.fit(self.df[self.freqs].T)
self.df.loc[:, self.freqs]=scaler.transform(
self.df[self.freqs].T).T
# MSC
def msc(self):
ref=np.mean(self.df[self.freqs],axis=0)
X=np.matrix(self.df[self.freqs],dtype='float')
for i in range(self.df.shape[0]):
A=np.vstack([np.matrix(ref,dtype='float'),
np.ones(X.shape[1])]).T
coef, resids, rank, s = np.linalg.lstsq(
A,X[i,:].T)
X[i,:]=(X[i,:]-coef[1])/coef[0]
self.df[self.freqs]=X
# OSC is supervised preprocessing, so it needs CV, for which a joint modeling step is needed
# this method only crossvalidates using PLS, for other models use the built in osc_params
def osc_cv(self,nicomp_range=range(10,130,10),ncomp_range=range(1,5),epsilon = 10e-6,
max_iters = 20,model="pls",model_parameter_range=range(1,11)):
# Separating X from Y for PLS
# Needs to be converted to numpy array from pandas df
X=self.df[self.freqs].to_numpy()
# Y need to be converted to numpy array from pandas series and reshaped to (N,1) from (N,)
Y=self.df[self.y_name].to_numpy().reshape(-1, 1)
# CV based on measurement day
if self.cval=="MD":
cv = LeaveOneGroupOut()
folds=list(cv.split(X=X,y=Y,groups=self.df[self.date_name]))
# kfold CV
elif self.cval=="kfold":
cv = KFold(n_splits=self.cval_param)
folds=list(cv.split(X))
else:
raise InputError("Invalid CV type!")
#Matrix for cv values for all the possible parameter combinations
cv_RMSE_all=np.zeros([len(folds),len(model_parameter_range),len(nicomp_range),len(ncomp_range)])
i=0
#possible internal component values for osc
for nicomp in nicomp_range:
j=0
#possible removed component values for osc
for ncomp in ncomp_range:
k=0
for train, val in folds:
# train osc
osc_obj=OSC("SWosc",nicomp,ncomp,epsilon, max_iters)
X_osc_train, W,P,mu_x=osc_obj.fit(X[train],Y[train])
# apply osc on validation set
# mean center data, alternatively the training set's mean can be used
# if you think it is a better estimate by mean="training"
X_osc_val=osc_obj.transform(X[val],mean="estimate")
l=0
#possible model patrameter values for pls
for param in model_parameter_range:
#setup pls model
pls = PLSRegression(param,scale=False)
#train pls
pls.fit(X_osc_train, Y[train])
#predict with pls and calculate error
cv_RMSE_all[k,l,i,j]=metrics.mean_squared_error(
Y[val], pls.predict(X_osc_val))**0.5
l=l+1
k=k+1
j=j+1
i=i+1
# Calculate mean performance across the folds
cv_RMSE_mean=np.mean(cv_RMSE_all,axis=0)
# Find maximum for every osc paremeter combination
cv_RMSE=np.amax(cv_RMSE_mean, axis=0)
cv_RPD=np.std(self.df[self.y_name])/cv_RMSE
fig = plt.figure(figsize=(10,5))
ax = plt.axes(projection="3d")
# Cartesian indexing (x,y) transposes matrix indexing (i,j)
x, y = np.meshgrid(list(ncomp_range),list(nicomp_range))
z=cv_RPD
ls = LightSource(200, 45)
rgb = ls.shade(z, cmap=cm.gist_earth, vert_exag=0.1, blend_mode='soft')
surf = ax.plot_surface(x, y, z, rstride=1, cstride=1, facecolors=rgb,
linewidth=0, antialiased=False, shade=False)
plt.show()
# Best model
print("Best RMSE: ",np.amin(cv_RMSE))
print("Best RPD: ",np.std(self.df[self.y_name])/np.amin(cv_RMSE))
print("Number of internal components: ",nicomp_range[np.where(
cv_RMSE==np.amin(cv_RMSE))[0][0]])
print("Number of removed components: ",ncomp_range[np.where(
cv_RMSE==np.amin(cv_RMSE))[1][0]])
return cv_RMSE
############### Plotting methods
# Plotting the current processed version of the spectra
def plot_spectra(self, processed=True, savefig=False, *args):
fig,ax = plt.subplots(figsize=(12, 8))
if processed:
# Plotting unprocessed spectra
ax.plot(self.df[self.freqs].T)
else:
# Plotting processed spectra
ax.plot(self.df0[self.freqs].T)
for arg in args:
ax.axvline(x=arg)
if savefig:
plt.savefig('plot_spectra.pdf')
# Plotting the fitted PLS model's regression weights on the spectra
def plot_pls(self):
#r=self.pls_obj.x_rotations_
r=self.pls_obj.coef_
fig, ax = plt.subplots(figsize=(12, 8))
ax.plot(self.df[self.freqs].T,c="grey",alpha=1)
ax.pcolorfast((np.min(self.freqs),np.max(self.freqs)), ax.get_ylim(),
r.T,cmap='seismic',vmin=-1,vmax=1, alpha=1)
norm = Normalize(vmin=-1, vmax=1)
scalarmappaple = cm.ScalarMappable(norm=norm,cmap='seismic')
scalarmappaple.set_array(r.T)
fig.colorbar(scalarmappaple)
# Plotting the fitted MCW-PLS model's sample weights for the individual spectra
def plot_mcw_pls(self):
a=np.diagonal(self.mcw_pls_obj.sample_weights)
cmap = plt.cm.get_cmap('seismic')
fig, ax = plt.subplots(figsize=(6, 4))
for i in range(self.df[self.freqs].shape[0]):
row=self.df[self.freqs].iloc[i]
ax.plot(row,c=cmap(a[i]),alpha=1)
scalarmappaple = cm.ScalarMappable(cmap=cmap)
scalarmappaple.set_array(a)
plt.colorbar(scalarmappaple)
r=self.mcw_pls_obj.BPLS
fig, ax = plt.subplots(figsize=(6, 4))
ax.plot(self.df[self.freqs].T,c="grey",alpha=1)
ax.pcolorfast((np.min(self.freqs),np.max(self.freqs)), ax.get_ylim(),
r.T,cmap='seismic',vmin=-1,vmax=1, alpha=1)
norm = Normalize(vmin=-1, vmax=1)
scalarmappaple = cm.ScalarMappable(norm=norm,cmap='seismic')
scalarmappaple.set_array(r.T)
fig.colorbar(scalarmappaple)
######################### Modeling methods
# Support vector regression
# For fitting a model with given parameters
def svr_pipe(self,gam,c,eps):
X=self.df[self.freqs].to_numpy()
Y=self.df[self.y_name].to_numpy().reshape(-1, 1)
self.svr_pipe_obj = Pipeline([('scaler', StandardScaler()),
('support vector regression',
SVR(kernel="rbf",gamma=gam,C=c,epsilon=eps))])
self.svr_pipe_obj.fit(X, Y)
# For evaluating a model with given parameters
def svr_eval(self, gam,c,eps):
X=self.df[self.freqs].to_numpy()
Y=self.df[self.y_name].to_numpy().reshape(-1, 1)
pipe = Pipeline([('scaler', StandardScaler()),
('support vector regression',
SVR(kernel="rbf",gamma=gam,C=c,epsilon=eps))])
self.eval_df=pd.DataFrame(columns = ["estimated","true"])
if self.cval=="MD":
cv = LeaveOneGroupOut()
folds=list(cv.split(X=X,y=Y,groups=self.df[self.date_name]))
cv_RMSE=np.zeros(len(folds))
i=0
for train, val in folds:
pipe.fit(X[train], Y[train])
cv_RMSE[i]=metrics.mean_squared_error(
Y[val], pipe.predict(X[val]))**0.5
eval_new=pd.DataFrame({'estimated': pipe.predict(X[val]).reshape((-1,)),
'true': Y[val].reshape((-1,))})
self.eval_df=self.eval_df.append(eval_new, ignore_index = True)
i=i+1
y_true=self.eval_df["true"]
y_est=self.eval_df["estimated"]
print(np.std(y_true)/metrics.mean_squared_error(y_true,y_est)**0.5)
print(np.std(y_true)/np.mean(cv_RMSE))
residuals=y_true-y_est
linreg = stats.linregress(y_true, y_est)
blue='#1f77b4'
# Observed vs predicted
fig,ax = plt.subplots(figsize=(5, 5))
ax.scatter(x=y_true,y=y_est)
# Perfect prediction
ax.plot([np.min(Y), np.max(Y)], [np.min(Y), np.max(Y)], 'k--', color = 'r',label='Perfect fit')
# Model fit
ax.plot(y_true, linreg.intercept + linreg.slope*y_true, blue,label='Predicted fit')
# Text location needs to be picked manually
#ax.text(48, 56, 'R$^2$ = %0.002f' % linreg.rvalue,color=blue)
ax.text(93, 95, 'R$^2$ = %0.002f' % linreg.rvalue,color=blue)
ax.set(xlabel="Observed (%)",ylabel="Predicted (%)")
ax.legend()
# Predicted vs residuals
fig,ax = plt.subplots(figsize=(5, 5))
ax.scatter(x=y_est,y=residuals)
ax.axhline(y=np.mean(residuals), color='r', linestyle='--',label='Mean = %0.6f' % np.mean(residuals))
ax.set(xlabel="Predicted (%)",ylabel="Residuals (%)")
ax.legend()
# QQ plot
fig,ax = plt.subplots(figsize=(5, 5))
stats.probplot(residuals,plot=ax)
ax.get_lines()[0].set_markerfacecolor(blue)
ax.get_lines()[0].set_markeredgecolor(blue)
ax.get_figure().gca().set_title("")
ax.get_figure().gca().set_ylabel("Residuals (%)")
# Residual density plot with normal density
normx = np.linspace(-8,8,1000)
normy = stats.norm.pdf(normx, loc=np.mean(residuals), scale=np.std(residuals))
fig,ax = plt.subplots(figsize=(5, 5))
sns.distplot(residuals,norm_hist=True,ax=ax,color=blue)
ax.plot(normx,normy,color='r')
sns.set_style("white")
# Sorted alphas plot
# Get alphas
alphas=self.svr_pipe_obj['support vector regression'].dual_coef_
# Take abs value and sort
alphas=abs(alphas)
alphas=np.sort(alphas)
# Add zero alphas
alphas=np.vstack((np.zeros((X.shape[0]-len(alphas.T),1)),alphas.T))
fig,ax = plt.subplots(figsize=(5, 5))
ax.plot(alphas)
ax.set(xlabel="Sample ranking",ylabel="SV absolute α value")
# Method for tuning an SVM regression's free parameters based on CV
# OSC built in option, as this preprocessing is supervised so needs to be validated at the same time
def svr_cv(self,gam_start=0.001,
c_start=100,
eps_start=0.1,
optimization="grid",gridscale=5,non_improve_lim=10,verbose=False,
osc_params=None):
# Separating X from Y for PLS
X=self.df[self.freqs].to_numpy()
Y=self.df[self.y_name].to_numpy().reshape(-1, 1)
sample_std=np.std(self.df[self.y_name])
# CV based on measurement day
if self.cval=="MD":
cv = LeaveOneGroupOut()
folds=list(cv.split(X=X,y=Y,groups=self.df[self.date_name]))
# kfold CV
elif self.cval=="kfold":
cv = KFold(n_splits=self.cval_param)
folds=list(cv.split(X))
else:
raise InputError("Invalid CV type!")
if optimization=="none":
cv_RMSE=np.zeros(len(folds))
# Only use RBF kernels, also standardize data
pipe = Pipeline([('scaler', StandardScaler()),
('support vector regression',
SVR(kernel="rbf",gamma=gam_start,C=c_start,epsilon=eps_start))])
l=0
for train, val in folds:
pipe.fit(X[train], Y[train])
cv_RMSE[l]=metrics.mean_squared_error(
Y[val], pipe.predict(X[val]))**0.5
l=l+1
gam_best=gam_start
c_best=c_start
eps_best=eps_start
rpd_best=sample_std/ | np.mean(cv_RMSE) | numpy.mean |
# coding=utf-8
# @Time : 2020/12/29 17:35
# @Auto : zzf-jeff
from torchocr.datasets.pipelines.compose import PIPELINES
from torchvision import transforms
import cv2
import os
import numpy as np
@PIPELINES.register_module()
class KeepKeys(object):
def __init__(self, keep_keys, **kwargs):
self.keep_keys = keep_keys
def __call__(self, data):
if len(self.keep_keys):
data_dict = {}
for k, v in data.items():
if k in self.keep_keys:
data_dict[k] = v
return data_dict
else:
return data
@PIPELINES.register_module()
class Normalize():
def __init__(self, mean, std, to_rgb=False):
self.mean = mean
self.std = std
def __call__(self, data):
transform = transforms.Normalize(mean=self.mean, std=self.std)
data['image'] = transform(data['image'])
return data
@PIPELINES.register_module()
class ToTensor(object):
"""Image ToTensor -->numpy2Tensor
Args:
image :原始图片
Returns:
result : Over ToTensor
"""
def __call__(self, data):
transform = transforms.ToTensor()
data['img'] = transform(data['img'])
return data
@PIPELINES.register_module()
class DecodeImage(object):
def __init__(self, img_mode='RGB', channel_first=False, **kwargs):
"""Decode image,read img
:param img_mode: GRAY or RGB
:param channel_first: hwc-->chw
:param kwargs:
"""
self.img_mode = img_mode
self.channel_first = channel_first
def __call__(self, data):
try:
if data is None:
return None
img_path = data['img_path']
img = cv2.imread(img_path)
if self.img_mode == 'GRAY':
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
elif self.img_mode == 'RGB':
assert img.shape[2] == 3, 'invalid shape of image[%s]' % (img.shape)
img = img[:, :, ::-1] # BGR-->RGB
if self.channel_first:
img = img.transpose((2, 0, 1))
data['image'] = img
return data
except Exception as e:
file_name = os.path.basename(__file__).split(".")[0]
print('{} --> '.format(file_name), e)
return None
@PIPELINES.register_module()
class NormalizeImage(object):
""" normalize image such as substract mean, divide std
"""
def __init__(self, scale=None, mean=None, std=None, order='hwc', **kwargs):
if isinstance(scale, str):
scale = eval(scale)
self.scale = np.float32(scale if scale is not None else 1.0 / 255.0)
shape = (3, 1, 1) if order == 'chw' else (1, 1, 3)
self.mean = np.array(mean).reshape(shape).astype('float32')
self.std = | np.array(std) | numpy.array |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
import os
import random
import numpy as np
import pytest
from astropy.wcs import WCS
from astropy.io.fits import Header
from numpy.testing import assert_allclose
from ... import reproject_exact, reproject_interp
from ..coadd import reproject_and_coadd
from ...tests.helpers import array_footprint_to_hdulist
ATOL = 1.e-9
DATA = os.path.join(os.path.dirname(__file__), '..', '..', 'tests', 'data')
@pytest.fixture(params=[reproject_interp, reproject_exact],
ids=["interp", "exact"])
def reproject_function(request):
return request.param
class TestReprojectAndCoAdd():
def setup_method(self, method):
self.wcs = WCS(naxis=2)
self.wcs.wcs.ctype = 'RA---TAN', 'DEC--TAN'
self.wcs.wcs.crpix = 322, 151
self.wcs.wcs.crval = 43, 23
self.wcs.wcs.cdelt = -0.1, 0.1
self.wcs.wcs.equinox = 2000.
self.array = np.random.random((399, 334))
def _get_tiles(self, views):
# Given a list of views as (imin, imax, jmin, jmax), construct
# tiles that can be passed into the co-adding code
input_data = []
for (jmin, jmax, imin, imax) in views:
array = self.array[jmin:jmax, imin:imax].copy()
wcs = self.wcs.deepcopy()
wcs.wcs.crpix[0] -= imin
wcs.wcs.crpix[1] -= jmin
input_data.append((array, wcs))
return input_data
@property
def _nonoverlapping_views(self):
ie = (0, 122, 233, 245, 334)
je = (0, 44, 45, 333, 335, 399)
views = []
for i in range(4):
for j in range(5):
views.append((je[j], je[j+1], ie[i], ie[i+1]))
return views
@property
def _overlapping_views(self):
ie = (0, 122, 233, 245, 334)
je = (0, 44, 45, 333, 335, 399)
views = []
for i in range(4):
for j in range(5):
views.append((je[j], je[j+1] + 10, ie[i], ie[i+1] + 10))
return views
@pytest.mark.parametrize('combine_function', ['mean', 'sum'])
def test_coadd_no_overlap(self, combine_function, reproject_function):
# Make sure that if all tiles are exactly non-overlapping, and
# we use 'sum' or 'mean', we get the exact input array back.
input_data = self._get_tiles(self._nonoverlapping_views)
input_data = [(self.array, self.wcs)]
array, footprint = reproject_and_coadd(input_data, self.wcs,
shape_out=self.array.shape,
combine_function=combine_function,
reproject_function=reproject_function)
assert_allclose(array, self.array, atol=ATOL)
assert_allclose(footprint, 1, atol=ATOL)
def test_coadd_with_overlap(self, reproject_function):
# Here we make the input tiles overlapping. We can only check the
# mean, not the sum.
input_data = self._get_tiles(self._overlapping_views)
array, footprint = reproject_and_coadd(input_data, self.wcs,
shape_out=self.array.shape,
combine_function='mean',
reproject_function=reproject_function)
assert_allclose(array, self.array, atol=ATOL)
def test_coadd_background_matching(self, reproject_function):
# Test out the background matching
input_data = self._get_tiles(self._overlapping_views)
for array, wcs in input_data:
array += random.uniform(-3, 3)
# First check that without background matching the arrays don't match
array, footprint = reproject_and_coadd(input_data, self.wcs,
shape_out=self.array.shape,
combine_function='mean',
reproject_function=reproject_function)
assert not np.allclose(array, self.array, atol=ATOL)
# Now check that once the backgrounds are matched the values agree
array, footprint = reproject_and_coadd(input_data, self.wcs,
shape_out=self.array.shape,
combine_function='mean',
reproject_function=reproject_function,
match_background=True)
# The absolute values of the two arrays will be offset since any
# solution that reproduces the offsets between images is valid
assert_allclose(array - np.mean(array),
self.array - np.mean(self.array), atol=ATOL)
def test_coadd_background_matching_with_nan(self, reproject_function):
# Test out the background matching when NaN values are present. We do
# this by using three arrays with the same footprint but with different
# parts masked.
array1 = self.array.copy() + random.uniform(-3, 3)
array2 = self.array.copy() + random.uniform(-3, 3)
array3 = self.array.copy() + random.uniform(-3, 3)
array1[:, 122:] = np.nan
array2[:, :50] = np.nan
array2[:, 266:] = np.nan
array3[:, :199] = np.nan
input_data = [(array1, self.wcs), (array2, self.wcs), (array3, self.wcs)]
array, footprint = reproject_and_coadd(input_data, self.wcs,
shape_out=self.array.shape,
combine_function='mean',
reproject_function=reproject_function,
match_background=True)
# The absolute values of the two arrays will be offset since any
# solution that reproduces the offsets between images is valid
assert_allclose(array - np.mean(array),
self.array - np.mean(self.array), atol=ATOL)
def test_coadd_with_weights(self, reproject_function):
# Make sure that things work properly when specifying weights
array1 = self.array + 1
array2 = self.array - 1
weight1 = np.cumsum(np.ones_like(self.array), axis=1) - 1
weight2 = weight1[:, ::-1]
input_data = [(array1, self.wcs), (array2, self.wcs)]
input_weights = [weight1, weight2]
array, footprint = reproject_and_coadd(input_data, self.wcs,
shape_out=self.array.shape,
combine_function='mean',
input_weights=input_weights,
reproject_function=reproject_function,
match_background=False)
expected = self.array + (2 * (weight1 / weight1.max()) - 1)
| assert_allclose(array, expected, atol=ATOL) | numpy.testing.assert_allclose |
# _*_ coding: utf-8 _*_
"""
Manipulating functions for grid.
References:
* https://bitbucket.org/tmiyachi/pymet
"""
import numpy as np
from numba import jit
from scipy import interpolate, ndimage
from pyproj import Geod
from dk_met_base import constants, arr
NA = np.newaxis
a0 = constants.Re
g = constants.g0
PI = constants.pi
d2r = PI/180.
def calc_dx_dy(lon, lat, shape='WGS84', radius=6370997.):
"""
This definition calculates the distance between grid points
that are in a latitude/longitude format.
Using pyproj GEOD; different Earth Shapes
https://jswhit.github.io/pyproj/pyproj.Geod-class.html
Common shapes: 'sphere', 'WGS84', 'GRS80'
:param lon: 1D or 2D longitude array.
:param lat: 1D or 2D latitude array.
:param shape: earth shape.
:param radius: earth radius.
:return: dx, dy; 2D arrays of distances between grid points
in the x and y direction in meters
:Example:
>>> lat = np.arange(90,-0.1,-0.5)
>>> lon = np.arange(0,360.1,0.5)
>>> dx, dy = calc_dx_dy(lon, lat)
"""
# check longitude and latitude
if lon.ndim == 1:
longitude, latitude = np.meshgrid(lon, lat)
else:
longitude = lon
latitude = lat
if radius != 6370997.:
gg = Geod(a=radius, b=radius)
else:
gg = Geod(ellps=shape)
dx = np.empty(latitude.shape)
dy = np.zeros(longitude.shape)
for i in range(latitude.shape[1]):
for j in range(latitude.shape[0] - 1):
_, _, dx[j, i] = gg.inv(
longitude[j, i], latitude[j, i], longitude[j + 1, i],
latitude[j + 1, i])
dx[j + 1, :] = dx[j, :]
for i in range(latitude.shape[1] - 1):
for j in range(latitude.shape[0]):
_, _, dy[j, i] = gg.inv(
longitude[j, i], latitude[j, i], longitude[j, i + 1],
latitude[j, i + 1])
dy[:, i + 1] = dy[:, i]
return dx, dy
def dvardx(var, lon, lat, xdim, ydim, cyclic=True, sphere=True):
"""
calculate center finite difference along x or longitude.
https://bitbucket.org/tmiyachi/pymet/src/8df8e3ff2f899d625939448d7e96755dfa535357/pymet/grid.py
:param var: ndarray, grid values.
:param lon: array_like, longitude
:param lat: array_like, latitude
:param xdim: the longitude dimension index
:param ydim: the latitude dimension index
:param cyclic: east-west boundary is cyclic
:param sphere: sphere coordinate
:return: ndarray
:Examples:
>>> var.shape
(24, 73, 72)
>>> lon = np.arange(0, 180, 2.5)
>>> lat = np.arange(-90, 90.1, 2.5)
>>> result = dvardx(var, lon, lat, 2, 1, cyclic=False)
>>> result.shape
(24, 73, 72)
"""
var = np.array(var)
ndim = var.ndim
var = np.rollaxis(var, xdim, ndim)
if cyclic and sphere:
dvar = np.concatenate(((var[..., 1] - var[..., -1])[..., NA],
(var[..., 2:] - var[..., :-2]),
(var[..., 0] - var[..., -2])[..., NA]), axis=-1)
dx = np.r_[(lon[1] + 360 - lon[-1]), (lon[2:] - lon[:-2]),
(lon[0] + 360 - lon[-2])]
else:
dvar = np.concatenate(((var[..., 1] - var[..., 0])[..., NA],
(var[..., 2:] - var[..., :-2]),
(var[..., -1] - var[..., -2])[..., NA]),
axis=-1)
dx = np.r_[(lon[1] - lon[0]), (lon[2:] - lon[:-2]),
(lon[-1] - lon[-2])]
dvar = np.rollaxis(dvar, ndim - 1, xdim)
if sphere:
dx = a0 * PI / 180. * arr.expand(dx, ndim, xdim) * \
arr.expand(np.cos(lat * d2r), ndim, ydim)
else:
dx = arr.expand(dx, ndim, xdim)
out = dvar / dx
return out
def dvardy(var, lat, ydim, sphere=True):
"""
calculate center finite difference along y or latitude.
https://bitbucket.org/tmiyachi/pymet/src/8df8e3ff2f899d625939448d7e96755dfa535357/pymet/grid.py
:param var: ndarray, grid values.
:param lat: array_like, latitude
:param ydim: the latitude dimension index
:param sphere: sphere coordinate
:return: ndarray
:Examples:
>>> var.shape
(24, 73, 144)
>>> lat = np.arange(-90, 90.1, 2.5)
>>> result = dvardy(var, lat, 1)
>>> result.shape
(24, 73, 144)
"""
var = np.array(var)
ndim = var.ndim
var = np.rollaxis(var, ydim, ndim)
dvar = np.concatenate([(var[..., 1] - var[..., 0])[..., NA],
(var[..., 2:]-var[..., :-2]),
(var[..., -1] - var[..., -2])[..., NA]],
axis=-1)
dy = np.r_[(lat[1]-lat[0]), (lat[2:]-lat[:-2]), (lat[-1]-lat[-2])]
if sphere:
dy = a0*PI/180.*dy
out = dvar/dy
out = np.rollaxis(out, ndim-1, ydim)
return out
def dvardp(var, lev, zdim, punit=100.):
"""
calculate center finite difference along vertical coordinate.
https://bitbucket.org/tmiyachi/pymet/src/8df8e3ff2f899d625939448d7e96755dfa535357/pymet/grid.py
:param var: ndarray, grid values.
:param lev: 1d-array, isobaric levels.
:param zdim: the vertical dimension index.
:param punit: pressure level units.
:return: ndarray.
"""
var = np.array(var)
ndim = var.ndim
lev = lev * punit
# roll lat dim axis to last
var = np.rollaxis(var, zdim, ndim)
dvar = np.concatenate([(var[..., 1] - var[..., 0])[..., NA],
(var[..., 2:] - var[..., :-2]),
(var[..., -1] - var[..., -2])[..., NA]],
axis=-1)
dp = np.r_[np.log(lev[1] / lev[0]) * lev[0],
np.log(lev[2:] / lev[:-2]) * lev[1:-1],
np.log(lev[-1] / lev[-2]) * lev[-1]]
out = dvar / dp
# reroll lat dim axis to original dim
out = np.rollaxis(out, ndim - 1, zdim)
return out
def d2vardx2(var, lon, lat, xdim, ydim, cyclic=True, sphere=True):
"""
calculate second center finite difference along x or longitude.
https://bitbucket.org/tmiyachi/pymet/src/8df8e3ff2f899d625939448d7e96755dfa535357/pymet/grid.py
:param var: ndarray, grid values.
:param lon: array_like, longitude
:param lat: array_like, latitude
:param xdim: the longitude dimension index
:param ydim: the latitude dimension index
:param cyclic: east-west boundary is cyclic
:param sphere: sphere coordinate
:return: ndarray
"""
var = np.array(var)
ndim = var.ndim
# roll lon dim axis to last
var = np.rollaxis(var, xdim, ndim)
if cyclic and sphere:
dvar = np.concatenate(((var[..., 1]-2*var[..., 0] +
var[..., -1])[..., NA],
(var[..., 2:]-2*var[..., 1:-1] + var[..., :-2]),
(var[..., 0]-2*var[..., -1] +
var[..., -2])[..., NA]), axis=-1)
dx = np.r_[(lon[1]+360-lon[-1]), (lon[2:]-lon[:-2]),
(lon[0]+360-lon[-2])]
else: # edge is zero
dvar = np.concatenate(((var[..., 0]-var[..., 0])[..., NA],
(var[..., 2:]-2*var[..., 1:-1]+var[..., :-2]),
(var[..., 0]-var[..., 0])[..., NA]), axis=-1)
dx = np.r_[(lon[1]-lon[0]), (lon[2:]-lon[:-2]), (lon[-1]-lon[-2])]
dvar = np.rollaxis(dvar, ndim-1, xdim)
if sphere:
dx2 = a0 ** 2 * (PI/180.) ** 2 * arr.expand(dx ** 2, ndim, xdim) * \
arr.expand(np.cos(lat * d2r) ** 2, ndim, ydim)
else:
dx2 = arr.expand(dx ** 2, ndim, xdim)
out = 4.*dvar/dx2
# reroll lon dim axis to original dim
out = np.rollaxis(out, ndim-1, xdim)
return out
def d2vardy2(var, lat, ydim, sphere=True):
"""
calculate second center finite difference along y or latitude.
https://bitbucket.org/tmiyachi/pymet/src/8df8e3ff2f899d625939448d7e96755dfa535357/pymet/grid.py
:param var: ndarray, grid values.
:param lat: array_like, latitude
:param ydim: the latitude dimension index
:param sphere: sphere coordinate
:return: ndarray
"""
var = np.array(var)
ndim = var.ndim
# roll lat dim axis to last
var = np.rollaxis(var, ydim, ndim)
# edge is zero
dvar = np.concatenate([(var[..., 0] - var[..., 0])[..., NA],
(var[..., 2:] - 2*var[..., 1:-1] + var[..., :-2]),
(var[..., 0] - var[..., 0])[..., NA]], axis=-1)
dy = np.r_[(lat[1]-lat[0]), (lat[2:]-lat[:-2]), (lat[-1]-lat[-2])]
if sphere:
dy2 = a0**2 * dy**2
else:
dy2 = dy**2
out = 4.*dvar/dy2
# reroll lat dim axis to original dim
out = np.rollaxis(out, ndim-1, ydim)
return out
def dvardvar(var1, var2, dim):
"""
Calculate d(var1)/d(var2) along axis=dim.
https://bitbucket.org/tmiyachi/pymet/src/8df8e3ff2f899d625939448d7e96755dfa535357/pymet/grid.py
:param var1: numpy nd array, denominator of derivative
:param var2: numpy nd array, numerator of derivative
:param dim: along dimension.
:return:
"""
var1, var2 = np.array(var1), np.array(var2)
ndim = var1.ndim
# roll dim axis to last
var1 = np.rollaxis(var1, dim, ndim)
var2 = np.rollaxis(var2, dim, ndim)
dvar1 = np.concatenate([(var1[..., 1] - var1[..., 0])[..., NA],
(var1[..., 2:] - var1[..., :-2]),
(var1[..., -1] - var1[..., -2])[..., NA]], axis=-1)
dvar2 = np.concatenate([(var2[..., 1] - var2[..., 0])[..., NA],
(var2[..., 2:] - var2[..., :-2]),
(var2[..., -1] - var2[..., -2])[..., NA]], axis=-1)
out = dvar1 / dvar2
# reroll lat dim axis to original dim
out = np.rollaxis(out, ndim - 1, dim)
return out
def div(u, v, lon, lat, xdim, ydim, cyclic=True, sphere=True):
"""
Calculate horizontal divergence.
:param u: ndarray, u-component wind.
:param v: ndarray, v-component wind.
:param lon: array_like, longitude.
:param lat: array_like, latitude.
:param xdim: the longitude dimension index
:param ydim: the latitude dimension index
:param cyclic: east-west boundary is cyclic
:param sphere: sphere coordinate
:return: ndarray
"""
u, v = np.array(u), np.array(v)
ndim = u.ndim
out = dvardx(u, lon, lat, xdim, ydim, cyclic=cyclic,
sphere=sphere) + dvardy(v, lat, ydim, sphere=sphere)
if sphere:
out = out - v * arr.expand(np.tan(lat * d2r), ndim, ydim) / a0
out = np.rollaxis(out, ydim, 0)
out[0, ...] = 0.
out[-1, ...] = 0.
out = np.rollaxis(out, 0, ydim + 1)
return out
def rot(u, v, lon, lat, xdim, ydim, cyclic=True, sphere=True):
"""
Calculate vertical vorticity.
:param u: ndarray, u-component wind.
:param v: ndarray, v-component wind.
:param lon: array_like, longitude.
:param lat: array_like, latitude.
:param xdim: the longitude dimension index
:param ydim: the latitude dimension index
:param cyclic: east-west boundary is cyclic
:param sphere: sphere coordinate
:return: ndarray
"""
u, v = np.array(u), np.array(v)
ndim = u.ndim
out = dvardx(v, lon, lat, xdim, ydim, cyclic=cyclic,
sphere=sphere) - dvardy(u, lat, ydim, sphere=sphere)
if sphere:
out = out + u * arr.expand(np.tan(lat * d2r), ndim, ydim) / a0
out = np.rollaxis(out, ydim, 0)
out[0, ...] = 0.
out[-1, ...] = 0.
out = np.rollaxis(out, 0, ydim + 1)
return out
def laplacian(var, lon, lat, xdim, ydim, cyclic=True, sphere=True):
"""
Calculate laplacian operation on sphere.
:param var: ndarray, grid values.
:param lon: array_like, longitude
:param lat: array_like, latitude
:param xdim: the longitude dimension index
:param ydim: the latitude dimension index
:param cyclic: east-west boundary is cyclic
:param sphere: sphere coordinate
:return: ndarray
"""
var = np.asarray(var)
ndim = var.ndim
if sphere:
out = d2vardx2(var, lon, lat, xdim, ydim,
cyclic=cyclic, sphere=sphere) + \
d2vardy2(var, lat, ydim, sphere=sphere) - \
arr.expand(np.tan(lat * d2r), ndim, ydim) * \
dvardy(var, lat, ydim)/a0
else:
out = d2vardx2(var, lon, lat, xdim, ydim,
cyclic=cyclic, sphere=sphere) + \
d2vardy2(var, lat, ydim, sphere=sphere)
return out
def grad(var, lon, lat, xdim, ydim, cyclic=True, sphere=True):
"""
Calculate gradient operator.
:param var: ndarray, grid values.
:param lon: array_like, longitude
:param lat: array_like, latitude
:param xdim: the longitude dimension index
:param ydim: the latitude dimension index
:param cyclic: east-west boundary is cyclic
:param sphere: sphere coordinate
:return: ndarray
"""
var = np.asarray(var)
outu = dvardx(var, lon, lat, xdim, ydim, cyclic=cyclic, sphere=sphere)
outv = dvardy(var, lat, ydim, sphere=sphere)
return outu, outv
def skgrad(var, lon, lat, xdim, ydim, cyclic=True, sphere=True):
"""
Calculate skew gradient.
:param var: ndarray, grid values.
:param lon: array_like, longitude
:param lat: array_like, latitude
:param xdim: the longitude dimension index
:param ydim: the latitude dimension index
:param cyclic: east-west boundary is cyclic
:param sphere: sphere coordinate
:return: ndarray
"""
var = np.asarray(var)
outu = -dvardy(var, lat, ydim, sphere=sphere)
outv = dvardx(var, lon, lat, xdim, ydim, cyclic=cyclic, sphere=sphere)
return outu, outv
def gradient_sphere(f, *varargs):
"""
Return the gradient of a 2-dimensional array on a sphere given a latitude
and longitude vector.
The gradient is computed using central differences in the interior
and first differences at the boundaries. The returned gradient hence has
the same shape as the input array.
https://github.com/scavallo/python_scripts/blob/master/utils/weather_modules.py
:param f: A 2-dimensional array containing samples of a scalar function.
:param varargs: latitude, longitude and so on.
:return: dfdx and dfdy arrays of the same shape as `f`
giving the derivative of `f` with
respect to each dimension.
:Example:
temperature = temperature(pressure,latitude,longitude)
levs = pressure vector
lats = latitude vector
lons = longitude vector
>>> tempin = temperature[5,:,:]
>>> dfdlat, dfdlon = gradient_sphere(tempin, lats, lons)
>>> dfdp, dfdlat, dfdlon = gradient_sphere(temperature, levs, lats, lons)
"""
r_earth = 6371200.
N = f.ndim # number of dimensions
n = len(varargs) # number of arguments
argsin = list(varargs)
if N != n:
raise SyntaxError(
"dimensions of input must match the remaining arguments")
df = np.gradient(f)
if n == 2:
lats = argsin[0]
lons = argsin[1]
dfdy = df[0]
dfdx = df[1]
elif n == 3:
levs = argsin[0]
lats = argsin[1]
lons = argsin[2]
dfdz = df[0]
dfdy = df[1]
dfdx = df[2]
else:
raise SyntaxError("invalid number of arguments")
otype = f.dtype.char
if otype not in ['f', 'd', 'F', 'D']:
otype = 'd'
latarr = np.zeros_like(f).astype(otype)
lonarr = np.zeros_like(f).astype(otype)
if N == 2:
nlat, nlon = np.shape(f)
for jj in range(0, nlat):
latarr[jj, :] = lats[jj]
for ii in range(0, nlon):
lonarr[:, ii] = lons[ii]
else:
nz, nlat, nlon = np.shape(f)
for jj in range(0, nlat):
latarr[:, jj, :] = lats[jj]
for ii in range(0, nlon):
lonarr[:, :, ii] = lons[ii]
# use central differences on interior and first differences on endpoints
dlats = np.zeros_like(lats).astype(otype)
dlats[1:-1] = (lats[2:] - lats[:-2])
dlats[0] = (lats[1] - lats[0])
dlats[-1] = (dlats[-2] - dlats[-1])
dlons = np.zeros_like(lons).astype(otype)
dlons[1:-1] = (lons[2:] - lons[:-2])
dlons[0] = (lons[1] - lons[0])
dlons[-1] = (dlons[-2] - dlons[-1])
dlatarr = np.zeros_like(f).astype(otype)
dlonarr = np.zeros_like(f).astype(otype)
if N == 2:
for jj in range(0, nlat):
dlatarr[jj, :] = dlats[jj]
for ii in range(0, nlon):
dlonarr[:, ii] = dlons[ii]
elif N == 3:
for jj in range(0, nlat):
dlatarr[:, jj, :] = dlats[jj]
for ii in range(0, nlon):
dlonarr[:, :, ii] = dlons[ii]
dlatsrad = dlatarr * (PI / 180.)
dlonsrad = dlonarr * (PI / 180.)
latrad = latarr * (PI / 180.)
if n == 2:
dx1 = r_earth * dlatsrad
dx2 = r_earth * np.cos(latrad) * dlonsrad
dfdy = dfdy / dx1
dfdx = dfdx / dx2
return dfdy, dfdx
elif n == 3:
dx1 = r_earth * dlatsrad
dx2 = r_earth * np.cos(latrad) * dlonsrad
dfdy = dfdy / dx1
dfdx = dfdx / dx2
zin = levs
dz = np.zeros_like(zin).astype(otype)
dz[1:-1] = (zin[2:] - zin[:-2]) / 2.0
dz[0] = (zin[1] - zin[0])
dz[-1] = (zin[-1] - zin[-2])
dx3 = np.ones_like(f).astype(otype)
for kk in range(0, nz):
dx3[kk, :, :] = dz[kk]
dfdz = dfdz / dx3
return dfdz, dfdy, dfdx
def vint(var, bottom, top, lev, zdim, punit=100.):
"""
Calculate vertical integration.
:param var: array_like.
:param bottom: bottom boundary of integration.
:param top: top boundary of integration.
:param lev: isobaric levels.
:param zdim: vertical dimension.
:param punit: levels units.
:return: array_like.
"""
var = np.ma.asarray(var)
lev = np.asarray(lev)
ndim = var.ndim
lev = lev[(lev <= bottom) & (lev >= top)]
lev_m = np.r_[bottom, (lev[1:] + lev[:-1])/2., top]
dp = lev_m[:-1] - lev_m[1:]
# roll lat dim axis to last
var = arr.mrollaxis(var, zdim, ndim)
out = var[..., (lev <= bottom) & (lev >= top)] * dp / g * punit
if bottom > top:
out = out.sum(axis=-1)
else:
out = -out.sum(axis=-1)
return out
def total_col(infld, pres, temp, hght):
"""
Compute column integrated value of infld.
https://github.com/scavallo/classcode/blob/master/utils/weather_modules.py
:param infld: Input 3D field to column integrate
:param pres: Input 3D air pressure (Pa)
:param temp: Input 3D temperature field (K)
:param hght: Input 3D geopotential height field (m
:return: Output total column integrated value
"""
[iz, iy, ix] = np.shape(infld)
density = pres / (287 * temp)
tmp = pres[0, :, :].squeeze()
coltot = np.zeros_like(tmp).astype('f')
for jj in range(0, iy):
for ii in range(0, ix):
colnow = infld[:, jj, ii] * density[:, jj, ii]
hghtnow = hght[:, jj, ii].squeeze()
coltot[jj, ii] = np.trapz(colnow[::-1], hghtnow[::-1])
return coltot
def vmean(var, bottom, top, lev, zdim):
"""
Calculate vertical mean.
:param var: array_like.
:param bottom: bottom boundary of integration.
:param top: top boundary of integration.
:param lev: isobaric levels.
:param zdim: vertical dimension.
:return: array_like.
"""
var = np.ma.asarray(var)
lev = np.asarray(lev)
ndim = var.ndim
lev = lev[(lev <= bottom) & (lev >= top)]
lev_m = np.r_[bottom, (lev[1:] + lev[:-1])/2., top]
dp = lev_m[:-1] - lev_m[1:]
# roll lat dim axis to last
var = arr.mrollaxis(var, zdim, ndim)
out = var[..., (lev <= bottom) & (lev >= top)] * dp
out = out.sum(axis=-1)/(dp.sum())
return out
def vinterp(var, oldz, newz, zdim, logintrp=True, bounds_error=True):
"""
perform vertical linear interpolation.
:param var: array_like variable.
:param oldz: original vertical level.
:param newz: new vertical level.
:param zdim: the dimension of vertical.
:param logintrp: log linear interpolation.
:param bounds_error: options for scipy.interpolate.interp1d.
:return:
"""
var = np.array(var)
ndim = var.ndim
new_z = np.array(newz)
old_z = np.array(oldz)
if logintrp:
old_z = np.log(old_z)
new_z = np.log(new_z)
old_zn = var.shape[zdim]
new_zn = len(new_z)
# roll z dim axis to last
var = np.rollaxis(var, zdim, ndim)
old_shape = var.shape
new_shape = list(old_shape)
new_shape[-1] = new_zn
var = var.reshape(-1, old_zn)
if old_z.ndim == ndim:
old_z = np.rollaxis(old_z, zdim, ndim).reshape(-1, old_zn)
f = interpolate.interp1d(old_z, var, axis=-1, kind='linear',
bounds_error=bounds_error)
out = f(new_z)
elif old_z.ndim == 1:
f = interpolate.interp1d(old_z, var, kind='linear',
bounds_error=bounds_error)
out = f(new_z)
# reroll lon dim axis to original dim
out = out.reshape(new_shape)
out = np.rollaxis(out, ndim - 1, zdim)
return out
def _grid_smooth_bes(x):
"""
Bessel function. (copied from RIP)
:param x: float number
:return: bessel function value.
"""
rint = 0.0
for i in range(1000):
u = i * 0.001 - 0.0005
rint = rint + np.sqrt(1 - u*u) * np.cos(x*u)*0.001
return 2.0 * x * rint / (4.0 * | np.arctan(1.0) | numpy.arctan |
import numpy as np
import pandas as pd
import pytest
from numpy.testing import assert_almost_equal
from numpy.testing import assert_array_almost_equal
from ruspy.config import TEST_RESOURCES_DIR
from ruspy.estimation.estimation import estimate
TEST_FOLDER = TEST_RESOURCES_DIR + "replication_test/"
@pytest.fixture(scope="module")
def inputs():
out = {}
disc_fac = 0.9999
num_states = 90
scale = 1e-5
num_params = 3
lb = np.concatenate((np.full(num_states, -np.inf), np.full(num_params, 0.0)))
ub = np.concatenate(( | np.full(num_states, 50.0) | numpy.full |
import numpy as np
from cvxopt import matrix
from cvxopt import solvers
import numpy as np
import gym
from gym import spaces
import matplotlib.pyplot as plt
# local modules
from cbf.utilities import cbf_microgrid_v0, cbf_microgrid_v1, cbf_microgrid_dist_v0, plot_signals
from models.buck_microgrid import Buck_microgrid_v0, Buck_microgrid_v1
with_L = False
inc_mat = np.array([[-1, 0, 0, -1],[1, -1, 0, 0],[0, 1, -1, 0],[0, 0, 1, 1 ]])
lap_mat = | np.matmul(inc_mat, inc_mat.T) | numpy.matmul |
import numpy as np
from scipy import signal
def met_preproc(s, fs, met_try='diff', o=None):
if o is None:
o = (2 * fs) + 1
if met_try == 'diff':
s = np.diff(np.concatenate((np.array([s[0]]), s)))
elif met_try == 'hpnc':
# note that this is acausal! (on purpose, to answer reviewer)
o = int(2 * (5 * fs) + 1)
hp_filter = {'a': 1, 'b': signal.firwin(o, [1/(fs/2)], pass_zero=False)}
#X s = signal.lfilter(hp_filter['b'], hp_filter['a'], s)
s = signal.filtfilt(hp_filter['b'], hp_filter['a'], s)
elif met_try == 'subsmooth':
s = s - signal.lfilter(np.ones(o)/o, 1, s)
else:
raise Exception("met_try in sig_preproc mispecified")
s = s/np.std(s)
return s
def slice_signal(event_ix, sig, time, ix_back=0, ix_forward=0):
ix_cut_before_event = ix_back
ix_cut_after_previous_event = ix_forward
# try to include first event
ix_start = event_ix[0] - np.round(np.mean(np.diff(event_ix)))
if ix_start < 0: ix_start = 0
ev_cut = np.zeros((len(event_ix), 2))
ev_cut[0][0] = ix_start
ev_cut[0][1] = event_ix[0]
for ix_a in range(1, len(event_ix)): # 1 indexing is on purpose.
ix_from = event_ix[ix_a - 1] + ix_cut_after_previous_event
ix_to = event_ix[ix_a] - ix_cut_before_event
assert ix_from < ix_to, 'ix_back or ix_forward is too big. ix_from: {}, ix_to: {}'.format(ix_from, ix_to)
ev_cut[ix_a][0] = np.round(ix_from)
ev_cut[ix_a][1] = np.round(ix_to)
sig_ev = list()
time_ev = list()
for ix_ev_cut in range(0, len(ev_cut)):
ix_s = int(ev_cut[ix_ev_cut][0])
ix_e = int(ev_cut[ix_ev_cut][1])
sig_ev.append(sig[ix_s:ix_e])
time_ev.append(time[ix_s:ix_e])
return sig_ev, time_ev
def slice_signal_matrix(event_ix, sig, time, fs, t_from=0, t_to=0, remove_baseline=False, ix_back=0, t_baseline=0):
""" t_from should be negative if you want to go before event"""
ix_from = np.round(t_from*fs).astype(int)
ix_to = | np.round(t_to*fs) | numpy.round |
"""
Test the reinforcement learning algorithm.
"""
import warnings
warnings.simplefilter(action='ignore', category=FutureWarning)
import keras
import audiosegment
import enum
import logging
import numpy as np
import os
import random
import sys
import unittest
path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..")
sys.path.insert(0, path)
import internals.rl.agent as agent # pylint: disable=locally-disabled, import-error
import internals.rl.environment as environment # pylint: disable=locally-disabled, import-error
# Configure the logger
logging.basicConfig(filename="TestLog.log", filemode='w', level=logging.DEBUG)
class XORSingleStepTestRig:
"""
XOR environment where each step is terminal and randomly drawn from the four possible inputs.
"""
def __init__(self):
pass
@staticmethod
def observation_space():
dtype = np.float32
high = np.array([1, 1], dtype=np.float32)
low = np.array([0, 0], dtype=np.float32)
shape = (2,)
return environment.ObservationSpace(dtype, high, low, shape)
@staticmethod
def action_shape():
return (1,)
@staticmethod
def sample():
"""
Return one of the four possible observations with uniform random chance.
"""
choices = [
np.array([1, 1], dtype=np.float32),
np.array([1, 0], dtype=np.float32),
np.array([0, 1], dtype=np.float32),
np.array([0, 0], dtype=np.float32)
]
return random.choice(choices)
@staticmethod
def behavior(obs, action, lastobs):
"""
Create an environment of the form:
{
Step.state of [1, 1]:
Step.state of [0, 0]:
Step.action == 0 => Reward = +1, end
Step.action otherwise => Reward = -1, end
Step.state of [1, 0]:
Step.state of [0, 1]:
Step.action == 1 => Reward = +1, end
Step.action otherwise => Reward = -1, end
}
Every step is terminal, regardless of action chosen. Each observation
is randomly drawn from the four possibilities at reset.
"""
if not hasattr(action, 'shape'):
action = np.array([action], dtype=np.float32)
assert action.shape == (1,)
obslist = [int(round(i)) for i in obs.tolist()]
if obslist == [1, 1] or obslist == [0, 0]:
if int(round(action[0])) == 0:
o = lastobs
r = 1
d = True
else:
o = lastobs
r = -1
d = True
else:
if int(round(action[0])) == 1:
o = lastobs
r = 1
d = True
else:
o = lastobs
r = -1
d = True
logging.debug("Observation: {} -> Action: {} -> Reward: {}".format(o, int(round(action[0])), r))
return o, r, d
class XORTestRig:
"""
XOR environment that goes through all four possible XOR inputs in order.
"""
def __init__(self):
pass
@staticmethod
def observation_space():
dtype = np.float32
high = np.array([1, 1], dtype=np.float32)
low = np.array([0, 0], dtype=np.float32)
shape = (2,)
return environment.ObservationSpace(dtype, high, low, shape)
@staticmethod
def action_shape():
return (1,)
@staticmethod
def behavior(obs, action, lastobs):
"""
Create an environment of the form:
{
Step.state of [1, 1]:
Step.state of [0, 0]:
Step.action == 0 => Reward = +1
Step.action otherwise => Reward = -1, end
Step.state of [1, 0]:
Step.state of [0, 1]:
Step.action == 1 => Reward = +1
Step.action otherwise => Reward = -1, end
}
Environment proceeds through the list:
[0, 0]
[0, 1]
[1, 0]
[1, 1]
and ends after the last item or as soon as the agent makes
an incorrect response.
"""
if not hasattr(action, 'shape'):
action = np.array([action], dtype=np.float32)
assert action.shape == (1,)
obslist = [int(round(i)) for i in obs.tolist()]
if obslist == [1, 1] or obslist == [0, 0]:
if int(round(action[0])) == 0:
nextobs = lastobs if obslist == [1, 1] else np.array([0, 1], dtype=np.float32)
done = obslist == [1, 1]
o = nextobs
r = 1
d = done
else:
o = lastobs
r = -1
d = True
else:
if int(round(action[0])) == 1:
nextobs = np.array([1, 0], dtype=np.float32) if obslist == [0, 1] else np.array([1, 1], dtype=np.float32)
o = nextobs
r = 1
d = False
else:
o = lastobs
r = -1
d = True
logging.debug("Observation: {} -> Action: {} -> Reward: {}".format(o, int(round(action[0])), r))
return o, r, d
class TestRL(unittest.TestCase):
__skip_the_long_ones = False
class FirstObs(enum.Enum):
XOR = | np.array([0, 0], dtype=np.float32) | numpy.array |
"""Solution for up-and-in option with antithetic Monte-Carlo"""
import numpy as np
################################################################################
# Simulation parameters
M = 10000
r = 0.02
sg = 0.3
dt = 1 / 252
T = 1
n = int(T / dt)
S0 = 1
H = 1.1
K = 0.9
################################################################################
if __name__ == '__main__':
# Generate random numbers from a normal distribution for the MC simulation
eps = np.random.normal(size=(n, M))
# Initialize empty vectors
V = np.zeros((M))
V_ = np.zeros((M))
W = np.zeros((M))
# Iterate through M iterations
for i in range(M):
S1 = np.zeros((n))
S2 = np.zeros((n))
S1[0] = S0
S2[0] = S0
# Iterate through n - 1 time steps (first time step is known)
for j in range(n - 1):
# normal pricing is stored in S1
S1[j + 1] = S1[j] * np.exp((r - 0.5 * sg ** 2) * dt \
+ sg * eps[j, i] * np.sqrt(dt))
# antitetic variate pricing is stored in S2
S2[j + 1] = S2[j] * np.exp((r - 0.5 * sg ** 2) * dt \
- sg * eps[j, i] * np.sqrt(dt))
# Find the maximum value of the realized stock price path
S_tmax = np.max(S1)
S_amax = np.max(S2)
# Test if the price path exceeded the barrier H
# if so, the option is exercisable
# then the pay off is max(S(T) - K, 0)
if S_tmax > H:
# normal pricing
V[i] = np.exp(-r * T) * np.max(S1[-1] - K, 0)
if S_amax > H:
# for use in antithetic pricing
V_[i] = np.exp(-r * T) * np.max(S2[-1] - K, 0)
# antithetic pricing
W[i] = 0.5 * (V[i] + V_[i])
# Print the results
print('Price (mean), normal pricing:', np.mean(V))
print('Price (mean), antithetic pricing:', | np.mean(W) | numpy.mean |
"""
Author: michealowen
Last edited: 2019.12.5,Thursday
种群模块,固定拓扑结构
"""
#encoding=UTF-8
import numpy as np
import genome
import numba
from mnist import MNIST
from activation import sigmoid,new_sigmoid
from normalization import Normalize
#两种变异类型,权值变异和偏置变异
MUTATE_TYPE = ['WEIGHT_MUTATE','BIAS_MUTATE']
class Population:
"""
种群类,完成个体间的选择,交叉,变异
"""
def __init__(self,pop_size,generation_size,layers,test_data,mutate_range=2):
'''
初始化种群
Params:
pop_size:种群大小
generation_size:遗传代数
layers:网络的拓扑结构 例如[784,30,10]
test_data:测试数据
mute_range:基因变异的幅度,(~5~5)
'''
self.pop_size = pop_size
self.generation_size = generation_size
self.layers = layers
self.test_data = test_data
#self.select_range = select_range
#self.crossover_rate = crossover_rate
#self.mutate_rate = 0
self.mutate_range = mutate_range
#初始化种群
self.__get_population()
self.evolution()
pass
def __get_population(self):
'''
初始化种群,种群大小为pop_size
'''
self.pop = []
for i in range(self.pop_size):
self.pop.append(genome.Genome(self.layers))
pass
def mutate(self):
'''
mutate_rate = e^(fitness/10)-1
'''
for p in self.pop:
#p.gene_string = np.array([s*(np.random.random()*2*self.mutate_range-self.mutate_range) if np.random.random() <= self.mutate_rate
#else s for s in p.gene_string ])
p.weights_string = np.array([s*(np.random.random()*2*self.mutate_range-self.mutate_range) if np.random.random() <= self.mutate_rate
else s for s in p.weights_string ])
p.bias_string = np.array([s*(np.random.random()*2*self.mutate_range-self.mutate_range) if | np.random.random() | numpy.random.random |
# -*- coding: utf-8 -*-
"""
Created on Sun Jan 21 15:39:49 2018
@author: ZMJ
"""
import numpy as np
import time
from scipy.ndimage import gaussian_filter
from skimage.morphology import reconstruction
##ROF去噪
def denoise_rof(im, U_init, tolerance=0.1, tau=0.125, tv_weight=100):
""" An implementation of the Rudin-Osher-Fatemi (ROF) denoising model
using the numerical procedure presented in Eq. (11) of A. Chambolle
(2005). Implemented using periodic boundary conditions
(essentially turning the rectangular image domain into a torus!).
Input:
im - noisy input image (grayscale)
U_init - initial guess for U
tv_weight - weight of the TV-regularizing term
tau - steplength in the Chambolle algorithm
tolerance - tolerance for determining the stop criterion
Output:
U - denoised and detextured image (also the primal variable)
T - texture residual"""
#---Initialization
m,n = im.shape #size of noisy image
U = U_init
Px = im #x-component to the dual field
Py = im #y-component of the dual field
error = 1
iteration = 0
#---Main iteration
while (error > tolerance):
Uold = U
#Gradient of primal variable
LyU = np.vstack((U[1:,:],U[0,:])) #Left translation w.r.t. the y-direction
LxU = np.hstack((U[:,1:],U.take([0],axis=1))) #Left translation w.r.t. the x-direction
GradUx = LxU-U #x-component of U's gradient
GradUy = LyU-U #y-component of U's gradient
#First we update the dual varible
PxNew = Px + (tau/tv_weight)*GradUx #Non-normalized update of x-component (dual)
PyNew = Py + (tau/tv_weight)*GradUy #Non-normalized update of y-component (dual)
NormNew = np.maximum(1,np.sqrt(PxNew**2+PyNew**2))
Px = PxNew/NormNew #Update of x-component (dual)
Py = PyNew/NormNew #Update of y-component (dual)
#Then we update the primal variable
RxPx =np.hstack((Px.take([-1],axis=1),Px[:,0:-1])) #Right x-translation of x-component
RyPy = np.vstack((Py[-1,:],Py[0:-1,:])) #Right y-translation of y-component
DivP = (Px-RxPx)+(Py-RyPy) #Divergence of the dual field.
U = im + tv_weight*DivP #Update of the primal variable
#Update of error-measure
error = np.linalg.norm(U-Uold)/np.sqrt(n*m);
iteration += 1;
#The texture residual
# T = im - U
return U
##形态学
def transform(img):
img=gaussian_filter(img,2.5)
seed=np.copy(img)
seed[1:-1,1:-1]=img.min()
mask=img
##morphology processing
pro_img=reconstruction(seed,mask,method="dilation")
return img-pro_img
def switchPreProcessing(band1,band2,mode="01"):
start=time.time()
if mode=="01":
X_band_3=np.array([(band-np.min(band))/(np.max(band)-np.min(band)) for band in band1])
X_band_4=np.array([(band-np.min(band))/(np.max(band)-np.min(band)) for band in band2])
X_band_5=np.fabs(np.subtract(X_band_3,X_band_4))
elif mode=="02":
X_band_3=np.fabs(np.subtract(band1,band2))
X_band_4=np.maximum(band1,band2)
X_band_5=np.minimum(band1,band2)
elif mode=="03":
x_band_temp=band1+band2
X_band_3=np.array([(band-np.mean(band)/(np.max(band)-np.min(band))) for band in band1])
X_band_4=np.array([(band-np.mean(band)/(np.max(band)-np.min(band))) for band in band2])
X_band_5=np.array([(band-np.mean(band)/(np.max(band)-np.min(band))) for band in x_band_temp])
elif mode=="04":
x_band_temp=band1+band2
X_band_3=np.array([(band-np.min(band)/(np.max(band)-np.min(band))) for band in band1])
X_band_4=np.array([(band-np.min(band)/(np.max(band)- | np.min(band) | numpy.min |
import numpy as np
import pytest
from ..utils import ArrayDeque, ExperienceCache, softmax
from ..errors import ArrayDequeOverflowError
def test_softmax():
rnd = np.random.RandomState(7)
w = rnd.randn(3, 5)
x = softmax(w, axis=1)
y = softmax(w + 100., axis=1)
z = softmax(w * 100., axis=1)
# check shape
assert x.shape == w.shape
# check normalization
np.testing.assert_almost_equal(x.sum(axis=1), np.ones(3))
# check translation invariance
np.testing.assert_almost_equal(y.sum(axis=1), np.ones(3))
np.testing.assert_almost_equal(x, y)
# check robustness by clipping
assert not np.any(np.isnan(z))
np.testing.assert_almost_equal(z.sum(axis=1), np.ones(3))
class TestArrayDeque:
def test_cycle(self):
d = ArrayDeque(shape=[], maxlen=3, overflow='cycle')
d.append(1)
d.append(2)
d.append(3)
np.testing.assert_array_equal(d.array, [1, 2, 3])
d.append(4)
np.testing.assert_array_equal(d.array, [2, 3, 4])
assert d.pop() == 4
np.testing.assert_array_equal(d.array, [2, 3])
d.append(5)
np.testing.assert_array_equal(d.array, [2, 3, 5])
d.append(6)
np.testing.assert_array_equal(d.array, [3, 5, 6])
assert d.popleft() == 3
np.testing.assert_array_equal(d.array, [5, 6])
assert d.pop() == 6
assert len(d) == 1
assert d
assert d.pop() == 5
assert len(d) == 0
assert not d
with pytest.raises(IndexError, match="pop from an empty deque"):
d.pop()
with pytest.raises(IndexError, match="pop from an empty deque"):
d.popleft()
def test_error(self):
d = ArrayDeque(shape=[], maxlen=3, overflow='error')
d.append(1), d.append(2), d.append(3)
np.testing.assert_array_equal(d.array, [1, 2, 3])
with pytest.raises(ArrayDequeOverflowError):
d.append(4)
def test_grow(self):
d = ArrayDeque(shape=[], maxlen=3, overflow='grow')
d.append(1), d.append(2), d.append(3)
np.testing.assert_array_equal(d.array, [1, 2, 3])
d.append(4)
np.testing.assert_array_equal(d.array, [1, 2, 3, 4])
assert d.pop() == 4
np.testing.assert_array_equal(d.array, [1, 2, 3])
assert d.popleft() == 1
assert d.pop() == 3
assert d.popleft() == 2
assert not d
with pytest.raises(IndexError, match="pop from an empty deque"):
d.pop()
with pytest.raises(IndexError, match="pop from an empty deque"):
d.popleft()
class TestExperienceCache:
@staticmethod
def create_obj(seed, length):
rnd = np.random.RandomState(seed)
ec = ExperienceCache()
for i in range(length):
X = rnd.randn(1, 5)
X[0, 0] = i
A = rnd.randint(4, size=1)
R = rnd.randn(1)
X_next = rnd.randn(1, 5)
ec.append(X, A, R, X_next)
return ec
def test_pop(self):
ec = self.create_obj(seed=13, length=7)
assert len(ec) == 7
X, A, R, X_next = ec.pop()
assert len(ec) == 6
np.testing.assert_array_almost_equal(
X, [[6.0, -0.072247, 0.122339, -0.126747, -0.735211]])
np.testing.assert_array_almost_equal(R, [0.318789])
np.testing.assert_array_almost_equal(A, [0])
np.testing.assert_array_almost_equal(
X_next, [[-1.38233, 1.486765, 1.580075, 1.75342, 0.529771]])
def test_popleft(self):
ec = self.create_obj(seed=13, length=7)
assert len(ec) == 7
X, A, R, X_next = ec.popleft()
assert len(ec) == 6
np.testing.assert_array_almost_equal(
X, [[0., 0.753766, -0.044503, 0.451812, 1.345102]])
np.testing.assert_array_almost_equal(R, [0.532338])
np.testing.assert_array_almost_equal(A, [2])
np.testing.assert_array_almost_equal(
X_next, [[-1.58899, -1.114284, 0.683527, 0.272894, -0.230848]])
def test_popleft_nstep(self):
n = 4
ec = self.create_obj(seed=13, length=7)
assert len(ec) == 7
X, A, R, X_next = ec.popleft_nstep(n)
assert R.shape == (4,)
assert len(ec) == 6
np.testing.assert_array_almost_equal(
X, [[0., 0.753766, -0.044503, 0.451812, 1.345102]])
np.testing.assert_array_almost_equal(
R, [0.532338, 0.466986, 1.476737, 0.490872])
np.testing.assert_array_almost_equal(A, [2])
np.testing.assert_array_almost_equal(
X_next, [[-1.38233, 1.486765, 1.580075, 1.75342, 0.529771]])
X, A, R, X_next = ec.popleft_nstep(n)
assert R.shape == (4,)
assert len(ec) == 5
assert X[0, 0] == 1
X, A, R, X_next = ec.popleft_nstep(n)
assert R.shape == (4,)
assert len(ec) == 4
assert X[0, 0] == 2
assert X_next is not None
X, A, R, X_next = ec.popleft_nstep(n)
assert R.shape == (4,)
assert len(ec) == 3
assert X[0, 0] == 3
assert X_next is not None
X, A, R, X_next = ec.popleft_nstep(n)
assert R.shape == (3,)
assert len(ec) == 2
assert X_next is None
np.testing.assert_array_almost_equal(
X, [[4., -1.512845, -0.764034, 0.10127, -0.317266]])
np.testing.assert_array_almost_equal(
R, [1.138333, -1.069344, 0.318789])
| np.testing.assert_array_almost_equal(A, [3]) | numpy.testing.assert_array_almost_equal |
#!/usr/bin/env python
# coding: utf-8
import os
import numpy as np
import random
import math
import pydicom
import pandas as pd
import shutil
import tensorflow as tf
import xml.etree.ElementTree as ET
from functools import partial, update_wrapper
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
os.environ['TF_ENABLE_AUTO_MIXED_PRECISION'] = '1'
# Retrieving blocks of a numpy array
from skimage.util import view_as_blocks
# Retrieving blocks of a numpy array with given stride sizes
from skimage.util.shape import view_as_windows
from random import randint
from tqdm import tqdm
from random import randint
import matplotlib.pyplot as plt
from keras.models import Model, load_model
from keras.layers import Input, Flatten, Dense, concatenate, Conv2D, Conv3D, MaxPooling2D, MaxPooling3D, \
Conv2DTranspose, Conv3DTranspose
from keras.layers import Activation, add, multiply, Lambda
from keras.layers import AveragePooling2D, AveragePooling3D, average, UpSampling2D, UpSampling3D, Dropout
from keras.optimizers import Adam, SGD, RMSprop
from keras.initializers import glorot_normal, random_normal, random_uniform
from keras.callbacks import ModelCheckpoint, TensorBoard, EarlyStopping
from tensorflow.keras.callbacks import *
from keras import backend as K
from keras.layers.normalization import BatchNormalization
from keras.losses import binary_crossentropy
import numpy as np
from hyperopt import fmin, hp, tpe, Trials, space_eval
from hyperopt.pyll import scope as ho_scope
from hyperopt.pyll.stochastic import sample as ho_sample
class plaquetypes:
limits = pd.DataFrame(
[['DenseCalcium', 351, 10000], ['Fibrous', 131, 350], ['FibrousFatty', 76, 130], ['NecroticCore', -30, 75],
['NonCalcified', -1000, 350]], columns=['type', 'lower', 'upper'])
# ,['MedisDenseCalcium',351,10000],['MedisFibrous',151,350],['MedisFibrousFatty',31,150],['MedisNecroticCore',-100,30]
def wrapped_partial(func, *args, **kwargs):
partial_func = partial(func, *args, **kwargs)
update_wrapper(partial_func, func)
return partial_func
def get_pairs(vesel_list):
return_list = []
for ID in vesel_list:
if ID.endswith('NoContour.dcm'):
return_list.append([ID, ID[:-13] + "Contour1.dcm", ID[:-13] + "Contour2.dcm", ID[:8]])
return return_list
def find_included_segment(xml_file):
try:
doc = ET.parse(xml_file)
root = doc.getroot()
info = 0
included = False
while not (included):
info += 1
if (root[2][info][25].attrib['value'] == 'SEGMENT_TYPE_NORMAL'):
breakpoints = [root[2][info][24].attrib['value'], root[2][info][1].attrib['value']]
included = True
except:
doc = ET.parse(xml_file)
root = doc.getroot()
info = 0
included = False
while not (included):
info += 1
if (root[3][info][25].attrib['value'] == 'SEGMENT_TYPE_NORMAL'):
breakpoints = [root[3][info][24].attrib['value'], root[3][info][1].attrib['value']]
included = True
return breakpoints
def get_xml(basic_path2, dicom):
dicom = dicom.replace('_', '/')
dicom = dicom[:-13] + 'data_model.xml'
xml_file = os.path.join(basic_path2, dicom)
return xml_file
def get_image_mask_for_ID_tuple(ID_tuple, basic_path, basic_path2, dir_to_save, plaques_only):
image_path = os.path.join(basic_path, ID_tuple[0])
mask_1_path = os.path.join(basic_path, ID_tuple[1])
mask_2_path = os.path.join(basic_path, ID_tuple[2])
image = pydicom.dcmread(image_path)
mask_1 = pydicom.dcmread(mask_1_path)
mask_2 = pydicom.dcmread(mask_2_path)
if plaques_only==True:
xml_file = get_xml(basic_path2, ID_tuple[0])
breakpoints = np.array(find_included_segment(xml_file))
breakpoints = breakpoints.astype(float)
breakpoints = breakpoints / image.SpacingBetweenSlices
if 'Plakk' in dir_to_save:
image_array = (image.pixel_array)[int(breakpoints[0]):int(breakpoints[1]), :, :]
mask_1_array = (mask_1.pixel_array)[int(breakpoints[0]):int(breakpoints[1]), :, :]
mask_2_array = (mask_2.pixel_array)[int(breakpoints[0]):int(breakpoints[1]), :, :]
else:
image_array = (image.pixel_array)[int(breakpoints[0]):, :, :]
mask_1_array = (mask_1.pixel_array)[int(breakpoints[0]):, :, :]
mask_2_array = (mask_2.pixel_array)[int(breakpoints[0]):, :, :]
else:
image_array = (image.pixel_array)
mask_1_array = (mask_1.pixel_array)
mask_2_array = (mask_2.pixel_array)
return [image_array, mask_1_array, mask_2_array]
def apply_breakpoints(image_array, breakpoints, dir_to_save):
if 'Plakk' in dir_to_save:
image_array = (image_array)[int(breakpoints[0]):int(breakpoints[1]), :, :]
else:
image_array = (image_array)[int(breakpoints[0]):, :, :]
return image_array
def osszefuz(x):
x.append(x[0][:7])
x.append(x[0][16:18])
return x
def save_all_patch_for_image_mask_pair(ID_tuple,
dir_to_save,
patch_shape,
stride_size,
train_val_test,
basic_path,
basic_path2,
truncate=True,
plaques_only=False
):
"""Saves all 3 dimensional patches
Arguments
-----------
ID_tuple
dir_to_save : string
Folder to save the patches.
train_val_test : string
possible values: 'train', 'val', or 'test'.
Subfolders for dataset split.
Outputs
-----------
None
"""
image_array, mask_1, mask_2 = get_image_mask_for_ID_tuple(ID_tuple, basic_path, basic_path2, dir_to_save,plaques_only)
mask_1 = np.where(mask_1 > 0, 1, 0)
mask_2 = np.where(mask_2 > 0, 1, 0)
dif_array = np.where(mask_2 - mask_1 == 1, 1, 0)
# dif_array = get_all_plaques(dif_array)
# Count saved patches
total_patches_for_ID = 0
image_to_pad = image_array
nodule_to_pad = mask_1
lung_to_pad = mask_2
dif_to_pad = dif_array
# Order of the saved patch, appended to filename
patch_count = 0
# Shape of original images
size_X = image_to_pad.shape[2]
size_Y = image_to_pad.shape[1]
size_Z = image_to_pad.shape[0]
image_to_block = np.zeros((size_Z + patch_shape[2],
size_Y,
size_X))
image_to_block[:size_Z, :size_Y, :size_X] = image_to_pad
nodule_to_block = np.zeros((size_Z + patch_shape[2],
size_Y,
size_X))
nodule_to_block[:size_Z, :size_Y, :size_X] = nodule_to_pad
lung_to_block = np.zeros((size_Z + patch_shape[2],
size_Y,
size_X))
lung_to_block[:size_Z, :size_Y, :size_X] = lung_to_pad
dif_to_block = np.zeros((size_Z + patch_shape[2],
size_Y,
size_X))
dif_to_block[:size_Z, :size_Y, :size_X] = dif_to_pad
# patch_shape is originally in order XYZ, however for view as window we need it in ZYX
patch_shape_ZYX = [patch_shape[2], patch_shape[1], patch_shape[0]]
# Same as patch_shape
stride_size_ZYX = [stride_size[2], stride_size[1], stride_size[0]]
# Create blocks of the numpy arrays using view_as_blocks from skimage.util
image_patches = view_as_windows(image_to_block, window_shape=patch_shape_ZYX, step=stride_size_ZYX)
nodule_patches = view_as_windows(nodule_to_block, window_shape=patch_shape_ZYX, step=stride_size_ZYX)
lung_patches = view_as_windows(lung_to_block, window_shape=patch_shape_ZYX, step=stride_size_ZYX)
dif_patches = view_as_windows(dif_to_block, window_shape=patch_shape_ZYX, step=stride_size_ZYX)
# view_as_windows creates 6 dimensional numpy arrays:
# first 3 dimensions encode the position of the patch, last 3 dimensions encode patch shape.
# We will iterate through the number of patches
number_of_patches = image_patches.shape[0] * image_patches.shape[1] * image_patches.shape[2]
for counter in range(number_of_patches):
patch_coor_1 = int(counter // (image_patches.shape[1] * image_patches.shape[2]))
patch_coor_2 = int(((counter - patch_coor_1 * image_patches.shape[1] * image_patches.shape[2])
// image_patches.shape[2]))
patch_coor_3 = int(counter - patch_coor_1 * image_patches.shape[1] * image_patches.shape[2]
- patch_coor_2 * image_patches.shape[2])
image_patch = image_patches[patch_coor_1][patch_coor_2][patch_coor_3]
nodule_patch = nodule_patches[patch_coor_1][patch_coor_2][patch_coor_3]
lung_patch = lung_patches[patch_coor_1][patch_coor_2][patch_coor_3]
dif_patch = dif_patches[patch_coor_1][patch_coor_2][patch_coor_3]
if truncate == True:
# vedd ki a 16:48
image_patch = image_patch[:, 16:48, 16:48]
nodule_patch = nodule_patch[:, 16:48, 16:48]
lung_patch = lung_patch[:, 16:48, 16:48]
dif_patch = dif_patch[:, 16:48, 16:48]
if plaques_only and np.count_nonzero(dif_patch) > 0:
image_patch_file = os.path.join(dir_to_save, train_val_test, "images",
ID_tuple[0][:-13] + str(patch_count) + '.npy')
np.save(image_patch_file, image_patch.astype(np.float32))
nodule_patch_file = os.path.join(dir_to_save, train_val_test, "masks_1",
ID_tuple[0][:-13] + str(patch_count) + '.npy')
np.save(nodule_patch_file, nodule_patch.astype(np.uint8))
lung_patch_file = os.path.join(dir_to_save, train_val_test, "masks_2",
ID_tuple[0][:-13] + str(patch_count) + '.npy')
np.save(lung_patch_file, lung_patch.astype(np.uint8))
plaque_patch_file = os.path.join(dir_to_save, train_val_test, "plaques",
ID_tuple[0][:-13] + str(patch_count) + '.npy')
np.save(plaque_patch_file, dif_patch.astype(np.uint8))
patch_count += 1
total_patches_for_ID += 1
if plaques_only == False:
image_patch_file = os.path.join(dir_to_save, train_val_test, "images",
ID_tuple[0][:-13] + str(patch_count) + '.npy')
np.save(image_patch_file, image_patch.astype(np.float32))
nodule_patch_file = os.path.join(dir_to_save, train_val_test, "masks_1",
ID_tuple[0][:-13] + str(patch_count) + '.npy')
np.save(nodule_patch_file, nodule_patch.astype(np.uint8))
lung_patch_file = os.path.join(dir_to_save, train_val_test, "masks_2",
ID_tuple[0][:-13] + str(patch_count) + '.npy')
np.save(lung_patch_file, lung_patch.astype(np.uint8))
plaque_patch_file = os.path.join(dir_to_save, train_val_test, "plaques",
ID_tuple[0][:-13] + str(patch_count) + '.npy')
np.save(plaque_patch_file, dif_patch.astype(np.uint8))
patch_count += 1
total_patches_for_ID += 1
def save_all_patch(ID_tuple_list,
dir_to_save,
patch_shape,
stride_size,
basic_path,
basic_path2,
truncate=True,
train_val_test_split=[0.8, 0.2, 0.0],
plaques_only=True,
val_patients=None,
test_patients=None):
# First delete the directory, where we would like to save the patches to avoid naming collisions
if os.path.exists(dir_to_save):
shutil.rmtree(dir_to_save)
# Create parent directory
os.mkdir(dir_to_save)
os.mkdir(os.path.join(dir_to_save, "file_logs"))
# Then create folders train, test, val containing images and masks folders.
train_dir, test_dir, val_dir = [os.path.join(dir_to_save, "train"),
os.path.join(dir_to_save, "test"),
os.path.join(dir_to_save, "val")]
# Create train_dir
os.mkdir(train_dir)
os.mkdir(os.path.join(train_dir, "images"))
os.mkdir(os.path.join(train_dir, "plaques"))
os.mkdir(os.path.join(train_dir, "masks_1"))
os.mkdir(os.path.join(train_dir, "masks_2"))
# Create test_dir
os.mkdir(test_dir)
os.mkdir(os.path.join(test_dir, "images"))
os.mkdir(os.path.join(test_dir, "plaques"))
os.mkdir(os.path.join(test_dir, "masks_1"))
os.mkdir(os.path.join(test_dir, "masks_2"))
# Create val_dir
os.mkdir(val_dir)
os.mkdir(os.path.join(val_dir, "images"))
os.mkdir(os.path.join(val_dir, "plaques"))
os.mkdir(os.path.join(val_dir, "masks_1"))
os.mkdir(os.path.join(val_dir, "masks_2"))
total_number_of_IDs = len(ID_tuple_list)
# Create thresholds for train-val-test split
number_of_IDs_train = int(train_val_test_split[0] * total_number_of_IDs)
number_of_IDs_val = int(train_val_test_split[1] * total_number_of_IDs)
number_of_IDs_test = int(train_val_test_split[2] * total_number_of_IDs)
patients = []
for counter, ID_tuple in tqdm(enumerate(ID_tuple_list)):
patients.append(ID_tuple[3])
patients = np.unique(patients)
random.seed(42)
if test_patients==None:
test_patients = random.sample(set(patients).difference(set(val_patients)),
int(len(patients) * train_val_test_split[2]))
if val_patients==None:
val_patients = random.sample(set(patients), int(len(patients) * train_val_test_split[1]))
# Save images to the corresponding subfolders using the functions above.
for counter, ID_tuple in tqdm(enumerate(ID_tuple_list)):
if ID_tuple[3].rstrip('_') in val_patients:
train_val_test = "val"
elif ID_tuple[3].rstrip('_') in test_patients:
train_val_test = "test"
else:
train_val_test = "train"
save_all_patch_for_image_mask_pair(ID_tuple,
patch_shape=patch_shape,
stride_size=stride_size,
truncate=truncate,
dir_to_save=dir_to_save,
train_val_test=train_val_test,
basic_path=basic_path,
basic_path2=basic_path2,
plaques_only=plaques_only)
return val_patients
epsilon = 1e-5
smooth = 1
def dsc(y_true, y_pred, args):
smooth = args.smooth
y_true_f = K.flatten(y_true)
y_pred_f = K.flatten(y_pred)
intersection = K.sum(y_true_f * y_pred_f)
score = (2. * intersection + smooth) / (K.sum(y_true_f) + K.sum(y_pred_f) + smooth)
return score
def dice_loss(y_true, y_pred, args):
loss = 1 - dsc(y_true, y_pred, args)
return loss
def tp(y_true, y_pred, args):
smooth = args.smooth
y_pred_pos = K.round(K.clip(y_pred, 0, 1))
y_pos = K.round(K.clip(y_true, 0, 1))
tp = (K.sum(y_pos * y_pred_pos) + smooth) / (K.sum(y_pos) + smooth)
return tp
def tn(y_true, y_pred, args):
smooth = args.smooth
y_pred_pos = K.round(K.clip(y_pred, 0, 1))
y_pred_neg = 1 - y_pred_pos
y_pos = K.round(K.clip(y_true, 0, 1))
y_neg = 1 - y_pos
tn = (K.sum(y_neg * y_pred_neg) + smooth) / (K.sum(y_neg) + smooth)
return tn
def fp(y_true, y_pred, args):
smooth = args.smooth
y_pred_pos = K.round(K.clip(y_pred, 0, 1))
y_pred_neg = 1 - y_pred_pos
y_pos = K.round(K.clip(y_true, 0, 1))
y_neg = 1 - y_pos
fp = (K.sum(y_neg * y_pred_pos) + smooth) / (K.sum(y_pred) + smooth)
return fp
def fn(y_true, y_pred, args):
smooth = args.smooth
y_pred_pos = K.round(K.clip(y_pred, 0, 1))
y_pred_neg = 1 - y_pred_pos
y_pos = K.round(K.clip(y_true, 0, 1))
y_neg = 1 - y_pos
fn = (K.sum(y_pos * y_pred_neg) + smooth) / (K.sum(y_pred_neg) + smooth)
return fn
def tversky(y_true, y_pred, args):
smooth = args.smooth
y_true_pos = K.flatten(y_true)
y_pred_pos = K.flatten(y_pred)
true_pos = K.sum(y_true_pos * y_pred_pos)
false_neg = K.sum(y_true_pos * (1 - y_pred_pos))
false_pos = K.sum((1 - y_true_pos) * y_pred_pos)
alpha = args.alpha
return (true_pos + smooth) / (true_pos + alpha * false_neg + (1 - alpha) * false_pos + smooth)
def tversky_loss(y_true, y_pred, args):
return 1 - tversky(y_true, y_pred, args)
def focal_tversky(y_true, y_pred, args):
gamma = args.gamma = 0.75
pt_1 = tversky(y_true, y_pred, args)
return K.pow((1 - pt_1), gamma)
def multiloss(y_true, y_pred, args):
if args.loss_type == 1:
return focal_tversky(y_true, y_pred, args)
else:
return dice_loss(y_true, y_pred, args)
# Visaulization functions
def gray_to_colored(im):
colored = np.repeat(np.expand_dims(im, axis=-1), 3, axis=-1).astype(float)
colored = 1 * (colored - np.amin(colored)) / (np.amax(colored) - np.amin(colored))
return colored
def superimpose_mask(image_array, mask_array, opacity=0.8):
superimposed = gray_to_colored(image_array)
reds = np.zeros(mask_array.shape + (3,)).astype(np.bool)
reds[:, :, 0] = mask_array == 1
superimposed[reds] = opacity * 1 + (1 - opacity) * superimposed[reds]
return superimposed
def visualize_slice_mask_pair(image_array, mask_1_array, mask_2_array, plaque_array, opacity=0.8, name=""):
ax, plots = plt.subplots(2, 4, figsize=(25, 10))
ax.suptitle(name)
plots[0, 0].axis('off')
plots[0, 0].imshow(mask_2_array - mask_1_array, cmap=plt.cm.bone)
plots[0, 1].axis('off')
plots[0, 1].imshow(mask_1_array, cmap=plt.cm.bone)
plots[0, 2].axis('off')
plots[0, 2].imshow(mask_2_array, cmap=plt.cm.bone)
plots[0, 3].axis('off')
plots[0, 3].imshow(plaque_array, cmap=plt.cm.bone)
plots[1, 0].axis('off')
plots[1, 0].imshow(superimpose_mask(image_array, mask_2_array - mask_1_array, opacity=opacity))
plots[1, 1].axis('off')
plots[1, 1].imshow(superimpose_mask(image_array, mask_1_array, opacity=opacity))
plots[1, 2].axis('off')
plots[1, 2].imshow(superimpose_mask(image_array, mask_2_array, opacity=opacity))
plots[1, 3].axis('off')
plots[1, 3].imshow(superimpose_mask(image_array, plaque_array, opacity=opacity))
plt.show()
def expand_as_3d(tensor, rep, name):
my_repeat = Lambda(lambda x, repnum: K.repeat_elements(x, repnum, axis=4), arguments={'repnum': rep},
name='psi_up' + name)(tensor)
return my_repeat
def AttnGatingBlock3D(x, g, inter_shape, name):
'''
Analogous implementation of the 3D attention gate used in the Attention U-Net 3D.
'''
shape_x = K.int_shape(x) # 32
shape_g = K.int_shape(g) # 16
theta_x = Conv3D(inter_shape, (2, 2, 2), strides=(2, 2, 2), padding='same', name='xl' + name)(x) # 16
shape_theta_x = K.int_shape(theta_x)
phi_g = Conv3D(inter_shape, (1, 1, 1), padding='same')(g)
upsample_g = Conv3DTranspose(inter_shape, (3, 3, 3), strides=(
shape_theta_x[1] // shape_g[1], shape_theta_x[2] // shape_g[2], shape_theta_x[3] // shape_g[3]), padding='same',
name='g_up' + name)(phi_g) # 16
concat_xg = add([upsample_g, theta_x])
act_xg = Activation('relu')(concat_xg)
psi = Conv3D(1, (1, 1, 1), padding='same', name='psi' + name)(act_xg)
sigmoid_xg = Activation('sigmoid')(psi)
shape_sigmoid = K.int_shape(sigmoid_xg)
upsample_psi = UpSampling3D(
size=(shape_x[1] // shape_sigmoid[1], shape_x[2] // shape_sigmoid[2], shape_x[3] // shape_sigmoid[3]))(
sigmoid_xg) # 32
upsample_psi = expand_as_3d(upsample_psi, shape_x[4], name)
y = multiply([upsample_psi, x], name='q_attn' + name)
result = Conv3D(shape_x[4], (1, 1, 1), padding='same', name='q_attn_conv' + name)(y)
result_bn = BatchNormalization(name='q_attn_bn' + name)(result)
return result_bn
def UnetConv3D(input, outdim, is_batchnorm, name):
'''
Analogous implementation of the pair of convolutional layers used by the U-Net 3D.
'''
x = Conv3D(outdim, (3, 3, 3), strides=(1, 1, 1), kernel_initializer="glorot_normal", padding="same",
name=name + '_1')(input)
if is_batchnorm:
x = BatchNormalization(name=name + '_1_bn')(x)
x = Activation('relu', name=name + '_1_act')(x)
x = Conv3D(outdim, (3, 3, 3), strides=(1, 1, 1), kernel_initializer="glorot_normal", padding="same",
name=name + '_2')(x)
if is_batchnorm:
x = BatchNormalization(name=name + '_2_bn')(x)
x = Activation('relu', name=name + '_2_act')(x)
return x
def UnetGatingSignal3D(input, is_batchnorm, name):
'''
Implementation of the gating signal appearing in the upsampling branch of the Attention U-Net 3D:
simply a 1x1 convolution followed by batch normalization and ReLU.
'''
shape = K.int_shape(input)
x = Conv3D(shape[4] * 1, (1, 1, 1), strides=(1, 1, 1), padding="same", kernel_initializer="glorot_normal",
name=name + '_conv')(input)
if is_batchnorm:
x = BatchNormalization(name=name + '_bn')(x)
x = Activation('relu', name=name + '_act')(x)
return x
def tiny_attn_unet3D(opt, input_size, args):
'''
Analogue of the above defined attn_unet3D with less layers, resulting in a smaller U shape.
'''
inputs = Input(shape=input_size)
conv1 = UnetConv3D(inputs, 8*args.kernel_power, is_batchnorm=True, name='conv1')
pool1 = MaxPooling3D(pool_size=(2, 2, 2))(conv1)
pool1 = Dropout(args.dropout)(pool1)
conv2 = UnetConv3D(pool1, 8*args.kernel_power, is_batchnorm=True, name='conv2')
pool2 = MaxPooling3D(pool_size=(2, 2, 2))(conv2)
pool2 = Dropout(args.dropout)(pool2)
center = UnetConv3D(pool2, 16*args.kernel_power, is_batchnorm=True, name='center')
g3 = UnetGatingSignal3D(center, is_batchnorm=True, name='g3')
attn3 = AttnGatingBlock3D(conv2, g3, 8*args.kernel_power, '_3')
up3 = concatenate([Conv3DTranspose(8*args.kernel_power, (3, 3, 3), strides=(2, 2, 2), padding='same', activation='relu',
kernel_initializer="glorot_normal")(center), attn3], name='up3')
up4 = concatenate([Conv3DTranspose(8*args.kernel_power, (3, 3, 3), strides=(2, 2, 2), padding='same', activation='relu',
kernel_initializer="glorot_normal")(up3), conv1], name='up4')
mask_1 = Conv3D(1, (1, 1, 1), activation='sigmoid', name='mask_1')(up4)
mask_2 = Conv3D(1, (1, 1, 1), activation='sigmoid', name='mask_2')(up4)
dif = Conv3D(1, (1, 1, 1), activation='sigmoid', name='dif')(up4)
model = Model(inputs=[inputs], outputs=[mask_1, mask_2, dif])
model.compile(optimizer=opt,
loss=[wrapped_partial(dice_loss, args=args), wrapped_partial(dice_loss, args=args),
wrapped_partial(multiloss, args=args)],
loss_weights=[0.1, 0.1, 0.8],
metrics=[[wrapped_partial(dsc, args=args)], [wrapped_partial(dsc, args=args)],
[wrapped_partial(dsc, args=args), wrapped_partial(tp, args=args),
wrapped_partial(tn, args=args)]])
return model
def full_ct_model_evaluation(image, model, z_stride, which_prediction):
# Shape of original images
size_X = image.shape[2]
size_Y = image.shape[1]
size_Z = image.shape[0]
image_paded = np.zeros((size_Z + 24,
size_Y,
size_X))
image_paded[:size_Z, :size_Y, :size_X] = image / 512
prediction_array = np.zeros((size_Z + 24,
size_Y,
size_X))
coverage_array = np.zeros((size_Z + 24,
size_Y,
size_X))
# Containers for batch predictions
patch_boundaries_list = []
counter = 0
# Stride along Z axis:
for z_start in range(0, prediction_array.shape[2], z_stride):
z_end = z_start + 24
if (np.count_nonzero(image[z_start:z_end, :, :]) > 1):
patch_boundaries_list.append([z_start, z_end])
for patch_index in range(0, len(patch_boundaries_list)):
# patch_boundaries in current batch
temporal_boundaries = patch_boundaries_list[patch_index]
temp_patches = []
# Extracting patches for prediction
current_patch = image_paded[temporal_boundaries[0]:temporal_boundaries[1],
16:48,
16:48]
current_patch = np.expand_dims(current_patch, axis=0)
# Updating prediction_array and coverage_array
predicted_patch = model.predict(np.expand_dims(current_patch, axis=-1))
# 0 belső maszk 1 külső maszk 2 differencia
prediction = predicted_patch[which_prediction]
prediction = np.reshape(prediction, [24, 32, 32])
prediction_array[temporal_boundaries[0]:temporal_boundaries[1],
16:48,
16:48] += prediction
# print(prediction_array[32, 32, 32])
coverage_array[temporal_boundaries[0]:temporal_boundaries[1],
:,
:] += 1
coverage_array = np.maximum(coverage_array, np.ones(coverage_array.shape))
# Taking the average prediction value for the pixels
prediction_array = | np.divide(prediction_array, coverage_array) | numpy.divide |
#!/usr/bin/env python
from __future__ import print_function
import gc
import matplotlib
matplotlib.use('PDF')
from matplotlib.cbook import report_memory
import numpy as np
from pylab import figure, show, close
# take a memory snapshot on indStart and compare it with indEnd
rand = np.random.rand
indStart, indEnd = 200, 401
for i in range(indEnd):
fig = figure(1)
fig.clf()
t1 = np.arange(0.0, 2.0, 0.01)
y1 = | np.sin(2 * np.pi * t1) | numpy.sin |
from stable_baselines3.common.env_util import make_atari_env
from stable_baselines3.common.vec_env import VecFrameStack
from stable_baselines3 import PPO
from easy_logx.easy_logx import EasyLog
import os
import time
import gym
from typing import Any, List, Tuple
from easy_logx.easy_logx import EasyLog
import pybullet as p
import pybullet_data
import gym
from gym import spaces
from gym.utils import seeding
import numpy as np
from math import sqrt
import random
import time
import math
import cv2
import torch
import os
from stable_baselines3.common.vec_env import VecVideoRecorder
from stable_baselines3.common.vec_env.vec_monitor import VecMonitor
import matplotlib.pyplot as plt
from stable_baselines3.common import results_plotter
from stable_baselines3.common.monitor import Monitor
from stable_baselines3.common.callbacks import BaseCallback
from stable_baselines3.common.results_plotter import load_results, ts2xy, plot_results
import pathlib
import torch as th
import torch.nn as nn
from typing import Tuple, Any, Dict, List, Type, Optional, Union, Callable
from stable_baselines3.common.torch_layers import BaseFeaturesExtractor
from stable_baselines3.common.policies import ActorCriticPolicy
import imageio
from kuka_visual_reach import KukaVisualReachEnv
from stable_baselines3.common.env_util import make_vec_env
from stable_baselines3.common.vec_env import DummyVecEnv,SubprocVecEnv,VecEnv
import logging
logger = EasyLog(log_level=logging.INFO)
logger.add_filehandler()
# change log
class CustomCNN(BaseFeaturesExtractor):
"""
:param observation_space: (gym.Space)
:param features_dim: (int) Number of features extracted.
This corresponds to the number of unit for the last layer.
"""
def __init__(self, observation_space: gym.spaces.Box, features_dim: int = 256):
super(CustomCNN, self).__init__(observation_space, features_dim)
# We assume CxHxW images (channels first)
# Re-ordering will be done by pre-preprocessing or wrapper
n_input_channels = observation_space.shape[0]
self.cnn = nn.Sequential(
nn.Conv2d(n_input_channels, 32, kernel_size=3, stride=2, padding=1),
nn.ReLU(),
nn.Conv2d(32, 32, kernel_size=3, stride=2, padding=1),
nn.ReLU(),
nn.Conv2d(32, 32, kernel_size=3, stride=2, padding=1),
nn.ReLU(),
nn.Conv2d(32, 32, kernel_size=3, stride=2, padding=1),
nn.ReLU(),
nn.Flatten(),
)
# Compute shape by doing one forward pass
with th.no_grad():
n_flatten = self.cnn(
th.as_tensor(observation_space.sample()[None]).float()
).shape[1]
self.linear = nn.Sequential(nn.Linear(n_flatten, features_dim), nn.ReLU())
def forward(self, observations: th.Tensor) -> th.Tensor:
return self.linear(self.cnn(observations))
class SaveOnBestTrainingRewardCallback(BaseCallback):
"""
Callback for saving a model (the check is done every ``check_freq`` steps)
based on the training reward (in practice, we recommend using ``EvalCallback``).
:param check_freq: (int)
:param log_dir: (str) Path to the folder where the model will be saved.
It must contains the file created by the ``Monitor`` wrapper.
:param verbose: (int)
"""
def __init__(self, check_freq: int, log_dir: str, verbose=1):
super(SaveOnBestTrainingRewardCallback, self).__init__(verbose)
self.check_freq = check_freq
self.log_dir = log_dir
self.save_path = os.path.join(log_dir, 'best_model')
self.best_mean_reward = -np.inf
def _init_callback(self) -> None:
# Create folder if needed
if self.save_path is not None:
os.makedirs(self.save_path, exist_ok=True)
def _on_step(self) -> bool:
if self.n_calls % self.check_freq == 0:
# Retrieve training reward
x, y = ts2xy(load_results(self.log_dir), 'timesteps')
if len(x) > 0:
# Mean training reward over the last 100 episodes
mean_reward = | np.mean(y[-100:]) | numpy.mean |
# -*- coding: utf-8 -*-
# Copyright © 2018 PyHelp Project Contributors
# https://github.com/jnsebgosselin/pyhelp
#
# This file is part of PyHelp.
# Licensed under the terms of the GNU General Public License.
# ---- Standard Library Imports
import os
import os.path as osp
# ---- Third Party imports
import numpy as np
import geopandas as gpd
import netCDF4
import pandas as pd
# ---- Local Libraries Imports
from pyhelp.preprocessing import write_d10d11_allcells, format_d10d11_inputs
from pyhelp.processing import run_help_allcells
from pyhelp.utils import savedata_to_hdf5
from pyhelp.weather_reader import (
save_precip_to_HELP, save_airtemp_to_HELP, save_solrad_to_HELP,
read_cweeds_file, join_daily_cweeds_wy2_and_wy3)
FNAME_CONN_TABLES = 'connect_table.npy'
class HELPManager(object):
def __init__(self, workdir, year_range, path_togrid=None):
super(HELPManager, self).__init__()
self.year_range = year_range
self.set_workdir(workdir)
self._setup_connect_tables()
if path_togrid is not None:
self.load_grid(path_togrid)
else:
self.grid = None
@property
def cellnames(self):
if self.grid is not None:
return self.grid['cid'].tolist()
else:
return []
@property
def inputdir(self):
"""
Return the path to the folder where the HELP input files are going to
be saved in the working directory. This folder is created in case it
doesn't already exist in the file system.
"""
inputdir = osp.join(self.workdir, 'help_input_files')
if not osp.exists(inputdir):
os.makedirs(inputdir)
return inputdir
@property
def workdir(self):
"""Return the path to the current working directory."""
return os.getcwd()
def set_workdir(self, dirname):
"""Set the working directory of the manager."""
if not osp.exists(dirname):
os.makedirs(dirname)
os.chdir(dirname)
# ---- Connect tables
@property
def path_connect_tables(self):
return osp.join(self.inputdir, FNAME_CONN_TABLES)
def _setup_connect_tables(self):
"""Setup the connect tables dictionary."""
if osp.exists(self.path_connect_tables):
self.connect_tables = | np.load(self.path_connect_tables) | numpy.load |
from flask import Flask,render_template,request
import re
import jieba
from sklearn.decomposition import PCA
from typing import List
from sklearn.metrics.pairwise import cosine_similarity
from operator import itemgetter
from gensim import models
import numpy as np
import pandas as pd
app = Flask(__name__)
# 结巴分词
def cut(string):
return list(jieba.cut(string))
# 拆分成列表
def sentenceslist(article):
setences = re.sub('([。!?\?])([^”’])', r"\1 \2", article) # 单字符断句符
setences = re.sub('(\.{6})([^”’])', r"\1 \2", setences) # 英文省略号
setences = re.sub('(\…{2})([^”’])', r"\1 \2", setences) # 中文省略号
setences = re.sub('([。!?\?][”’])([^,。!?\?])', r'\1 \2', setences)
sentences_list = setences.split(' ')
sentence_list_list = []
for sentence in sentences_list:
sentence = cut(sentence)
sentence_list_list.append(sentence)
return sentences_list,sentence_list_list
# PCA与句子向量
def sentence_to_vec(setencelist, a = 0.0001):
model = models.Word2Vec.load("./model/wiki_corpus.model")
sentence_set = []
j = 0
for sentence in setencelist:
vs = np.zeros((250,)) # add all word2vec values into one vector for the sentence
sentence_length = len(sentence)
for word in sentence:
if word in model:
w_v = model[word]
p_w = model.wv.vocab[word].count
a_value = a / (a + p_w/459358208) # smooth inverse frequency, SIF
vs = np.add(vs, np.multiply(a_value, w_v))
else:
continue
vs = np.divide(vs, sentence_length)
sentence_set.append(vs) # add to our existing re-calculated set of sentences
# print(vs)
# calculate PCA of this sentence set
# sentence_set = np.mat
# rix(sentence_set).astype(np.float)
pca = PCA()
pca.fit(np.array(sentence_set))
u = pca.components_[0] # the PCA vector
u = np.multiply(u, np.transpose(u)) # u x uT
# pad the vector? (occurs if we have less sentences than embeddings_size)
if len(u) < 250:
for i in range(250 - len(u)):
u = np.append(u, 0) # add needed extension for multiplication below
# resulting sentence vectors, vs = vs -u x uT x vs
sentence_vecs = []
all_vs = np.zeros((250,))
for vs in sentence_set:
sub = | np.multiply(u,vs) | numpy.multiply |
import argparse
import os
import numpy as np
from tqdm import tqdm
from glob import glob
from PIL import Image
import tensorflow as tf
import medmnist
from medmnist import INFO, Evaluator
from medmnist.info import DEFAULT_ROOT
def main(data_flag, input_root, output_root, model_dir, run):
if not os.path.isdir(output_root):
os.makedirs(output_root)
_ = getattr(medmnist, INFO[data_flag]['python_class'])(
split="train", root=input_root, download=True)
dataroot = os.path.join(input_root, '%s.npz' % (data_flag))
npz_file = np.load(dataroot)
train_img = npz_file['train_images']
train_label = npz_file['train_labels']
val_img = npz_file['val_images']
val_label = npz_file['val_labels']
test_img = npz_file['test_images']
test_label = npz_file['test_labels']
label_dict_path = glob(os.path.join(model_dir, '*.txt'))[0]
model_path = glob(os.path.join(model_dir, '*.tflite'))[0]
idx = []
labels = INFO[data_flag]['label']
task = INFO[data_flag]['task']
with open(label_dict_path) as f:
line = f.readline()
while line:
idx.append(line[:-1].lower())
line = f.readline()
index = []
for key in labels:
index.append(idx.index(labels[key].lower()))
test(data_flag, train_img, index, model_path, 'train', output_root, run)
test(data_flag, val_img, index, model_path, 'val', output_root, run)
test(data_flag, test_img, index, model_path, 'test', output_root, run)
def load_tflite(ckpt_path):
tflite_model = tf.lite.Interpreter(model_path=ckpt_path)
tflite_model.allocate_tensors()
input_details = tflite_model.get_input_details()
output_details = tflite_model.get_output_details()
return tflite_model, input_details, output_details
def test_single_img(img, tflite_model, input_details, output_details):
img = Image.fromarray(np.uint8(img)).resize((224, 224)).convert('RGB')
img = np.expand_dims( | np.array(img) | numpy.array |
import numpy as np
import pysc2
from pysc2.agents import base_agent
from pysc2.env import sc2_env
from pysc2.lib import actions, features, units
from pysc2 import maps, lib
from s2clientprotocol import sc2api_pb2 as sc_pb
from sc2env.pysc2_util import register_map
from sc2env.utility import getOneHotState
import os
SCREEN_SIZE = 40
#MAP_NAME = 'FourTowersWithFriendlyUnits'
#MAP_NAME = 'FourTowersWithFriendlyUnitsFixedEnemies'
MAP_NAME = 'FourTowersWithFriendlyUnitsFixedEnemiesFixedPosition'
class FourTowerSequentialFriendlyUnits():
def __init__(self, reward_types, map_name = None):
if map_name is None:
map_name = MAP_NAME
maps_dir = os.path.join(os.path.dirname(__file__), '..', 'maps')
print(maps_dir)
register_map(maps_dir, map_name)
self.sc2_env = sc2_env.SC2Env(
map_name = map_name,
players = [sc2_env.Agent(sc2_env.Race.protoss)],
agent_interface_format = features.AgentInterfaceFormat(
feature_dimensions = features.Dimensions(screen = SCREEN_SIZE, minimap = 30),
action_space = actions.ActionSpace.FEATURES,
camera_width_world_units = 28
),
step_mul = 16,
game_steps_per_episode = 0,
score_index = 0,
visualize = True,)
# lib.renderer_human.zoom(1.5)
self.current_obs = None
self.actions_taken = 0
self.decomposed_rewards_all = []
self.decomposed_rewards = []
self.decomposed_rewards_mark = 0
self.signal_of_finished = 1
self.end_state = None
self.reward_types = reward_types
self.decomposed_reward_dict = {}
for rt in reward_types:
self.decomposed_reward_dict[rt] = 0
self.input_screen_features = {
"PLAYER_RELATIVE":[1, 3, 4],
"UNIT_TYPE": [48, 105, 73, 83, 52, 109, 51, 107],
'HIT_POINT': 0,
'HIT_POINT_RATIO': 0
}
'''
self.decomposed_reward_dict = {
'damageToEnemyMarine' : 0,
'damageByEnemyMarine' : 0,
'damageToEnemyZergling' : 0,
'damageByEnemyZergling' : 0,
'damageToEnemyMarauder' : 0,
'damageByEnemyMarauder' : 0,
'damageToEnemyHydralisk' : 0,
'damageByEnemyHydralisk' : 0,
'damageToEnemyThor' : 0,
'damageByEnemyThor' : 0,
'damageToEnemyUltralisk' : 0,
'damageByEnemyUltralisk' : 0,
'damageToFriendZealot' : 0
}
'''
def action_space():
return Discrete(2)
def observation_space():
return (84, 84, 1)
def print_current_alerts(self):
return self.current_obs[3]
def reset(self):
# Move the camera in any direction
# This runs the ResetEpisode trigger built into the map
self.decomposed_rewards_all = []
self.decomposed_rewards = []
self.decomposed_rewards_mark = 0
action = actions.FUNCTIONS.move_camera([0, 0])
self.last_timestep = self.sc2_env.step([action])[0]
observation = self.unpack_timestep(self.last_timestep)
self.current_obs = observation
self.actions_taken = 0
np.set_printoptions(threshold=np.nan,linewidth=np.nan)
# print(observation)
state = observation[3]['feature_screen']
player_relative = np.array(state[5])
player_relative[np.array(state[6]) == 73] = 3
player_relative[np.array(state[12]) == 1] = 3
state[5] = player_relative.tolist()
# print(type(state))
state = getOneHotState(state, self.input_screen_features)
state = np.reshape(state, (1, -1))
self.end_state = None
data = self.sc2_env._controllers[0]._client.send(observation = sc_pb.RequestObservation())
self.sc2_env._controllers[0]._client.send(action = sc_pb.RequestAction())
data = data.observation.raw_data.units
rewards, sof = self.getRewards(data)
self.signal_of_finished = sof
for key in self.decomposed_reward_dict:
self.decomposed_reward_dict[key] = 0
return state
"""
def getOneHotState(self, state):
#extend player id
PLAYER_ID = [1, 3, 16]
tstate = self.int_map_to_onehot(np.array(state[4]),PLAYER_ID)
#extend unit type
UNIT_TYPE = [48, 105, 73, 83, 52, 109, 51, 107]
tstate = np.append(tstate, self.int_map_to_onehot(np.array(state[6]),UNIT_TYPE), axis=0)
#append unit hit point
tstate = np.append(tstate, self.normalizeExceptZeros(state[8],
(0, 500)), axis=0)
#append unit hit point ratio
SCALE = 255
hit_point_ratio = state[9] / SCALE
hit_point_ratio = np.reshape(hit_point_ratio, (1, SCREEN_SIZE, SCREEN_SIZE))
tstate = np.append(tstate, hit_point_ratio, axis=0)
'''
#extend unit density
MAX_UNIT_DENSITY = 4
unit_density = np.clip(state[14] / MAX_UNIT_DENSITY, 0, 1)
unit_density = np.reshape(unit_density, (1, SCREEN_SIZE, SCREEN_SIZE))
tstate = np.append(tstate, unit_density, axis=0)
'''
# print(tstate)
# print(tstate.shape)
return tstate
def normalizeExceptZeros(self, state, certainRange = None):
state = np.array(state)
if certainRange is None:
# state[state == 0] = state.min(state[np.nonzero(state)])
nstate = (state - state.min()) / (state.max() - state.min())
else:
nstate = (state - certainRange[0]) / (certainRange[1] - certainRange[0])
nstate = np.reshape(nstate, (1, SCREEN_SIZE, SCREEN_SIZE))
return nstate
"""
def getRewards(self, data):
rewards = []
l = len(self.reward_types)
for x in data:
if x.shield == 199:
sof = x.health
elif x.shield > 100:
rt = self.reward_types[int(x.shield - 101)]
#print(x.shield)
if 'damageToEnemy' in rt:
self.decomposed_reward_dict[rt] = x.health - 1
else:
self.decomposed_reward_dict[rt] = (x.health - 1) * -1
return rewards, sof
def noop(self):
return actions.FUNCTIONS.no_op()
def step(self, action):
done = False
dead = False
### ACTION TAKING ###
# print(action)
if self.actions_taken == 0 and self.check_action(self.current_obs, 12):
if action == 0:
action = actions.FUNCTIONS.Attack_screen("now", [0,0])
elif action == 1:
action = actions.FUNCTIONS.Attack_screen("now", [39,0])
elif action == 2:
action = actions.FUNCTIONS.Attack_screen("now", [0,39])
elif action == 3:
action = actions.FUNCTIONS.Attack_screen("now", [39,39])
elif action == 4:
action = actions.FUNCTIONS.no_op()
else:
print("Invalid action: check final layer of network")
action = actions.FUNCTIONS.no_op()
else:
action = actions.FUNCTIONS.no_op()
# print(self.actions_taken == 0, self.check_action(self.current_obs, 12))
# print(action)
####################
### STATE PREPARATION ###
self.last_timestep = self.sc2_env.step([action])[0]
observation = self.unpack_timestep(self.last_timestep)
self.current_obs = observation
#########################
### REWARD PREPARATION AND TERMINATION ###
data = self.sc2_env._controllers[0]._client.send(observation=sc_pb.RequestObservation())
data = data.observation.raw_data.units
rewards, sof = self.getRewards(data)
state = observation[3]['feature_screen']
player_relative = np.array(state[5])
player_relative[np.array(state[6]) == 73] = 3
player_relative[np.array(state[12]) == 1] = 3
state[5] = player_relative.tolist()
state = getOneHotState(state, self.input_screen_features)
state = np.reshape(state, (1, -1))
#print(state.shape)
self.decomposed_rewards_all.append([])
la = len(self.decomposed_rewards_all)
for key in self.decomposed_reward_dict:
self.decomposed_rewards_all[la - 1].append(self.decomposed_reward_dict[key])
# print(self.signal_of_finished,sof)
if self.signal_of_finished != sof:
done = True
if sof == 1:
dead = True
else:
dead = False
self.decomposed_rewards.append([])
for i in range(len(self.reward_types)):
l = len(self.decomposed_rewards)
la = len(self.decomposed_rewards_all)
if not dead:
self.decomposed_rewards[l - 1].append(
self.decomposed_rewards_all[la - 1][i] - self.decomposed_rewards_all[self.decomposed_rewards_mark][i]
)
else:
self.decomposed_rewards[l - 1].append(
self.decomposed_rewards_all[la - 2][i] - self.decomposed_rewards_all[self.decomposed_rewards_mark][i]
)
self.decomposed_rewards_mark = la - 1
self.signal_of_finished = sof
'''
if len(state) < 41:
current_len_state = len(state)
for x in range(current_len_state, 41):
state.append(0.0)
# print(done,dead)
'''
if dead:
state = observation[3]['feature_screen']
player_relative = np.array(state[5])
player_relative[np.array(state[6]) == 73] = 3
player_relative[ | np.array(state[12]) | numpy.array |
'''
Author: <NAME>
Email: <EMAIL>
Date created: 2020/1/8
Python Version: 3.6
'''
import sys
import os
import numpy as np
import tensorflow as tf
from tensorflow.keras.callbacks import EarlyStopping, TensorBoard, ReduceLROnPlateau
from tensorflow.keras.initializers import he_normal
from tensorflow.keras.layers import Dense, Input
from tensorflow.keras.models import Model as keras_Model
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.metrics import FalseNegatives, FalsePositives, TruePositives, TrueNegatives, Recall
import datetime
sys.path.append('.')
from src.models.metrics import f1
from src.models.losses import FocalLoss
class Model(object):
def __init__(self, seq_length, embedding_dim, learning_rate=0.001, batch_size=32, patience=15, log_dir=None):
self.seq_length = seq_length
self.embedding_dim = embedding_dim
self.learning_rate = learning_rate
self.batch_size = batch_size
self.patience = patience
self.log_dir = log_dir
print(self.patience, self.learning_rate)
def build_model(self):
with tf.name_scope('Model'):
self.model = self.build()
self.model.compile(optimizer=Adam(lr=self.learning_rate),
loss=FocalLoss(alpha=.25, gamma=2),
metrics=['accuracy', f1, TrueNegatives(),
FalseNegatives(), TruePositives(),
FalsePositives()])
print(self.model.summary())
def build(self):
reg = None
# model structure
input1 = Input(shape=(self.seq_length, self.embedding_dim))
first_dense = self.shared_module(input1)
output = Dense(1, activation='sigmoid',
activity_regularizer=reg,
kernel_initializer=he_normal(seed=1))(first_dense)
model = keras_Model(inputs=input1, outputs=output)
return model
def load(self, fname):
self.model.load_weights(fname)
def fit(self, x_train, x_valid, y_train, y_valid):
def arr_concate(train_arr, valid_arr):
return np.concatenate([train_arr, valid_arr], axis=0)
# concatenate the trian and valid inputs
if isinstance(x_train, tuple):
x_train_valid = [arr_concate(x_train[0], x_valid[0]), arr_concate(x_train[1], x_valid[1])]
else:
x_train_valid = arr_concate(x_train, x_valid)
y_train_valid = arr_concate(y_train, y_valid)
# patient early stopping
es = EarlyStopping(monitor='val_loss', mode='min', verbose=0,
patience=self.patience)
logdir = os.path.join(self.log_dir, datetime.datetime.now().strftime("%Y%m%d-%H%M%S"))
tb = TensorBoard(log_dir=logdir)
# save initial weights
tmp_model_path = os.path.join('models/interim', str(os.getpid()) + 'model.h5')
self.model.save_weights(tmp_model_path)
# calculate the weights
(_, data_count) = | np.unique(y_train_valid, return_counts=True) | numpy.unique |
from collections import OrderedDict
import numpy as np
import matplotlib as mpl
mpl.rcParams['hatch.linewidth']=2.0
import matplotlib.pyplot as plt
fs=25
plt.rc('xtick',labelsize=int(fs*.8))
plt.rc('ytick',labelsize=int(fs*.8))
import ROOT as rt
from ROOT import TH1F,TColor
import os
# FIXME SetYTitle
class BinaryClassifierResponse(object):
def __init__(self,
name,
title,
directory,
pt):
f=np.load("jj25{}.npz".format(pt))
self.bdt=f["bdtset"]
#cmult,nmult,ptd,axis1,axis2,
#cmult,nmult,ptd,axis1,axis2,
#dr,pt/pt,mult/mult
self.eve=f["eveset"]
self.pairlist=f["pairlist"]
self._name = name
self._title = title
self._path = os.path.join(directory, name + ".{ext}")
def append(self, pt,var):
res=30
maxv=self.bdt[:,var].max()
if(maxv<self.bdt[:,var].max()):
maxv=self.bdt[:,var].max()
print(pt)
if(pt==100):maxpt=175
if(pt==200):maxpt=357
if(pt==500):maxpt=874
if(pt==1000):maxpt=1750
if(pt==100):
ptmin=0.815*pt
ptmax=1.159*pt
if(pt==200):
ptmin=0.819*pt
ptmax=1.123*pt
if(pt==500):
ptmin=0.821*pt
ptmax=1.093*pt
if(pt==1000):
ptmin=0.8235*pt
ptmax=1.076*pt
if(var=="eta"):
#q1hist=rt.TH1F("q1hist","pp#rightarrowqq", res, -1,1)
#q2hist=rt.TH1F("q2hist","Z+jet", res, -1,1)
#g1hist=rt.TH1F("g1hist","dijet", res, -1,1)
#g2hist=rt.TH1F("g2hist","Z+jet", res, -1,1)
q1hist=rt.TH1F("q1hist","pp#rightarrowqq", res, -2.4,2.4)
q2hist=rt.TH1F("q2hist","Z+jet", res, -2.4,2.4)
g1hist=rt.TH1F("g1hist","dijet", res, -2.4,2.4)
g2hist=rt.TH1F("g2hist","Z+jet", res, -2.4,2.4)
elif(var=="pt"):
q1hist=rt.TH1F("q1hist","dijet", res, 0, maxpt)
q2hist=rt.TH1F("q2hist","Z+jet", res, 0, maxpt)
g1hist=rt.TH1F("g1hist","dijet", res, 0, maxpt)
g2hist=rt.TH1F("g2hist","Z+jet", res, 0, maxpt)
else:
maxv=int(0.8*maxv)
vb=int(maxv)
#if(pt==500 or pt==1000):vb=int(vb/2)
#vb=res
print("max",maxv)
q1hist=rt.TH1F("q1hist","dijet", vb,0, maxv)
q2hist=rt.TH1F("q2hist","Z+jet", vb,0, maxv)
g1hist=rt.TH1F("g1hist","dijet", vb,0, maxv)
g2hist=rt.TH1F("g2hist","Z+jet", vb,0, maxv)
res=int(vb)
for k in range(len(self.bdt)):
pair=np.argmax(self.eve[k])
pair=self.pairlist[np.argmax(self.eve[k])]
"""if(pair==0):
q1hist.Fill(self.bdt[k][var])
if(pair==1):
q2hist.Fill(self.bdt[k][var])
if(pair==2):
g1hist.Fill(self.bdt[k][var])
if(pair==3):
g2hist.Fill(self.bdt[k][var])"""
if(pair[0]=="q"):
q1hist.Fill(self.bdt[k][0])
if(pair[1]=="q"):
q2hist.Fill(self.bdt[k][5])
if(pair[0]=="g"):
g1hist.Fill(self.bdt[k][0])
if(pair[1]=="g"):
g2hist.Fill(self.bdt[k][5])
q1hist.Scale(1.0 / q1hist.Integral())
#q2hist.Scale(1.0 / q2hist.Integral())
g1hist.Scale(1.0 / g1hist.Integral())
#g2hist.Scale(1.0 / g2hist.Integral())
q1hist.Draw("hist")
q1=[]
q2=[]
g1=[]
g2=[]
for i in range(res):
q1.append(q1hist.GetBinContent(i+1))
q2.append(q2hist.GetBinContent(i+1))
g1.append(g1hist.GetBinContent(i+1))
g2.append(g2hist.GetBinContent(i+1))
print(g2hist.GetEntries())
fs=25
plt.figure(figsize=(12,8))
plt.title("jet $p_T$ range {}~{} GeV".format(pt,int(pt*1.1)),fontdict={"weight":"bold","size":fs*1.})
plt.ylabel("Fraction of Events",fontsize=fs*1.3)
if(var=='eta'):
xax=np.append(np.arange(-2.4,2.4,((-q1hist.GetBinLowEdge(0)+q1hist.GetBinLowEdge(res))/res))[:res],2.4)
plt.xlabel("jet $\eta$",fontsize=fs*1.3)
plt.fill_between(xax,np.append(q1,0),alpha=0.6,linewidth=2,facecolor='azure',edgecolor='C0',label=r"pp$\rightarrow$qq",step='post')
plt.plot(xax,np.append(q1,0),color='C0',alpha=0.5,drawstyle='steps-post',linewidth=2)
plt.plot(xax, | np.append(q2,0) | numpy.append |
import numpy as np
from classification.classifier import Classifier
class NaiveBayes(Classifier):
def __init__(self, name='Naive Bayes'):
super().__init__(1,1,name,_type=3)
self.name = name
def _predict(self, x):
if len(self._labels) == 0:
print("It is necessary to train the classifier before using it to make predictions")
return
# it might look complex but it's just prior + posterior probabilities for each label
probs = np.array([np.log(self.P_C[i])+np.sum(np.log(self.gaussian(x,i))) for i in range(self.M)])
return self._labels[np.argmax(probs)]
def fit(self, X, Y, *args, **kwargs):
if not isinstance(Y, np.ndarray):
Y = np.array(Y)
self._labels = np.unique(Y)
self.N = X.shape[1]
self.M = len(self._labels)
self.mean = np.zeros(X.shape)
self.var = np.zeros(X.shape)
self.P_C = np.array([len(np.where(Y==i)[0])/float(len(Y)) for i in self._labels])
# for each class
for idx, cl in enumerate(self._labels):
indexes = np.where(Y==cl)[0]
self.mean[idx,: ] = np.mean(X[indexes], axis=0)
self.var[idx,:] = np.var(X[indexes], axis=0)
def gaussian(self, x, idx):
return | np.exp(-((x-self.mean[idx])**2/(2*self.var[idx]))) | numpy.exp |
import sys
sys.path.append('..')
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import scipy.optimize
import projgrad
from scipy.stats.mstats import gmean
import matplotlib
colors = matplotlib.rcParams['axes.prop_cycle'].by_key()['color']
black = matplotlib.rcParams['axes.labelcolor']
tcellcolor = '#0E1E97'
tcellcoloralt = '#0e7b97'
import plotting
from lib import *
from optparse import OptionParser
parser = OptionParser()
parser.add_option("-t", "--talk", action="store_true", dest="talk", default=False,
help="optimize figure for talks")
(options, args) = parser.parse_args()
talk = options.talk
if talk:
plt.style.use('../talk.mplstyle')
else:
plt.style.use('../paper.mplstyle')
def fcompfull_dC(x, t, alpha, K, dC, delta=0.0):
"dC: function called as dC(C, t) giving rhs for dC/dt"
T, C = x
B = 0.5*(T+C+K - ((T+C+K)**2 - 4*T*C)**.5)
return [alpha*B-delta*T, dC(C, t)]
def make_dnu(x, xt, factor):
x /= | np.sum(x) | numpy.sum |
# NiftyRec - Ray-tracing tools
# <NAME>
# Center for Medical Image Computing (CMIC), University College Lonson (UCL)
# 2009-2012, London
# Aalto University, School of Science
# Summer 2013, Helsinki
# Martinos Center for Biomedical Imaging, Harvard University/MGH
# Jan. 2014, Boston
from .SimpleWrap import localpath, filepath, call_c_function, find_c_library, NOT_FOUND, FOUND, FOUND_NOT_LOADABLE, \
load_c_library
import numpy as np
import os,platform
__all__ = ['has_NiftyPy',
'test_library_niftyrec_c','gpu_set','gpu_reset','gpu_list',
'gpu_exists',
'PET_project','PET_backproject','PET_project_compressed',
'PET_backproject_compressed',
'PET_compress_projection','PET_uncompress_projection',
'PET_initialize_compression_structure',
'PET_compress_projection_array','PET_get_subset_sparsity',
'PET_get_subset_projection_array',
'SPECT_project_parallelholes','SPECT_backproject_parallelholes',
'CT_project_conebeam','CT_backproject_conebeam',
'CT_project_parallelbeam','CT_backproject_parallelbeam',
'ET_spherical_phantom','ET_cylindrical_phantom',
'ET_spheres_ring_phantom',
'TR_grid_from_box_and_affine','TR_resample_grid','TR_resample_box',
'TR_gradient_grid','TR_gradient_box',
'TR_transform_grid',
'INTERPOLATION_LINEAR','INTERPOLATION_POINT']
library_name = "_et_array_interface"
niftyrec_lib_paths = [localpath(),filepath(__file__),'./',
'/usr/local/niftyrec/lib/',
'C:/Program Files/NiftyRec/lib/']
INTERPOLATION_LINEAR = 0
INTERPOLATION_POINT = 1
####################################### Error handling: ########################################
class ErrorInCFunction(Exception):
def __init__(self, msg, status, function_name):
self.msg = str(msg)
self.status = status
self.function_name = function_name
if self.status == status_io_error():
self.status_msg = "IO Error"
elif self.status == status_initialisation_error():
self.status_msg = "Error with the initialisation of the C library"
elif self.status == status_parameter_error():
self.status_msg = "One or more of the specified parameters are not right"
elif self.status == status_unhandled_error():
self.status_msg = "Unhandled error, likely a bug. "
else:
self.status_msg = "Unspecified Error"
def __str__(self):
return "'%s' returned by the C Function '%s' (error code %d). %s" % (
self.status_msg, self.function_name, self.status, self.msg)
class ErrorGPU(Exception):
def __init__(self, msg):
self.msg = msg
def __str__(self):
return "%s" % str(self.msg)
def status_success():
"""Returns the value returned by the function calls to the library in case of success. """
r = call_c_function(niftyrec_c.status_success,
[{'name': 'return_value', 'type': 'uint', 'value': None}])
return r.return_value
def status_io_error():
"""Returns the integer value returned by the function calls to the library in case of IO error. """
r = call_c_function(niftyrec_c.status_io_error,
[{'name':'return_value','type':'uint','value':None}])
return r.return_value
def status_initialisation_error():
"""Returns the value returned by the function calls to the library in case of initialisation error. """
r = call_c_function(niftyrec_c.status_initialisation_error,
[{'name':'return_value','type':'uint','value':None}])
return r.return_value
def status_parameter_error():
"""Returns the value returned by the function calls to the library in case of parameter error. """
r = call_c_function(niftyrec_c.status_parameter_error,
[{'name':'return_value','type':'uint','value':None}])
return r.return_value
def status_unhandled_error():
"""Returns the value returned by the function calls to the library in case of unhandled error. """
r = call_c_function(niftyrec_c.status_unhandled_error,
[{'name':'return_value','type':'uint','value':None}])
return r.return_value
class LibraryNotFound(Exception):
def __init__(self, msg):
self.msg = msg
def __str__(self):
return "Library cannot be found: %s" % str(self.msg)
####################################### Load library: ########################################
def test_library_niftyrec_c():
"""Test whether the C library niftyrec_c responds. """
number = 101 # just a number
descriptor = [{'name':'input','type':'int','value':number},
{'name':'output','type':'int','value':None},]
r = call_c_function(niftyrec_c.echo,descriptor)
return r.output == number
# search for the library in the list of locations 'niftyrec_lib_paths'
# and in the locations in the environment variables "LD_LIBRARY_PATH", "DYLD_LIBRARY_PATH" and "PATH"
if platform.system() == 'Linux':
sep = ":"
elif platform.system() == 'Darwin':
sep = ":"
elif platform.system() == 'Windows':
sep = ";"
try:
if os.environ.has_key('LD_LIBRARY_PATH'):
niftyrec_lib_paths = niftyrec_lib_paths + os.environ[
'LD_LIBRARY_PATH'].split(sep)
except:
if 'LD_LIBRARY_PATH' in os.environ:
niftyrec_lib_paths = niftyrec_lib_paths + os.environ[
'LD_LIBRARY_PATH'].split(sep)
try:
if os.environ.has_key('DYLD_LIBRARY_PATH'):
niftyrec_lib_paths = niftyrec_lib_paths + os.environ[
'DYLD_LIBRARY_PATH'].split(sep)
except:
if 'DYLD_LIBRARY_PATH' in os.environ:
niftyrec_lib_paths = niftyrec_lib_paths + os.environ[
'DYLD_LIBRARY_PATH'].split(sep)
try:
if os.environ.has_key('PATH'):
niftyrec_lib_paths = niftyrec_lib_paths + os.environ['PATH'].split(sep)
except:
if 'PATH' in os.environ:
niftyrec_lib_paths = niftyrec_lib_paths + os.environ['PATH'].split(sep)
(found,fullpath,path) = find_c_library(library_name,niftyrec_lib_paths)
if found == NOT_FOUND:
has_NiftyPy = False
print(
"The library %s cannot be FOUND, please make sure that the path to the NiftyRec libraries has been exported. " % fullpath)
print(
"1) Before launching Python, type the following in the terminal (the same terminal): ")
path = "'path to the niftyrec libraries'"
if platform.system() == 'Linux':
print("export LD_LIBRARY_PATH=%s" % path)
elif platform.system() == 'Darwin':
print("export DYLD_LIBRARY_PATH=%s" % path)
elif platform.system() == 'Windows':
print(
"Add %s to the system PATH using Control Panel -> Advanced Settings -> System -> .." % path)
raise LibraryNotFound("NiftyRec" + " (" + str(library_name) + ") ")
elif found == FOUND_NOT_LOADABLE:
has_NiftyPy = False
print(
"The library %s cannot be LOADED, please make sure that the path to the NiftyRec libraries has been exported. " % fullpath)
print(
"1) Before launching Python, type the following in the terminal (the same terminal): ")
if platform.system() == 'Linux':
print("export LD_LIBRARY_PATH=%s" % path)
elif platform.system() == 'Darwin':
print("export DYLD_LIBRARY_PATH=%s" % path)
elif platform.system() == 'Windows':
print(
"Add %s to the system PATH using Control Panel -> Advanced Settings -> System -> .." % path)
raise LibraryNotFound("NiftyRec" + " (" + str(library_name) + ") ")
else:
has_NiftyPy = True
niftyrec_c = load_c_library(fullpath)
#################################### Create interface to the C functions: ####################################
def gpu_list():
"""List GPUs and get information. """
MAX_GPUs = 1000
INFO_SIZE = 5
descriptor = [
{'name':'N','type':'array','value':None,'dtype':np.int32,'size':(1,)},
{
'name':'info','type':'array','value':None,'dtype':np.int32,
'size':(MAX_GPUs,INFO_SIZE)
},]
r = call_c_function(niftyrec_c.et_array_list_gpus,descriptor)
if not r.status == status_success():
raise ErrorInCFunction("The execution of 'gpu_list' was unsuccessful.",
r.status,
'niftyrec_c.et_array_list_gpus')
N = r.dictionary['N'][0]
info = r.dictionary['info']
gpus = []
for i in range(N):
gpus.append({
'id':info[i,0],'gflops':info[i,1],
'multiprocessors':info[i,2],'clock':info[i,3],
'globalmemory':info[i,4]
})
return gpus
def gpu_exists(gpu_id):
for gpu in gpu_list():
if gpu['id'] == gpu_id:
return True
return False
def gpu_set(gpu_id = 0):
"""Set GPU (when multiple GPUs are installed in the system). """
if not gpu_exists(gpu_id):
gpus = gpu_list()
raise ErrorGPU(
"The execution of 'gpu_set' was unsuccessful - the requested GPU ID does not exist. The following GPUs have been found: %s" % str(
gpus))
descriptor = [{'name':'id','type':'int','value':gpu_id},]
r = call_c_function(niftyrec_c.et_array_set_gpu_pointer,descriptor)
# print "STATUS:",r.status
if not r.status == status_success():
raise ErrorInCFunction("The execution of 'gpu_set' was unsuccessful.",
r.status,'niftyrec_c.et_array_set_gpu')
def gpu_reset():
"""Reset the currently selected GPU. """
r = call_c_function(niftyrec_c.et_array_reset_gpu,[])
if not r.status == status_success():
raise ErrorInCFunction(
"The execution of 'gpu_reset' was unsuccessful.",r.status,
'niftyrec_c.et_array_reset_gpu')
# print "STATUS:",r.status
def PET_project(activity, attenuation, binning,
use_gpu=0): # FIXME: in this and all other functions, replace 'binning' object with (only the required) raw variables
"""PET projection """
descriptor = [{'name': 'activity', 'type': 'array', 'value': activity},
{'name': 'activity_size_x', 'type': 'int', 'value': activity.shape[0]},
{'name': 'activity_size_y', 'type': 'int', 'value': activity.shape[1]},
{'name': 'activity_size_z', 'type': 'int', 'value': activity.shape[2]},
{'name': 'attenuation', 'type': 'array', 'value': attenuation},
{'name': 'attenuation_size_x', 'type': 'int', 'value': attenuation.shape[0]},
{'name': 'attenuation_size_y', 'type': 'int', 'value': attenuation.shape[1]},
{'name': 'attenuation_size_z', 'type': 'int', 'value': attenuation.shape[2]},
{'name': 'use_gpu', 'type': 'int', 'value': use_gpu}, ]
r = call_c_function(niftyrec_c.PET_project, descriptor)
if not r.status == status_success():
raise ErrorInCFunction("The execution of 'PET_project' was unsuccessful.", r.status, 'niftyrec_c.PET_project')
return r.dictionary['projection']
def PET_backproject(projection_data, attenuation, binning, use_gpu=0):
"""PET back-projection """
descriptor = []
r = call_c_function(niftyrec_c.PET_backproject, descriptor)
if not r.status == status_success():
raise ErrorInCFunction("The execution of 'PET_backproject' was unsuccessful.", r.status,
'niftyrec_c.PET_backproject')
return r.dictionary
def PET_project_compressed(activity,attenuation,offsets,locations,active,
N_axial,N_azimuthal,angles,N_u,N_v,size_u,size_v,
activity_size_x,activity_size_y,activity_size_z,
attenuation_size_x,attenuation_size_y,attenuation_size_z,
T_activity_x,T_activity_y,T_activity_z,
R_activity_x,R_activity_y,R_activity_z,
T_attenuation_x,T_attenuation_y,T_attenuation_z,
R_attenuation_x,R_attenuation_y,R_attenuation_z,
use_gpu,N_samples,sample_step,background,background_attenuation,
truncate_negative_values,direction,block_size):
"""PET projection; output projection data is compressed. """
N_locations = locations.shape[1]
# accept attenuation=None:
if attenuation is None:
attenuation = np.zeros((0,0,0))
descriptor = [{'name': 'projection', 'type': 'array', 'value': None, 'dtype': np.float32, 'size': (N_locations)},
{'name': 'activity', 'type': 'array', 'value': activity},
{'name': 'N_activity_x', 'type': 'uint', 'value': activity.shape[0]},
{'name': 'N_activity_y', 'type': 'uint', 'value': activity.shape[1]},
{'name': 'N_activity_z', 'type': 'uint', 'value': activity.shape[2]},
{'name': 'activity_size_x', 'type': 'float', 'value': activity_size_x},
{'name': 'activity_size_y', 'type': 'float', 'value': activity_size_y},
{'name': 'activity_size_z', 'type': 'float', 'value': activity_size_z},
{'name': 'T_activity_x', 'type': 'float', 'value': T_activity_x},
{'name': 'T_activity_y', 'type': 'float', 'value': T_activity_y},
{'name': 'T_activity_z', 'type': 'float', 'value': T_activity_z},
{'name': 'R_activity_x', 'type': 'float', 'value': R_activity_x},
{'name': 'R_activity_y', 'type': 'float', 'value': R_activity_y},
{'name': 'R_activity_z', 'type': 'float', 'value': R_activity_z},
{'name': 'attenuation', 'type': 'array', 'value': attenuation},
{'name': 'N_attenuation_x', 'type': 'uint', 'value': attenuation.shape[0]},
{'name': 'N_attenuation_y', 'type': 'uint', 'value': attenuation.shape[1]},
{'name': 'N_attenuation_z', 'type': 'uint', 'value': attenuation.shape[2]},
{'name': 'attenuation_size_x', 'type': 'float', 'value': attenuation_size_x},
{'name': 'attenuation_size_y', 'type': 'float', 'value': attenuation_size_y},
{'name': 'attenuation_size_z', 'type': 'float', 'value': attenuation_size_z},
{'name': 'T_attenuation_x', 'type': 'float', 'value': T_attenuation_x},
{'name': 'T_attenuation_y', 'type': 'float', 'value': T_attenuation_y},
{'name': 'T_attenuation_z', 'type': 'float', 'value': T_attenuation_z},
{'name': 'R_attenuation_x', 'type': 'float', 'value': R_attenuation_x},
{'name': 'R_attenuation_y', 'type': 'float', 'value': R_attenuation_y},
{'name': 'R_attenuation_z', 'type': 'float', 'value': R_attenuation_z},
{'name': 'N_axial', 'type': 'uint', 'value': N_axial},
{'name': 'N_azimuthal', 'type': 'uint', 'value': N_azimuthal},
{'name': 'angles', 'type': 'array', 'value': angles},
{'name': 'N_u', 'type': 'uint', 'value': N_u},
{'name': 'N_v', 'type': 'uint', 'value': N_v},
{'name': 'size_u', 'type': 'float', 'value': size_u},
{'name': 'size_v', 'type': 'float', 'value': size_v},
{'name': 'N_locations', 'type': 'uint', 'value': N_locations},
{'name': 'offsets', 'type': 'array', 'value': offsets},
{'name': 'locations', 'type': 'array', 'value': locations},
{'name': 'active', 'type': 'array', 'value': active},
{'name': 'N_samples', 'type': 'uint', 'value': N_samples},
{'name': 'sample_step', 'type': 'float', 'value': sample_step},
{'name': 'background', 'type': 'float', 'value': background},
{'name': 'background_attenuation', 'type': 'float', 'value': background_attenuation},
{'name': 'truncate_negative_values', 'type': 'uint', 'value': truncate_negative_values},
{'name': 'use_gpu', 'type': 'uint', 'value': use_gpu},
{'name': 'direction', 'type': 'uint', 'value': direction},
{'name': 'block_size', 'type': 'uint', 'value': block_size},
{'name': 'time_profiling', 'type': 'array', 'value': None, 'dtype': np.float32, 'size': (7)},
]
r = call_c_function(niftyrec_c.PET_project_compressed,descriptor)
if not r.status == status_success():
raise ErrorInCFunction(
"The execution of 'PET_project_compressed' was unsuccessful.",
r.status,
'niftyrec_c.PET_project_compressed')
# print r.dictionary['time_profiling']
T = r.dictionary['time_profiling'] / 1000.0 # [usec to ms]
timing_dict = {
"T0_transfer_to_gpu":T[0],"T1_alloc":T[1],"T2_rotate":T[2],
"T3_resample":T[3],"T4_integral":T[4],"T5_transfer_to_host":T[5],
"T6_free":T[6],
}
return r.dictionary["projection"],timing_dict
def PET_project_compressed_test(activity,attenuation,N_axial,N_azimuthal,
offsets,locations,active):
N_locations = locations.shape[1]
# accept attenuation=None:
if attenuation is None:
attenuation = np.zeros((0,0,0))
descriptor = [{
'name':'projection','type':'array','value':None,
'dtype':np.float32,'size':(N_locations),
},
{'name':'activity','type':'array','value':activity},
{
'name':'N_activity_x','type':'uint',
'value':activity.shape[0]
},
{
'name':'N_activity_y','type':'uint',
'value':activity.shape[1]
},
{
'name':'N_activity_z','type':'uint',
'value':activity.shape[2]
},
{'name':'attenuation','type':'array','value':attenuation},
{
'name':'N_attenuation_x','type':'uint',
'value':attenuation.shape[0]
},
{
'name':'N_attenuation_y','type':'uint',
'value':attenuation.shape[1]
},
{
'name':'N_attenuation_z','type':'uint',
'value':attenuation.shape[2]
},
{'name':'N_axial','type':'uint','value':N_axial},
{'name':'N_azimuthal','type':'uint','value':N_azimuthal},
{'name':'N_locations','type':'uint','value':N_locations},
{'name':'offsets','type':'array','value':offsets},
{'name':'locations','type':'array','value':locations},
{'name':'active','type':'array','value':active},]
r = call_c_function(niftyrec_c.PET_project_compressed_test,descriptor)
if not r.status == status_success():
raise ErrorInCFunction(
"The execution of 'PET_project_compressed_test' was unsuccessful.",
r.status,
'niftyrec_c.PET_project_compressed_test')
return r.dictionary["projection"]
def PET_backproject_compressed(projection_data,attenuation,offsets,locations,
active,
N_axial,N_azimuthal,angles,N_u,N_v,size_u,
size_v,
N_activity_x,N_activity_y,N_activity_z,
activity_size_x,activity_size_y,activity_size_z,
attenuation_size_x,attenuation_size_y,
attenuation_size_z,
T_activity_x,T_activity_y,T_activity_z,
R_activity_x,R_activity_y,R_activity_z,
T_attenuation_x,T_attenuation_y,T_attenuation_z,
R_attenuation_x,R_attenuation_y,
R_attenuation_z,
use_gpu,N_samples,sample_step,background,
background_attenuation,direction,
block_size):
"""PET back-projection; input projection data is compressed. """
N_locations = locations.shape[1]
# accept attenuation=None:
if attenuation is None:
attenuation = np.zeros((0,0,0))
descriptor = [{'name': 'back_projection', 'type': 'array', 'value': None, 'dtype': np.float32,
'size': (N_activity_x, N_activity_y, N_activity_z), 'order': "F"},
{'name': 'N_activity_x', 'type': 'uint', 'value': N_activity_x},
{'name': 'N_activity_y', 'type': 'uint', 'value': N_activity_y},
{'name': 'N_activity_z', 'type': 'uint', 'value': N_activity_z},
{'name': 'activity_size_x', 'type': 'float', 'value': activity_size_x},
{'name': 'activity_size_y', 'type': 'float', 'value': activity_size_y},
{'name': 'activity_size_z', 'type': 'float', 'value': activity_size_z},
{'name': 'T_activity_x', 'type': 'float', 'value': T_activity_x},
{'name': 'T_activity_y', 'type': 'float', 'value': T_activity_y},
{'name': 'T_activity_z', 'type': 'float', 'value': T_activity_z},
{'name': 'R_activity_x', 'type': 'float', 'value': R_activity_x},
{'name': 'R_activity_y', 'type': 'float', 'value': R_activity_y},
{'name': 'R_activity_z', 'type': 'float', 'value': R_activity_z},
{'name': 'attenuation', 'type': 'array', 'value': attenuation},
{'name': 'N_attenuation_x', 'type': 'uint', 'value': attenuation.shape[0]},
{'name': 'N_attenuation_y', 'type': 'uint', 'value': attenuation.shape[1]},
{'name': 'N_attenuation_z', 'type': 'uint', 'value': attenuation.shape[2]},
{'name': 'attenuation_size_x', 'type': 'float', 'value': attenuation_size_x},
{'name': 'attenuation_size_y', 'type': 'float', 'value': attenuation_size_y},
{'name': 'attenuation_size_z', 'type': 'float', 'value': attenuation_size_z},
{'name': 'T_attenuation_x', 'type': 'float', 'value': T_attenuation_x},
{'name': 'T_attenuation_y', 'type': 'float', 'value': T_attenuation_y},
{'name': 'T_attenuation_z', 'type': 'float', 'value': T_attenuation_z},
{'name': 'R_attenuation_x', 'type': 'float', 'value': R_attenuation_x},
{'name': 'R_attenuation_y', 'type': 'float', 'value': R_attenuation_y},
{'name': 'R_attenuation_z', 'type': 'float', 'value': R_attenuation_z},
{'name': 'N_axial', 'type': 'uint', 'value': N_axial},
{'name': 'N_azimuthal', 'type': 'uint', 'value': N_azimuthal},
{'name': 'angles', 'type': 'array', 'value': angles},
{'name': 'N_u', 'type': 'uint', 'value': N_u},
{'name': 'N_v', 'type': 'uint', 'value': N_v},
{'name': 'size_u', 'type': 'float', 'value': size_u},
{'name': 'size_v', 'type': 'float', 'value': size_v},
{'name': 'N_locations', 'type': 'uint', 'value': N_locations},
{'name': 'offsets', 'type': 'array', 'value': offsets},
{'name': 'locations', 'type': 'array', 'value': locations},
{'name': 'active', 'type': 'array', 'value': active},
{'name': 'projection_data', 'type': 'array', 'value': projection_data},
{'name': 'use_gpu', 'type': 'uint', 'value': use_gpu},
{'name': 'N_samples', 'type': 'uint', 'value': N_samples},
{'name': 'sample_step', 'type': 'float', 'value': sample_step},
{'name': 'background_activity', 'type': 'float', 'value': background},
{'name': 'background_attenuation', 'type': 'float', 'value': background_attenuation},
{'name': 'direction', 'type': 'uint', 'value': direction},
{'name': 'block_size', 'type': 'uint', 'value': block_size},
{'name': 'time_profiling', 'type': 'array', 'value': None, 'dtype': np.float32, 'size': (10)},
]
r = call_c_function(niftyrec_c.PET_backproject_compressed,descriptor)
if not r.status == status_success():
raise ErrorInCFunction(
"The execution of 'PET_backproject_compressed' was unsuccessful.",
r.status,
'niftyrec_c.PET_backproject_compressed')
T = r.dictionary['time_profiling'] / 1000.0 # [usec to ms]
timing_dict = {
"T0_transfer_to_gpu":T[0],"T1_alloc":T[1],"T2_rotate":T[2],
"T3_resample":T[3],"T4_integral":T[4],"T5_transfer_to_host":T[5],
"T6_free":T[6],
"T7_accumulate":T[7],"T8_clear_memory":T[8],"T9_copy_texture":T[9]
}
return r.dictionary["back_projection"],timing_dict
def PET_initialize_compression_structure(N_axial,N_azimuthal,N_u,N_v):
"""Obtain 'offsets' and 'locations' arrays for fully sampled PET compressed projection data. """
descriptor = [{'name':'N_axial','type':'uint','value':N_axial},
{'name':'N_azimuthal','type':'uint','value':N_azimuthal},
{'name':'N_u','type':'uint','value':N_u},
{'name':'N_v','type':'uint','value':N_v},
{
'name':'offsets','type':'array','value':None,
'dtype':np.int32,'size':(N_azimuthal,N_axial),
'order':'F'
},
{
'name':'locations','type':'array','value':None,
'dtype':np.uint16,
'size':(3,N_u * N_v * N_axial * N_azimuthal),'order':'F'
},
]
r = call_c_function(niftyrec_c.PET_initialize_compression_structure,
descriptor)
if not r.status == status_success():
raise ErrorInCFunction(
"The execution of 'PET_initialize_compression_structure' was unsuccessful.",
r.status,
'niftyrec_c.PET_initialize_compression_structure')
return [r.dictionary['offsets'],r.dictionary['locations']]
def PET_compress_projection(offsets,data,locations,N_u,N_v):
"""Find the zero entries in fully sampled PET projection data and compress it."""
N_locations = locations.shape[1]
N_axial = offsets.shape[1]
N_azimuthal = offsets.shape[0]
descriptor = [{'name':'N_locations','type':'uint','value':N_locations},
{'name':'N_axial','type':'uint','value':N_axial},
{'name':'N_azimuthal','type':'uint','value':N_azimuthal},
{'name':'N_u','type':'uint','value':N_u},
{'name':'N_v','type':'uint','value':N_v},
{'name':'offsets','type':'array','value':offsets},
{'name':'data','type':'array','value':data},
{'name':'locations','type':'array','value':locations},
{
'name':'projection','type':'array','value':None,
'dtype':np.float32,'size':(N_locations,),
'order':'F'
},
]
r = call_c_function(niftyrec_c.PET_compress_projection,descriptor)
if not r.status == status_success():
raise ErrorInCFunction(
"The execution of 'PET_compress_projection' was unsuccessful.",
r.status,
'niftyrec_c.PET_compress_projection')
return r.dictionary['projection']
def PET_uncompress_projection(offsets,data,locations,N_u,N_v):
"""Uncompress compressed PET projection data. """
N_locations = locations.shape[1]
N_axial = offsets.shape[1]
N_azimuthal = offsets.shape[0]
descriptor = [{'name':'N_locations','type':'uint','value':N_locations},
{'name':'N_axial','type':'uint','value':N_axial},
{'name':'N_azimuthal','type':'uint','value':N_azimuthal},
{'name':'N_u','type':'uint','value':N_u},
{'name':'N_v','type':'uint','value':N_v},
{'name':'offsets','type':'array','value':offsets},
{'name':'data','type':'array','value':data},
{'name':'locations','type':'array','value':locations},
{
'name':'projection','type':'array','value':None,
'dtype':np.float32,
'size':(N_v * N_u * N_azimuthal * N_axial,),'order':'F'
},
]
r = call_c_function(niftyrec_c.PET_uncompress_projection,descriptor)
if not r.status == status_success():
raise ErrorInCFunction(
"The execution of 'PET_uncompress_projection' was unsuccessful.",
r.status,
'niftyrec_c.PET_uncompress_projection')
return r.dictionary['projection']
def PET_compress_projection_array(data,N_ax,N_az,N_u,N_v,threshold = 1e-15):
"""Compress 4D projection array. Returns compressed data structure: offsets, locations, compressed data array. """
active = data > threshold
N_active = active.sum()
data_size = (N_active,)
offsets_size = (N_az,N_ax)
locations_size = (3,N_active)
descriptor = [{'name':'N_axial','type':'uint','value':N_ax},
{'name':'N_azimuthal','type':'uint','value':N_az},
{'name':'N_u','type':'uint','value':N_u},
{'name':'N_v','type':'uint','value':N_v},
{'name':'threshold','type':'float','value':threshold},
{'name':'N_active','type':'uint','value':N_active},
{'name':'active','type':'array','value':active},
{'name':'data','type':'array','value':data},
{
'name':'offsets','type':'array','value':None,
'dtype':np.int32,'size':offsets_size,
'order':'F'
},
{
'name':'locations','type':'array','value':None,
'dtype':np.uint16,'size':locations_size,
'order':'F'
},
{
'name':'compressed','type':'array','value':None,
'dtype':np.float32,'size':data_size,
'order':'F'
},
]
r = call_c_function(niftyrec_c.PET_compress_projection_array,descriptor)
if not r.status == status_success():
raise ErrorInCFunction(
"The execution of 'PET_compress_projection_array' was unsuccessful.",
r.status,
'niftyrec_c.PET_compress_projection_array')
return r.dictionary['compressed'],r.dictionary['offsets'],r.dictionary[
'locations']
def PET_get_subset_sparsity(offsets,locations,subsets_matrix,N_u,N_v,
N_locations,N_locations_sub):
"""Extracts a subset from sparsity structure. The function takes offsets and locations and a subset matrix as input and returns offsets and locations for the specified subset. """
N_subsets = subsets_matrix.sum()
N_ax = subsets_matrix.shape[1]
N_az = subsets_matrix.shape[0]
offsets_size = (1,N_subsets)
locations_size = (3,N_locations_sub)
descriptor = [{'name':'N_axial','type':'uint','value':N_ax},
{'name':'N_azimuthal','type':'uint','value':N_az},
{'name':'N_u','type':'uint','value':N_u},
{'name':'N_v','type':'uint','value':N_v},
{'name':'N_locations','type':'uint','value':N_locations},
{'name':'offsets','type':'array','value':offsets},
{'name':'locations','type':'array','value':locations},
{
'name':'subsets_matrix','type':'array',
'value':subsets_matrix
},
{
'name':'offsets_sub','type':'array','value':None,
'dtype':np.int32,'size':offsets_size,
'order':'F'
},
{
'name':'locations_sub','type':'array','value':None,
'dtype':np.uint16,'size':locations_size,
'order':'F'
},
]
r = call_c_function(niftyrec_c.PET_get_subset_sparsity,descriptor)
if not r.status == status_success():
raise ErrorInCFunction(
"The execution of 'PET_get_subset_sparsity' was unsuccessful.",
r.status,
'niftyrec_c.PET_get_subset_sparsity')
return r.dictionary['offsets_sub'],r.dictionary['locations_sub']
def PET_get_subset_projection_array(data,subsets_matrix,offsets,locations,N_u,
N_v,N_locations,N_locations_sub):
"""Extracts a subset from a compressed projection data array. """
N_subsets = subsets_matrix.sum()
N_ax = subsets_matrix.shape[1]
N_az = subsets_matrix.shape[0]
offsets_size = (1,N_subsets)
locations_size = (3,N_locations_sub)
data_size = (N_locations_sub,)
descriptor = [{'name':'N_axial','type':'uint','value':N_ax},
{'name':'N_azimuthal','type':'uint','value':N_az},
{'name':'N_u','type':'uint','value':N_u},
{'name':'N_v','type':'uint','value':N_v},
{'name':'N_locations','type':'uint','value':N_locations},
{'name':'data','type':'array','value':data},
{'name':'offsets','type':'array','value':offsets},
{'name':'locations','type':'array','value':locations},
{
'name':'offsets_sub','type':'array','value':None,
'dtype':np.int32,'size':offsets_size,
'order':'F'
},
{
'name':'locations_sub','type':'array','value':None,
'dtype':np.uint16,'size':locations_size,
'order':'F'
},
{
'name':'subsets_matrix','type':'array',
'value':subsets_matrix
},
{
'name':'data_sub','type':'array','value':None,
'dtype':np.float32,'size':data_size,
'order':'F'
},
]
r = call_c_function(niftyrec_c.PET_get_subset_projection_array,descriptor)
if not r.status == status_success():
raise ErrorInCFunction(
"The execution of 'PET_get_subset_projection_array' was unsuccessful.",
r.status,
'niftyrec_c.PET_get_subset_projection_array')
return r.dictionary['data_sub'],r.dictionary['offsets_sub'],r.dictionary[
'locations_sub']
def ET_spherical_phantom(shape, size, center, radius, inner_value, outer_value):
"""Create a spherical phantom. """
descriptor = [
{
'name':'image','type':'array','value':None,'dtype':np.float32,
'size':(shape[0], shape[1], shape[2]),
'order':"F"
},
{'name':'Nx','type':'uint','value':shape[0]},
{'name':'Ny','type':'uint','value':shape[1]},
{'name':'Nz','type':'uint','value':shape[2]},
{'name':'sizex','type':'float','value':size[0]},
{'name':'sizey','type':'float','value':size[1]},
{'name':'sizez','type':'float','value':size[2]},
{'name':'centerx','type':'float','value':center[0]},
{'name':'centery','type':'float','value':center[1]},
{'name':'centerz','type':'float','value':center[2]},
{'name':'radius','type':'float','value':radius},
{'name':'inner_value','type':'float','value':inner_value},
{'name':'outer_value','type':'float','value':outer_value},]
r = call_c_function(niftyrec_c.ET_spherical_phantom,descriptor)
if not r.status == status_success():
raise ErrorInCFunction(
"The execution of 'ET_spherical_phantom' was unsuccessful.",
r.status,
'niftyrec_c.ET_spherical_phantom')
return r.dictionary['image']
def ET_cylindrical_phantom(shape, size, center, radius, length, axis, inner_value,
outer_value):
"""Create a cylindrical phantom. """
descriptor = [
{
'name':'image','type':'array','value':None,'dtype':np.float32,
'size':(shape[0], shape[1], shape[2]),
'order':"F"
},
{'name':'Nx','type':'uint','value':shape[0]},
{'name':'Ny','type':'uint','value':shape[1]},
{'name':'Nz','type':'uint','value':shape[2]},
{'name':'sizex','type':'float','value':size[0]},
{'name':'sizey','type':'float','value':size[1]},
{'name':'sizez','type':'float','value':size[2]},
{'name':'centerx','type':'float','value':center[0]},
{'name':'centery','type':'float','value':center[1]},
{'name':'centerz','type':'float','value':center[2]},
{'name':'radius','type':'float','value':radius},
{'name':'length','type':'float','value':length},
{'name':'axis','type':'uint','value':axis},
{'name':'inner_value','type':'float','value':inner_value},
{'name':'outer_value','type':'float','value':outer_value},]
r = call_c_function(niftyrec_c.ET_cylindrical_phantom,descriptor)
if not r.status == status_success():
raise ErrorInCFunction(
"The execution of 'ET_cylindrical_phantom' was unsuccessful.",
r.status,
'niftyrec_c.ET_cylindrical_phantom')
return r.dictionary['image']
def ET_spheres_ring_phantom(shape, size, center, ring_radius, min_sphere_radius,
max_sphere_radius, N_spheres = 6,
inner_value = 1.0, outer_value = 0.0, taper = 0,
axis = 0):
"""Create a phantom with a ring of spheres of variable radius. """
descriptor = [
{
'name':'image','type':'array','value':None,'dtype':np.float32,
'size':(shape[0], shape[1], shape[2]),
'order':"F"
},
{'name':'Nx','type':'uint','value':shape[0]},
{'name':'Ny','type':'uint','value':shape[1]},
{'name':'Nz','type':'uint','value':shape[2]},
{'name':'sizex','type':'float','value':size[0]},
{'name':'sizey','type':'float','value':size[1]},
{'name':'sizez','type':'float','value':size[2]},
{'name':'centerx','type':'float','value':center[0]},
{'name':'centery','type':'float','value':center[1]},
{'name':'centerz','type':'float','value':center[2]},
{'name':'ring_radius','type':'float','value':ring_radius},
{'name':'min_sphere_radius','type':'float','value':min_sphere_radius},
{'name':'max_sphere_radius','type':'float','value':max_sphere_radius},
{'name':'N_spheres','type':'uint','value':N_spheres},
{'name':'inner_value','type':'float','value':inner_value},
{'name':'outer_value','type':'float','value':outer_value},
{'name':'taper','type':'float','value':taper},
{'name':'ring_axis','type':'uint','value':axis},]
r = call_c_function(niftyrec_c.ET_spheres_ring_phantom,descriptor)
if not r.status == status_success():
raise ErrorInCFunction(
"The execution of 'ET_spheres_ring_phantom' was unsuccessful.",
r.status,
'niftyrec_c.ET_spheres_ring_phantom')
return r.dictionary['image']
def ET_cylinders_ring_phantom(shape, size, center, ring_radius, length,
min_cylinder_radius, max_cylinder_radius, N_cylinders = 6,
inner_value = 1.0, outer_value = 0.0, taper = 0,
axis = 0):
"""Create a phantom with a ring of spheres of variable radius. """
descriptor = [
{
'name':'image','type':'array','value':None,'dtype':np.float32,
'size':(shape[0], shape[1], shape[2]),
'order':"F"
},
{'name':'Nx','type':'uint','value':shape[0]},
{'name':'Ny','type':'uint','value':shape[1]},
{'name':'Nz','type':'uint','value':shape[2]},
{'name':'sizex','type':'float','value':size[0]},
{'name':'sizey','type':'float','value':size[1]},
{'name':'sizez','type':'float','value':size[2]},
{'name':'centerx','type':'float','value':center[0]},
{'name':'centery','type':'float','value':center[1]},
{'name':'centerz','type':'float','value':center[2]},
{'name':'ring_radius','type':'float','value':ring_radius},
{'name':'length','type':'float','value':length},
{'name':'min_cylinder_radius','type':'float','value':min_cylinder_radius},
{'name':'max_cylinder_radius','type':'float','value':max_cylinder_radius},
{'name':'N_cylinders','type':'uint','value':N_cylinders},
{'name':'inner_value','type':'float','value':inner_value},
{'name':'outer_value','type':'float','value':outer_value},
{'name':'taper','type':'float','value':taper},
{'name':'ring_axis','type':'uint','value':axis},]
r = call_c_function(niftyrec_c.ET_cylinders_ring_phantom,descriptor)
if not r.status == status_success():
raise ErrorInCFunction(
"The execution of 'ET_cylinders_ring_phantom' was unsuccessful.",
r.status,
'niftyrec_c.ET_cylinders_ring_phantom')
return r.dictionary['image']
def SPECT_project_parallelholes(activity,cameras,attenuation = None,psf = None,
background = 0.0,
background_attenuation = 0.0,use_gpu = 1,
truncate_negative_values = 0):
"""SPECT projection; parallel-holes geometry. """
# accept attenuation=None and psf=None:
if attenuation is None:
attenuation = np.zeros((0,0,0))
if psf is None:
psf = np.zeros((0,0,0))
N_projections = cameras.shape[0]
descriptor = [{'name':'activity','type':'array','value':activity},
{
'name':'activity_size','type':'array',
'value':np.int32(activity.shape)
},
{
'name':'projection','type':'array','value':None,
'dtype':np.float32,
'size':(
activity.shape[0],activity.shape[1],N_projections),
'order':"F"
},
{
'name':'projection_size','type':'array',
'value':np.int32([N_projections,activity.shape[0],
activity.shape[1]])
},
{
'name':'cameras','type':'array','value':cameras,
'order':"F"
},
{
'name':'cameras_size','type':'array',
'value':np.int32(cameras.shape)
},
{'name':'psf','type':'array','value':psf,'order':"F"},
{
'name':'psf_size','type':'array',
'value':np.int32(psf.shape)
},
{'name':'attenuation','type':'array','value':attenuation},
{
'name':'attenuation_size','type':'array',
'value':np.int32(attenuation.shape)
},
{'name':'background','type':'float','value':background},
{
'name':'background_attenuation','type':'float',
'value':background_attenuation
},
{'name':'use_gpu','type':'int','value':use_gpu},
{
'name':'truncate_negative_values','type':'int',
'value':truncate_negative_values
},]
r = call_c_function(niftyrec_c.SPECT_project_parallelholes,descriptor)
if not r.status == status_success():
raise ErrorInCFunction(
"The execution of 'SPECT_project_parallelholes' was unsuccessful.",
r.status,
'niftyrec_c.SPECT_project_parallelholes')
return r.dictionary['projection']
def SPECT_backproject_parallelholes(projection,cameras,attenuation = None,
psf = None,background = 0.0,
background_attenuation = 0.0,use_gpu = 1,
truncate_negative_values = 0):
"""SPECT backprojection; parallel-holes geometry. """
# accept attenuation=None and psf=None:
if attenuation is None:
attenuation = np.zeros((0,0,0))
if psf is None:
psf = np.zeros((0,0,0))
N_projections = cameras.shape[0]
descriptor = [{'name':'projection','type':'array','value':projection},
{
'name':'projection_size','type':'array',
'value':np.int32(projection.shape)
},
{
'name':'backprojection','type':'array','value':None,
'dtype':np.float32,
'size':(projection.shape[0],projection.shape[1],
projection.shape[0]),'order':"F"
},
{
'name':'backprojection_size','type':'array',
'value':np.int32(
[projection.shape[0],projection.shape[1],
projection.shape[0]])
},
{
'name':'cameras','type':'array','value':cameras,
'order':"F"
},
{
'name':'cameras_size','type':'array',
'value':np.int32(cameras.shape)
},
{'name':'psf','type':'array','value':psf,'order':"F"},
{
'name':'psf_size','type':'array',
'value':np.int32(psf.shape)
},
{'name':'attenuation','type':'array','value':attenuation},
{
'name':'attenuation_size','type':'array',
'value': | np.int32(attenuation.shape) | numpy.int32 |
# Copyright 2020, The TensorFlow 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.
# Lint as: python3
"""Tests for tensorflow_privacy.privacy.membership_inference_attack.seq2seq_mia."""
from absl.testing import absltest
import numpy as np
from tensorflow_privacy.privacy.membership_inference_attack.data_structures import AttackType
from tensorflow_privacy.privacy.membership_inference_attack.data_structures import PrivacyReportMetadata
from tensorflow_privacy.privacy.membership_inference_attack.seq2seq_mia import create_seq2seq_attacker_data
from tensorflow_privacy.privacy.membership_inference_attack.seq2seq_mia import run_seq2seq_attack
from tensorflow_privacy.privacy.membership_inference_attack.seq2seq_mia import Seq2SeqAttackInputData
class Seq2SeqAttackInputDataTest(absltest.TestCase):
def test_validator(self):
valid_logits_train = iter([np.array([]), np.array([])])
valid_logits_test = iter([np.array([]), np.array([])])
valid_labels_train = iter([np.array([]), np.array([])])
valid_labels_test = iter([np.array([]), np.array([])])
invalid_logits_train = []
invalid_logits_test = []
invalid_labels_train = []
invalid_labels_test = []
self.assertRaises(
ValueError,
Seq2SeqAttackInputData(logits_train=valid_logits_train).validate)
self.assertRaises(
ValueError,
Seq2SeqAttackInputData(labels_train=valid_labels_train).validate)
self.assertRaises(
ValueError,
Seq2SeqAttackInputData(logits_test=valid_logits_test).validate)
self.assertRaises(
ValueError,
Seq2SeqAttackInputData(labels_test=valid_labels_test).validate)
self.assertRaises(ValueError, Seq2SeqAttackInputData(vocab_size=0).validate)
self.assertRaises(ValueError, Seq2SeqAttackInputData(train_size=0).validate)
self.assertRaises(ValueError, Seq2SeqAttackInputData(test_size=0).validate)
self.assertRaises(ValueError, Seq2SeqAttackInputData().validate)
# Tests that both logits and labels must be set.
self.assertRaises(
ValueError,
Seq2SeqAttackInputData(
logits_train=valid_logits_train,
logits_test=valid_logits_test,
vocab_size=0,
train_size=0,
test_size=0).validate)
self.assertRaises(
ValueError,
Seq2SeqAttackInputData(
labels_train=valid_labels_train,
labels_test=valid_labels_test,
vocab_size=0,
train_size=0,
test_size=0).validate)
# Tests that vocab, train, test sizes must all be set.
self.assertRaises(
ValueError,
Seq2SeqAttackInputData(
logits_train=valid_logits_train,
logits_test=valid_logits_test,
labels_train=valid_labels_train,
labels_test=valid_labels_test).validate)
self.assertRaises(
ValueError,
Seq2SeqAttackInputData(
logits_train=invalid_logits_train,
logits_test=invalid_logits_test,
labels_train=invalid_labels_train,
labels_test=invalid_labels_test,
vocab_size=0,
train_size=0,
test_size=0).validate)
class Seq2SeqTrainedAttackerTest(absltest.TestCase):
def test_create_seq2seq_attacker_data_logits_and_labels(self):
attack_input = Seq2SeqAttackInputData(
logits_train=iter([
np.array([
np.array([[0.1, 0.1, 0.8], [0.7, 0.3, 0]], dtype=np.float32),
np.array([[0.4, 0.5, 0.1]], dtype=np.float32)
],
dtype=object),
np.array(
[np.array([[0.25, 0.6, 0.15], [1, 0, 0]], dtype=np.float32)],
dtype=object),
np.array([
np.array([[0.9, 0, 0.1], [0.25, 0.5, 0.25]], dtype=np.float32),
np.array([[0, 1, 0], [0.2, 0.1, 0.7]], dtype=np.float32)
],
dtype=object)
]),
logits_test=iter([
np.array([
np.array([[0.25, 0.4, 0.35], [0.2, 0.4, 0.4]], dtype=np.float32)
],
dtype=object),
np.array([
np.array([[0.3, 0.3, 0.4], [0.4, 0.4, 0.2]], dtype=np.float32),
| np.array([[0.3, 0.35, 0.35]], dtype=np.float32) | numpy.array |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright (C) 2016-2018 <NAME>, SMBYC
# Email: xcorredorl at ideam.gov.co
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
import dask.array as da
import numpy as np
from stack_composed.image import Image
def statistic(stat, images, band, num_process, chunksize):
# create a empty initial wrapper raster for managed dask parallel
# in chunks and storage result
wrapper_array = da.empty(Image.wrapper_shape, chunks=chunksize)
chunksize = wrapper_array.chunks[0][0]
# call built in numpy statistical functions, with a specified axis. if
# axis=2 means it will Compute along the 'depth' axis, per pixel.
# with the return being n by m, the shape of each band.
#
# Compute the median
if stat == 'median':
def stat_func(stack_chunk, metadata):
return np.nanmedian(stack_chunk, axis=2)
# Compute the arithmetic mean
if stat == 'mean':
def stat_func(stack_chunk, metadata):
return np.nanmean(stack_chunk, axis=2)
# Compute the geometric mean
if stat == 'gmean':
def stat_func(stack_chunk, metadata):
product = np.nanprod(stack_chunk, axis=2)
count = np.count_nonzero(np.nan_to_num(stack_chunk), axis=2)
gmean = np.array([p ** (1.0 / c) for p, c in zip(product, count)])
gmean[gmean == 1] = np.nan
return gmean
# Compute the maximum value
if stat == 'max':
def stat_func(stack_chunk, metadata):
return np.nanmax(stack_chunk, axis=2)
# Compute the minimum value
if stat == 'min':
def stat_func(stack_chunk, metadata):
return np.nanmin(stack_chunk, axis=2)
# Compute the standard deviation
if stat == 'std':
def stat_func(stack_chunk, metadata):
return np.nanstd(stack_chunk, axis=2)
# Compute the valid pixels
# this count the valid data (no nans) across the z-axis
if stat == 'valid_pixels':
def stat_func(stack_chunk, metadata):
return stack_chunk.shape[2] - np.isnan(stack_chunk).sum(axis=2)
# Compute the percentile NN
if stat.startswith('percentile_'):
p = int(stat.split('_')[1])
def stat_func(stack_chunk, metadata):
return np.nanpercentile(stack_chunk, p, axis=2)
# Compute the last valid pixel
if stat == 'last_pixel':
def last_pixel(pixel_time_series, index_sort):
if np.isnan(pixel_time_series).all():
return np.nan
for index in index_sort:
if not np.isnan(pixel_time_series[index]):
return pixel_time_series[index]
def stat_func(stack_chunk, metadata):
index_sort = np.argsort(metadata['date'])[::-1] # from the most recent to the oldest
return np.apply_along_axis(last_pixel, 2, stack_chunk, index_sort)
# Compute the julian day of the last valid pixel
if stat == 'jday_last_pixel':
def jday_last_pixel(pixel_time_series, index_sort, jdays):
if np.isnan(pixel_time_series).all():
return 0 # better np.nan but there is bug with multiprocessing with return nan value here
for index in index_sort:
if not np.isnan(pixel_time_series[index]):
return jdays[index]
def stat_func(stack_chunk, metadata):
index_sort = np.argsort(metadata['date'])[::-1] # from the most recent to the oldest
return np.apply_along_axis(jday_last_pixel, 2, stack_chunk, index_sort, metadata['jday'])
# Compute the julian day of the median value
if stat == 'jday_median':
def jday_median(pixel_time_series, index_sort, jdays):
if np.isnan(pixel_time_series).all():
return 0 # better np.nan but there is bug with multiprocessing with return nan value here
jdays = [jdays[index] for index in index_sort if not np.isnan(pixel_time_series[index])]
return np.ceil(np.median(jdays))
def stat_func(stack_chunk, metadata):
index_sort = np.argsort(metadata['date']) # from the oldest to most recent
return np.apply_along_axis(jday_median, 2, stack_chunk, index_sort, metadata['jday'])
# Compute the trimmed median with lower limit and upper limit
if stat.startswith('trim_mean_'):
# TODO: check this stats when the time series have few data
lower = int(stat.split('_')[2])
upper = int(stat.split('_')[3])
def trim_mean(pixel_time_series):
if np.isnan(pixel_time_series).all():
return 0 # better np.nan but there is bug with multiprocessing with return nan value here
pts = pixel_time_series[~np.isnan(pixel_time_series)]
if len(pts) <= 2:
return np.percentile(pts, (lower+upper)/2)
return np.mean(pts[(pts >= np.percentile(pts, lower)) & (pts <= np.percentile(pts, upper))])
def stat_func(stack_chunk, metadata):
return np.apply_along_axis(trim_mean, 2, stack_chunk)
# Compute the linear trend using least-squares method
if stat == 'linear_trend':
def linear_trend(pixel_time_series, index_sort, date_list):
if np.isnan(pixel_time_series).all() or len(pixel_time_series[~np.isnan(pixel_time_series)]) == 1:
return np.nan
# Unix timestamp in days
x = [int(int(date_list[index].strftime("%s")) / 86400) for index in index_sort]
x = [i-x[0] for i in x] # diff from minimum
pts = np.array([pixel_time_series[index] for index in index_sort])
y = np.ma.array(pts, mask=np.isnan(pts))
ssxm, ssxym, ssyxm, ssym = np.ma.cov(x, y, bias=1).flat
slope = ssxym / ssxm
return slope*1000000
def stat_func(stack_chunk, metadata):
index_sort = | np.argsort(metadata['date']) | numpy.argsort |
"""Test functions.
This module implements several known mathematical functions, that can
be used to test RBFOpt.
Licensed under Revised BSD license, see LICENSE.
(C) Copyright Singapore University of Technology and Design 2014.
(C) Copyright International Business Machines Corporation 2017.
"""
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
import sys
import math
import numpy as np
from rbfopt.rbfopt_black_box import RbfoptBlackBox
class branin:
"""
Branin function of the Dixon-Szego test set.
"""
@classmethod
def evaluate(cls, x):
assert(len(x)==2)
value = ((x[1] - (5.1/(4*math.pi*math.pi))*x[0]*x[0] +
5/math.pi*x[0] - 6)**2 + 10*(1-1/(8*math.pi)) *
math.cos(x[0]) +10)
return(value)
dimension = 2
var_lower = np.array([-5, 0])
var_upper = np.array([10, 15])
optimum_point = np.array([9.42477796, 2.47499998])
additional_optima = np.array([ [-3.14159265, 12.27500000],
[3.14159265, 2.27500000] ])
optimum_value = 0.397887357729739
var_type = np.array(['R'] * 2)
# -- end class
class hartman3:
"""
Hartman3 function of the Dixon-Szego test set.
"""
@classmethod
def evaluate(cls, x):
assert(len(x)==3)
value = -math.fsum([ cls.c[i] *
np.exp(-math.fsum([cls.a[j][i]*
(x[j] - cls.p[j][i])**2
for j in range(3)]))
for i in range(4) ])
return(value)
a = [ [3.0, 0.1, 3.0, 0.1],
[10.0, 10.0, 10.0, 10.0],
[30.0, 35.0, 30.0, 35.0] ]
p = [ [0.36890, 0.46990, 0.10910, 0.03815],
[0.11700, 0.43870, 0.87320, 0.57430],
[0.26730, 0.74700, 0.55470, 0.88280] ]
c = [1.0, 1.2, 3.0, 3.2]
dimension = 3
var_lower = np.array([0, 0, 0])
var_upper = np.array([1, 1, 1])
optimum_point = np.array([0.1, 0.55592003, 0.85218259])
optimum_value = -3.8626347486217725
var_type = np.array(['R'] * 3)
# -- end class
class hartman6:
"""
Hartman6 function of the Dixon-Szego test set.
"""
@classmethod
def evaluate(cls, x):
assert(len(x)==6)
value = -math.fsum([ cls.c[i] *
np.exp(-math.fsum([cls.a[j][i]*
(x[j] - cls.p[j][i])**2
for j in range(6)]))
for i in range(4) ])
return(value)
a = [ [10.00, 0.05, 3.00, 17.00],
[3.00, 10.00, 3.50, 8.00],
[17.00, 17.00, 1.70, 0.05],
[3.50, 0.10, 10.00, 10.00],
[1.70, 8.00, 17.00, 0.10],
[8.00, 14.00, 8.00, 14.00] ]
p = [ [0.1312, 0.2329, 0.2348, 0.4047],
[0.1696, 0.4135, 0.1451, 0.8828],
[0.5569, 0.8307, 0.3522, 0.8732],
[0.0124, 0.3736, 0.2883, 0.5743],
[0.8283, 0.1004, 0.3047, 0.1091],
[0.5886, 0.9991, 0.6650, 0.0381] ]
c = [1.0, 1.2, 3.0, 3.2]
dimension = 6
var_lower = np.array([0, 0, 0, 0, 0, 0])
var_upper = np.array([1, 1, 1, 1, 1, 1])
optimum_point = np.array([0.20168952, 0.15001069, 0.47687398,
0.27533243, 0.31165162, 0.65730054])
optimum_value = -3.32236801141551
var_type = np.array(['R'] * 6)
# -- end class
class camel:
"""
Six-hump Camel function of the Dixon-Szego test set.
"""
@classmethod
def evaluate(cls, x):
assert(len(x)==2)
value = ((4 - 2.1*x[0]**2 + x[0]**4/3)*x[0]**2 +
x[0]*x[1] + (-4 + 4*x[1]**2)*x[1]**2)
return(value)
dimension = 2
var_lower = np.array([-3, -2])
var_upper = np.array([3, 2])
optimum_point = np.array([0.08984201, -0.7126])
optimum_value = -1.0316284535
var_type = np.array(['R'] * 2)
# -- end class
class goldsteinprice:
"""
Goldstein & Price function of the Dixon-Szego test set.
"""
@classmethod
def evaluate(cls, x):
assert(len(x)==2)
value= ((1 + (x[0] + x[1] + 1)**2 *
(19 - 14*x[0] + 3*x[0]**2 - 14*x[1] + 6*x[0]*x[1] +
3*x[1]**2)) *
(30 + (2*x[0] - 3*x[1])**2 *
(18 - 32*x[0] + 12*x[0]**2 + 48*x[1] - 36*x[0]*x[1] +
27*x[1]**2)))
return(value)
dimension = 2
var_lower = np.array([-2, -2])
var_upper = np.array([2, 2])
optimum_point = np.array([0.0, -1.0])
optimum_value = 3
var_type = np.array(['R'] * 2)
# -- end class
class shekel5:
"""
Shekel5 function of the Dixon-Szego test set.
"""
@classmethod
def evaluate(cls, x):
assert(len(x)==4)
value = -math.fsum([ 1.0 /
(math.fsum([math.fsum([ (x[i] - cls.a[i][j])**2
for i in range(4) ]),
cls.c[j]])) for j in range(5) ])
return(value)
a = [ [4.0, 1.0, 8.0, 6.0, 3.0],
[4.0, 1.0, 8.0, 6.0, 7.0],
[4.0, 1.0, 8.0, 6.0, 3.0],
[4.0, 1.0, 8.0, 6.0, 7.0] ]
c = [0.1, 0.2, 0.2, 0.4, 0.4]
dimension = 4
var_lower = np.array([0, 0, 0, 0])
var_upper = np.array([10, 10, 10, 10])
optimum_point = np.array([4, 4, 4, 4])
optimum_value = -10.1531958509790
var_type = np.array(['R'] * 4)
# -- end class
class shekel7:
"""
Shekel7 function of the Dixon-Szego test set.
"""
@classmethod
def evaluate(cls, x):
assert(len(x)==4)
value = -math.fsum([ 1.0 /
(math.fsum([math.fsum([ (x[i] - cls.a[i][j])**2
for i in range(4) ]),
cls.c[j]])) for j in range(7) ])
return(value)
a = [ [4.0, 1.0, 8.0, 6.0, 3.0, 2.0, 5.0],
[4.0, 1.0, 8.0, 6.0, 7.0, 9.0, 5.0],
[4.0, 1.0, 8.0, 6.0, 3.0, 2.0, 3.0],
[4.0, 1.0, 8.0, 6.0, 7.0, 9.0, 3.0] ]
c = [0.1, 0.2, 0.2, 0.4, 0.4, 0.6, 0.3]
dimension = 4
var_lower = np.array([0, 0, 0, 0])
var_upper = np.array([10, 10, 10, 10])
optimum_point = np.array([4, 4, 4, 4])
optimum_value = -10.4028188369303
var_type = np.array(['R'] * 4)
# -- end class
class shekel10:
"""
Shekel10 function of the Dixon-Szego test set.
"""
@classmethod
def evaluate(cls, x):
assert(len(x)==4)
value = -math.fsum([ 1.0 /
(math.fsum([math.fsum([ (x[i] - cls.a[i][j])**2
for i in range(4) ]),
cls.c[j]])) for j in range(10) ])
return(value)
a = [ [4.0, 1.0, 8.0, 6.0, 3.0, 2.0, 5.0, 8.0, 6.0, 7.0],
[4.0, 1.0, 8.0, 6.0, 7.0, 9.0, 5.0, 1.0, 2.0, 3.6],
[4.0, 1.0, 8.0, 6.0, 3.0, 2.0, 3.0, 8.0, 6.0, 7.0],
[4.0, 1.0, 8.0, 6.0, 7.0, 9.0, 3.0, 1.0, 2.0, 3.6] ]
c = [0.1, 0.2, 0.2, 0.4, 0.4, 0.6, 0.3, 0.7, 0.5, 0.5]
dimension = 4
var_lower = np.array([0, 0, 0, 0])
var_upper = np.array([10, 10, 10, 10])
optimum_point = np.array([4, 4, 4, 4])
optimum_value = -10.53628372621960
var_type = np.array(['R'] * 4)
# -- end class
class ex4_1_1:
"""
ex4_1_1 function of the GlobalLib test set.
"""
@classmethod
def evaluate(cls, x):
assert(len(x)==1)
value = (x[0]**6 - (52.0/25.0)*x[0]**5 + (39.0/80.0)*x[0]**4 +
(71.0/10.0)*x[0]**3 - (79.0/20.0)*x[0]**2 - x[0] +
1.0/10.0)
return(value)
dimension = 1
var_lower = np.array([-2])
var_upper = np.array([11])
optimum_point = np.array([-1.19131])
optimum_value = -7.487312360731
var_type = np.array(['R'])
# -- end class
class ex4_1_2:
"""
ex4_1_2 function of the GlobalLib test set.
"""
@classmethod
def evaluate(cls, x):
assert(len(x)==1)
a = [-500, 2.5, 1.666666666, 1.25, 1.0, 0.8333333, 0.714285714,
0.625, 0.555555555, 1.0, -43.6363636, 0.41666666, 0.384615384,
0.357142857, 0.3333333, 0.3125, 0.294117647, 0.277777777,
0.263157894, 0.25, 0.238095238, 0.227272727, 0.217391304,
0.208333333, 0.2, 0.192307692, 0.185185185, 0.178571428,
0.344827586, 0.6666666, -15.48387097, 0.15625, 0.1515151,
0.14705882, 0.14285712, 0.138888888, 0.135135135, 0.131578947,
0.128205128, 0.125, 0.121951219, 0.119047619, 0.116279069,
0.113636363, 0.1111111, 0.108695652, 0.106382978, 0.208333333,
0.408163265, 0.8]
value = math.fsum([a[i]*x[0]**(i+1) for i in range(50)])
return(value)
dimension = 1
var_lower = np.array([1])
var_upper = np.array([2])
optimum_point = np.array([1.09106])
optimum_value = -663.4993631230575
var_type = np.array(['R'] * 1)
# -- end class
class ex8_1_1:
"""
ex8_1_1 function of the GlobalLib test set.
"""
@classmethod
def evaluate(cls, x):
assert(len(x)==2)
value = np.cos(x[0])*np.sin(x[1]) - x[0]/(x[1]**2+1)
return(value)
dimension = 2
var_lower = np.array([-1, -1])
var_upper = np.array([2, 1])
optimum_point = np.array([2.0, 0.105783])
optimum_value = -2.0218067833
var_type = np.array(['R'] * 2)
# -- end class
class ex8_1_4:
"""
ex8_1_4 function of the GlobalLib test set.
"""
@classmethod
def evaluate(cls, x):
assert(len(x)==2)
value = 12*x[0]**2-6.3*x[0]**4+x[0]**6-6*x[0]*x[1]+6*x[1]**2
return(value)
dimension = 2
var_lower = np.array([-2, -5])
var_upper = np.array([4, 2])
optimum_point = np.array([0.0, 0.0])
optimum_value = 0.0
var_type = np.array(['R'] * 2)
# -- end class
class least:
"""
least function of the GlobalLib test set.
"""
@classmethod
def evaluate(cls, x):
assert(len(x)==3)
value = ((127 + (-x[1]*np.exp(-5*x[2])) - x[0])**2 +
(151 + (-x[1]*np.exp(-3*x[2])) - x[0])**2 +
(379 + (-x[1]*np.exp(-x[2])) - x[0])**2 +
(421 + (-x[1]*np.exp(5*x[2])) - x[0])**2 +
(460 + (-x[1]*np.exp(3*x[2])) - x[0])**2 +
(426 + (-x[1]*np.exp(x[2])) - x[0])**2)
return(value)
dimension = 3
var_lower = np.array([0, -200, -5])
var_upper = np.array([600, 200, 5] )
optimum_point = np.array([516.651174172, -149.351893696, -0.206642767973])
optimum_value = 14085.139848928
var_type = np.array(['R'] * 3)
# -- end class
class rbrock:
"""
rbrock function of the GlobalLib test set.
"""
@classmethod
def evaluate(cls, x):
assert(len(x)==2)
value = (100*(x[1] - x[0]**2)**2 + (1 - x[0])**2)
return(value)
dimension = 2
var_lower = np.array([-10, -10])
var_upper = np.array([5, 10])
optimum_point = np.array([1.0, 1.0])
optimum_value = 0.0
var_type = np.array(['R'] * 2)
# -- end class
class perm_6:
"""
perm function of dimension 6 from <NAME>.
http://www.mat.univie.ac.at/~neum/glopt/my_problems.html
We use parameters (6, 60) here.
"""
@classmethod
def evaluate(cls, x):
assert(len(x)==6)
beta = 60
value = math.fsum([ (math.fsum([((i + 1)**k + beta) *
((x[i]/(i+1))**k - 1)
for i in range(6)]))**2
for k in range(6) ]) + 1000
return(value)
dimension = 6
var_lower = np.array([-6 for i in range(6)])
var_upper = np.array([6 for i in range(6)])
optimum_point = np.array([(i+1) for i in range(6)])
optimum_value = 1000.0
var_type = np.array(['R'] * 6)
# -- end class
class perm0_8:
"""
perm0 function of dimension 8 from <NAME>.
http://www.mat.univie.ac.at/~neum/glopt/my_problems.html
We use parameters (8, 100) here.
"""
@classmethod
def evaluate(cls, x):
assert(len(x)==8)
beta = 100
value = math.fsum([ (math.fsum([(i + 1 + beta) *
(x[i]**k - (1/(i+1))**k)
for i in range(8)]))**2
for k in range(8) ]) + 1000
return(value)
dimension = 8
var_lower = np.array([-1 for i in range(8)])
var_upper = np.array([1 for i in range(8)])
optimum_point = np.array([1.0/(i+1) for i in range(8)])
optimum_value = 1000.0
var_type = np.array(['R'] * 8)
# -- end class
class schoen_6_1:
"""
schoen function of dimension 6 with 50 stationary points.
"""
@classmethod
def evaluate(cls, x):
assert(len(x)==6)
numerator = 0.0
denominator = 0.0
dist = np.sum((x - cls.z)**2, axis=1)
for i in range(50):
prod = 1.0
for j in range(50):
if (i != j):
prod *= dist[j]
numerator += cls.f[i]*prod
denominator += prod
value = numerator/denominator
return(value)
z = np.array(
[[0.298854, 0.181010, 0.984817, 0.125272, 0.548396, 0.894658],
[0.800371, 0.817380, 0.398577, 0.652349, 0.250843, 0.130235],
[0.268631, 0.929778, 0.640422, 0.462004, 0.492930, 0.434955],
[0.257863, 0.729198, 0.210810, 0.364378, 0.228216, 0.947432],
[0.767627, 0.592150, 0.103788, 0.696895, 0.472449, 0.244504],
[0.369630, 0.110889, 0.072344, 0.515753, 0.068087, 0.103057],
[0.425457, 0.807081, 0.491209, 0.449497, 0.065690, 0.592775],
[0.544229, 0.619841, 0.704609, 0.573098, 0.044844, 0.305800],
[0.164031, 0.722884, 0.670496, 0.517915, 0.176386, 0.921565],
[0.153788, 0.703577, 0.899129, 0.406134, 0.941356, 0.538215],
[0.984781, 0.510479, 0.573361, 0.884599, 0.399472, 0.712935],
[0.488416, 0.403997, 0.888823, 0.048434, 0.265197, 0.478025],
[0.047985, 0.280071, 0.709960, 0.278919, 0.035737, 0.037699],
[0.656172, 0.498412, 0.458622, 0.982970, 0.041234, 0.921127],
[0.590802, 0.359690, 0.396516, 0.338153, 0.320793, 0.847369],
[0.649160, 0.846974, 0.451818, 0.064864, 0.818545, 0.955844],
[0.583716, 0.669610, 0.463098, 0.492710, 0.989690, 0.002397],
[0.097300, 0.112389, 0.128759, 0.182995, 0.262808, 0.701887],
[0.487363, 0.892520, 0.269056, 0.116046, 0.905416, 0.808013],
[0.908316, 0.023997, 0.670399, 0.985859, 0.178548, 0.450410],
[0.230409, 0.381732, 0.613667, 0.697260, 0.016950, 0.736507],
[0.132544, 0.526349, 0.650042, 0.084086, 0.979257, 0.771499],
[0.872978, 0.008826, 0.587481, 0.624637, 0.623175, 0.939539],
[0.447828, 0.836386, 0.223285, 0.422756, 0.344488, 0.555953],
[0.546839, 0.153934, 0.953017, 0.640891, 0.666774, 0.647583],
[0.762237, 0.608920, 0.401447, 0.056202, 0.203535, 0.890609],
[0.655150, 0.444544, 0.495582, 0.247926, 0.155128, 0.188004],
[0.481813, 0.387178, 0.597276, 0.634671, 0.285404, 0.714793],
[0.976385, 0.018854, 0.262585, 0.640434, 0.086314, 0.669879],
[0.120164, 0.882300, 0.057626, 0.695111, 0.735135, 0.004711],
[0.414644, 0.715618, 0.642033, 0.770645, 0.407019, 0.502945],
[0.257475, 0.620029, 0.840603, 0.638546, 0.636521, 0.883558],
[0.788980, 0.374926, 0.448016, 0.081941, 0.225763, 0.944905],
[0.661591, 0.178832, 0.790349, 0.141653, 0.424235, 0.571960],
[0.546361, 0.624907, 0.190470, 0.412713, 0.124748, 0.662788],
[0.226384, 0.065829, 0.960836, 0.767766, 0.089695, 0.441792],
[0.303675, 0.370047, 0.973692, 0.830432, 0.424719, 0.173571],
[0.548375, 0.823234, 0.334253, 0.078398, 0.097269, 0.195120],
[0.646225, 0.100478, 0.723833, 0.891035, 0.386094, 0.360272],
[0.362757, 0.114700, 0.731020, 0.783785, 0.250399, 0.244399],
[0.904335, 0.869074, 0.479004, 0.525872, 0.359411, 0.338333],
[0.563175, 0.245903, 0.694417, 0.833524, 0.205055, 0.132535],
[0.401356, 0.920963, 0.401902, 0.120625, 0.765834, 0.381552],
[0.769562, 0.279591, 0.567598, 0.017192, 0.697366, 0.813451],
[0.738572, 0.984740, 0.007616, 0.005382, 0.592976, 0.771773],
[0.683721, 0.824097, 0.731623, 0.936945, 0.182420, 0.393537],
[0.375859, 0.541929, 0.974640, 0.377459, 0.754060, 0.019335],
[0.410275, 0.619158, 0.148428, 0.419225, 0.637412, 0.204038],
[0.552701, 0.472723, 0.491747, 0.017922, 0.198525, 0.074668],
[0.749510, 0.158720, 0.395476, 0.528285, 0.143614, 0.961610]])
f = np.array(
[-1000, -1000, -1000, 672.2, 861.4, 520.9, 121.0, 11.5, 48.2,
702.4, 536.2, 457.7, 801.3, 787.7, 768.6, 292.4, 960.0, 573.1,
303.7, 283.3, 474.1, 216.9, 462.2, 853.6, 677.1, 464.6, 830.6,
831.8, 109.6, 967.6, 122.9, 896.2, 490.2, 710.4, 81.1, 802.9,
999.8, 945.5, 672.3, 712.9, 235.8, 266.5, 772.4, 326.6, 585.5,
16.9, 135.9, 224.2, 382.1, 614.6])
dimension = 6
var_lower = np.array([0 for i in range(6)])
var_upper = np.array([1 for i in range(6)])
optimum_point = np.array([0.298854, 0.181010, 0.984817,
0.125272, 0.548396, 0.894658])
optimum_value = -1000
var_type = np.array(['R'] * 6)
# -- end class
class schoen_6_2:
"""
schoen function of dimension 6 with 50 stationary points.
"""
@classmethod
def evaluate(cls, x):
assert(len(x)==6)
numerator = 0.0
denominator = 0.0
dist = np.sum((x - cls.z)**2, axis=1)
for i in range(50):
prod = 1.0
for j in range(50):
if (i != j):
prod *= dist[j]
numerator += cls.f[i]*prod
denominator += prod
value = numerator/denominator
return(value)
z = np.array(
[[0.669711, 0.815540, 0.646120, 0.377447, 0.111538, 0.040529],
[0.000632, 0.706804, 0.857031, 0.473778, 0.993569, 0.616184],
[0.625617, 0.880221, 0.534547, 0.760235, 0.276998, 0.735438],
[0.774577, 0.922914, 0.947791, 0.315328, 0.414841, 0.785803],
[0.079768, 0.131498, 0.225123, 0.464621, 0.638041, 0.992795],
[0.471038, 0.244503, 0.565776, 0.898397, 0.604639, 0.306230],
[0.642233, 0.482219, 0.034943, 0.934805, 0.972714, 0.153664],
[0.550151, 0.310507, 0.042126, 0.230722, 0.444375, 0.117355],
[0.789984, 0.488482, 0.065237, 0.842940, 0.793454, 0.799489],
[0.850183, 0.754551, 0.516033, 0.166362, 0.201966, 0.044234],
[0.000601, 0.896758, 0.304433, 0.149125, 0.178398, 0.871836],
[0.056787, 0.932745, 0.218009, 0.778061, 0.131847, 0.356237],
[0.210266, 0.221479, 0.014831, 0.200901, 0.656693, 0.891819],
[0.528515, 0.178025, 0.188138, 0.411485, 0.217833, 0.907579],
[0.195801, 0.663099, 0.477312, 0.395250, 0.655791, 0.820570],
[0.933208, 0.789323, 0.350520, 0.855434, 0.491082, 0.874993],
[0.251047, 0.543513, 0.529644, 0.218495, 0.351637, 0.608904],
[0.963286, 0.793004, 0.650148, 0.881362, 0.904832, 0.005397],
[0.431744, 0.438965, 0.044544, 0.834968, 0.330614, 0.451282],
[0.234845, 0.328576, 0.388284, 0.339183, 0.206086, 0.600034],
[0.512783, 0.961787, 0.959109, 0.632098, 0.910614, 0.912025],
[0.454168, 0.743189, 0.834284, 0.955817, 0.072172, 0.523068],
[0.696968, 0.720236, 0.341060, 0.054580, 0.045599, 0.549192],
[0.272955, 0.318845, 0.700767, 0.426325, 0.895755, 0.843128],
[0.992189, 0.332899, 0.272784, 0.019284, 0.073711, 0.434800],
[0.154276, 0.639611, 0.924641, 0.587242, 0.358453, 0.548022],
[0.021506, 0.450392, 0.515150, 0.032232, 0.650223, 0.849384],
[0.316499, 0.513234, 0.958219, 0.843587, 0.125408, 0.836643],
[0.538587, 0.261750, 0.732136, 0.030271, 0.893345, 0.270532],
[0.987469, 0.708780, 0.446487, 0.968784, 0.734448, 0.788229],
[0.353358, 0.135036, 0.249018, 0.565029, 0.740519, 0.250807],
[0.810372, 0.656510, 0.472093, 0.225741, 0.420513, 0.202519],
[0.848128, 0.551586, 0.513140, 0.956164, 0.483389, 0.404478],
[0.292239, 0.297077, 0.934202, 0.468329, 0.872274, 0.992632],
[0.828869, 0.534749, 0.716451, 0.405855, 0.164485, 0.531068],
[0.130616, 0.757677, 0.284500, 0.438300, 0.957643, 0.725899],
[0.503542, 0.640368, 0.381914, 0.847206, 0.134660, 0.762294],
[0.653851, 0.646544, 0.436036, 0.944225, 0.310369, 0.392362],
[0.539397, 0.027168, 0.697972, 0.209293, 0.992890, 0.008113],
[0.902045, 0.171034, 0.194924, 0.620057, 0.002203, 0.557433],
[0.802612, 0.085835, 0.380626, 0.492568, 0.238166, 0.961837],
[0.466993, 0.647847, 0.113397, 0.015357, 0.928904, 0.166425],
[0.892021, 0.869756, 0.681364, 0.129555, 0.394682, 0.745036],
[0.060675, 0.869904, 0.757236, 0.220765, 0.615988, 0.754288],
[0.031815, 0.340961, 0.455958, 0.529616, 0.840036, 0.365200],
[0.834595, 0.603639, 0.745330, 0.085080, 0.184636, 0.238718],
[0.575681, 0.250761, 0.874497, 0.870401, 0.854591, 0.968971],
[0.359629, 0.724830, 0.455053, 0.120311, 0.258563, 0.932004],
[0.209891, 0.990298, 0.767661, 0.284193, 0.375076, 0.154363],
[0.410402, 0.437385, 0.639614, 0.946647, 0.579466, 0.524775]])
f = np.array(
[-1000, -1000, -1000, 109.6, 132.4, 558.2, 158.0, 6.2, 205.4,
593.9, 2.4, 399.8, 395.9, 212.6, 976.1, 104.4, 552.1, 436.3,
837.1, 283.7, 779.7, 392.1, 85.8, 885.1, 401.5, 367.5, 694.4,
691.6, 933.1, 590.7, 246.2, 370.0, 54.3, 719.4, 95.2, 276.0,
829.1, 613.6, 242.8, 424.6, 320.6, 666.1, 479.2, 420.0, 956.6,
241.0, 21.1, 169.8, 178.1, 394.4])
dimension = 6
var_lower = np.array([0 for i in range(6)])
var_upper = np.array([1 for i in range(6)])
optimum_point = np.array([0.669711, 0.815540, 0.646120,
0.377447, 0.111538, 0.040529])
optimum_value = -1000
var_type = np.array(['R'] * 6)
# -- end class
class schoen_10_1:
"""
schoen function of dimension 10 with 50 stationary points.
"""
@classmethod
def evaluate(cls, x):
assert(len(x)==10)
numerator = 0.0
denominator = 0.0
dist = np.sum((x - cls.z)**2, axis=1)
for i in range(50):
prod = 1.0
for j in range(50):
if (i != j):
prod *= dist[j]
numerator += cls.f[i]*prod
denominator += prod
value = numerator/denominator
return(value)
z = np.array(
[[0.914871, 0.765230, 0.139426, 0.617466, 0.823635,
0.794003, 0.801171, 0.568811, 0.279434, 0.540422],
[0.976983, 0.593277, 0.701115, 0.585262, 0.669106,
0.272906, 0.177127, 0.143389, 0.561181, 0.018744],
[0.385208, 0.984106, 0.390066, 0.905970, 0.169600,
0.191291, 0.564157, 0.689910, 0.857031, 0.715390],
[0.975998, 0.536904, 0.819333, 0.801793, 0.564454,
0.336124, 0.654190, 0.044197, 0.717416, 0.465807],
[0.750519, 0.415284, 0.258927, 0.736115, 0.597744,
0.763716, 0.747691, 0.969633, 0.188117, 0.964954],
[0.412888, 0.671756, 0.380214, 0.558595, 0.768370,
0.998320, 0.212183, 0.606757, 0.531315, 0.303569],
[0.196682, 0.139879, 0.108608, 0.736975, 0.755971,
0.021390, 0.852398, 0.188596, 0.920133, 0.045012],
[0.956270, 0.729258, 0.397664, 0.013146, 0.519861,
0.300011, 0.008396, 0.820346, 0.176841, 0.402298],
[0.126432, 0.872346, 0.923581, 0.297492, 0.992744,
0.486525, 0.915493, 0.589980, 0.498242, 0.989945],
[0.697409, 0.026641, 0.875467, 0.503039, 0.563285,
0.096769, 0.933643, 0.884419, 0.585825, 0.395465],
[0.494783, 0.824300, 0.153326, 0.202651, 0.579815,
0.416954, 0.707624, 0.497959, 0.568876, 0.812841],
[0.126963, 0.757337, 0.648583, 0.787445, 0.822586,
0.401155, 0.301350, 0.562707, 0.744074, 0.088372],
[0.293611, 0.835864, 0.925111, 0.760322, 0.729456,
0.096840, 0.651466, 0.975836, 0.691353, 0.038384],
[0.999250, 0.916829, 0.205699, 0.027241, 0.156956,
0.206598, 0.175242, 0.811219, 0.660192, 0.119865],
[0.387978, 0.665180, 0.774376, 0.135223, 0.766238,
0.380668, 0.058279, 0.727506, 0.991527, 0.345759],
[0.299341, 0.066231, 0.680305, 0.392230, 0.319985,
0.698292, 0.100236, 0.394973, 0.096232, 0.362943],
[0.281548, 0.860858, 0.647870, 0.981650, 0.110777,
0.836484, 0.697387, 0.659942, 0.694425, 0.434991],
[0.606706, 0.052287, 0.858208, 0.738885, 0.158495,
0.002367, 0.933796, 0.112986, 0.647308, 0.421573],
[0.776505, 0.101364, 0.610406, 0.275033, 0.548409,
0.998967, 0.536743, 0.943903, 0.960993, 0.251672],
[0.371347, 0.491122, 0.772374, 0.860206, 0.752131,
0.338591, 0.826739, 0.312111, 0.768881, 0.862719],
[0.866886, 0.358220, 0.131205, 0.276334, 0.334111,
0.429525, 0.752197, 0.167524, 0.437764, 0.162916],
[0.584246, 0.511215, 0.659647, 0.349220, 0.954428,
0.477982, 0.386041, 0.813944, 0.753530, 0.983276],
[0.697327, 0.499835, 0.530487, 0.599958, 0.497257,
0.998852, 0.106262, 0.186978, 0.887481, 0.749174],
[0.041611, 0.278918, 0.999095, 0.825221, 0.218320,
0.383711, 0.077041, 0.642061, 0.668906, 0.758298],
[0.072437, 0.592862, 0.040655, 0.446330, 0.651659,
0.055738, 0.631924, 0.890039, 0.192989, 0.741054],
[0.533886, 0.135079, 0.787647, 0.593408, 0.749228,
0.749045, 0.190386, 0.755508, 0.465321, 0.465156],
[0.748843, 0.696419, 0.882124, 0.843895, 0.858057,
0.220107, 0.350310, 0.102947, 0.453576, 0.875940],
[0.560231, 0.580247, 0.381834, 0.807535, 0.184636,
0.615702, 0.628408, 0.081783, 0.793384, 0.233639],
[0.384827, 0.589138, 0.630013, 0.634506, 0.630712,
0.521293, 0.494486, 0.681700, 0.288512, 0.319808],
[0.721978, 0.452289, 0.426726, 0.323106, 0.781584,
0.999325, 0.043670, 0.884560, 0.520936, 0.430684],
[0.810388, 0.624041, 0.811624, 0.105973, 0.199807,
0.440644, 0.864152, 0.282280, 0.397116, 0.499932],
[0.973889, 0.677797, 0.080137, 0.549098, 0.625445,
0.577342, 0.538642, 0.388039, 0.552273, 0.793807],
[0.365176, 0.228017, 0.623500, 0.084450, 0.177343,
0.910108, 0.632719, 0.521458, 0.894843, 0.707893],
[0.502069, 0.622312, 0.958019, 0.744999, 0.515695,
0.407885, 0.590739, 0.736542, 0.297555, 0.237955],
[0.313835, 0.090014, 0.336274, 0.433171, 0.330864,
0.105751, 0.160367, 0.651934, 0.207260, 0.293577],
[0.886072, 0.592935, 0.498116, 0.321835, 0.011216,
0.543911, 0.506579, 0.216779, 0.406812, 0.261349],
[0.789947, 0.881332, 0.696597, 0.742955, 0.252224,
0.718157, 0.188217, 0.371208, 0.178640, 0.347720],
[0.482759, 0.663618, 0.622706, 0.036170, 0.278854,
0.088147, 0.482808, 0.134824, 0.028828, 0.944537],
[0.184705, 0.662346, 0.917194, 0.186490, 0.918392,
0.955111, 0.636015, 0.447595, 0.813716, 0.372839],
[0.231741, 0.637199, 0.745257, 0.201568, 0.697485,
0.897022, 0.239791, 0.495219, 0.153831, 0.387172],
[0.198061, 0.194102, 0.550259, 0.751804, 0.503973,
0.034252, 0.788267, 0.731760, 0.118338, 0.057247],
[0.068470, 0.545180, 0.668845, 0.714932, 0.688014,
0.203845, 0.146138, 0.109039, 0.470214, 0.441797],
[0.085180, 0.142394, 0.938665, 0.071422, 0.946796,
0.697832, 0.472400, 0.161384, 0.325715, 0.122550],
[0.637672, 0.986961, 0.969438, 0.989508, 0.381318,
0.800871, 0.012035, 0.326007, 0.459124, 0.645374],
[0.147210, 0.954608, 0.361146, 0.094699, 0.092327,
0.301664, 0.478447, 0.008274, 0.680576, 0.004184],
[0.768792, 0.812618, 0.915766, 0.029070, 0.506944,
0.457816, 0.839167, 0.024706, 0.990756, 0.088779],
[0.872678, 0.601536, 0.948347, 0.621023, 0.415621,
0.289340, 0.291338, 0.190461, 0.664007, 0.583513],
[0.641216, 0.700152, 0.080576, 0.355500, 0.294700,
0.338614, 0.563964, 0.528079, 0.759223, 0.508432],
[0.738489, 0.077376, 0.429485, 0.300586, 0.576927,
0.185931, 0.231659, 0.954833, 0.614178, 0.092903],
[0.729321, 0.318607, 0.768657, 0.899419, 0.749499,
0.623403, 0.671793, 0.052835, 0.973726, 0.168336]])
f = np.array(
[-1000, -1000, -1000, 799.1, 396.8, 370.3, 400.2, 239.7,
678.8, 868.9, 564.4, 681.6, 153.0, 760.7, 562.9, 434.9,
579.2, 260.6, 88.5, 601.3, 754.8, 894.8, 672.8, 633.7, 921.8,
43.2, 286.2, 945.5, 716.0, 72.7, 631.2, 640.3, 425.1, 825.8,
555.8, 136.9, 805.7, 786.5, 400.0, 856.4, 548.0, 510.8, 52.3,
111.6, 686.6, 888.2, 315.4, 333.9, 61.5, 755.2])
dimension = 10
var_lower = np.array([0 for i in range(10)])
var_upper = np.array([1 for i in range(10)])
optimum_point = np.array([0.914871, 0.765230, 0.139426, 0.617466,
0.823635, 0.794003, 0.801171, 0.568811,
0.279434, 0.540422])
optimum_value = -1000
var_type = np.array(['R'] * 10)
# -- end class
class schoen_10_2:
"""
schoen function of dimension 10 with 50 stationary points.
"""
@classmethod
def evaluate(cls, x):
assert(len(x)==10)
numerator = 0.0
denominator = 0.0
dist = np.sum((x - cls.z)**2, axis=1)
for i in range(50):
prod = 1.0
for j in range(50):
if (i != j):
prod *= dist[j]
numerator += cls.f[i]*prod
denominator += prod
value = numerator/denominator
return(value)
z = np.array(
[[0.131461, 0.965235, 0.046134, 0.983011, 0.719813,
0.827542, 0.662422, 0.570546, 0.578707, 0.013264],
[0.068454, 0.682785, 0.582736, 0.434517, 0.310613,
0.869876, 0.993949, 0.629156, 0.590599, 0.356378],
[0.632837, 0.961665, 0.015079, 0.378878, 0.805608,
0.685239, 0.528658, 0.752934, 0.717790, 0.374865],
[0.286191, 0.912944, 0.400358, 0.902532, 0.324887,
0.850063, 0.483503, 0.764147, 0.147726, 0.159851],
[0.303483, 0.754790, 0.090527, 0.653764, 0.164323,
0.402931, 0.593477, 0.448444, 0.711483, 0.113869],
[0.057398, 0.302029, 0.596351, 0.565466, 0.694204,
0.974864, 0.323989, 0.298493, 0.859391, 0.238714],
[0.139267, 0.214902, 0.608462, 0.297987, 0.499810,
0.578553, 0.548077, 0.208442, 0.046162, 0.246848],
[0.680420, 0.783181, 0.828103, 0.475810, 0.680401,
0.188455, 0.015200, 0.650103, 0.762389, 0.063985],
[0.409243, 0.600740, 0.302354, 0.588411, 0.436291,
0.294790, 0.701477, 0.994162, 0.433749, 0.535320],
[0.077949, 0.530126, 0.869737, 0.387811, 0.705317,
0.632911, 0.442087, 0.082918, 0.441383, 0.591975],
[0.622628, 0.054964, 0.020475, 0.145616, 0.163873,
0.321546, 0.282867, 0.743494, 0.750568, 0.732386],
[0.538574, 0.066932, 0.225204, 0.290045, 0.613242,
0.529365, 0.384018, 0.946557, 0.974384, 0.425297],
[0.108817, 0.850094, 0.886417, 0.161581, 0.082973,
0.506354, 0.589650, 0.638991, 0.045151, 0.688464],
[0.917742, 0.365119, 0.484176, 0.173231, 0.210253,
0.303688, 0.992141, 0.023109, 0.977178, 0.535146],
[0.183469, 0.198085, 0.511596, 0.275610, 0.753700,
0.437328, 0.986237, 0.028654, 0.767921, 0.997910],
[0.484908, 0.759122, 0.577318, 0.359934, 0.935730,
0.617833, 0.770173, 0.311175, 0.004831, 0.157457],
[0.634077, 0.236972, 0.016427, 0.261753, 0.349712,
0.245870, 0.412238, 0.523557, 0.985327, 0.094060],
[0.477875, 0.803438, 0.496728, 0.848920, 0.497386,
0.938203, 0.279797, 0.287076, 0.395184, 0.980546],
[0.450215, 0.193712, 0.975838, 0.103925, 0.077410,
0.709573, 0.253072, 0.311723, 0.885664, 0.204528],
[0.557312, 0.815198, 0.097914, 0.539142, 0.826048,
0.130070, 0.049858, 0.223634, 0.076387, 0.831224],
[0.927559, 0.324916, 0.563393, 0.209281, 0.344394,
0.953384, 0.298679, 0.890637, 0.966615, 0.380006],
[0.026403, 0.997573, 0.479163, 0.379686, 0.687928,
0.832002, 0.214326, 0.348248, 0.073151, 0.062646],
[0.726869, 0.911171, 0.961920, 0.874884, 0.216867,
0.076966, 0.776240, 0.495777, 0.963492, 0.425246],
[0.357483, 0.486330, 0.759177, 0.748362, 0.889904,
0.350438, 0.232983, 0.823613, 0.792656, 0.441264],
[0.875826, 0.359459, 0.214808, 0.425850, 0.493328,
0.456048, 0.523145, 0.504154, 0.090128, 0.472437],
[0.813400, 0.808407, 0.427211, 0.902524, 0.210376,
0.490662, 0.915939, 0.169439, 0.078865, 0.485371],
[0.877334, 0.982207, 0.679085, 0.486335, 0.940715,
0.585964, 0.289279, 0.694886, 0.172625, 0.201457],
[0.141599, 0.476124, 0.762246, 0.067045, 0.411332,
0.813196, 0.134138, 0.302390, 0.856145, 0.349243],
[0.346912, 0.082142, 0.787442, 0.857465, 0.371129,
0.448550, 0.967943, 0.775340, 0.943681, 0.656127],
[0.619267, 0.547196, 0.470422, 0.141566, 0.584198,
0.952226, 0.196462, 0.629549, 0.685469, 0.824365],
[0.014209, 0.789812, 0.836373, 0.186139, 0.493840,
0.710697, 0.910033, 0.368287, 0.865953, 0.140892],
[0.482763, 0.072574, 0.026730, 0.143687, 0.739505,
0.419649, 0.013683, 0.662644, 0.785254, 0.234561],
[0.821421, 0.844100, 0.153937, 0.671762, 0.290469,
0.631347, 0.591435, 0.498966, 0.043395, 0.176771],
[0.404994, 0.496656, 0.951774, 0.497357, 0.715401,
0.023378, 0.493045, 0.342766, 0.117055, 0.698590],
[0.985857, 0.831692, 0.423498, 0.215757, 0.341260,
0.790760, 0.941186, 0.716883, 0.062641, 0.582012],
[0.676905, 0.280897, 0.800638, 0.898913, 0.735995,
0.592412, 0.433021, 0.432772, 0.874477, 0.112375],
[0.377382, 0.118941, 0.529204, 0.419434, 0.673891,
0.074904, 0.129868, 0.819585, 0.220536, 0.353223],
[0.233415, 0.136703, 0.487256, 0.777498, 0.901915,
0.612402, 0.778635, 0.436718, 0.484520, 0.641969],
[0.273297, 0.670196, 0.344525, 0.669751, 0.180230,
0.530085, 0.393284, 0.326043, 0.260840, 0.364690],
[0.931213, 0.676123, 0.912481, 0.898258, 0.001887,
0.408306, 0.917215, 0.496959, 0.287951, 0.562511],
[0.047196, 0.780338, 0.895994, 0.088169, 0.552425,
0.130790, 0.308504, 0.232476, 0.187952, 0.105936],
[0.343517, 0.356222, 0.416018, 0.450278, 0.487765,
0.040510, 0.592363, 0.771635, 0.577849, 0.315843],
[0.527759, 0.529503, 0.210423, 0.756794, 0.892670,
0.339374, 0.445837, 0.363265, 0.432114, 0.942045],
[0.560107, 0.110906, 0.115725, 0.761393, 0.969105,
0.921166, 0.455014, 0.593512, 0.111887, 0.217300],
[0.463382, 0.635591, 0.329484, 0.573602, 0.492558,
0.474174, 0.371906, 0.850465, 0.467637, 0.261373],
[0.033051, 0.422543, 0.294155, 0.699026, 0.846231,
0.047967, 0.686826, 0.480273, 0.463181, 0.345601],
[0.285473, 0.723925, 0.202386, 0.671909, 0.685277,
0.993969, 0.415329, 0.155218, 0.233826, 0.088752],
[0.029705, 0.651519, 0.813239, 0.677718, 0.961189,
0.285385, 0.824635, 0.837670, 0.524970, 0.815489],
[0.519627, 0.508274, 0.141067, 0.156163, 0.274566,
0.536322, 0.834749, 0.852042, 0.656166, 0.964211],
[0.119675, 0.971352, 0.052983, 0.178217, 0.408438,
0.215091, 0.102098, 0.256312, 0.051758, 0.906712]])
f = np.array(
[-1000, -1000, -1000, 90.4, 830.9, 52.7, 375.2, 289.7, 244.1,
470.2, 111.7, 968.9, 903.4, 918.5, 820.3, 441.2, 687.5, 836.9,
11.0, 454.5, 929.3, 952.6, 937.2, 870.5, 211.7, 378.4, 320.3,
729.6, 420.8, 213.8, 717.7, 285.4, 522.8, 748.3, 371.0, 501.2,
568.6, 111.9, 645.2, 486.2, 157.0, 968.5, 137.6, 127.2, 943.4,
437.2, 199.7, 415.4, 966.0, 362.3])
dimension = 10
var_lower = np.array([0 for i in range(10)])
var_upper = np.array([1 for i in range(10)])
optimum_point = np.array([0.131461, 0.965235, 0.046134, 0.983011,
0.719813, 0.827542, 0.662422, 0.570546,
0.578707, 0.013264])
optimum_value = -1000
var_type = np.array(['R'] * 10)
# -- end class
class schaeffer_f7_12_1:
"""
Schaeffer F7 function.
"""
@classmethod
def evaluate(cls, x):
assert(len(x)==12)
value = 0
normalizer = 1.0/float(len(x)-1)
for i in range(len(x)-1):
si = 2**i*np.sqrt((x[i]-cls.optimum_point[i])**2 +
(x[i+1]-cls.optimum_point[i+1])**2)
value += (normalizer * np.sqrt(si) *
(np.sin(50*si**0.20) + 1))**2
return value - 10
dimension = 12
var_lower = np.array([-50 for i in range(12)])
var_upper = np.array([50 for i in range(12)])
optimum_point = np.array([-34.32567, -34.98896, 07.69262, 30.3388,
-48.24371, 23.18355, 24.93374, 32.07436,
46.86153, 04.64872, 25.64591, -16.69128])
optimum_value = -10
var_type = np.array(['R'] * 12)
# -- end class
class schaeffer_f7_12_2:
"""
Schaeffer F7 function.
"""
@classmethod
def evaluate(cls, x):
assert(len(x)==12)
value = 0
normalizer = 1.0/float(len(x)-1)
for i in range(len(x)-1):
si = 3**i*np.sqrt((x[i]-cls.optimum_point[i])**2 +
(x[i+1]-cls.optimum_point[i+1])**2)
value += (normalizer * np.sqrt(si) *
(np.sin(50*si**0.20) + 1))**2
return value + 10
dimension = 12
var_lower = np.array([-50 for i in range(12)])
var_upper = np.array([50 for i in range(12)])
optimum_point = np.array([-08.214, 30.69133, 48.26095, -04.94219,
15.15357, 00.4841, -13.54025, -40.78766,
-16.02916, 16.42138, 39.30248, -49.56986])
optimum_value = 10
var_type = np.array(['R'] * 12)
# -- end class
# After this point, all functions are MINLP
class gear:
"""
gear function of the MINLPLib test set.
"""
@classmethod
def evaluate(cls, x):
assert(len(x)==4)
value = ((0.14427932477276 - x[0]*x[1]/(x[2]*x[3]))**2)
return(value)
dimension = 4
var_lower = np.array([12, 12, 12, 12])
var_upper = np.array([60, 60, 60, 60])
optimum_point = np.array([12.0, 23.0, 58.0, 33.0])
optimum_value = 0.0
var_type = np.array(['I'] * 4)
# -- end class
class gear4:
"""
gear4 function of the MINLPLib test set.
"""
@classmethod
def evaluate(cls, x):
assert(len(x)==5)
value = -1000000*x[0]*x[1]/(x[2]*x[3]) + 2*x[4] + 144279.32477276
# There is a constraint:
# -1000000*x[0]*x[1]/(x[2]*x[3]) + x[4] + 144279.32477276 >= 0
penalty = 10*max(0,-(-1000000*x[0]*x[1]/(x[2]*x[3]) + x[4] +
144279.32477276))
return(value + penalty)
dimension = 5
var_lower = np.array([12, 12, 12, 12, 0])
var_upper = np.array([60, 60, 60, 60, 100])
optimum_point = np.array([19.0, 16.0, 43.0, 49.0, 1.64342847396619])
optimum_value = 1.6434284739
var_type = np.array(['I'] * 4 + ['R'])
# -- end class
class nvs02:
"""
nvs02 function of the MINLPLib test set.
"""
@classmethod
def evaluate(cls, x):
assert(len(x)==5)
value = (0.0001*(5.3578547*np.sqrt(x[2]) + 0.8356891*x[0]*x[4] +
37.293239*x[0]) + 5.9207859)
# There are three constraints:
# 0 <= (0.0056858*x[1]*x[4] + 0.0006262*x[0]*x[3] -
# 0.0022053*x[2]*x[4] + 85.334407) <= 92
# 90 <= (0.0071317*x[1]*x[4] + 0.0029955*x[0]*x[1] +
# 0.0021813*math.sqrt(x[2]) + 80.51249) <= 110
# 20 <= (0.0047026*x[2]*x[4] + 0.0012547*x[0]*x[2] +
# 0.0019085*x[2]*x[3] + 9.300961) <= 25
penalty = 0.0
penalty += 10*max(0, -(0.0056858*x[1]*x[4] + 0.0006262*x[0]*x[3] -
0.0022053*x[2]*x[4] + 85.334407))
penalty += 10*max(0, (0.0056858*x[1]*x[4] + 0.0006262*x[0]*x[3] -
0.0022053*x[2]*x[4] + 85.334407) - 92)
penalty += 10*max(0, -(0.0071317*x[1]*x[4] + 0.0029955*x[0]*x[1] +
0.0021813*np.sqrt(x[2]) + 80.51249) + 90)
penalty += 10*max(0, (0.0071317*x[1]*x[4] + 0.0029955*x[0]*x[1] +
0.0021813*np.sqrt(x[2]) + 80.51249) - 110)
penalty += 10*max(0, -(0.0047026*x[2]*x[4] + 0.0012547*x[0]*x[2] +
0.0019085*x[2]*x[3] + 9.300961) + 20)
penalty += 10*max(0, (0.0047026*x[2]*x[4] + 0.0012547*x[0]*x[2] +
0.0019085*x[2]*x[3] + 9.300961) - 25)
return(value + penalty)
dimension = 5
var_lower = np.array([0, 0, 0, 0, 0])
var_upper = np.array([200, 200, 200, 200, 200])
optimum_point = np.array([0.0, 9.0, 9.0, 200.0, 197.0])
optimum_value = 5.9223932564100004
var_type = np.array(['I'] * 5)
# -- end class
class nvs03:
"""
nvs03 function of the MINLPLib test set.
"""
@classmethod
def evaluate(cls, x):
assert(len(x)==2)
value = (-8 + x[0])**2 + (-2 + x[1])**2
# There are two constraints:
# -0.1*x[0]**2 + x[1] >= 0
# -0.333333333333333*x[0] - x[1] + 4.5 >= 0.0
penalty = 0.0
penalty += 100*max(0, -(-0.1*x[0]**2 + x[1]))
penalty += 100*max(0, -(-0.333333333333333*x[0] - x[1] + 4.5))
return(value + penalty)
dimension = 2
var_lower = np.array([0, 0])
var_upper = np.array([200, 200])
optimum_point = np.array([4.0, 2.0])
optimum_value = 16.0
var_type = np.array(['I'] * 2)
# -- end class
class nvs04:
"""
nvs04 function of the MINLPLib test set.
"""
@classmethod
def evaluate(cls, x):
assert(len(x)==2)
value = 100*(0.5 + x[1] - (0.6 + x[0])**2)**2 + (0.4 - x[0])**2
return(value)
dimension = 2
var_lower = np.array([0, 0])
var_upper = np.array([200, 200])
optimum_point = np.array([1.0, 2.0])
optimum_value = 0.72
var_type = np.array(['I'] * 2)
# -- end class
class nvs06:
"""
nvs06 function of the MINLPLib test set.
"""
@classmethod
def evaluate(cls, x):
assert(len(x)==2)
value = (0.1*((x[0])**2 + (1 + (x[1])**2)/(x[0])**2 +
(100 + ((x[0])**2)*(x[1])**2)/(x[0]*x[1])**4) + 1.2)
return(value)
dimension = 2
var_lower = np.array([1, 1])
var_upper = np.array([200, 200])
optimum_point = np.array([2.0, 2.0])
optimum_value = 1.7703125
var_type = np.array(['I'] * 2)
# -- end class
class nvs07:
"""
nvs07 function of the MINLPLib test set.
"""
@classmethod
def evaluate(cls, x):
assert(len(x)==3)
value = 2*x[1]**2 + x[0] + 5*x[2]
# There are two constraints:
# x[2]**2 * x[1] + 5*x[2] + 3*x[0] - 10 >= 0
# x[0] - x[2] - 2.66 >= 0
penalty = 0.0
penalty += 10*max(0, -(x[2]**2 * x[1] + 5*x[2] + 3*x[0] - 10))
penalty += 10*max(0, -(x[0] - x[2] - 2.66))
return(value + penalty)
dimension = 3
var_lower = np.array([0, 0, 0])
var_upper = np.array([200, 200, 200])
optimum_point = np.array([4.0, 0.0, 0.0])
optimum_value = 4.0
var_type = np.array(['I'] * 3)
# -- end class
class nvs09:
"""
nvs09 function of the MINLPLib test set.
"""
@classmethod
def evaluate(cls, x):
assert(len(x)==10)
value = ((np.log(x[0] - 2))**2 + (np.log(10 - x[0]))**2 +
(np.log(x[1] - 2))**2 + (np.log(10 - x[1]))**2 +
(np.log(x[2] - 2))**2 + (np.log(10 - x[2]))**2 +
(np.log(x[3] - 2))**2 + (np.log(10 - x[3]))**2 +
(np.log(x[4] - 2))**2 + (np.log(10 - x[4]))**2 +
(np.log(x[5] - 2))**2 + (np.log(10 - x[5]))**2 +
(np.log(x[6] - 2))**2 + (np.log(10 - x[6]))**2 +
(np.log(x[7] - 2))**2 + (np.log(10 - x[7]))**2 +
(np.log(x[8] - 2))**2 + (np.log(10 - x[8]))**2 +
(np.log(x[9] - 2))**2 + (np.log(10 - x[9]))**2 -
(x[0]*x[1]*x[2]*x[3]*x[4]*x[5]*x[6]*x[7]*x[8]*x[9])**0.2)
return(value)
dimension = 10
var_lower = np.array([3 for i in range(10)])
var_upper = np.array([9 for i in range(10)])
optimum_point = np.array([9, 9, 9, 9, 9, 9, 9, 9, 9, 9])
optimum_value = -43.134336918035
var_type = np.array(['I'] * 10)
# -- end class
class nvs14:
"""
nvs14 function of the MINLPLib test set.
"""
@classmethod
def evaluate(cls, x):
assert(len(x)==5)
value = (5.3578547*x[2]**2 + 0.8356891*x[0]*x[4] + 37.293239*x[0] -
40792.141)
# There are three constraints:
# 0 <= (0.0056858*x[1]*x[4] + 0.0006262*x[0]*x[3] -
# 0.0022053*x[2]*x[4] + 85.334407) <= 92
# 90 <= (0.0071317*x[1]*x[4] + 0.0029955*x[0]*x[1] +
# 0.0021813*x[2]**2 + 80.51249) <= 110
# 20 <= (0.0047026*x[2]*x[4] + 0.0012547*x[0]*x[2] +
# 0.0019085*x[2]*x[3] + 9.300961) <= 25
penalty = 0.0
penalty += 1000*max(0, -(0.0056858*x[1]*x[4] + 0.0006262*x[0]*x[3] -
0.0022053*x[2]*x[4] + 85.334407))
penalty += 1000*max(0, (0.0056858*x[1]*x[4] + 0.0006262*x[0]*x[3] -
0.0022053*x[2]*x[4] + 85.334407) - 92)
penalty += 1000*max(0, -(0.0071317*x[1]*x[4] + 0.0029955*x[0]*x[1] +
0.0021813*x[2]**2 + 80.51249) + 90)
penalty += 1000*max(0, (0.0071317*x[1]*x[4] + 0.0029955*x[0]*x[1] +
0.0021813*x[2]**2 + 80.51249) - 110)
penalty += 1000*max(0, -(0.0047026*x[2]*x[4] + 0.0012547*x[0]*x[2] +
0.0019085*x[2]*x[3] + 9.300961) + 20)
penalty += 1000*max(0, (0.0047026*x[2]*x[4] + 0.0012547*x[0]*x[2] +
0.0019085*x[2]*x[3] + 9.300961) - 25)
return(value + penalty)
dimension = 5
var_lower = np.array([0, 0, 0, 0, 0])
var_upper = np.array([200, 200, 200, 200, 200])
optimum_point = np.array([0.0, 7.0, 9.0, 175.0, 200.0])
optimum_value = -40358.1547693
var_type = np.array(['I'] * 5)
# -- end class
class nvs15:
"""
nvs15 function of the MINLPLib test set.
"""
@classmethod
def evaluate(cls, x):
assert(len(x)==3)
value = (2*x[0]**2 - 8*x[0] + 2*x[1]**2 - 6*x[1] + x[2]**2 - 4*x[2] +
2*x[0]*x[1] + 2*x[0]*x[2] + 9)
# There is one constraint:
# - x[0] - x[1] - 2*x[2] + 3 >= 0
penalty = 0.0
penalty += 10*max(0, -(-x[0] - x[1] - 2*x[2] + 3))
return(value + penalty)
dimension = 3
var_lower = np.array([0, 0, 0])
var_upper = np.array([200, 200, 200])
optimum_point = np.array([2.0, 0.0, 0.0])
optimum_value = 1.0
var_type = np.array(['I'] * 3)
# -- end class
class nvs16:
"""
nvs16 function of the MINLPLib test set.
"""
@classmethod
def evaluate(cls, x):
assert(len(x)==2)
value = ((1.5 - x[0]*(1 - x[1]))**2 +
(2.25 - x[0]*(1 - x[1]**2))**2 +
(2.625 - x[0]*(1 - x[1]**3))**2)
return(value)
dimension = 2
var_lower = np.array([0, 0])
var_upper = np.array([200, 200])
optimum_point = np.array([2.0, 0.0])
optimum_value = 0.703125
var_type = np.array(['I'] * 2)
# -- end class
class prob03:
"""
prob03 function of the MINLPLib test set.
"""
@classmethod
def evaluate(cls, x):
assert(len(x)==2)
value = 3*x[0] + 2*x[1]
# There is one constraint:
# x[0]*x[1] - 3.5 >= 0
penalty = 10*max(0, -(x[0]*x[1] - 3.5))
return(value + penalty)
dimension = 2
var_lower = np.array([1, 1])
var_upper = np.array([5, 5])
optimum_point = np.array([2.0, 2.0])
optimum_value = 10.0
var_type = np.array(['I'] * 2)
# -- end class
class sporttournament06:
"""
sporttournament06 function of the MINLPLib test set.
"""
@classmethod
def evaluate(cls, x):
assert(len(x)==15)
value = (2*x[0]*x[2] - 2*x[0] + 2*x[2] + 2*x[0]*x[6] - 2*x[6]
+ 2*x[1]*x[4] - 2*x[1] - 2*x[4] + 2*x[1]*x[9] -
4*x[9] - 2*x[2]*x[3] + 2*x[3] - 2*x[2]*x[11] -
2*x[2]*x[13] - 2*x[3]*x[4] + 2*x[3]*x[8] - 2*x[8] -
2*x[3]*x[14] + 2*x[4]*x[5] - 2*x[5] + 2*x[4]*x[7] -
2*x[7] + 2*x[5]*x[8] - 2*x[6]*x[7] + 2*x[6]* x[11] +
2*x[6]*x[12] + 2*x[7]*x[9] + 2*x[7]*x[14] +
2*x[8]*x[10] - 2*x[10] - 2*x[8]*x[11] + 2*x[9]* x[10]
+ 2*x[9]*x[11] - 2*x[12]*x[14] + 2*x[13]*x[14])
return(value)
dimension = 15
var_lower = np.array([0] * 15)
var_upper = np.array([1] * 15)
optimum_point = np.array([0.0, 1.0, 1.0, 1.0, 0.0, 1.0, 1.0, 1.0,
0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0])
optimum_value = -12.0
var_type = np.array(['I'] * 15)
# -- end class
class st_miqp1:
"""
st_miqp1 function of the MINLPLib test set.
"""
@classmethod
def evaluate(cls, x):
assert(len(x)==5)
value = (50*x[0]*x[0] + 42*x[0] + 50*x[1]*x[1] + 44*x[1] +
50*x[2]*x[2] + 45*x[2] + 50*x[3]*x[3]
+ 47*x[3] + 50*x[4]*x[4] + 47.5*x[4])
# There is one constraint:
# 20*x[0] + 12*x[1] + 11*x[2] + 7*x[3] + 4*x[4] - 40 >= 0
penalty = 100*max(0, -(20*x[0] + 12*x[1] + 11*x[2] + 7*x[3] +
4*x[4] - 40))
return(value + penalty)
dimension = 5
var_lower = np.array([0, 0, 0, 0, 0])
var_upper = np.array([1, 1, 1, 1, 1])
optimum_point = np.array([1.0, 1.0, 1.0, 0.0, 0.0])
optimum_value = 281.0
var_type = np.array(['I'] * 5)
# -- end class
class st_miqp3:
"""
st_miqp3 function of the MINLPLib test set.
"""
@classmethod
def evaluate(cls, x):
assert(len(x)==2)
value = (6*x[0]*x[0] - 3*x[1])
# There is one constraint:
# 4*x[0] - x[1] >= 0
penalty = 10*max(0, -(4*x[0] - x[1]))
return(value + penalty)
dimension = 2
var_lower = np.array([0, 0])
var_upper = np.array([3, 50])
optimum_point = np.array([1.0, 4.0])
optimum_value = -6.0
var_type = np.array(['I'] * 2)
# -- end class
class st_test1:
"""
st_test1 function of the MINLPLib test set.
"""
@classmethod
def evaluate(cls, x):
assert(len(x)==5)
value = (50*x[0]*x[0] + 42*x[0] + 50*x[1]*x[1] - 44*x[1] +
50*x[3]*x[3] - 47*x[3] + 50*x[4]*x[4] - 47.5*x[4] + 45*x[2])
# There is one constraint:
# -20*x[0] - 12*x[1] - 11*x[2] - 7*x[3] - 4*x[4] + 40 >= 0
penalty = 10*max(0, -(-20*x[0] - 12*x[1] - 11*x[2] - 7*x[3] -
4*x[4] + 40))
return(value + penalty)
dimension = 5
var_lower = np.array([0, 0, 0, 0, 0])
var_upper = np.array([1, 1, 1, 1, 1])
optimum_point = np.array([0.0, 0.0, 0.0, 0.0, 0.0])
optimum_value = 0.0
var_type = np.array(['I'] * 5)
# -- end class
class schoen_6_1_int:
"""
schoen function of dimension 6 with 50 stationary points.
Mixed integer version.
"""
@classmethod
def evaluate(cls, x):
assert(len(x)==6)
numerator = 0.0
denominator = 0.0
dist = np.sum((x/10 - cls.z)**2, axis=1)
for i in range(50):
prod = 1.0
for j in range(50):
if (i != j):
prod *= dist[j]
numerator += cls.f[i]*prod
denominator += prod
value = numerator/denominator
return(value)
z = np.array(
[[0.298854, 0.181010, 0.984817, 0.125272, 0.548396, 0.894658],
[0.800371, 0.817380, 0.398577, 0.652349, 0.250843, 0.130235],
[0.268631, 0.929778, 0.640422, 0.462004, 0.492930, 0.434955],
[0.257863, 0.729198, 0.210810, 0.364378, 0.228216, 0.947432],
[0.767627, 0.592150, 0.103788, 0.696895, 0.472449, 0.244504],
[0.369630, 0.110889, 0.072344, 0.515753, 0.068087, 0.103057],
[0.425457, 0.807081, 0.491209, 0.449497, 0.065690, 0.592775],
[0.544229, 0.619841, 0.704609, 0.573098, 0.044844, 0.305800],
[0.164031, 0.722884, 0.670496, 0.517915, 0.176386, 0.921565],
[0.153788, 0.703577, 0.899129, 0.406134, 0.941356, 0.538215],
[0.984781, 0.510479, 0.573361, 0.884599, 0.399472, 0.712935],
[0.488416, 0.403997, 0.888823, 0.048434, 0.265197, 0.478025],
[0.047985, 0.280071, 0.709960, 0.278919, 0.035737, 0.037699],
[0.656172, 0.498412, 0.458622, 0.982970, 0.041234, 0.921127],
[0.590802, 0.359690, 0.396516, 0.338153, 0.320793, 0.847369],
[0.649160, 0.846974, 0.451818, 0.064864, 0.818545, 0.955844],
[0.583716, 0.669610, 0.463098, 0.492710, 0.989690, 0.002397],
[0.097300, 0.112389, 0.128759, 0.182995, 0.262808, 0.701887],
[0.487363, 0.892520, 0.269056, 0.116046, 0.905416, 0.808013],
[0.908316, 0.023997, 0.670399, 0.985859, 0.178548, 0.450410],
[0.230409, 0.381732, 0.613667, 0.697260, 0.016950, 0.736507],
[0.132544, 0.526349, 0.650042, 0.084086, 0.979257, 0.771499],
[0.872978, 0.008826, 0.587481, 0.624637, 0.623175, 0.939539],
[0.447828, 0.836386, 0.223285, 0.422756, 0.344488, 0.555953],
[0.546839, 0.153934, 0.953017, 0.640891, 0.666774, 0.647583],
[0.762237, 0.608920, 0.401447, 0.056202, 0.203535, 0.890609],
[0.655150, 0.444544, 0.495582, 0.247926, 0.155128, 0.188004],
[0.481813, 0.387178, 0.597276, 0.634671, 0.285404, 0.714793],
[0.976385, 0.018854, 0.262585, 0.640434, 0.086314, 0.669879],
[0.120164, 0.882300, 0.057626, 0.695111, 0.735135, 0.004711],
[0.414644, 0.715618, 0.642033, 0.770645, 0.407019, 0.502945],
[0.257475, 0.620029, 0.840603, 0.638546, 0.636521, 0.883558],
[0.788980, 0.374926, 0.448016, 0.081941, 0.225763, 0.944905],
[0.661591, 0.178832, 0.790349, 0.141653, 0.424235, 0.571960],
[0.546361, 0.624907, 0.190470, 0.412713, 0.124748, 0.662788],
[0.226384, 0.065829, 0.960836, 0.767766, 0.089695, 0.441792],
[0.303675, 0.370047, 0.973692, 0.830432, 0.424719, 0.173571],
[0.548375, 0.823234, 0.334253, 0.078398, 0.097269, 0.195120],
[0.646225, 0.100478, 0.723833, 0.891035, 0.386094, 0.360272],
[0.362757, 0.114700, 0.731020, 0.783785, 0.250399, 0.244399],
[0.904335, 0.869074, 0.479004, 0.525872, 0.359411, 0.338333],
[0.563175, 0.245903, 0.694417, 0.833524, 0.205055, 0.132535],
[0.401356, 0.920963, 0.401902, 0.120625, 0.765834, 0.381552],
[0.769562, 0.279591, 0.567598, 0.017192, 0.697366, 0.813451],
[0.738572, 0.984740, 0.007616, 0.005382, 0.592976, 0.771773],
[0.683721, 0.824097, 0.731623, 0.936945, 0.182420, 0.393537],
[0.375859, 0.541929, 0.974640, 0.377459, 0.754060, 0.019335],
[0.4, 0.6, 0.1, 0.4, 0.637412, 0.204038],
[0.5, 0.4, 0.4, 0.0, 0.198525, 0.074668],
[0.7, 0.1, 0.3, 0.5, 0.143614, 0.961610]])
f = np.array(
[672.2, 861.4, 520.9, 121.0, 11.5, 48.2, 702.4, 536.2,
457.7, 801.3, 787.7, 768.6, 292.4, 960.0, 573.1, 303.7,
283.3, 474.1, 216.9, 462.2, 853.6, 677.1, 464.6, 830.6,
831.8, 109.6, 967.6, 122.9, 896.2, 490.2, 710.4, 81.1,
802.9, 999.8, 945.5, 672.3, 712.9, 235.8, 266.5, 772.4,
326.6, 585.5, 16.9, 135.9, 224.2, 382.1, 614.6, -1000,
-1000, -1000])
dimension = 6
var_lower = np.array([0 for i in range(6)])
var_upper = np.array([10 for i in range(6)])
optimum_point = np.array([04., 06., 01., 04., 06.37412, 02.04038])
optimum_value = -1000
var_type = np.array(['I'] * 4 + ['R'] * 2)
# -- end class
class schoen_6_2_int:
"""
schoen function of dimension 6 with 50 stationary points.
Mixed integer version.
"""
@classmethod
def evaluate(cls, x):
assert(len(x)==6)
numerator = 0.0
denominator = 0.0
dist = np.sum((x/10 - cls.z)**2, axis=1)
for i in range(50):
prod = 1.0
for j in range(50):
if (i != j):
prod *= dist[j]
numerator += cls.f[i]*prod
denominator += prod
value = numerator/denominator
return(value)
z = np.array(
[[0.669711, 0.815540, 0.646120, 0.377447, 0.111538, 0.040529],
[0.000632, 0.706804, 0.857031, 0.473778, 0.993569, 0.616184],
[0.625617, 0.880221, 0.534547, 0.760235, 0.276998, 0.735438],
[0.774577, 0.922914, 0.947791, 0.315328, 0.414841, 0.785803],
[0.079768, 0.131498, 0.225123, 0.464621, 0.638041, 0.992795],
[0.471038, 0.244503, 0.565776, 0.898397, 0.604639, 0.306230],
[0.642233, 0.482219, 0.034943, 0.934805, 0.972714, 0.153664],
[0.550151, 0.310507, 0.042126, 0.230722, 0.444375, 0.117355],
[0.789984, 0.488482, 0.065237, 0.842940, 0.793454, 0.799489],
[0.850183, 0.754551, 0.516033, 0.166362, 0.201966, 0.044234],
[0.000601, 0.896758, 0.304433, 0.149125, 0.178398, 0.871836],
[0.056787, 0.932745, 0.218009, 0.778061, 0.131847, 0.356237],
[0.210266, 0.221479, 0.014831, 0.200901, 0.656693, 0.891819],
[0.528515, 0.178025, 0.188138, 0.411485, 0.217833, 0.907579],
[0.195801, 0.663099, 0.477312, 0.395250, 0.655791, 0.820570],
[0.933208, 0.789323, 0.350520, 0.855434, 0.491082, 0.874993],
[0.251047, 0.543513, 0.529644, 0.218495, 0.351637, 0.608904],
[0.963286, 0.793004, 0.650148, 0.881362, 0.904832, 0.005397],
[0.431744, 0.438965, 0.044544, 0.834968, 0.330614, 0.451282],
[0.234845, 0.328576, 0.388284, 0.339183, 0.206086, 0.600034],
[0.512783, 0.961787, 0.959109, 0.632098, 0.910614, 0.912025],
[0.454168, 0.743189, 0.834284, 0.955817, 0.072172, 0.523068],
[0.696968, 0.720236, 0.341060, 0.054580, 0.045599, 0.549192],
[0.272955, 0.318845, 0.700767, 0.426325, 0.895755, 0.843128],
[0.992189, 0.332899, 0.272784, 0.019284, 0.073711, 0.434800],
[0.154276, 0.639611, 0.924641, 0.587242, 0.358453, 0.548022],
[0.021506, 0.450392, 0.515150, 0.032232, 0.650223, 0.849384],
[0.316499, 0.513234, 0.958219, 0.843587, 0.125408, 0.836643],
[0.538587, 0.261750, 0.732136, 0.030271, 0.893345, 0.270532],
[0.987469, 0.708780, 0.446487, 0.968784, 0.734448, 0.788229],
[0.353358, 0.135036, 0.249018, 0.565029, 0.740519, 0.250807],
[0.810372, 0.656510, 0.472093, 0.225741, 0.420513, 0.202519],
[0.848128, 0.551586, 0.513140, 0.956164, 0.483389, 0.404478],
[0.292239, 0.297077, 0.934202, 0.468329, 0.872274, 0.992632],
[0.828869, 0.534749, 0.716451, 0.405855, 0.164485, 0.531068],
[0.130616, 0.757677, 0.284500, 0.438300, 0.957643, 0.725899],
[0.503542, 0.640368, 0.381914, 0.847206, 0.134660, 0.762294],
[0.653851, 0.646544, 0.436036, 0.944225, 0.310369, 0.392362],
[0.539397, 0.027168, 0.697972, 0.209293, 0.992890, 0.008113],
[0.902045, 0.171034, 0.194924, 0.620057, 0.002203, 0.557433],
[0.802612, 0.085835, 0.380626, 0.492568, 0.238166, 0.961837],
[0.466993, 0.647847, 0.113397, 0.015357, 0.928904, 0.166425],
[0.892021, 0.869756, 0.681364, 0.129555, 0.394682, 0.745036],
[0.060675, 0.869904, 0.757236, 0.220765, 0.615988, 0.754288],
[0.031815, 0.340961, 0.455958, 0.529616, 0.840036, 0.365200],
[0.834595, 0.603639, 0.745330, 0.085080, 0.184636, 0.238718],
[0.575681, 0.250761, 0.874497, 0.870401, 0.854591, 0.968971],
[0.3, 0.7, 0.4, 0.1, 0.258563, 0.932004],
[0.2, 0.9, 0.7, 0.2, 0.375076, 0.154363],
[0.4, 0.4, 0.6, 0.9, 0.579466, 0.524775]])
f = np.array(
[109.6, 132.4, 558.2, 158.0, 6.2, 205.4, 593.9, 2.4,
399.8, 395.9, 212.6, 976.1, 104.4, 552.1, 436.3, 837.1,
283.7, 779.7, 392.1, 85.8, 885.1, 401.5, 367.5, 694.4,
691.6, 933.1, 590.7, 246.2, 370.0, 54.3, 719.4, 95.2,
276.0, 829.1, 613.6, 242.8, 424.6, 320.6, 666.1, 479.2,
420.0, 956.6, 241.0, 21.1, 169.8, 178.1, 394.4, -1000,
-1000, -1000])
dimension = 6
var_lower = np.array([0 for i in range(6)])
var_upper = np.array([10 for i in range(6)])
optimum_point = np.array([03., 07., 04., 01., 02.58563, 09.32004])
optimum_value = -1000
var_type = np.array(['I'] * 4 + ['R'] * 2)
# -- end class
class schoen_10_1_int:
"""
schoen function of dimension 10 with 50 stationary points.
Mixed integer version.
"""
@classmethod
def evaluate(cls, x):
assert(len(x)==10)
numerator = 0.0
denominator = 0.0
dist = np.sum((x/10 - cls.z)**2, axis=1)
for i in range(50):
prod = 1.0
for j in range(50):
if (i != j):
prod *= dist[j]
numerator += cls.f[i]*prod
denominator += prod
value = numerator/denominator
return(value)
z = np.array(
[[0.914871, 0.765230, 0.139426, 0.617466, 0.823635,
0.794003, 0.801171, 0.568811, 0.279434, 0.540422],
[0.976983, 0.593277, 0.701115, 0.585262, 0.669106,
0.272906, 0.177127, 0.143389, 0.561181, 0.018744],
[0.385208, 0.984106, 0.390066, 0.905970, 0.169600,
0.191291, 0.564157, 0.689910, 0.857031, 0.715390],
[0.975998, 0.536904, 0.819333, 0.801793, 0.564454,
0.336124, 0.654190, 0.044197, 0.717416, 0.465807],
[0.750519, 0.415284, 0.258927, 0.736115, 0.597744,
0.763716, 0.747691, 0.969633, 0.188117, 0.964954],
[0.412888, 0.671756, 0.380214, 0.558595, 0.768370,
0.998320, 0.212183, 0.606757, 0.531315, 0.303569],
[0.196682, 0.139879, 0.108608, 0.736975, 0.755971,
0.021390, 0.852398, 0.188596, 0.920133, 0.045012],
[0.956270, 0.729258, 0.397664, 0.013146, 0.519861,
0.300011, 0.008396, 0.820346, 0.176841, 0.402298],
[0.126432, 0.872346, 0.923581, 0.297492, 0.992744,
0.486525, 0.915493, 0.589980, 0.498242, 0.989945],
[0.697409, 0.026641, 0.875467, 0.503039, 0.563285,
0.096769, 0.933643, 0.884419, 0.585825, 0.395465],
[0.494783, 0.824300, 0.153326, 0.202651, 0.579815,
0.416954, 0.707624, 0.497959, 0.568876, 0.812841],
[0.126963, 0.757337, 0.648583, 0.787445, 0.822586,
0.401155, 0.301350, 0.562707, 0.744074, 0.088372],
[0.293611, 0.835864, 0.925111, 0.760322, 0.729456,
0.096840, 0.651466, 0.975836, 0.691353, 0.038384],
[0.999250, 0.916829, 0.205699, 0.027241, 0.156956,
0.206598, 0.175242, 0.811219, 0.660192, 0.119865],
[0.387978, 0.665180, 0.774376, 0.135223, 0.766238,
0.380668, 0.058279, 0.727506, 0.991527, 0.345759],
[0.299341, 0.066231, 0.680305, 0.392230, 0.319985,
0.698292, 0.100236, 0.394973, 0.096232, 0.362943],
[0.281548, 0.860858, 0.647870, 0.981650, 0.110777,
0.836484, 0.697387, 0.659942, 0.694425, 0.434991],
[0.606706, 0.052287, 0.858208, 0.738885, 0.158495,
0.002367, 0.933796, 0.112986, 0.647308, 0.421573],
[0.776505, 0.101364, 0.610406, 0.275033, 0.548409,
0.998967, 0.536743, 0.943903, 0.960993, 0.251672],
[0.371347, 0.491122, 0.772374, 0.860206, 0.752131,
0.338591, 0.826739, 0.312111, 0.768881, 0.862719],
[0.866886, 0.358220, 0.131205, 0.276334, 0.334111,
0.429525, 0.752197, 0.167524, 0.437764, 0.162916],
[0.584246, 0.511215, 0.659647, 0.349220, 0.954428,
0.477982, 0.386041, 0.813944, 0.753530, 0.983276],
[0.697327, 0.499835, 0.530487, 0.599958, 0.497257,
0.998852, 0.106262, 0.186978, 0.887481, 0.749174],
[0.041611, 0.278918, 0.999095, 0.825221, 0.218320,
0.383711, 0.077041, 0.642061, 0.668906, 0.758298],
[0.072437, 0.592862, 0.040655, 0.446330, 0.651659,
0.055738, 0.631924, 0.890039, 0.192989, 0.741054],
[0.533886, 0.135079, 0.787647, 0.593408, 0.749228,
0.749045, 0.190386, 0.755508, 0.465321, 0.465156],
[0.748843, 0.696419, 0.882124, 0.843895, 0.858057,
0.220107, 0.350310, 0.102947, 0.453576, 0.875940],
[0.560231, 0.580247, 0.381834, 0.807535, 0.184636,
0.615702, 0.628408, 0.081783, 0.793384, 0.233639],
[0.384827, 0.589138, 0.630013, 0.634506, 0.630712,
0.521293, 0.494486, 0.681700, 0.288512, 0.319808],
[0.721978, 0.452289, 0.426726, 0.323106, 0.781584,
0.999325, 0.043670, 0.884560, 0.520936, 0.430684],
[0.810388, 0.624041, 0.811624, 0.105973, 0.199807,
0.440644, 0.864152, 0.282280, 0.397116, 0.499932],
[0.973889, 0.677797, 0.080137, 0.549098, 0.625445,
0.577342, 0.538642, 0.388039, 0.552273, 0.793807],
[0.365176, 0.228017, 0.623500, 0.084450, 0.177343,
0.910108, 0.632719, 0.521458, 0.894843, 0.707893],
[0.502069, 0.622312, 0.958019, 0.744999, 0.515695,
0.407885, 0.590739, 0.736542, 0.297555, 0.237955],
[0.313835, 0.090014, 0.336274, 0.433171, 0.330864,
0.105751, 0.160367, 0.651934, 0.207260, 0.293577],
[0.886072, 0.592935, 0.498116, 0.321835, 0.011216,
0.543911, 0.506579, 0.216779, 0.406812, 0.261349],
[0.789947, 0.881332, 0.696597, 0.742955, 0.252224,
0.718157, 0.188217, 0.371208, 0.178640, 0.347720],
[0.482759, 0.663618, 0.622706, 0.036170, 0.278854,
0.088147, 0.482808, 0.134824, 0.028828, 0.944537],
[0.184705, 0.662346, 0.917194, 0.186490, 0.918392,
0.955111, 0.636015, 0.447595, 0.813716, 0.372839],
[0.231741, 0.637199, 0.745257, 0.201568, 0.697485,
0.897022, 0.239791, 0.495219, 0.153831, 0.387172],
[0.198061, 0.194102, 0.550259, 0.751804, 0.503973,
0.034252, 0.788267, 0.731760, 0.118338, 0.057247],
[0.068470, 0.545180, 0.668845, 0.714932, 0.688014,
0.203845, 0.146138, 0.109039, 0.470214, 0.441797],
[0.085180, 0.142394, 0.938665, 0.071422, 0.946796,
0.697832, 0.472400, 0.161384, 0.325715, 0.122550],
[0.637672, 0.986961, 0.969438, 0.989508, 0.381318,
0.800871, 0.012035, 0.326007, 0.459124, 0.645374],
[0.147210, 0.954608, 0.361146, 0.094699, 0.092327,
0.301664, 0.478447, 0.008274, 0.680576, 0.004184],
[0.768792, 0.812618, 0.915766, 0.029070, 0.506944,
0.457816, 0.839167, 0.024706, 0.990756, 0.088779],
[0.872678, 0.601536, 0.948347, 0.621023, 0.415621,
0.289340, 0.291338, 0.190461, 0.664007, 0.583513],
[0.6, 0.7, 0.0, 0.355500, 0.294700,
0.3, 0.5, 0.5, 0.759223, 0.508432],
[0.7, 0.0, 0.4, 0.300586, 0.576927,
0.1, 0.2, 0.9, 0.614178, 0.092903],
[0.7, 0.3, 0.7, 0.899419, 0.749499,
0.6, 0.6, 0.0, 0.973726, 0.168336]])
f = np.array(
[799.1, 396.8, 370.3, 400.2, 239.7, 678.8, 868.9, 564.4,
681.6, 153.0, 760.7, 562.9, 434.9, 579.2, 260.6, 88.5,
601.3, 754.8, 894.8, 672.8, 633.7, 921.8, 43.2, 286.2,
945.5, 716.0, 72.7, 631.2, 640.3, 425.1, 825.8, 555.8,
136.9, 805.7, 786.5, 400.0, 856.4, 548.0, 510.8, 52.3,
111.6, 686.6, 888.2, 315.4, 333.9, 61.5, 755.2, -1000,
-1000, -1000])
dimension = 10
var_lower = np.array([0 for i in range(10)])
var_upper = np.array([10 for i in range(10)])
optimum_point = np.array([06., 07., 00., 03.55500, 02.94700,
03., 05., 05., 07.59223, 05.08432])
optimum_value = -1000
var_type = np.array(['I'] * 3 + ['R'] * 2 + ['I'] * 3 + ['R'] * 2)
# -- end class
class schoen_10_2_int:
"""
schoen function of dimension 10 with 50 stationary points.
Mixed integer version.
"""
@classmethod
def evaluate(cls, x):
assert(len(x)==10)
numerator = 0.0
denominator = 0.0
dist = np.sum((x/10 - cls.z)**2, axis=1)
for i in range(50):
prod = 1.0
for j in range(50):
if (i != j):
prod *= dist[j]
numerator += cls.f[i]*prod
denominator += prod
value = numerator/denominator
return(value)
z = np.array(
[[0.131461, 0.965235, 0.046134, 0.983011, 0.719813,
0.827542, 0.662422, 0.570546, 0.578707, 0.013264],
[0.068454, 0.682785, 0.582736, 0.434517, 0.310613,
0.869876, 0.993949, 0.629156, 0.590599, 0.356378],
[0.632837, 0.961665, 0.015079, 0.378878, 0.805608,
0.685239, 0.528658, 0.752934, 0.717790, 0.374865],
[0.286191, 0.912944, 0.400358, 0.902532, 0.324887,
0.850063, 0.483503, 0.764147, 0.147726, 0.159851],
[0.303483, 0.754790, 0.090527, 0.653764, 0.164323,
0.402931, 0.593477, 0.448444, 0.711483, 0.113869],
[0.057398, 0.302029, 0.596351, 0.565466, 0.694204,
0.974864, 0.323989, 0.298493, 0.859391, 0.238714],
[0.139267, 0.214902, 0.608462, 0.297987, 0.499810,
0.578553, 0.548077, 0.208442, 0.046162, 0.246848],
[0.680420, 0.783181, 0.828103, 0.475810, 0.680401,
0.188455, 0.015200, 0.650103, 0.762389, 0.063985],
[0.409243, 0.600740, 0.302354, 0.588411, 0.436291,
0.294790, 0.701477, 0.994162, 0.433749, 0.535320],
[0.077949, 0.530126, 0.869737, 0.387811, 0.705317,
0.632911, 0.442087, 0.082918, 0.441383, 0.591975],
[0.622628, 0.054964, 0.020475, 0.145616, 0.163873,
0.321546, 0.282867, 0.743494, 0.750568, 0.732386],
[0.538574, 0.066932, 0.225204, 0.290045, 0.613242,
0.529365, 0.384018, 0.946557, 0.974384, 0.425297],
[0.108817, 0.850094, 0.886417, 0.161581, 0.082973,
0.506354, 0.589650, 0.638991, 0.045151, 0.688464],
[0.917742, 0.365119, 0.484176, 0.173231, 0.210253,
0.303688, 0.992141, 0.023109, 0.977178, 0.535146],
[0.183469, 0.198085, 0.511596, 0.275610, 0.753700,
0.437328, 0.986237, 0.028654, 0.767921, 0.997910],
[0.484908, 0.759122, 0.577318, 0.359934, 0.935730,
0.617833, 0.770173, 0.311175, 0.004831, 0.157457],
[0.634077, 0.236972, 0.016427, 0.261753, 0.349712,
0.245870, 0.412238, 0.523557, 0.985327, 0.094060],
[0.477875, 0.803438, 0.496728, 0.848920, 0.497386,
0.938203, 0.279797, 0.287076, 0.395184, 0.980546],
[0.450215, 0.193712, 0.975838, 0.103925, 0.077410,
0.709573, 0.253072, 0.311723, 0.885664, 0.204528],
[0.557312, 0.815198, 0.097914, 0.539142, 0.826048,
0.130070, 0.049858, 0.223634, 0.076387, 0.831224],
[0.927559, 0.324916, 0.563393, 0.209281, 0.344394,
0.953384, 0.298679, 0.890637, 0.966615, 0.380006],
[0.026403, 0.997573, 0.479163, 0.379686, 0.687928,
0.832002, 0.214326, 0.348248, 0.073151, 0.062646],
[0.726869, 0.911171, 0.961920, 0.874884, 0.216867,
0.076966, 0.776240, 0.495777, 0.963492, 0.425246],
[0.357483, 0.486330, 0.759177, 0.748362, 0.889904,
0.350438, 0.232983, 0.823613, 0.792656, 0.441264],
[0.875826, 0.359459, 0.214808, 0.425850, 0.493328,
0.456048, 0.523145, 0.504154, 0.090128, 0.472437],
[0.813400, 0.808407, 0.427211, 0.902524, 0.210376,
0.490662, 0.915939, 0.169439, 0.078865, 0.485371],
[0.877334, 0.982207, 0.679085, 0.486335, 0.940715,
0.585964, 0.289279, 0.694886, 0.172625, 0.201457],
[0.141599, 0.476124, 0.762246, 0.067045, 0.411332,
0.813196, 0.134138, 0.302390, 0.856145, 0.349243],
[0.346912, 0.082142, 0.787442, 0.857465, 0.371129,
0.448550, 0.967943, 0.775340, 0.943681, 0.656127],
[0.619267, 0.547196, 0.470422, 0.141566, 0.584198,
0.952226, 0.196462, 0.629549, 0.685469, 0.824365],
[0.014209, 0.789812, 0.836373, 0.186139, 0.493840,
0.710697, 0.910033, 0.368287, 0.865953, 0.140892],
[0.482763, 0.072574, 0.026730, 0.143687, 0.739505,
0.419649, 0.013683, 0.662644, 0.785254, 0.234561],
[0.821421, 0.844100, 0.153937, 0.671762, 0.290469,
0.631347, 0.591435, 0.498966, 0.043395, 0.176771],
[0.404994, 0.496656, 0.951774, 0.497357, 0.715401,
0.023378, 0.493045, 0.342766, 0.117055, 0.698590],
[0.985857, 0.831692, 0.423498, 0.215757, 0.341260,
0.790760, 0.941186, 0.716883, 0.062641, 0.582012],
[0.676905, 0.280897, 0.800638, 0.898913, 0.735995,
0.592412, 0.433021, 0.432772, 0.874477, 0.112375],
[0.377382, 0.118941, 0.529204, 0.419434, 0.673891,
0.074904, 0.129868, 0.819585, 0.220536, 0.353223],
[0.233415, 0.136703, 0.487256, 0.777498, 0.901915,
0.612402, 0.778635, 0.436718, 0.484520, 0.641969],
[0.273297, 0.670196, 0.344525, 0.669751, 0.180230,
0.530085, 0.393284, 0.326043, 0.260840, 0.364690],
[0.931213, 0.676123, 0.912481, 0.898258, 0.001887,
0.408306, 0.917215, 0.496959, 0.287951, 0.562511],
[0.047196, 0.780338, 0.895994, 0.088169, 0.552425,
0.130790, 0.308504, 0.232476, 0.187952, 0.105936],
[0.343517, 0.356222, 0.416018, 0.450278, 0.487765,
0.040510, 0.592363, 0.771635, 0.577849, 0.315843],
[0.527759, 0.529503, 0.210423, 0.756794, 0.892670,
0.339374, 0.445837, 0.363265, 0.432114, 0.942045],
[0.560107, 0.110906, 0.115725, 0.761393, 0.969105,
0.921166, 0.455014, 0.593512, 0.111887, 0.217300],
[0.463382, 0.635591, 0.329484, 0.573602, 0.492558,
0.474174, 0.371906, 0.850465, 0.467637, 0.261373],
[0.033051, 0.422543, 0.294155, 0.699026, 0.846231,
0.047967, 0.686826, 0.480273, 0.463181, 0.345601],
[0.285473, 0.723925, 0.202386, 0.671909, 0.685277,
0.993969, 0.415329, 0.155218, 0.233826, 0.088752],
[0.0, 0.6, 0.8, 0.677718, 0.961189,
0.2, 0.8, 0.8, 0.524970, 0.815489],
[0.5, 0.5, 0.1, 0.156163, 0.274566,
0.5, 0.8, 0.8, 0.656166, 0.964211],
[0.1, 0.9, 0.0, 0.178217, 0.408438,
0.2, 0.1, 0.2, 0.051758, 0.906712]])
f = np.array(
[90.4, 830.9, 52.7, 375.2, 289.7, 244.1, 470.2, 111.7,
968.9, 903.4, 918.5, 820.3, 441.2, 687.5, 836.9, 11.0,
454.5, 929.3, 952.6, 937.2, 870.5, 211.7, 378.4, 320.3,
729.6, 420.8, 213.8, 717.7, 285.4, 522.8, 748.3, 371.0,
501.2, 568.6, 111.9, 645.2, 486.2, 157.0, 968.5, 137.6,
127.2, 943.4, 437.2, 199.7, 415.4, 966.0, 362.3, -1000,
-1000, -1000])
dimension = 10
var_lower = np.array([0 for i in range(10)])
var_upper = np.array([10 for i in range(10)])
optimum_point = np.array([00., 06., 08., 06.77718, 09.61189,
02., 08., 08., 05.24970, 08.15489])
optimum_value = -1000
var_type = np.array(['I'] * 3 + ['R'] * 2 + ['I'] * 3 + ['R'] * 2)
# -- end class
class branin_cat:
"""
Branin function of the Dixon-Szego test set, with categorical vars.
"""
@classmethod
def evaluate(cls, x):
assert(len(x)==3)
if (x[2] == 0):
fun = lambda x : np.cos(x)
elif (x[2] == 1):
fun = lambda x : np.sin(x)
elif (x[2] == 2):
fun = lambda x : (np.cos(x + np.pi/4))**2
elif (x[2] == 3):
fun = lambda x : (np.sin(x + np.pi/4))**2
value = ((x[1] - (5.1/(4*np.pi*np.pi))*x[0]*x[0] +
5/np.pi*x[0] - 6)**2 + 10*(1-1/(8*np.pi)) *
fun(x[0]) +10)
return(value)
dimension = 3
var_lower = np.array([-5, 0, 0])
var_upper = np.array([10, 15, 3])
optimum_point = np.array([9.42477796, 2.47499998, 0])
additional_optima = np.array([ [-3.14159265, 12.27500000, 0],
[3.14159265, 2.27500000, 0] ])
optimum_value = 0.397887357729739
var_type = np.array(['R', 'R', 'C'])
# -- end class
class hartman3_cat:
"""
Hartman3 function of the Dixon-Szego test set, with categorical vars.
"""
@classmethod
def evaluate(cls, x):
assert(len(x)==4)
value = -math.fsum([cls.c[int(x[3]), i] *
np.exp(-math.fsum([cls.a[j][i]*
(x[j] - cls.p[j][i])**2
for j in range(3)]))
for i in range(4) ])
return(value)
a = np.array([ [3.0, 0.1, 3.0, 0.1],
[10.0, 10.0, 10.0, 10.0],
[30.0, 35.0, 30.0, 35.0] ])
p = np.array([ [0.36890, 0.46990, 0.10910, 0.03815],
[0.11700, 0.43870, 0.87320, 0.57430],
[0.26730, 0.74700, 0.55470, 0.88280] ])
c = np.array([[3.2, 2.5, 0.2, 0.7],
[1.0, 1.2, 3.0, 3.2],
[2.2, 1.2, 3.1, 1.7],
[0.1, 2.1, 0.3, 3.7],
[1.8, 0.4, 3.1, 2.4]])
dimension = 4
var_lower = np.array([0, 0, 0, 0])
var_upper = np.array([1, 1, 1, 4])
optimum_point = np.array([0.155995, 0.536521, 0.843994, 3])
optimum_value = -4.822787424687719
var_type = np.array(['R', 'R', 'R', 'C'])
# -- end class
class hartman6_cat:
"""
Hartman6 function of the Dixon-Szego test set, with categorical vars.
"""
@classmethod
def evaluate(cls, x):
assert(len(x)==7)
value = -math.fsum([cls.c[int(x[0]), i] *
np.exp(-math.fsum([cls.a[j][i]*
(x[j+1] - cls.p[j][i])**2
for j in range(6)]))
for i in range(4) ])
return(value)
a = np.array([ [10.00, 0.05, 3.00, 17.00],
[3.00, 10.00, 3.50, 8.00],
[17.00, 17.00, 1.70, 0.05],
[3.50, 0.10, 10.00, 10.00],
[1.70, 8.00, 17.00, 0.10],
[8.00, 14.00, 8.00, 14.00] ])
p = np.array([ [0.1312, 0.2329, 0.2348, 0.4047],
[0.1696, 0.4135, 0.1451, 0.8828],
[0.5569, 0.8307, 0.3522, 0.8732],
[0.0124, 0.3736, 0.2883, 0.5743],
[0.8283, 0.1004, 0.3047, 0.1091],
[0.5886, 0.9991, 0.6650, 0.0381] ])
c = np.array([[1.0, 1.2, 3.0, 3.2],
[3.2, 2.5, 0.2, 0.7],
[2.2, 1.2, 3.1, 1.7],
[0.1, 2.1, 0.3, 3.7],
[1.8, 0.4, 3.1, 2.4]])
dimension = 7
var_lower = np.array([0, 0, 0, 0, 0, 0, 0])
var_upper = np.array([4, 1, 1, 1, 1, 1, 1])
optimum_point = np.array([2, 0.177401, 0.153512, 0.516698,
0.256499, 0.323092, 0.646352])
optimum_value = -3.96231691936822
var_type = np.array(['C'] + ['R'] * 6)
# -- end class
class ex8_1_1_cat:
"""
ex8_1_1 function of the GlobalLib test set.
"""
@classmethod
def evaluate(cls, x):
assert(len(x)==4)
if (x[2] == 0):
fun1 = lambda x : np.sin(x)
elif (x[2] == 1):
fun1 = lambda x : np.cos(x)
elif (x[2] == 2):
fun1 = lambda x : (np.cos(x + np.pi/4))**2
elif (x[2] == 3):
fun1 = lambda x : (np.sin(x + np.pi/4))**2
if (x[3] == 0):
fun2 = lambda x : (np.sin(x + np.pi/4))**2
elif (x[3] == 1):
fun2 = lambda x : np.sin(x)
elif (x[3] == 2):
fun2 = lambda x : (np.cos(x + np.pi/4))**2
elif (x[3] == 3):
fun2 = lambda x : np.cos(x)
value = fun1(x[0])*fun2(x[1]) - x[0]/(x[1]**2+1)
return(value)
dimension = 4
var_lower = np.array([-1, -1, 0, 0])
var_upper = np.array([2, 1, 3, 3])
optimum_point = np.array([2.0, -0.00030, 1, 3])
optimum_value = -2.4161466378205514
var_type = np.array(['R'] * 2 + ['C', 'C'])
# -- end class
class schoen_10_1_cat:
"""
schoen function of dimension 10 with categorical variables.
"""
@classmethod
def evaluate(cls, x):
assert(len(x)==12)
numerator = 0.0
denominator = 0.0
# Categorical variable determining function for the first 25
# points. We want these functions to be nonnegative on
# distances.
if (x[0] == 0):
fun1 = lambda x : x**2
elif (x[0] == 1):
fun1 = lambda x : np.abs(x + 50)
elif (x[0] == 2):
fun1 = lambda x : np.log(x + 10)
elif (x[0] == 3):
fun1 = lambda x : (np.sin(x))**2
if (x[1] == 0):
fun2 = lambda x : np.log(x + 10)
elif (x[1] == 1):
fun2 = lambda x : np.abs(x + 50)
elif (x[1] == 2):
fun2 = lambda x : x**2
elif (x[1] == 3):
fun2 = lambda x : (np.sin(x))**2
dist1 = np.sum(fun1(x[2:] - cls.z), axis=1)
dist2 = np.sum(fun2(x[2:] - cls.z), axis=1)
for i in range(25):
prod = 1.0
for j in range(50):
if (i != j):
prod *= dist1[j]
numerator += cls.f[i]*prod
denominator += prod
for i in range(25, 50):
prod = 1.0
for j in range(50):
if (i != j):
prod *= dist2[j]
numerator += cls.f[i]*prod
denominator += prod
value = numerator/denominator
return(value)
z = np.array(
[[0.914871, 0.765230, 0.139426, 0.617466, 0.823635,
0.794003, 0.801171, 0.568811, 0.279434, 0.540422],
[0.976983, 0.593277, 0.701115, 0.585262, 0.669106,
0.272906, 0.177127, 0.143389, 0.561181, 0.018744],
[0.385208, 0.984106, 0.390066, 0.905970, 0.169600,
0.191291, 0.564157, 0.689910, 0.857031, 0.715390],
[0.975998, 0.536904, 0.819333, 0.801793, 0.564454,
0.336124, 0.654190, 0.044197, 0.717416, 0.465807],
[0.750519, 0.415284, 0.258927, 0.736115, 0.597744,
0.763716, 0.747691, 0.969633, 0.188117, 0.964954],
[0.412888, 0.671756, 0.380214, 0.558595, 0.768370,
0.998320, 0.212183, 0.606757, 0.531315, 0.303569],
[0.196682, 0.139879, 0.108608, 0.736975, 0.755971,
0.021390, 0.852398, 0.188596, 0.920133, 0.045012],
[0.956270, 0.729258, 0.397664, 0.013146, 0.519861,
0.300011, 0.008396, 0.820346, 0.176841, 0.402298],
[0.126432, 0.872346, 0.923581, 0.297492, 0.992744,
0.486525, 0.915493, 0.589980, 0.498242, 0.989945],
[0.697409, 0.026641, 0.875467, 0.503039, 0.563285,
0.096769, 0.933643, 0.884419, 0.585825, 0.395465],
[0.494783, 0.824300, 0.153326, 0.202651, 0.579815,
0.416954, 0.707624, 0.497959, 0.568876, 0.812841],
[0.126963, 0.757337, 0.648583, 0.787445, 0.822586,
0.401155, 0.301350, 0.562707, 0.744074, 0.088372],
[0.293611, 0.835864, 0.925111, 0.760322, 0.729456,
0.096840, 0.651466, 0.975836, 0.691353, 0.038384],
[0.999250, 0.916829, 0.205699, 0.027241, 0.156956,
0.206598, 0.175242, 0.811219, 0.660192, 0.119865],
[0.387978, 0.665180, 0.774376, 0.135223, 0.766238,
0.380668, 0.058279, 0.727506, 0.991527, 0.345759],
[0.299341, 0.066231, 0.680305, 0.392230, 0.319985,
0.698292, 0.100236, 0.394973, 0.096232, 0.362943],
[0.281548, 0.860858, 0.647870, 0.981650, 0.110777,
0.836484, 0.697387, 0.659942, 0.694425, 0.434991],
[0.606706, 0.052287, 0.858208, 0.738885, 0.158495,
0.002367, 0.933796, 0.112986, 0.647308, 0.421573],
[0.776505, 0.101364, 0.610406, 0.275033, 0.548409,
0.998967, 0.536743, 0.943903, 0.960993, 0.251672],
[0.371347, 0.491122, 0.772374, 0.860206, 0.752131,
0.338591, 0.826739, 0.312111, 0.768881, 0.862719],
[0.866886, 0.358220, 0.131205, 0.276334, 0.334111,
0.429525, 0.752197, 0.167524, 0.437764, 0.162916],
[0.584246, 0.511215, 0.659647, 0.349220, 0.954428,
0.477982, 0.386041, 0.813944, 0.753530, 0.983276],
[0.697327, 0.499835, 0.530487, 0.599958, 0.497257,
0.998852, 0.106262, 0.186978, 0.887481, 0.749174],
[0.041611, 0.278918, 0.999095, 0.825221, 0.218320,
0.383711, 0.077041, 0.642061, 0.668906, 0.758298],
[0.072437, 0.592862, 0.040655, 0.446330, 0.651659,
0.055738, 0.631924, 0.890039, 0.192989, 0.741054],
[0.533886, 0.135079, 0.787647, 0.593408, 0.749228,
0.749045, 0.190386, 0.755508, 0.465321, 0.465156],
[0.748843, 0.696419, 0.882124, 0.843895, 0.858057,
0.220107, 0.350310, 0.102947, 0.453576, 0.875940],
[0.560231, 0.580247, 0.381834, 0.807535, 0.184636,
0.615702, 0.628408, 0.081783, 0.793384, 0.233639],
[0.384827, 0.589138, 0.630013, 0.634506, 0.630712,
0.521293, 0.494486, 0.681700, 0.288512, 0.319808],
[0.721978, 0.452289, 0.426726, 0.323106, 0.781584,
0.999325, 0.043670, 0.884560, 0.520936, 0.430684],
[0.810388, 0.624041, 0.811624, 0.105973, 0.199807,
0.440644, 0.864152, 0.282280, 0.397116, 0.499932],
[0.973889, 0.677797, 0.080137, 0.549098, 0.625445,
0.577342, 0.538642, 0.388039, 0.552273, 0.793807],
[0.365176, 0.228017, 0.623500, 0.084450, 0.177343,
0.910108, 0.632719, 0.521458, 0.894843, 0.707893],
[0.502069, 0.622312, 0.958019, 0.744999, 0.515695,
0.407885, 0.590739, 0.736542, 0.297555, 0.237955],
[0.313835, 0.090014, 0.336274, 0.433171, 0.330864,
0.105751, 0.160367, 0.651934, 0.207260, 0.293577],
[0.886072, 0.592935, 0.498116, 0.321835, 0.011216,
0.543911, 0.506579, 0.216779, 0.406812, 0.261349],
[0.789947, 0.881332, 0.696597, 0.742955, 0.252224,
0.718157, 0.188217, 0.371208, 0.178640, 0.347720],
[0.482759, 0.663618, 0.622706, 0.036170, 0.278854,
0.088147, 0.482808, 0.134824, 0.028828, 0.944537],
[0.184705, 0.662346, 0.917194, 0.186490, 0.918392,
0.955111, 0.636015, 0.447595, 0.813716, 0.372839],
[0.231741, 0.637199, 0.745257, 0.201568, 0.697485,
0.897022, 0.239791, 0.495219, 0.153831, 0.387172],
[0.198061, 0.194102, 0.550259, 0.751804, 0.503973,
0.034252, 0.788267, 0.731760, 0.118338, 0.057247],
[0.068470, 0.545180, 0.668845, 0.714932, 0.688014,
0.203845, 0.146138, 0.109039, 0.470214, 0.441797],
[0.085180, 0.142394, 0.938665, 0.071422, 0.946796,
0.697832, 0.472400, 0.161384, 0.325715, 0.122550],
[0.637672, 0.986961, 0.969438, 0.989508, 0.381318,
0.800871, 0.012035, 0.326007, 0.459124, 0.645374],
[0.147210, 0.954608, 0.361146, 0.094699, 0.092327,
0.301664, 0.478447, 0.008274, 0.680576, 0.004184],
[0.768792, 0.812618, 0.915766, 0.029070, 0.506944,
0.457816, 0.839167, 0.024706, 0.990756, 0.088779],
[0.872678, 0.601536, 0.948347, 0.621023, 0.415621,
0.289340, 0.291338, 0.190461, 0.664007, 0.583513],
[0.641216, 0.700152, 0.080576, 0.355500, 0.294700,
0.338614, 0.563964, 0.528079, 0.759223, 0.508432],
[0.738489, 0.077376, 0.429485, 0.300586, 0.576927,
0.185931, 0.231659, 0.954833, 0.614178, 0.092903],
[0.729321, 0.318607, 0.768657, 0.899419, 0.749499,
0.623403, 0.671793, 0.052835, 0.973726, 0.168336]])
f = np.array(
[-1000, -1000, -1000, 799.1, 396.8, 370.3, 400.2, 239.7,
678.8, 868.9, 564.4, 681.6, 153.0, 760.7, 562.9, 434.9,
579.2, 260.6, 88.5, 601.3, 754.8, 894.8, 672.8, 633.7, 921.8,
43.2, 286.2, 945.5, 716.0, 72.7, 631.2, 640.3, 425.1, 825.8,
555.8, 136.9, 805.7, 786.5, 400.0, 856.4, 548.0, 510.8, 52.3,
111.6, 686.6, 888.2, 315.4, 333.9, 61.5, 755.2])
dimension = 12
var_lower = np.array([0, 0] + [0 for i in range(10)])
var_upper = np.array([3, 3] + [1 for i in range(10)])
optimum_point = np.array([0, 2, 0.914871, 0.765230, 0.139426, 0.617466,
0.823635, 0.794003, 0.801171, 0.568811,
0.279434, 0.540422])
optimum_value = -1000
var_type = np.array(['C', 'C'] + ['R'] * 10)
# -- end class
class schoen_10_2_cat:
"""
schoen function of dimension 10 with categorical variables.
"""
@classmethod
def evaluate(cls, x):
assert(len(x)==12)
numerator = 0.0
denominator = 0.0
# Categorical variable determining function for the first 25
# points. We want these functions to be nonnegative on
# distances.
if (x[0] == 0):
fun1 = lambda x : x**2
elif (x[0] == 1):
fun1 = lambda x : np.abs(x + 50)
elif (x[0] == 2):
fun1 = lambda x : np.log(x + 10)
elif (x[0] == 3):
fun1 = lambda x : (np.sin(x))**2
if (x[1] == 0):
fun2 = lambda x : np.log(x + 10)
elif (x[1] == 1):
fun2 = lambda x : np.abs(x + 50)
elif (x[1] == 2):
fun2 = lambda x : x**2
elif (x[1] == 3):
fun2 = lambda x : (np.sin(x))**2
dist1 = np.sum(fun1(x[2:] - cls.z), axis=1)
dist2 = np.sum(fun2(x[2:] - cls.z), axis=1)
for i in range(25):
prod = 1.0
for j in range(50):
if (i != j):
prod *= dist1[j]
numerator += cls.f[i]*prod
denominator += prod
for i in range(25, 50):
prod = 1.0
for j in range(50):
if (i != j):
prod *= dist2[j]
numerator += cls.f[i]*prod
denominator += prod
value = numerator/denominator
return(value)
z = np.array(
[[0.131461, 0.965235, 0.046134, 0.983011, 0.719813,
0.827542, 0.662422, 0.570546, 0.578707, 0.013264],
[0.068454, 0.682785, 0.582736, 0.434517, 0.310613,
0.869876, 0.993949, 0.629156, 0.590599, 0.356378],
[0.632837, 0.961665, 0.015079, 0.378878, 0.805608,
0.685239, 0.528658, 0.752934, 0.717790, 0.374865],
[0.286191, 0.912944, 0.400358, 0.902532, 0.324887,
0.850063, 0.483503, 0.764147, 0.147726, 0.159851],
[0.303483, 0.754790, 0.090527, 0.653764, 0.164323,
0.402931, 0.593477, 0.448444, 0.711483, 0.113869],
[0.057398, 0.302029, 0.596351, 0.565466, 0.694204,
0.974864, 0.323989, 0.298493, 0.859391, 0.238714],
[0.139267, 0.214902, 0.608462, 0.297987, 0.499810,
0.578553, 0.548077, 0.208442, 0.046162, 0.246848],
[0.680420, 0.783181, 0.828103, 0.475810, 0.680401,
0.188455, 0.015200, 0.650103, 0.762389, 0.063985],
[0.409243, 0.600740, 0.302354, 0.588411, 0.436291,
0.294790, 0.701477, 0.994162, 0.433749, 0.535320],
[0.077949, 0.530126, 0.869737, 0.387811, 0.705317,
0.632911, 0.442087, 0.082918, 0.441383, 0.591975],
[0.622628, 0.054964, 0.020475, 0.145616, 0.163873,
0.321546, 0.282867, 0.743494, 0.750568, 0.732386],
[0.538574, 0.066932, 0.225204, 0.290045, 0.613242,
0.529365, 0.384018, 0.946557, 0.974384, 0.425297],
[0.108817, 0.850094, 0.886417, 0.161581, 0.082973,
0.506354, 0.589650, 0.638991, 0.045151, 0.688464],
[0.917742, 0.365119, 0.484176, 0.173231, 0.210253,
0.303688, 0.992141, 0.023109, 0.977178, 0.535146],
[0.183469, 0.198085, 0.511596, 0.275610, 0.753700,
0.437328, 0.986237, 0.028654, 0.767921, 0.997910],
[0.484908, 0.759122, 0.577318, 0.359934, 0.935730,
0.617833, 0.770173, 0.311175, 0.004831, 0.157457],
[0.634077, 0.236972, 0.016427, 0.261753, 0.349712,
0.245870, 0.412238, 0.523557, 0.985327, 0.094060],
[0.477875, 0.803438, 0.496728, 0.848920, 0.497386,
0.938203, 0.279797, 0.287076, 0.395184, 0.980546],
[0.450215, 0.193712, 0.975838, 0.103925, 0.077410,
0.709573, 0.253072, 0.311723, 0.885664, 0.204528],
[0.557312, 0.815198, 0.097914, 0.539142, 0.826048,
0.130070, 0.049858, 0.223634, 0.076387, 0.831224],
[0.927559, 0.324916, 0.563393, 0.209281, 0.344394,
0.953384, 0.298679, 0.890637, 0.966615, 0.380006],
[0.026403, 0.997573, 0.479163, 0.379686, 0.687928,
0.832002, 0.214326, 0.348248, 0.073151, 0.062646],
[0.726869, 0.911171, 0.961920, 0.874884, 0.216867,
0.076966, 0.776240, 0.495777, 0.963492, 0.425246],
[0.357483, 0.486330, 0.759177, 0.748362, 0.889904,
0.350438, 0.232983, 0.823613, 0.792656, 0.441264],
[0.875826, 0.359459, 0.214808, 0.425850, 0.493328,
0.456048, 0.523145, 0.504154, 0.090128, 0.472437],
[0.813400, 0.808407, 0.427211, 0.902524, 0.210376,
0.490662, 0.915939, 0.169439, 0.078865, 0.485371],
[0.877334, 0.982207, 0.679085, 0.486335, 0.940715,
0.585964, 0.289279, 0.694886, 0.172625, 0.201457],
[0.141599, 0.476124, 0.762246, 0.067045, 0.411332,
0.813196, 0.134138, 0.302390, 0.856145, 0.349243],
[0.346912, 0.082142, 0.787442, 0.857465, 0.371129,
0.448550, 0.967943, 0.775340, 0.943681, 0.656127],
[0.619267, 0.547196, 0.470422, 0.141566, 0.584198,
0.952226, 0.196462, 0.629549, 0.685469, 0.824365],
[0.014209, 0.789812, 0.836373, 0.186139, 0.493840,
0.710697, 0.910033, 0.368287, 0.865953, 0.140892],
[0.482763, 0.072574, 0.026730, 0.143687, 0.739505,
0.419649, 0.013683, 0.662644, 0.785254, 0.234561],
[0.821421, 0.844100, 0.153937, 0.671762, 0.290469,
0.631347, 0.591435, 0.498966, 0.043395, 0.176771],
[0.404994, 0.496656, 0.951774, 0.497357, 0.715401,
0.023378, 0.493045, 0.342766, 0.117055, 0.698590],
[0.985857, 0.831692, 0.423498, 0.215757, 0.341260,
0.790760, 0.941186, 0.716883, 0.062641, 0.582012],
[0.676905, 0.280897, 0.800638, 0.898913, 0.735995,
0.592412, 0.433021, 0.432772, 0.874477, 0.112375],
[0.377382, 0.118941, 0.529204, 0.419434, 0.673891,
0.074904, 0.129868, 0.819585, 0.220536, 0.353223],
[0.233415, 0.136703, 0.487256, 0.777498, 0.901915,
0.612402, 0.778635, 0.436718, 0.484520, 0.641969],
[0.273297, 0.670196, 0.344525, 0.669751, 0.180230,
0.530085, 0.393284, 0.326043, 0.260840, 0.364690],
[0.931213, 0.676123, 0.912481, 0.898258, 0.001887,
0.408306, 0.917215, 0.496959, 0.287951, 0.562511],
[0.047196, 0.780338, 0.895994, 0.088169, 0.552425,
0.130790, 0.308504, 0.232476, 0.187952, 0.105936],
[0.343517, 0.356222, 0.416018, 0.450278, 0.487765,
0.040510, 0.592363, 0.771635, 0.577849, 0.315843],
[0.527759, 0.529503, 0.210423, 0.756794, 0.892670,
0.339374, 0.445837, 0.363265, 0.432114, 0.942045],
[0.560107, 0.110906, 0.115725, 0.761393, 0.969105,
0.921166, 0.455014, 0.593512, 0.111887, 0.217300],
[0.463382, 0.635591, 0.329484, 0.573602, 0.492558,
0.474174, 0.371906, 0.850465, 0.467637, 0.261373],
[0.033051, 0.422543, 0.294155, 0.699026, 0.846231,
0.047967, 0.686826, 0.480273, 0.463181, 0.345601],
[0.285473, 0.723925, 0.202386, 0.671909, 0.685277,
0.993969, 0.415329, 0.155218, 0.233826, 0.088752],
[0.029705, 0.651519, 0.813239, 0.677718, 0.961189,
0.285385, 0.824635, 0.837670, 0.524970, 0.815489],
[0.519627, 0.508274, 0.141067, 0.156163, 0.274566,
0.536322, 0.834749, 0.852042, 0.656166, 0.964211],
[0.119675, 0.971352, 0.052983, 0.178217, 0.408438,
0.215091, 0.102098, 0.256312, 0.051758, 0.906712]])
f = np.array(
[-1000, -1000, -1000, 90.4, 830.9, 52.7, 375.2, 289.7, 244.1,
470.2, 111.7, 968.9, 903.4, 918.5, 820.3, 441.2, 687.5, 836.9,
11.0, 454.5, 929.3, 952.6, 937.2, 870.5, 211.7, 378.4, 320.3,
729.6, 420.8, 213.8, 717.7, 285.4, 522.8, 748.3, 371.0, 501.2,
568.6, 111.9, 645.2, 486.2, 157.0, 968.5, 137.6, 127.2, 943.4,
437.2, 199.7, 415.4, 966.0, 362.3])
dimension = 12
var_lower = np.array([0, 0] + [0 for i in range(10)])
var_upper = np.array([3, 3] + [1 for i in range(10)])
optimum_point = np.array([0, 2, 0.131461, 0.965235, 0.046134, 0.983011,
0.719813, 0.827542, 0.662422, 0.570546,
0.578707, 0.013264])
optimum_value = -1000
var_type = np.array(['C', 'C'] + ['R'] * 10)
# -- end class
class gear4_cat:
"""
gear4 function of the MINLPLib test set, with categorical variables
"""
@classmethod
def evaluate(cls, x):
assert(len(x)==6)
if (x[5] == 0):
fun = lambda x, y : np.sqrt(x + y)
elif (x[5] == 1):
fun = lambda x, y : x/y
elif (x[5] == 2):
fun = lambda x, y : np.log(x * y * 2)
elif (x[5] == 3):
fun = lambda x, y : x/(y + 10)
elif (x[5] == 4):
fun = lambda x, y : np.max(x, y)
value = -1000000*x[0]*x[1]/(x[2]*x[3]) + 2*x[4] + 144279.32477276
# There is a constraint:
# -1000000*x[0]*x[1]/(x[2]*x[3]) + x[4] + 144279.32477276 >= 0
penalty = 10*max(0,-(-1000000*x[0]*x[1]/(x[2]*x[3]) + x[4] +
144279.32477276))
return(value + penalty)
dimension = 6
var_lower = np.array([12, 12, 12, 12, 0, 0])
var_upper = | np.array([60, 60, 60, 60, 100, 4]) | numpy.array |
# 1. Only add your code inside the function (including newly improted packages).
# You can design a new function and call the new function in the given functions.
# 2. For bonus: Give your own picturs. If you have N pictures, name your pictures such as ["t3_1.png", "t3_2.png", ..., "t3_N.png"], and put them inside the folder "images".
# 3. Not following the project guidelines will result in a 10% reduction in grades
import json
import cv2
import numpy as np
import matplotlib.pyplot as plt
# Use the keypoints to stitch the images
def get_stitched_image(img1, img2, M):
# Get width and height of input images
w1, h1 = img1.shape[:2]
w2, h2 = img2.shape[:2]
# Get the canvas dimensions
img1_dims = | np.float32([[0, 0], [0, w1], [h1, w1], [h1, 0]]) | numpy.float32 |
"""Classes and methods used across the project"""
import json
import numpy as np
import matplotlib.pyplot as plt
import sys
import os
import time
import fma_utils
"""Generic Utils"""
class ProgressBar:
"""Terminal progress bar
Arguments:
total: Relative size corresponding to completed task
status: In progress status message
bar_len: Actual size of progress bar when full
max_len: Anything beyond this is truncated
update_freq: Write to terminal st this rate (increase to save time on i/o)
"""
def __init__(self, total, status='', **kwargs):
self.total = total
self.status = status
self.params = {
'max_len': 150,
'bar_len': 60,
'update_freq': 2
}
self.params.update(kwargs)
self.update_time = None
self.completed = False
def update(self, count):
"""Updates the progress bar with a new progress value"""
curr_time = time.time()
if self.update_time is not None and self.update_time + self.params['update_freq'] > curr_time:
return
self.update_time = curr_time
filled_len = self.params['bar_len'] if self.total == 0 else \
int(round(self.params['bar_len'] * count / float(self.total)))
percents = 100.0 if self.total == 0 else round(100.0 * count / float(self.total), 1)
clear = ' ' * self.params['max_len'] # Blank line is used to clear previous content on the terminal
bar = '=' * filled_len + '-' * (self.params['bar_len'] - filled_len)
output = ('[%s] %s%s ...%s' % (bar, percents, '%', self.status))
if len(output) > self.params['max_len']:
output = output[:self.params['max_len']]
sys.stdout.write('%s\r' % clear)
sys.stdout.write(output)
sys.stdout.write('\n' if self.completed else '\r')
sys.stdout.flush()
def complete(self, status=''):
"""Fills the progress bar to completion and updates the status message"""
self.completed = True
self.status = status
self.update_time = None
self.update(self.total)
def cached(key_fn=lambda *a, **k: str(a + tuple(k.values()))):
"""Decorator for caching method outputs by key"""
def args_wrap(fn):
cache = {}
def fn_wrap(*args, **kwargs):
key = None if key_fn is None else key_fn(*args, **kwargs)
if key not in cache:
cache[key] = fn(*args, **kwargs)
return cache[key]
return fn_wrap
return args_wrap
def plot_learning_curve(data_a, data_b, title='Learning Curve', x_label='Epoch', y_label='Loss', legend_a='Train',
legend_b='CV', block=False, close=False):
"""Plots learning curve for a training process in a non-blocking way
Arguments:
data_a: Numpy Array or list values to plot (typically training set errors)
data_b: Optional Numpy Array or list values to plot (typically cv set errors)
block: Set True to block code execution while the plot is displayed
close: Set True to close an existing plot before plotting. Can be useful for showing plots successively
"""
if close:
plt.close()
data_a = np.array(data_a).reshape(-1)
plt.plot( | np.arange(1, data_a.size + 1) | numpy.arange |
from __future__ import absolute_import
import hnswlib
import numpy as np
from ann_benchmarks.algorithms.base import BaseANN
class HnswLib(BaseANN):
def __init__(self, efConstruction: int, M: int, metric: str):
self.efConstruction = efConstruction
self.M = M
self.metric = {'angular': 'cosine', 'euclidean': 'l2'}[metric]
self.name = f"hnswlib(e={self.efConstruction},m={self.M})"
def __str__(self):
return f"{self.name}[ef={self.ef}]"
def done(self):
del self.p
def fit(self, X):
self.p = hnswlib.Index(space=self.metric, dim=len(X[0]))
self.p.init_index(max_elements=len(X), ef_construction=self.efConstruction, M=self.M)
data_labels = np.arange(len(X))
self.p.set_num_threads(1)
self.p.add_items( | np.asarray(X) | numpy.asarray |
#! /usr/bin python
#------------------------------------------------------------------------------
# PROGRAM: plot_ncc_stripes_rebinning.py
#------------------------------------------------------------------------------
# Version 0.3
# 26 September, 2021
# <NAME>
# https://patternizer.github.io
# patternizer AT gmail DOT com
# michael DOT a DOT taylor AT uea DOT ac DOT uk
#------------------------------------------------------------------------------
#------------------------------------------------------------------------------
# IMPORT PYTHON LIBRARIES
#------------------------------------------------------------------------------
# Dataframe libraries:
import numpy as np
import pandas as pd
import xarray as xr
# Datetime libraries:
from datetime import datetime
import nc_time_axis
import cftime
from cftime import num2date, DatetimeNoLeap
# Plotting libraries:
import matplotlib
#matplotlib.use('agg')
import matplotlib.pyplot as plt; plt.close('all')
import matplotlib.colors as mcolors
from matplotlib import cm
from matplotlib.cm import ScalarMappable
from matplotlib import rcParams
from pandas.plotting import register_matplotlib_converters
register_matplotlib_converters()
# Statistics libraries:
from scipy import stats
# Silence library version notifications
import warnings
warnings.filterwarnings("ignore", category=UserWarning)
warnings.filterwarnings("ignore", category=RuntimeWarning)
warnings.filterwarnings("ignore", message="numpy.dtype size changed")
warnings.filterwarnings("ignore", message="numpy.ufunc size changed")
#------------------------------------------------------------------------------
#------------------------------------------------------------------------------
# SETTINGS:
#------------------------------------------------------------------------------
fontsize = 10
nsmooth = 10
cbar_max = 12.0
cbar_max_norwich_era = 12.0
barwidthfraction = 1.0
t_start = -2580000
t_end = 2200
use_timemask = False
use_logarithm = False
use_log10_scale = False
use_overlay_annotations = False
use_hires_norwich = False
use_dark_theme = True
use_smoothing = False
use_overlay_axis = False
use_norwich_era_colormap = True
use_overlay_timeseries = True
use_overlay_baseline = False
use_overlay_colorbar = True
plot_forecast_variability = False
plot_color_mapping = False
plot_climate_timeseries = False
plot_climate_bars = True
plot_climate_stripes = True
#projectionstr = 'RCP3pd'
#projectionstr = 'RCP45'
#projectionstr = 'RCP6'
#projectionstr = 'RCP85'
#projectionstr = 'SSP119'
#projectionstr = 'SSP126'
#projectionstr = 'SSP245'
projectionstr = 'SSP370'
#projectionstr = 'SSP585'
#baselinestr = 'baseline_1851_1900'
baselinestr = 'baseline_1961_1990'
#baselinestr = 'baseline_1971_2000'
pathstr = 'DATA/'
pages2kstr = 'PAGES2k.txt'
hadcrut5str = 'HadCRUT5.csv'
fairstr = 'fair' + '_' + projectionstr.lower() + '.csv'
lovarstr = 'variability_realisation0.txt' # via Tim
hivarstr = 'variability_realisation1.txt' # via Tim
paleostr = 'paleo_data_compilation.xls'
pages2k_file = pathstr + pages2kstr
hadcrut5_file = pathstr + hadcrut5str
fair_file = pathstr + fairstr
lo_var_file = pathstr + lovarstr
hi_var_file = pathstr + hivarstr
paleo_file = pathstr + paleostr
ipcc_rgb_txtfile = np.loadtxt("DATA/temp_div.txt") # IPCC AR6 temp div colormap file
cmap = mcolors.LinearSegmentedColormap.from_list('colormap', ipcc_rgb_txtfile) # ipcc_colormap
#cmap = plt.cm.get_cmap('RdBu_r')
#cmap = plt.cm.get_cmap('bwr')
#------------------------------------------------------------------------------
# DARK THEME
#------------------------------------------------------------------------------
if use_dark_theme == True:
matplotlib.rcParams['text.usetex'] = False
# rcParams['font.family'] = ['DejaVu Sans']
# rcParams['font.sans-serif'] = ['Avant Garde']
rcParams['font.family'] = 'sans-serif'
rcParams['font.sans-serif'] = ['Avant Garde', 'Lucida Grande', 'Verdana', 'DejaVu Sans' ]
plt.rc('text',color='white')
plt.rc('lines',color='white')
plt.rc('patch',edgecolor='white')
plt.rc('grid',color='lightgray')
plt.rc('xtick',color='white')
plt.rc('ytick',color='white')
plt.rc('axes',labelcolor='white')
plt.rc('axes',facecolor='black')
plt.rc('axes',edgecolor='lightgray')
plt.rc('figure',facecolor='black')
plt.rc('figure',edgecolor='black')
plt.rc('savefig',edgecolor='black')
plt.rc('savefig',facecolor='black')
else:
matplotlib.rcParams['text.usetex'] = False
# rcParams['font.family'] = ['DejaVu Sans']
# rcParams['font.sans-serif'] = ['Avant Garde']
rcParams['font.family'] = 'sans-serif'
rcParams['font.sans-serif'] = ['Avant Garde', 'Lucida Grande', 'Verdana', 'DejaVu Sans' ]
plt.rc('text',color='black')
plt.rc('lines',color='black')
plt.rc('patch',edgecolor='black')
plt.rc('grid',color='lightgray')
plt.rc('xtick',color='black')
plt.rc('ytick',color='black')
plt.rc('axes',labelcolor='black')
plt.rc('axes',facecolor='white')
plt.rc('axes',edgecolor='black')
plt.rc('figure',facecolor='white')
plt.rc('figure',edgecolor='white')
plt.rc('savefig',edgecolor='white')
plt.rc('savefig',facecolor='white')
# Calculate current time
now = datetime.now()
currentdy = str(now.day).zfill(2)
currentmn = str(now.month).zfill(2)
currentyr = str(now.year)
titletime = str(currentdy) + '/' + currentmn + '/' + currentyr
#------------------------------------------------------------------------------
# LOAD: PAGES2k (via Ed Hawkins with thanks) --> df_pages2k
# NB: convert time to year.decimal
#------------------------------------------------------------------------------
# FORMAT:
# Year CE | raw instrumental target data | reconstruction ensemble 50th | 2.5th | 97.5th percentiles |
# 31-year butterworth filtered instrumental target data | 31-year butterworth filtered reconstruction 50th |
# 2.5th | 97.5th percentiles
nheader = 5
f = open(pages2k_file)
lines = f.readlines()
years = [] # [0001,2000]
obs = []
for i in range(nheader,len(lines)):
words = lines[i].split()
year = words[0].zfill(4)
val = (len(words)-1)*[None]
for j in range(len(val)):
try: val[j] = float(words[j+1])
except:
pass
years.append(year)
obs.append(val)
f.close()
obs = np.array(obs)
t_pages2k = xr.cftime_range(start=years[0], periods=len(years), freq='A', calendar='gregorian')[0:1849]
ts_pages2k_instr = pd.to_numeric(obs[:,1][0:1849], errors='coerce')
ts_pages2k_recon = pd.to_numeric(obs[:,5][0:1849], errors='coerce')
ts_pages2k = np.append(ts_pages2k_recon[0:-36],ts_pages2k_instr[-36:],axis=None)
df_pages2k = pd.DataFrame()
df_pages2k['t_pages2k'] = t_pages2k.year.astype(float)
df_pages2k['ts_pages2k'] = ts_pages2k
#------------------------------------------------------------------------------
# LOAD: HadCRUT5 (via <NAME> and UKMO with thanks) --> df_hadcrut5
# NB: convert time to year.decimal
#------------------------------------------------------------------------------
hadcrut5 = pd.read_csv(hadcrut5_file)
t_hadcrut5_monthly = xr.cftime_range(start='1850', periods=len(hadcrut5), freq='MS', calendar='noleap')
ts_hadcrut5_monthly = hadcrut5['Anomaly (deg C)'].values
df_hadcrut5 = pd.DataFrame()
df_hadcrut5['t_hadcrut5'] = t_hadcrut5_monthly.year.astype(float) + t_hadcrut5_monthly.month.astype(float)/12.0
df_hadcrut5['ts_hadcrut5'] = ts_hadcrut5_monthly
years = np.unique(t_hadcrut5_monthly.year)
yearly = []
SD = []
for yyyy in years:
year_data = df_hadcrut5[np.floor(df_hadcrut5['t_hadcrut5']).astype('int') == yyyy]['ts_hadcrut5']
yearly_mean = np.nanmean(year_data)
yearly_SD = np.nanstd(year_data)
yearly.append(yearly_mean)
SD.append(yearly_SD)
df_hadcrut5_yearly = pd.DataFrame()
df_hadcrut5_yearly['t_hadcrut5'] = years.astype('float')
df_hadcrut5_yearly['ts_hadcrut5'] = yearly
df_hadcrut5_yearly['ts_hadcrut5_SD'] = SD
df_hadcrut5_yearly = df_hadcrut5_yearly[df_hadcrut5_yearly.t_hadcrut5 <= 2020]
#------------------------------------------------------------------------------
# LOAD: FaIR v1.6.3 projections (constrained by HadCRUT5-analysis) --> df_fair
# NB: convert time to year.decimal
#------------------------------------------------------------------------------
fair = pd.read_csv(fair_file)
df_fair = pd.DataFrame()
df_fair['t_fair'] = fair.Year.values.astype('float')
#------------------------------------------------------------------------------
# LOAD: internal variability for FaIR v1.6.4 projections calculated by Tim from the instrumental record.
#------------------------------------------------------------------------------
nheader = 0
f_lo = open(lo_var_file)
f_hi = open(hi_var_file)
lines_lo = f_lo.readlines()
lines_hi = f_hi.readlines()
years = []
obs_lo = []
obs_hi = []
#for i in range(nheader,len(lineslo)):
for i in range(nheader,180):
words_lo = lines_lo[i].split()
words_hi = lines_hi[i].split()
year = int(words_lo[0].zfill(4)) + 671 # 1350 --> 2021 offset
val_lo = (len(words_lo)-1)*[None]
val_hi = (len(words_hi)-1)*[None]
for j in range(len(val_lo)):
try:
val_lo[j] = float(words_lo[j+1])
val_hi[j] = float(words_hi[j+1])
except:
pass
years.append(year)
obs_lo.append(val_lo)
obs_hi.append(val_hi)
f_lo.close()
f_hi.close()
obs_lo = np.array(obs_lo).ravel()
obs_hi = np.array(obs_hi).ravel()
df_variability = pd.DataFrame({'lo_var':obs_lo, 'hi_var':obs_hi}, index=years)
if (projectionstr == 'SSP119') | (projectionstr == 'SSP126') | (projectionstr == 'SSP245') | (projectionstr == 'RCP3pd') | (projectionstr == 'RCP45'):
df_fair['ts_fair'] = fair.Global.values + df_variability.lo_var.values
elif (projectionstr == 'SSP370') | (projectionstr == 'SSP585') | (projectionstr == 'RCP6') | (projectionstr == 'RCP85'):
df_fair['ts_fair'] = fair.Global.values + df_variability.hi_var.values
#------------------------------------------------------------------------------
# LOAD: geological anomalies: 65.5229 Myr ( before 2015 )
# NB: paleo_file is from the "data_compilation" sheet in All_palaeotemps.xlsx
# made available at: hhttp://gergs.net/?attachment_id=4310
#------------------------------------------------------------------------------
xl = pd.ExcelFile(paleo_file)
df_xl = xl.parse('Sheet1',header=2)
# FORMAT:
# Royer et al (2004) Friedrich et al (2012) & Hansen et al (2013) Zachos et al (2008) & Hansen et al (2013) Lisiecki and Raymo (2005) & Hansen et al (2013) EPICA <NAME>, Antarctica (x 0.5) NGRIP, Greenland & Johnsen et al (1989) (x 0.5) Marcott et al (2013) Berkeley Earth land-ocean IPCC AR5 RCP8.5
# Age My Royer / Veizer (x 2.0) Royer / Veizer - CO₂ from proxies (x 2.0) Low High Axis [] Age My Age ky before 2015 δ18O Tdo Ts T anomaly Age My Age ky before 2015 δ18O Tdo Ts T anomaly Age My Age ky before 2015 δ18O Tdo Ts T anomaly Age ky before 2015 T T global Age ky before 2015 δ18O Ts T anomaly T global Age ky before 2015 T 1σ Decade Age ky before 2015 T average Year Age ky before 2015 T
t_epica = df_xl.iloc[:,28] * -1.0e3 + 2015.0
ts_epica = df_xl.iloc[:,30]
t_lisiecki = df_xl.iloc[:,22] * -1.0e3 + 2015.0
ts_lisiecki = df_xl.iloc[:,26]
t_zachos = df_xl.iloc[:,15] * -1.0e3 + 2015.0
ts_zachos = df_xl.iloc[:,19]
# CONCATENATE: epochs and store in dataframe
t_paleo = np.array( list(t_epica) + list(t_lisiecki) + list(t_zachos) ).ravel().astype(int)
ts_paleo = np.array( list(ts_epica) + list(ts_lisiecki) + list(ts_zachos) ).ravel()
df_paleo = pd.DataFrame()
df_paleo['t_paleo'] = t_paleo
df_paleo['ts_paleo'] = ts_paleo
# TRIM: to +1 CE
df_paleo = df_paleo[ df_paleo.t_paleo < 1 ].dropna()
#------------------------------------------------------------------------------
# COMPUTE: baseline yearly means from HadCRUT5 ( monthly )
#------------------------------------------------------------------------------
mu_1851_1900 = np.nanmean( df_hadcrut5[(df_hadcrut5['t_hadcrut5']>=1851) & (df_hadcrut5['t_hadcrut5']<=1900)]['ts_hadcrut5'] ) # -0.507873106
mu_1961_1990 = np.nanmean( df_hadcrut5[(df_hadcrut5['t_hadcrut5']>=1961) & (df_hadcrut5['t_hadcrut5']<=1990)]['ts_hadcrut5'] ) # 0.005547222
mu_1971_2000 = np.nanmean( df_hadcrut5[(df_hadcrut5['t_hadcrut5']>=1971) & (df_hadcrut5['t_hadcrut5']<=2000)]['ts_hadcrut5'] ) # 0.176816667
if baselinestr == 'baseline_1851_1900':
mu = mu_1851_1900
baseline_start = 1851
baseline_end = 1900
elif baselinestr == 'baseline_1961_1990':
mu = mu_1961_1990
baseline_start = 1961
baseline_end = 1990
else:
mu = mu_1971_2000
baseline_start = 1971
baseline_end = 2000
baseline_midpoint = baseline_start+int(np.floor(baseline_end-baseline_start)/2)
cbarstr = r'Anomaly, $^{\circ}$C ( from ' + str(baseline_start) + '-' + str(baseline_end) +' )'
#------------------------------------------------------------------------------
# ALIGN: FaIR projections relative to chosen baseline
# NB: FaIR projections are calculated relative to 1880-2015 emission trends and so we
# need to subtract off the difference between the selected baseline and the 1851-1900 baseline
#------------------------------------------------------------------------------
df_fair = df_fair - ( mu - mu_1851_1900 )
#------------------------------------------------------------------------------
# MERGE: dataframes
# NB: PALEO + PAGES2k + HadCRUT5 + FaIR
#------------------------------------------------------------------------------
t = (np.floor(df_paleo.t_paleo).append( | np.floor(df_pages2k.t_pages2k) | numpy.floor |
from tieler.tile_cpp import fill_mesh
from tieler.periodicity import compute_vertex_periodicity
from dolfin import Mesh, info, Timer, CompiledSubDomain
from collections import namedtuple
from copy import deepcopy
import numpy as np
try:
from itertools import izip
except ImportError:
izip = zip
# MAIN IDEA:
# We have x, cells, ... representing a single cell. To get the tile
# repeated ntimes I don't simply stack next to each other.
# Consider 1+1+1+1+1+1+1+1 has 7 additions. But (4+4) where 4 = 2+2 where
# 2 = 1+1 is three! So providided that `+` scales reasonably with input
# size this is more efficient. Here + is really unary. For input other
# than power of 2 it is necessary to extend it to binary, e.g. 5 = (2+2)+1
def powers2(num):
'''List (descending) of powers of two in the number'''
powers = [int(power)
for power, value in enumerate(reversed(format(num, 'b')))
if value != '0']
info('Number of binary + %d' % (len(powers) - 1))
info('Largest tile does %d unary +' % (max(powers) - 1))
return powers[::-1]
# Basic data structure representing tile consists of coordinates and
# cells as indices in to the coord array. master/slave vertices define a
# map for gluing tiles in certain direction. The periodic maps for the
# remaining dirs are in vertex_mappings. Marked entities (encode by their
# vertex numbering) are in data
Tile = namedtuple('Tile', ('coords', 'cells',
'master_vertices', 'slave_vertices', 'mappings',
'data'))
def make_tile(x, cells, master_vertices, slave_vertices, vertex_mappings, data):
'''Freeze the tile from input data.'''
# As the data further evolves I need to make copy
return Tile(deepcopy(x), deepcopy(cells),
np.copy(master_vertices), np.copy(slave_vertices),
[vm.copy() for vm in vertex_mappings],
data.copy())
def merge(x, x_cells, shift, master_vertices, slave_vertices, y=None, y_cells=None):
'''
The + operation for tiles (x, x_cells) [(y, y_cells)]. Tiles are glued
by shifting y by shift. Return x, cells for the resulting merged mesh
and a map from tile y local vertex numbering to the global numbering
of the mesh
'''
if y is None and y_cells is None: y, y_cells = x, x_cells
n = len(y)
# To make the tile piece we add all but the master vertices (as these
# are already (slaves) in x-tile
new_vertices = set(range(n))
new_vertices.difference_update(master_vertices)
new_vertices = np.fromiter(new_vertices, dtype=int)
assert np.all(np.diff(new_vertices) > 0)
# Offset the free
translate = np.empty(n, dtype=int)
translate[new_vertices] = len(x) + np.arange(len(new_vertices))
# Those at master positions take slave values
translate[master_vertices] = slave_vertices
# Verices of the glued tiles
x = np.vstack([x, y[new_vertices] + shift])
# Cells of the glued tiles
new_cells = np.empty_like(y_cells)
new_cells.ravel()[:] = translate[y_cells.flat]
x_cells = np.vstack([x_cells, new_cells])
return x, x_cells, translate
def TileMesh(tile, shape, mesh_data={}, TOL=1E-9):
'''
[tile tile;
tile tile;
tile tile;
tile tile]
The shape is an ntuple describing the number of pieces put next
to each other in the i-th axis. mesh_data : (tdim, tag) -> [entities]
is the way to encode mesh data of the tile.
'''
# Sanity for glueing
gdim = tile.geometry().dim()
assert len(shape) <= gdim, (shape, gdim)
# While evolve is general mesh writing is limited to simplices only (FIXME)
# so we bail out early
assert str(tile.ufl_cell()) in ('interval', 'triangle', 'tetrahedron')
t = Timer('evolve')
# Do nothing
if all(v == 1 for v in shape): return tile, mesh_data
# We want to evolve cells, vertices of the mesh using geometry information
# and periodicity info
x = tile.coordinates()
min_x = np.min(x, axis=0)
max_x = np.max(x, axis=0)
shifts = max_x - min_x
shifts_x = [] # Geometry
vertex_mappings = [] # Periodicity
# Compute geometrical shift for EVERY direction:
for axis in range(len(shape)):
shift = shifts[axis]
# Vector to shift cell vertices
shift_x = np.zeros(gdim); shift_x[axis] = shift
shifts_x.append(shift_x)
# Compute periodicity in the vertices
to_master = lambda x, shift=shift_x: x - shift
# Mapping facets
master = CompiledSubDomain('near(x[i], A, tol)', i=axis, A=min_x[axis], tol=TOL)
slave = CompiledSubDomain('near(x[i], A, tol)', i=axis, A=max_x[axis], tol=TOL)
error, vertex_mapping = compute_vertex_periodicity(tile, master, slave, to_master)
# Fail when exended direction is no periodic
assert error < 10*TOL, error
vertex_mappings.append(vertex_mapping)
# The final piece of information is cells
cells = np.empty((tile.num_cells(), tile.ufl_cell().num_vertices()), dtype='uintp')
cells.ravel()[:] = tile.cells().flat
# Evolve the mesh by tiling along the last direction in shape
while shape:
x, cells, vertex_mappings, shape = \
evolve(x, cells, vertex_mappings, shape, shifts_x, mesh_data=mesh_data)
info('\tEvolve took %g s ' % t.stop())
# We evolve data but the mesh function is made out of it outside
mesh = make_mesh(x, cells, tdim=tile.topology().dim(), gdim=gdim)
return mesh, mesh_data
def evolve(x, cells, vertex_mappings, shape, shifts_x, mesh_data={}):
'''Evolve tile [and its data]along the last axis'''
axis, gdim = len(shape) - 1, x.shape[1]
assert gdim > axis >= 0
# Do nothing for 1
if shape[axis] == 1:
vertex_mappings.pop() # No longer needed
shifts_x.pop() # Do not touch x and cells
return x, cells, vertex_mappings, shape[:-1]
# Glue how many times
refine = shape[axis]
# Get the sizes of tiles (the real sizes are powers of two of these)
# The idea is to do unary + on each base tile and power. Then binary
# + on the resulting tile
tile_sizes = powers2(refine)
# Iff refine was a power of two then there is no need to merge as
# at the end of tile evolution is the final mesh data. Otherwise
# we develop the tiles in their LOCAL numbering => they each start
# from their copy
vertex_mapping, shift_x = vertex_mappings.pop(), shifts_x.pop()
master_vertices = list(vertex_mapping.values())
slave_vertices = list(vertex_mapping.keys())
tiles = []
# Are we even or odd (to keep the initial tile)
if 0 in tile_sizes:
tiles = [make_tile(x, cells,
master_vertices, slave_vertices, vertex_mappings,
mesh_data)]
# Done with this size
tile_sizes.pop()
# We need to evolve tiles of sizes which are power of 2. The idea
# is to get them while evolving to the largest one
size = 1
max_size = max(tile_sizes)
target_size = tile_sizes.pop()
# The body of the loop corresponds to unary +
while size <= max_size:
x, cells, translate = merge(x, cells, shift_x, master_vertices, slave_vertices)
# For the directions that do not evolve we add the new periodic pairs
for vm in vertex_mappings:
keys, values = np.array(list(vm.items())).T
vm.update(dict(izip(translate[keys], translate[values])))
# Update the periodicty mapping - slaves are new
slave_vertices = translate[slave_vertices]
# Add the entities defined in terms of the vertices
if mesh_data: mesh_data = evolve_data(mesh_data, translate)
# We might be at a needed size
if size == target_size:
tiles.append(make_tile(
x, cells, master_vertices, slave_vertices, vertex_mappings, mesh_data))
if tile_sizes: target_size = tile_sizes.pop()
# Iterate
size += 1 # Remember powers of 2 (like divide)
shift_x *= 2 # so we double
assert not tile_sizes
# Now that the tiles are prepare we want to glue them
tile0 = tiles.pop()
# No glueing of one tile
if not tiles:
return tile0.coords, tile0.cells, tile0.mappings, shape[:-1]
# Otherwise extend data of the largest tile
x, cells, vertex_mappings = tile0.coords, tile0.cells, tile0.mappings
slave_vertices = tile0.slave_vertices
# Now the binary +
dx = shift_x / 2**max_size # Recover length of the base tile
shift_x = 0
shifts = (2**p for p in powers2(refine))
while tiles:
next_tile = tiles.pop()
# Shift for next tile to be added to x
shift_x = shift_x + dx*next(shifts)
x, cells, translate = merge(x, cells, shift_x,
next_tile.master_vertices, slave_vertices,
next_tile.coords, next_tile.cells)
# Updata periodicity mappings of next tile using new global map
for vm, next_vm in zip(vertex_mappings, next_tile.mappings):
keys, values = np.array(list(next_vm.items())).T
vm.update(dict(izip(translate[keys], translate[values])))
# Data evolve
if mesh_data: mesh_data = evolve_data(mesh_data, translate, next_tile.data)
# New global slabes
slave_vertices = translate[next_tile.slave_vertices]
return x, cells, vertex_mappings, shape[:-1]
def evolve_data(data, mapping, other=None):
'''
Add data of new tile. A new tile is this one or other. Mapping has
local to global from new tile to the summed tile.
'''
if other is None: other = data
for key in data.keys():
old = data[key]
new = np.empty_like(other[key])
new.ravel()[:] = mapping[other[key].flat]
data[key] = | np.vstack([old, new]) | numpy.vstack |
from typing import Sequence, Union
import numpy as np
import scipy.stats
from .registry import registry
from sklearn.preprocessing import normalize
@registry.register_metric('mse')
def mean_squared_error(target: Sequence[float],
prediction: Sequence[float]) -> float:
target_array = np.asarray(target)
prediction_array = np.asarray(prediction)
return np.mean(np.square(target_array - prediction_array))
@registry.register_metric('mae')
def mean_absolute_error(target: Sequence[float],
prediction: Sequence[float]) -> float:
target_array = np.asarray(target)
prediction_array = np.asarray(prediction)
return np.mean(np.abs(target_array - prediction_array))
@registry.register_metric('spearmanr')
def spearmanr(target: Sequence[float],
prediction: Sequence[float]) -> float:
target_array = np.asarray(target)
prediction_array = | np.asarray(prediction) | numpy.asarray |
"""
Defines functions used to construct basis vectors, convert between coordinate systems, build meshes, etc.
"""
import miepy
import numpy as np
def sph_to_cart(r, theta, phi, origin=None):
"""convert spherical coordinates (r, theta, phi) centered at origin to cartesian coordinates (x, y, z)"""
if origin is None:
origin = np.zeros(3, dtype=float)
x = origin[0] + r*np.sin(theta)*np.cos(phi)
y = origin[1] + r*np.sin(theta)*np.sin(phi)
z = origin[2] + r*np.cos(theta)
return x,y,z
def cart_to_sph(x, y, z, origin=None):
"""convert cartesian coordinates (x, y, z) to spherical coordinates (r, theta, phi) centered at origin"""
if origin is None:
origin = np.zeros(3, dtype=float)
x0,y0,z0 = origin
r = ((x - x0)**2 + (y - y0)**2 + (z - z0)**2)**0.5
theta = np.arccos((z - z0)/r)
phi = np.arctan2(y - y0, x - x0)
return r, theta, phi
def cyl_to_cart(r, phi, z, origin=None):
"""convert cylindrical coordinates (r, phi, z) centered at origin to cartesian coordinates (x, y, z)"""
if origin is None:
origin = np.zeros(3, dtype=float)
x = origin[0] + r*np.cos(phi)
y = origin[1] + r*np.sin(phi)
return x, y, z + origin[2]
def cart_to_cyl(x, y, z, origin=None):
"""convert cartesian coordinates (x, y, z) to cylindrical coordinates (r, phi, z) centered at origin"""
if origin is None:
origin = np.zeros(3, dtype=float)
x0,y0,z0 = origin
r = ((x - x0)**2 + (y - y0)**2)**0.5
phi = np.arctan2(y - y0, x - x0)
return r, phi, z - z0
#TODO: if theta is scalar, or phi is scalar... same with other functions here
#TODO: implement origin
def sph_basis_vectors(theta, phi, origin=None):
"""obtain the spherical basis vectors (r_hat, theta_hat, phi_hat) for given theta, phi"""
if origin is None:
origin = np.zeros(3, dtype=float)
r_hat = np.array([np.sin(theta)*np.cos(phi), np.sin(theta)*np.sin(phi), np.cos(theta)])
theta_hat = np.array([np.cos(theta)*np.cos(phi), np.cos(theta)*np.sin(phi), -1*np.sin(theta)])
phi_hat = np.array([-1*np.sin(phi), np.cos(phi), np.zeros_like(phi)])
return r_hat, theta_hat, phi_hat
#TODO: implement origin
def vec_cart_to_sph(F, theta, phi, origin=None):
"""convert a vector field F from cartesian to spherical coordinates
Arguments:
F[3,...] vector field values
theta theta coordinates
phi phi coordinates
"""
if origin is None:
origin = np.zeros(3, dtype=float)
Fsph = np.zeros_like(F)
r_hat, theta_hat, phi_hat = sph_basis_vectors(theta, phi)
Fsph[0] = np.sum(F*r_hat, axis=0)
Fsph[1] = np.sum(F*theta_hat, axis=0)
Fsph[2] = np.sum(F*phi_hat, axis=0)
return Fsph
#TODO: implement origin
def vec_sph_to_cart(F, theta, phi, origin=None):
"""convert a vector field F from spherical to cartesian coordinates
Arguments:
F[3,...] vector field values
theta theta coordinates
phi phi coordinates
"""
if origin is None:
origin = np.zeros(3, dtype=float)
Fcart = np.zeros_like(F)
r_hat, theta_hat, phi_hat = sph_basis_vectors(theta, phi)
for i in range(3):
Fcart[i] = F[0]*r_hat[i] + F[1]*theta_hat[i] + F[2]*phi_hat[i]
return Fcart
def sphere_mesh(sampling):
"""
Obtain a THETA,PHI mesh for discretizing the surface of the sphere, consistent
with the format required by the project and decompose functions
Returns (THETA,PHI) meshgrids
Arguments:
sampling number of points to sample between 0 and pi
"""
phi = np.linspace(0, 2*np.pi, 2*sampling)
tau = np.linspace(-1, 1, sampling)
theta = np.arccos(tau)
THETA,PHI = | np.meshgrid(theta, phi, indexing='ij') | numpy.meshgrid |
from typing import Tuple, Dict, Any, Union, Callable
import numpy as np
import scipy.ndimage as ndi
from common.exceptionmanager import catch_error_exception
from common.functionutil import ImagesUtil
from preprocessing.imagegenerator import ImageGenerator
_epsilon = 1e-6
class TransformRigidImages(ImageGenerator):
def __init__(self,
size_image: Union[Tuple[int, int, int], Tuple[int, int]],
is_normalize_data: bool = False,
type_normalize_data: str = 'samplewise',
is_zca_whitening: bool = False,
is_inverse_transform: bool = False,
rescale_factor: float = None,
preprocessing_function: Callable[[np.ndarray], np.ndarray] = None
) -> None:
super(TransformRigidImages, self).__init__(size_image, num_images=1)
if is_normalize_data:
if type_normalize_data == 'featurewise':
self._featurewise_center = True
self._featurewise_std_normalization = True
self._samplewise_center = False
self._samplewise_std_normalization = False
else:
# type_normalize_data == 'samplewise'
self._featurewise_center = False
self._featurewise_std_normalization = False
self._samplewise_center = True
self._samplewise_std_normalization = True
else:
self._featurewise_center = False
self._featurewise_std_normalization = False
self._samplewise_center = False
self._samplewise_std_normalization = False
self._is_zca_whitening = is_zca_whitening
self._zca_epsilon = 1e-6
self._rescale_factor = rescale_factor
self._preprocessing_function = preprocessing_function
self._mean = None
self._std = None
self._principal_components = None
self._is_inverse_transform = is_inverse_transform
self._initialize_gendata()
def update_image_data(self, in_shape_image: Tuple[int, ...]) -> None:
# self._num_images = in_shape_image[0]
pass
def _initialize_gendata(self) -> None:
self._transform_matrix = None
self._transform_params = None
self._count_trans_in_images = 0
def _update_gendata(self, **kwargs) -> None:
seed = kwargs['seed']
(self._transform_matrix, self._transform_params) = self._calc_gendata_random_transform(seed)
self._count_trans_in_images = 0
def _get_image(self, in_image: np.ndarray) -> np.ndarray:
is_type_input_image = (self._count_trans_in_images == 0)
self._count_trans_in_images += 1
return self._get_transformed_image(in_image, is_type_input_image=is_type_input_image)
def _get_transformed_image(self, in_image: np.ndarray, is_type_input_image: bool = False) -> np.ndarray:
if ImagesUtil.is_without_channels(self._size_image, in_image.shape):
in_image = np.expand_dims(in_image, axis=-1)
is_reshape_input_image = True
else:
is_reshape_input_image = False
in_image = self._calc_transformed_image(in_image, is_type_input_image=is_type_input_image)
if is_type_input_image:
in_image = self._standardize(in_image)
if is_reshape_input_image:
in_image = np.squeeze(in_image, axis=-1)
return in_image
def _get_inverse_transformed_image(self, in_image: np.ndarray, is_type_input_image: bool = False) -> np.ndarray:
if ImagesUtil.is_without_channels(self._size_image, in_image.shape):
in_image = np.expand_dims(in_image, axis=-1)
is_reshape_input_image = True
else:
is_reshape_input_image = False
if is_type_input_image:
in_image = self._standardize_inverse(in_image)
in_image = self._calc_inverse_transformed_image(in_image, is_type_input_image=is_type_input_image)
if is_reshape_input_image:
in_image = np.squeeze(in_image, axis=-1)
return in_image
def _calc_transformed_image(self, in_array: np.ndarray, is_type_input_image: bool = False) -> np.ndarray:
raise NotImplementedError
def _calc_inverse_transformed_image(self, in_array: np.ndarray, is_type_input_image: bool = False) -> np.ndarray:
raise NotImplementedError
def _calc_gendata_random_transform(self, seed: int = None) -> Tuple[np.ndarray, Dict[str, Any]]:
raise NotImplementedError
def _calc_gendata_inverse_random_transform(self, seed: int = None) -> Tuple[np.ndarray, Dict[str, Any]]:
raise NotImplementedError
def _standardize(self, in_image: np.ndarray) -> np.ndarray:
if self._preprocessing_function:
in_image = self._preprocessing_function(in_image)
if self._rescale_factor:
in_image *= self._rescale_factor
if self._samplewise_center:
in_image -= np.mean(in_image, keepdims=True)
if self._samplewise_std_normalization:
in_image /= (np.std(in_image, keepdims=True) + _epsilon)
template_message_error = 'This ImageDataGenerator specifies \'%s\', but it hasn\'t been fit on any ' \
'training data. Fit it first by calling \'fit(numpy_data)\'.'
if self._featurewise_center:
if self._mean is not None:
in_image -= self._mean
else:
message = template_message_error % ('featurewise_center')
catch_error_exception(message)
if self._featurewise_std_normalization:
if self._std is not None:
in_image /= (self._std + _epsilon)
else:
message = template_message_error % ('featurewise_std_normalization')
catch_error_exception(template_message_error % (message))
if self._is_zca_whitening:
if self._principal_components is not None:
flatx = np.reshape(in_image, (-1, np.prod(in_image.shape[-3:])))
whitex = np.dot(flatx, self._principal_components)
in_image = np.reshape(whitex, in_image.shape)
else:
message = template_message_error % ('zca_whitening')
catch_error_exception(message)
return in_image
def _standardize_inverse(self, in_image: np.ndarray) -> np.ndarray:
template_message_error = 'This ImageDataGenerator specifies \'%s\', but it hasn\'t been fit on any ' \
'training data. Fit it first by calling \'fit(numpy_data)\'.'
if self._is_zca_whitening:
if self._principal_components is not None:
flatx = np.reshape(in_image, (-1, np.prod(in_image.shape[-3:])))
inverse_principal_componens = np.divide(1.0, self._principal_components)
whitex = np.dot(flatx, inverse_principal_componens)
in_image = np.reshape(whitex, in_image.shape)
else:
message = template_message_error % ('zca_whitening')
catch_error_exception(message)
if self._featurewise_std_normalization:
if self._std is not None:
in_image *= self._std
else:
message = template_message_error % ('featurewise_std_normalization')
catch_error_exception(message)
if self._featurewise_center:
if self._mean is not None:
in_image += self._mean
else:
message = template_message_error % ('featurewise_center')
catch_error_exception(message)
if self._samplewise_std_normalization:
in_image *= np.std(in_image, keepdims=True)
if self._samplewise_center:
in_image += np.mean(in_image, keepdims=True)
if self._rescale_factor:
in_image /= self._rescale_factor
if self._preprocessing_function:
catch_error_exception('Not implemented inverse preprocessing function')
return in_image
@staticmethod
def _flip_axis(in_image: np.ndarray, axis: int) -> np.ndarray:
in_image = np.asarray(in_image).swapaxes(axis, 0)
in_image = in_image[::-1, ...]
in_image = in_image.swapaxes(0, axis)
return in_image
@staticmethod
def _apply_channel_shift(in_image: np.ndarray, intensity: int, channel_axis: int = 0) -> np.ndarray:
in_image = np.rollaxis(in_image, channel_axis, 0)
min_x, max_x = np.min(in_image), np.max(in_image)
channel_images = [np.clip(x_channel + intensity, min_x, max_x) for x_channel in in_image]
in_image = np.stack(channel_images, axis=0)
in_image = np.rollaxis(in_image, 0, channel_axis + 1)
return in_image
def _apply_brightness_shift(self, in_image: np.ndarray, brightness: int) -> np.ndarray:
catch_error_exception('Not implemented brightness shifting option...')
# in_image = array_to_img(in_image)
# in_image = imgenhancer_Brightness = ImageEnhance.Brightness(in_image)
# in_image = imgenhancer_Brightness.enhance(brightness)
# in_image = img_to_array(in_image)
def get_text_description(self) -> str:
raise NotImplementedError
class TransformRigidImages2D(TransformRigidImages):
_img_row_axis = 0
_img_col_axis = 1
_img_channel_axis = 2
def __init__(self,
size_image: Tuple[int, int],
is_normalize_data: bool = False,
type_normalize_data: str = 'samplewise',
is_zca_whitening: bool = False,
rotation_range: float = 0.0,
width_shift_range: float = 0.0,
height_shift_range: float = 0.0,
brightness_range: Tuple[float, float] = None,
shear_range: float = 0.0,
zoom_range: Union[float, Tuple[float, float]] = 0.0,
channel_shift_range: float = 0.0,
fill_mode: str = 'nearest',
cval: float = 0.0,
horizontal_flip: bool = False,
vertical_flip: bool = False,
rescale_factor: float = None,
preprocessing_function: Callable[[np.ndarray], np.ndarray] = None
) -> None:
self._rotation_range = rotation_range
self._width_shift_range = width_shift_range
self._height_shift_range = height_shift_range
self._brightness_range = brightness_range
self._shear_range = shear_range
self._channel_shift_range = channel_shift_range
self._fill_mode = fill_mode
self._cval = cval
self._horizontal_flip = horizontal_flip
self._vertical_flip = vertical_flip
if np.isscalar(zoom_range):
self._zoom_range = (1 - zoom_range, 1 + zoom_range)
elif len(zoom_range) == 2:
self._zoom_range = (zoom_range[0], zoom_range[1])
else:
message = '\'zoom_range\' should be a float or a tuple of two floats. Received %s' % (str(zoom_range))
catch_error_exception(message)
if self._brightness_range is not None:
if len(self._brightness_range) != 2:
message = '\'brightness_range\' should be a tuple of two floats. Received %s' % (str(brightness_range))
catch_error_exception(message)
super(TransformRigidImages2D, self).__init__(size_image,
is_normalize_data=is_normalize_data,
type_normalize_data=type_normalize_data,
is_zca_whitening=is_zca_whitening,
rescale_factor=rescale_factor,
preprocessing_function=preprocessing_function)
def _calc_transformed_image(self, in_image: np.ndarray, is_type_input_image: bool = False) -> np.ndarray:
# Apply: 1st: rigid transformations
# 2nd: channel shift intensity / flipping
if self._transform_matrix is not None:
in_image = self._apply_transform(in_image, self._transform_matrix,
channel_axis=self._img_channel_axis,
fill_mode=self._fill_mode, cval=self._cval)
if is_type_input_image and (self._transform_params.get('channel_shift_intensity') is not None):
in_image = self._apply_channel_shift(in_image, self._transform_params['channel_shift_intensity'],
channel_axis=self._img_channel_axis)
if self._transform_params.get('flip_horizontal', False):
in_image = self._flip_axis(in_image, axis=self._img_col_axis)
if self._transform_params.get('flip_vertical', False):
in_image = self._flip_axis(in_image, axis=self._img_row_axis)
if is_type_input_image and (self._transform_params.get('brightness') is not None):
in_image = self._apply_brightness_shift(in_image, self._transform_params['brightness'])
return in_image
def _calc_inverse_transformed_image(self, in_image: np.ndarray, is_type_input_image: bool = False) -> np.ndarray:
# Apply: 1st: channel shift intensity / flipping
# 2nd: rigid transformations
if is_type_input_image and (self._transform_params.get('brightness') is not None):
in_image = self._apply_brightness_shift(in_image, self._transform_params['brightness'])
if self._transform_params.get('flip_vertical', False):
in_image = self._flip_axis(in_image, axis=self._img_row_axis)
if self._transform_params.get('flip_horizontal', False):
in_image = self._flip_axis(in_image, axis=self._img_col_axis)
if is_type_input_image and (self._transform_params.get('channel_shift_intensity') is not None):
in_image = self._apply_channel_shift(in_image, self._transform_params['channel_shift_intensity'],
channel_axis=self._img_channel_axis)
if self._transform_matrix is not None:
in_image = self._apply_transform(in_image, self._transform_matrix,
channel_axis=self._img_channel_axis,
fill_mode=self._fill_mode, cval=self._cval)
return in_image
def _calc_gendata_random_transform(self, seed: int = None) -> Tuple[np.ndarray, Dict[str, Any]]:
# compute composition of homographies
if seed is not None:
np.random.seed(seed)
# ****************************************************
if self._rotation_range:
theta = np.deg2rad(np.random.uniform(-self._rotation_range, self._rotation_range))
else:
theta = 0
if self._height_shift_range:
tx = np.random.uniform(-self._height_shift_range, self._height_shift_range)
if np.max(self._height_shift_range) < 1:
tx *= self._size_image[self._img_row_axis]
else:
tx = 0
if self._width_shift_range:
ty = np.random.uniform(-self._width_shift_range, self._width_shift_range)
if np.max(self._width_shift_range) < 1:
ty *= self._size_image[self._img_col_axis]
else:
ty = 0
if self._shear_range:
shear = np.deg2rad(np.random.uniform(-self._shear_range, self._shear_range))
else:
shear = 0
if self._zoom_range[0] == 1 and self._zoom_range[1] == 1:
zx, zy = 1, 1
else:
zx, zy = np.random.uniform(self._zoom_range[0], self._zoom_range[1], 2)
flip_horizontal = (np.random.random() < 0.5) * self._horizontal_flip
flip_vertical = (np.random.random() < 0.5) * self._vertical_flip
channel_shift_intensity = None
if self._channel_shift_range != 0:
channel_shift_intensity = np.random.uniform(-self._channel_shift_range, self._channel_shift_range)
brightness = None
if self._brightness_range is not None:
brightness = np.random.uniform(self._brightness_range[0], self._brightness_range[1])
transform_parameters = {'flip_horizontal': flip_horizontal,
'flip_vertical': flip_vertical,
'channel_shift_intensity': channel_shift_intensity,
'brightness': brightness}
# ****************************************************
# ****************************************************
transform_matrix = None
if theta != 0:
rotation_matrix = np.array([[np.cos(theta), -np.sin(theta), 0],
[np.sin(theta), np.cos(theta), 0],
[0, 0, 1]])
transform_matrix = rotation_matrix
if tx != 0 or ty != 0:
shift_matrix = np.array([[1, 0, tx],
[0, 1, ty],
[0, 0, 1]])
transform_matrix = shift_matrix if transform_matrix is None else np.dot(transform_matrix, shift_matrix)
if shear != 0:
shear_matrix = np.array([[1, -np.sin(shear), 0],
[0, np.cos(shear), 0],
[0, 0, 1]])
transform_matrix = shear_matrix if transform_matrix is None else np.dot(transform_matrix, shear_matrix)
if zx != 1 or zy != 1:
zoom_matrix = np.array([[zx, 0, 0],
[0, zy, 0],
[0, 0, 1]])
transform_matrix = zoom_matrix if transform_matrix is None else np.dot(transform_matrix, zoom_matrix)
if transform_matrix is not None:
h, w = self._size_image[self._img_row_axis], self._size_image[self._img_col_axis]
transform_matrix = self._transform_matrix_offset_center(transform_matrix, h, w)
# ****************************************************
return (transform_matrix, transform_parameters)
def _calc_gendata_inverse_random_transform(self, seed: int = None) -> Tuple[np.ndarray, Dict[str, Any]]:
# compute composition of inverse homographies
if seed is not None:
np.random.seed(seed)
# ****************************************************
if self._rotation_range:
theta = np.deg2rad(np.random.uniform(-self._rotation_range, self._rotation_range))
else:
theta = 0
if self._height_shift_range:
tx = np.random.uniform(-self._height_shift_range, self._height_shift_range)
if self._height_shift_range < 1:
tx *= self._size_image[self._img_row_axis]
else:
tx = 0
if self._width_shift_range:
ty = np.random.uniform(-self._width_shift_range, self._width_shift_range)
if self._width_shift_range < 1:
ty *= self._size_image[self._img_col_axis]
else:
ty = 0
if self._shear_range:
shear = np.deg2rad(np.random.uniform(-self._shear_range, self._shear_range))
else:
shear = 0
if self._zoom_range[0] == 1 and self._zoom_range[1] == 1:
zx, zy = 1, 1
else:
zx, zy = np.random.uniform(self._zoom_range[0], self._zoom_range[1], 2)
flip_horizontal = (np.random.random() < 0.5) * self._horizontal_flip
flip_vertical = (np.random.random() < 0.5) * self._vertical_flip
channel_shift_intensity = None
if self._channel_shift_range != 0:
channel_shift_intensity = np.random.uniform(-self._channel_shift_range, self._channel_shift_range)
brightness = None
if self._brightness_range is not None:
brightness = np.random.uniform(self._brightness_range[0], self._brightness_range[1])
transform_parameters = {'flip_horizontal': flip_horizontal,
'flip_vertical': flip_vertical,
'channel_shift_intensity': channel_shift_intensity,
'brightness': brightness}
# ****************************************************
# ****************************************************
transform_matrix = None
if theta != 0:
rotation_matrix = np.array([[np.cos(theta), np.sin(theta), 0],
[-np.sin(theta), np.cos(theta), 0],
[0, 0, 1]])
transform_matrix = rotation_matrix
if tx != 0 or ty != 0:
shift_matrix = np.array([[1, 0, -tx],
[0, 1, -ty],
[0, 0, 1]])
transform_matrix = shift_matrix if transform_matrix is None else np.dot(transform_matrix, shift_matrix)
if shear != 0:
shear_matrix = np.array([[1, np.tan(shear), 0],
[0, 1.0 / np.cos(shear), 0],
[0, 0, 1]])
transform_matrix = shear_matrix if transform_matrix is None else np.dot(transform_matrix, shear_matrix)
if zx != 1 or zy != 1:
zoom_matrix = np.array([[1.0 / zx, 0, 0],
[0, 1.0 / zy, 0],
[0, 0, 1]])
transform_matrix = zoom_matrix if transform_matrix is None else np.dot(transform_matrix, zoom_matrix)
if transform_matrix is not None:
h, w = self._size_image[self._img_row_axis], self._size_image[self._img_col_axis]
transform_matrix = self._transform_matrix_offset_center(transform_matrix, h, w)
# ****************************************************
return (transform_matrix, transform_parameters)
@staticmethod
def _transform_matrix_offset_center(matrix: np.ndarray, x: int, y: int) -> np.ndarray:
o_x = float(x) / 2 + 0.5
o_y = float(y) / 2 + 0.5
offset_matrix = np.array([[1, 0, o_x], [0, 1, o_y], [0, 0, 1]])
reset_matrix = np.array([[1, 0, -o_x], [0, 1, -o_y], [0, 0, 1]])
transform_matrix = np.dot(np.dot(offset_matrix, matrix), reset_matrix)
return transform_matrix
@staticmethod
def _apply_transform(in_image: np.ndarray, transform_matrix: np.ndarray,
channel_axis: int = 0, fill_mode: str = 'nearest', cval: float = 0.0) -> np.ndarray:
in_image = np.rollaxis(in_image, channel_axis, 0)
final_affine_matrix = transform_matrix[:2, :2]
final_offset = transform_matrix[:2, 2]
channel_images = [ndi.interpolation.affine_transform(x_channel, final_affine_matrix, final_offset, order=1,
mode=fill_mode, cval=cval) for x_channel in in_image]
in_image = np.stack(channel_images, axis=0)
in_image = np.rollaxis(in_image, 0, channel_axis + 1)
return in_image
def get_text_description(self) -> str:
message = 'Rigid 2D transformations of images, with parameters...\n'
message += 'rotation (plane_XY) range: \'%s\'...\n' % (self._rotation_range)
message += 'shift (width, height) range: \'(%s, %s)\'...\n' \
% (self._width_shift_range, self._height_shift_range)
message += 'flip (horizontal, vertical): \'(%s, %s)\'...\n' \
% (self._horizontal_flip, self._vertical_flip)
message += 'zoom (min, max) range: \'(%s, %s)\'...\n' % (self._zoom_range[0], self._zoom_range[1])
message += 'shear (plane_XY) range: \'%s\'...\n' % (self._shear_range)
message += 'fill mode, when applied transformation: \'%s\'...\n' % (self._fill_mode)
return message
class TransformRigidImages3D(TransformRigidImages):
_img_dep_axis = 0
_img_row_axis = 1
_img_col_axis = 2
_img_channel_axis = 3
def __init__(self,
size_image: Tuple[int, int, int],
is_normalize_data: bool = False,
type_normalize_data: str = 'samplewise',
is_zca_whitening: bool = False,
rotation_xy_range: float = 0.0,
rotation_xz_range: float = 0.0,
rotation_yz_range: float = 0.0,
width_shift_range: float = 0.0,
height_shift_range: float = 0.0,
depth_shift_range: float = 0.0,
brightness_range: Tuple[float, float] = None,
shear_xy_range: float = 0.0,
shear_xz_range: float = 0.0,
shear_yz_range: float = 0.0,
zoom_range: Union[float, Tuple[float, float]] = 0.0,
channel_shift_range: float = 0.0,
fill_mode: str = 'nearest',
cval: float = 0.0,
horizontal_flip: bool = False,
vertical_flip: bool = False,
axialdir_flip: bool = False,
rescale_factor: float = None,
preprocessing_function: Callable[[np.ndarray], np.ndarray] = None
) -> None:
self._rotation_xy_range = rotation_xy_range
self._rotation_xz_range = rotation_xz_range
self._rotation_yz_range = rotation_yz_range
self._width_shift_range = width_shift_range
self._height_shift_range = height_shift_range
self._depth_shift_range = depth_shift_range
self._brightness_range = brightness_range
self._shear_xy_range = shear_xy_range
self._shear_xz_range = shear_xz_range
self._shear_yz_range = shear_yz_range
self._channel_shift_range = channel_shift_range
self._fill_mode = fill_mode
self._cval = cval
self._horizontal_flip = horizontal_flip
self._vertical_flip = vertical_flip
self._axialdir_flip = axialdir_flip
if np.isscalar(zoom_range):
self._zoom_range = (1 - zoom_range, 1 + zoom_range)
elif len(zoom_range) == 2:
self._zoom_range = (zoom_range[0], zoom_range[1])
else:
message = '\'zoom_range\' should be a float or a tuple of two floats. Received %s' % (str(zoom_range))
catch_error_exception(message)
if self._brightness_range is not None:
if len(self._brightness_range) != 2:
message = '\'brightness_range\' should be a tuple of two floats. Received %s' % (str(brightness_range))
catch_error_exception(message)
super(TransformRigidImages3D, self).__init__(size_image,
is_normalize_data=is_normalize_data,
type_normalize_data=type_normalize_data,
is_zca_whitening=is_zca_whitening,
rescale_factor=rescale_factor,
preprocessing_function=preprocessing_function)
def _calc_transformed_image(self, in_image: np.ndarray, is_type_input_image: bool = False) -> np.ndarray:
# Apply: 1st: rigid transformations
# 2nd: channel shift intensity / flipping
if self._transform_matrix is not None:
in_image = self._apply_transform(in_image, self._transform_matrix,
channel_axis=self._img_channel_axis,
fill_mode=self._fill_mode, cval=self._cval)
if is_type_input_image and (self._transform_params.get('channel_shift_intensity') is not None):
in_image = self._apply_channel_shift(in_image, self._transform_params['channel_shift_intensity'],
channel_axis=self._img_channel_axis)
if self._transform_params.get('flip_horizontal', False):
in_image = self._flip_axis(in_image, axis=self._img_col_axis)
if self._transform_params.get('flip_vertical', False):
in_image = self._flip_axis(in_image, axis=self._img_row_axis)
if self._transform_params.get('flip_axialdir', False):
in_image = self._flip_axis(in_image, axis=self._img_dep_axis)
if is_type_input_image and (self._transform_params.get('brightness') is not None):
in_image = self._apply_brightness_shift(in_image, self._transform_params['brightness'])
return in_image
def _calc_inverse_transformed_image(self, in_image: np.ndarray, is_type_input_image: bool = False) -> np.ndarray:
# Apply: 1st: channel shift intensity / flipping
# 2nd: rigid transformations
if is_type_input_image and (self._transform_params.get('brightness') is not None):
in_image = self._apply_brightness_shift(in_image, self._transform_params['brightness'])
if self._transform_params.get('flip_axialdir', False):
in_image = self._flip_axis(in_image, axis=self._img_dep_axis)
if self._transform_params.get('flip_vertical', False):
in_image = self._flip_axis(in_image, axis=self._img_row_axis)
if self._transform_params.get('flip_horizontal', False):
in_image = self._flip_axis(in_image, axis=self._img_col_axis)
if is_type_input_image and (self._transform_params.get('channel_shift_intensity') is not None):
in_image = self._apply_channel_shift(in_image, self._transform_params['channel_shift_intensity'],
channel_axis=self._img_channel_axis)
if self._transform_matrix is not None:
in_image = self._apply_transform(in_image, self._transform_matrix,
channel_axis=self._img_channel_axis,
fill_mode=self._fill_mode, cval=self._cval)
return in_image
def _calc_gendata_random_transform(self, seed: int = None) -> Tuple[np.ndarray, Dict[str, Any]]:
# compute composition of homographies
if seed is not None:
np.random.seed(seed)
# ****************************************************
if self._rotation_xy_range:
angle_xy = np.deg2rad(np.random.uniform(-self._rotation_xy_range, self._rotation_xy_range))
else:
angle_xy = 0
if self._rotation_xz_range:
angle_xz = np.deg2rad(np.random.uniform(-self._rotation_xz_range, self._rotation_xz_range))
else:
angle_xz = 0
if self._rotation_yz_range:
angle_yz = np.deg2rad(np.random.uniform(-self._rotation_yz_range, self._rotation_yz_range))
else:
angle_yz = 0
if self._height_shift_range:
tx = np.random.uniform(-self._height_shift_range, self._height_shift_range)
if self._height_shift_range < 1:
tx *= self._size_image[self._img_row_axis]
else:
tx = 0
if self._width_shift_range:
ty = np.random.uniform(-self._width_shift_range, self._width_shift_range)
if self._width_shift_range < 1:
ty *= self._size_image[self._img_col_axis]
else:
ty = 0
if self._depth_shift_range:
tz = np.random.uniform(-self._depth_shift_range, self._depth_shift_range)
if self._depth_shift_range < 1:
tz *= self._size_image[self._img_dep_axis]
else:
tz = 0
if self._shear_xy_range:
shear_xy = np.deg2rad(np.random.uniform(-self._shear_xy_range, self._shear_xy_range))
else:
shear_xy = 0
if self._shear_xz_range:
shear_xz = np.deg2rad(np.random.uniform(-self._shear_xz_range, self._shear_xz_range))
else:
shear_xz = 0
if self._shear_yz_range:
shear_yz = np.deg2rad(np.random.uniform(-self._shear_yz_range, self._shear_yz_range))
else:
shear_yz = 0
if self._zoom_range[0] == 1 and self._zoom_range[1] == 1:
(zx, zy, zz) = (1, 1, 1)
else:
(zx, zy, zz) = np.random.uniform(self._zoom_range[0], self._zoom_range[1], 3)
flip_horizontal = (np.random.random() < 0.5) * self._horizontal_flip
flip_vertical = (np.random.random() < 0.5) * self._vertical_flip
flip_axialdir = (np.random.random() < 0.5) * self._axialdir_flip
channel_shift_intensity = None
if self._channel_shift_range != 0:
channel_shift_intensity = np.random.uniform(-self._channel_shift_range, self._channel_shift_range)
brightness = None
if self._brightness_range is not None:
brightness = np.random.uniform(self._brightness_range[0], self._brightness_range[1])
transform_parameters = {'flip_horizontal': flip_horizontal,
'flip_vertical': flip_vertical,
'flip_axialdir': flip_axialdir,
'channel_shift_intensity': channel_shift_intensity,
'brightness': brightness}
# ****************************************************
# ****************************************************
transform_matrix = None
if angle_xy != 0:
rotation_matrix = np.array([[1, 0, 0, 0],
[0, np.cos(angle_xy), -np.sin(angle_xy), 0],
[0, np.sin(angle_xy), np.cos(angle_xy), 0],
[0, 0, 0, 1]])
transform_matrix = rotation_matrix
if angle_xz != 0:
rotation_matrix = np.array([[np.cos(angle_xz), np.sin(angle_xz), 0, 0],
[-np.sin(angle_xz), np.cos(angle_xz), 0, 0],
[0, 0, 1, 0],
[0, 0, 0, 1]])
transform_matrix = \
rotation_matrix if transform_matrix is None else np.dot(transform_matrix, rotation_matrix)
if angle_yz != 0:
rotation_matrix = np.array([[np.cos(angle_yz), 0, np.sin(angle_yz), 0],
[0, 1, 0, 0],
[-np.sin(angle_yz), 0, np.cos(angle_yz), 0],
[0, 0, 0, 1]])
transform_matrix = \
rotation_matrix if transform_matrix is None else np.dot(transform_matrix, rotation_matrix)
if tx != 0 or ty != 0 or tz != 0:
shift_matrix = np.array([[1, 0, 0, tz],
[0, 1, 0, tx],
[0, 0, 1, ty],
[0, 0, 0, 1]])
transform_matrix = shift_matrix if transform_matrix is None else np.dot(transform_matrix, shift_matrix)
if shear_xy != 0:
shear_matrix = np.array([[1, 0, 0, 0],
[0, 1, -np.sin(shear_xy), 0],
[0, 0, np.cos(shear_xy), 0],
[0, 0, 0, 1]])
transform_matrix = shear_matrix if transform_matrix is None else np.dot(transform_matrix, shear_matrix)
if shear_xz != 0:
shear_matrix = np.array([[np.cos(shear_xz), 0, 0, 0],
[-np.sin(shear_xz), 1, 0, 0],
[0, 0, 1, 0],
[0, 0, 0, 1]])
transform_matrix = shear_matrix if transform_matrix is None else | np.dot(transform_matrix, shear_matrix) | numpy.dot |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.4'
# jupytext_version: 1.1.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # S_rSquareData [<img src="https://www.arpm.co/lab/icons/icon_permalink.png" width=30 height=30 style="display: inline;">](https://www.arpm.co/lab/redirect.php?code=S_rSquareData&codeLang=Python)
# For details, see [here](https://www.arpm.co/lab/redirect.php?permalink=eb-ex-unv-rsquare).
# ## Prepare the environment
# +
import os
import os.path as path
import sys
sys.path.append(path.abspath('../../functions-legacy'))
from numpy import ones, round, log, sqrt
from numpy import sum as npsum
import numpy as np
np.seterr(divide='ignore')
from scipy.io import loadmat
import matplotlib.pyplot as plt
plt.style.use('seaborn')
from CONFIG import GLOBAL_DB, TEMPORARY_DB
from MultivRsquare import MultivRsquare
# input parameters
try:
db = loadmat(os.path.join(GLOBAL_DB, 'db_ExSummary'), squeeze_me=True)
except FileNotFoundError:
db = loadmat(os.path.join(TEMPORARY_DB, 'db_ExSummary'), squeeze_me=True)
t_ = db['t_']
epsi = db['epsi']
v = db['v']
j_ = t_ # dimension of data set
p = ones((1, j_)) / j_ # uniform Flexible Probabilities
x = epsi[0] # model data
x_tilde = epsi[1] # fit data
# log values
y = round(log(v[0, 1:])) # model data
y_tilde = round(log(v[1, 1:])) # fit data
z = x_tilde
# -
# ## Compute the residuals
u_x = x - x_tilde
u_y = y - y_tilde
# ## Compute the data mean and variance
# +
m_x = npsum(p * x)
m_y = | npsum(p * y) | numpy.sum |
#!/usr/bin/env python
from __future__ import absolute_import, print_function
import numpy as np
import IPython
UNCERTAINTIES_AVAIL = True
try:
import uncertainties
except ImportError:
UNCERTAINTIES_AVAIL = False
__author__ = "<NAME>"
__email__ = "<EMAIL>"
__copyright__ = "Copyright 2014 <NAME>"
__credits__ = ["<NAME>"]
__license__ = """Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including without
limitation the rights to use, copy, modify, merge, publish, distribute,
sublicense, and/or sell copies of the Software, and to permit persons to whom
the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE."""
def TeX(s):
return r'$' + s + r'$'
def smartFormat(x, sigFigs=7, sciThresh=(7, 6), keepAllSigFigs=False,
alignOnDec=False, threeSpacing=True, alwaysShowSign=False,
forcedExp=None, demarc=r'$', alignChar=r"&",
leftSep=r"{,}", rightSep=r"{\,}", decSep=r".",
nanSub=r"--", inftyThresh=np.infty,
expLeftFmt=r"{\times 10^{", expRightFmt=r"}}"):
if hasattr(x, '__iter__'):
is_iterable = True
vals = x
else:
is_iterable = False
vals = [x]
return_vals = []
for val in vals:
effectivelyZero = False
if UNCERTAINTIES_AVAIL:
if isinstance(val, uncertainties.UFloat):
val = val.nominal_value
if (np.isinf(val) and not np.isneginf(val)) or val >= inftyThresh:
if alignOnDec:
return_vals.append(demarc+r"\infty" + demarc + r" " + alignChar)
continue
else:
return_vals.append(demarc+r"\infty"+demarc)
continue
if np.isneginf(val) or val <= -inftyThresh:
if alignOnDec:
return_vals.append(demarc+r"-\infty" + demarc + " " + alignChar)
continue
else:
return_vals.append(demarc+r"-\infty"+demarc)
continue
elif np.isnan(val):
if alignOnDec:
return_vals.append(nanSub + r" " + alignChar)
continue
else:
return_vals.append(nanSub)
continue
elif val == 0:
effectivelyZero = True
if not effectivelyZero:
#-- Record sign of number
sign = np.sign(val)
#-- Create unsigned version of number
val_unsigned = sign * val
#-- Find exact (decimal) magnitude
exact_mag = np.log10(val_unsigned)
#-- Find floor of exact magnitude (integral magnitude)
floor_mag = float(np.floor(exact_mag))
#-- Where is the most significant digit?
mostSigDig = floor_mag
#-- Where is the least significant digit?
leastSigDig = mostSigDig-sigFigs+1
#print('mostSigDig', mostSigDig)
#print('leastSigDig', leastSigDig)
#-- Round number to have correct # of sig figs
val_u_rnd = np.round(val_unsigned, -int(leastSigDig))
#------------------------------------------------------------
# Repeat process from above to find mag, etc.
#
#-- Find exact (decimal) magnitude
exact_mag = np.log10(val_u_rnd)
#-- Find floor of exact magnitude (integral magnitude)
floor_mag = float(np.floor(exact_mag))
#-- Where is the most significant digit?
mostSigDig = floor_mag
#-- Where is the least significant digit?
leastSigDig = mostSigDig-sigFigs+1
#------------------------------------------------------------
#-- Mantissa (integral value)
val_mantissa = | np.int64(val_u_rnd * 10**(-leastSigDig)) | numpy.int64 |
import numpy as np
import argparse
from time import time, strftime
import pygame
import go
import playmodel
import cProfile
parser = argparse.ArgumentParser()
parser.add_argument("--epochs", "-e", default=10000, type=int)
parser.add_argument("--output-intv", "-o", dest="output_intv", default=1000, type=int)
parser.add_argument("--size", "-s", dest="size", default=19, type=int)
parser.add_argument("--playouts", "-p", dest="playouts", default=1000, type=int)
parser.add_argument("--selfplay", "-S", dest="self_play", action="store_true")
parser.add_argument("--use-model", "-m", dest="use_model", type=str, default="", action="store")
parser.add_argument("--playas", type=str, dest="playas", default="random", action="store")
args = parser.parse_args()
# training parameters
EPOCHS = args.epochs
TRAIN_RECORD_SIZE = 4
LEARN_THRESHOLD = TRAIN_RECORD_SIZE * 5
PRINT_INTV = args.output_intv
WHITE = go.WHITE
BLACK = go.BLACK
BOARD_SIZE = args.size
if args.playas == "b":
PLAYAS = BLACK
elif args.playas == "w":
PLAYAS = WHITE
else:
PLAYAS = np.random.randint(2)
BACKGROUND = 'images/ramin.jpg'
COLOR = ((0, 0, 0), (255, 255, 255))
GRID_SIZE = 20
DRAW_BOARD_SIZE = (GRID_SIZE * BOARD_SIZE + 20, GRID_SIZE * BOARD_SIZE + 20)
print("Board size:", BOARD_SIZE)
print("Komi:", KOMI)
class Stone(go.Stone):
def __init__(self, board, point):
"""Create, initialize and draw a stone."""
super(Stone, self).__init__(board, point)
if board.is_drawn and self.islegal:
board.draw_stones()
class Board(go.Board):
def __init__(self, size, komi, is_drawn=True):
"""Create, initialize and draw an empty board.
"""
self.is_drawn = is_drawn
super(Board, self).__init__(size, komi)
if is_drawn:
self.outline = pygame.Rect(GRID_SIZE+5, GRID_SIZE+5, DRAW_BOARD_SIZE[0]-GRID_SIZE*2, DRAW_BOARD_SIZE[1]-GRID_SIZE*2)
self.draw_board()
def draw_board(self):
"""Draw the board to the background and blit it to the screen.
The board is drawn by first drawing the outline, then the 19x19
grid and finally by adding hoshi to the board. All these
operations are done with pygame's draw functions.
This method should only be called once, when initializing the
board.
"""
pygame.draw.rect(background, BLACK, self.outline, 3)
# Outline is inflated here for future use as a collidebox for the mouse
self.outline.inflate_ip(20, 20)
for i in range(self.size-1):
for j in range(self.size-1):
rect = pygame.Rect(5+GRID_SIZE+(GRID_SIZE*i), 5+GRID_SIZE+(GRID_SIZE*j), GRID_SIZE, GRID_SIZE)
pygame.draw.rect(background, COLOR[BLACK], rect, 1)
if self.size >= 13:
for i in range(3):
for j in range(3):
coords = (5+4*GRID_SIZE+(GRID_SIZE*6*i), 5+4*GRID_SIZE+(GRID_SIZE*6*j))
pygame.draw.circle(background, COLOR[BLACK], coords, 5, 0)
screen.blit(background, (0, 0))
pygame.display.update()
def draw_stones(self):
"""
This method is called every time the board is updated by add_stone() and it is succesful
"""
screen.blit(background, (0, 0))
for g in self.groups:
for p in g.stones:
coords = (5+GRID_SIZE+p[0]*GRID_SIZE, 5+GRID_SIZE+p[1]*GRID_SIZE)
pygame.draw.circle(screen, COLOR[g.color], coords, GRID_SIZE//2, 0)
pygame.display.update()
def write_game_log(self, logfile):
COLOR_CHAR = ("B", "W")
logstr = ""
for entry in self.log:
logstr += COLOR_CHAR[entry[0]] + " " + str(entry[1]) + "\n"
logfile.write(logstr)
win, score_diff, outstr = self.score(output=True)
logfile.write(outstr+"\n")
def train():
open("log.txt", "w")
record_times = []
b_win_count = 0
for epoch in range(EPOCHS):
#temperature = 1.0
steps = 0
pass_count = 0
winner = None
reward = 0 # reward is viewed from BLACK
while True:
temperature = (1 + 1 / BOARD_SIZE) ** -steps # more step, less temperature
t = time()
prev_grid = board.grid.copy()
play_as = board.next
x, y = model.decide(board, temperature)
if y == BOARD_SIZE: # pass = size_square -> y = pass//BOARD_SIZE = BOARD_SIZE
pass_count += 1
board.pass_move()
else:
added_stone = Stone(board, (x, y))
if added_stone.islegal:
pass_count = 0
else:
continue
record_times.append(time()-t)
if pass_count >= 2:
winner, score_diff = board.score()
reward = playmodel.WIN_REWARD if winner == BLACK else playmodel.LOSE_REWARD # reward is viewd from BLACK
board.log_endgame(winner, "by " + str(score_diff))
if winner == BLACK:
b_win_count += 1
model.push_step(prev_grid, play_as, board.grid.copy())
if winner is not None:
break
steps += 1
# end while game
#temperature = max(min_temperature, initial_temperature / (1 + temperature_decay * epoch))
model.enqueue_new_record(reward)
if epoch > LEARN_THRESHOLD:
model.learn(learn_record_size = TRAIN_RECORD_SIZE, verbose=((epoch+1)%PRINT_INTV==0))
if (epoch+1) % PRINT_INTV == 0:
model.save(str(BOARD_SIZE)+"_tmp.h5")
print("epoch: %d\t B win rate: %.3f"%(epoch, b_win_count/(epoch+1)))
board.write_game_log(open("log.txt", "a"))
print("decide + update time", np.sum(record_times), np.mean(record_times), np.std(record_times))
board.clear()
# end for epochs
print(strftime(str(BOARD_SIZE)+"_%Y%m%d%H%M"))
model.save(strftime(str(BOARD_SIZE)+"_%Y%m%d%H%M")+".h5")
def test(ai_play_as):
print("begin test")
pass_count = 0
steps = 0
while True:
pygame.time.wait(250)
if ai_play_as == board.next:
x, y = model.decide_monte_carlo(board, arg.playout)
if x >= BOARD_SIZE or y >= BOARD_SIZE:
print("model passes")
pass_count += 1
board.pass_move()
else:
print("model choose (%d, %d)" % (x, y))
pass_count = 0
added_stone = Stone(board, (x, y))
if not added_stone.islegal:
print("model tried illegal move")
break
steps += 1
else:
for event in pygame.event.get():
if event.type == pygame.QUIT:
exit()
if event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1 and board.outline.collidepoint(event.pos):
x = int(round(((event.pos[0]-GRID_SIZE-5) / GRID_SIZE), 0))
y = int(round(((event.pos[1]-GRID_SIZE-5) / GRID_SIZE), 0))
added_stone = Stone(board, (x, y))
pass_count = 0
steps += 1
print("player choose (%d, %d)"%(x, y))
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_p:
pass_count += 1
break
if pass_count >= 2:
break
print("game over")
winner, score_diff, out_str = board.score(output=True)
print(out_str)
# end while True
def self_play():
print("begin self play")
pass_count = 0
measure_times = []
game_over = False
while not game_over and pass_count < 2:
pygame.time.wait(250)
for event in pygame.event.get():
if event.type == pygame.QUIT:
exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_p:
game_over = True
continue
t = time()
# cProfile.run("x, y = model.decide(board, args.playouts)", "mcts_search.profile")
x, y = model.decide_monte_carlo(board, args.playouts)
print(time()-t)
measure_times.append(time()-t)
if y == BOARD_SIZE:
board.pass_move()
play_as = "B" if board.next == WHITE else "W"
print(play_as, "pass")
pass_count += 1
if pass_count >= 2: break
elif y < 0:
board.pass_move()
play_as = "B" if board.next == WHITE else "W"
print(play_as, "resigned")
game_over = True
else:
added_stone = Stone(board, (x, y))
if not added_stone.islegal:
print("B" if play_as == "W" else "W", "tried illegal move (%d, %d)"%(x, y))
# game_over = True
# break
else:
pass_count = 0
play_as = "B" if board.next == WHITE else "W"
print(play_as, "choose (%d, %d)\t intuition:%.3f"%(x, y))
print("game over")
winner, score_diff, out_str = board.score(output=True)
print(out_str)
print("decision time", np.sum(measure_times), np.mean(measure_times), | np.std(measure_times) | numpy.std |
# -*- mode: python; coding: utf-8 -*-
# Copyright (C) 1997-2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, <NAME>
# Copyright 2003 <NAME>
# Copyright 2006, 2009-2011 (inclusive) <NAME>
# Copyright 2011-2017 (inclusive) <NAME>
#
# This software is provided as is without any warranty whatsoever. Permission
# to use, copy, modify, and distribute modified or unmodified copies is
# granted, provided this copyright and disclaimer are included unchanged.
### lmmin is a Levenberg-Marquardt least-squares minimizer derived
### (circuitously) from the classic MINPACK implementation. Usage information
### is given in the docstring farther below. Various important pieces of
### information that are out of the scope of the docstring follow immediately
### below.
# == Provenance ==
#
# This implementation of the Levenberg-Marquardt technique has its origins in
# MINPACK-1 (the lmdif and lmdir subroutines), by <NAME>, <NAME>, and
# <NAME>, implemented around 1980.
#
# In 1997-1998, <NAME> ported the FORTRAN code (with permission) to
# IDL, resulting in the MPFIT procedure.
#
# Around 2003, <NAME> ported the mpfit.pro file to Python and the Numeric
# module, creating mpfit.py. (It would be helpful to be able to identify the
# precise version that was ported, so that bugfixes to mpfit.pro could be
# forward-ported. The bug corrected on "21 Nov 2003" in mpfit.pro was
# originally present in this version, so the Python port likely happened
# before then.)
#
# Around 2006, mpfit.py was ported to the Numpy module to create nmpfit.py.
# Based on STSCI version control logs it appears that this was done by Nadia
# Dencheva.
#
# In 2011-2012, <NAME> began fixing bugs in the port and significantly
# reworking the API, creating this file, lmmin.py. Previous authors deserve
# all of the credit for anything that works and none of the blame for anything
# that doesn't.
#
# (There exists a C-based Levenberg-Marquardt minimizer named lmmin by Joachim
# Wuttke [http://joachimwuttke.de/lmfit/]. This implementation is not directly
# related to that one, although lmmin also appears to stem from the original
# MINPACK implementation.)
#
#
# == Transposition ==
#
# This version of the MINPACK implementation differs from the others of which
# I am aware in that it transposes the matrices used in intermediate
# calculations. While in both Fortran and Python, an n-by-m matrix is
# visualized as having n rows and m columns, in Fortran the columns are
# directly adjacent in memory, and hence the preferred inner axis for
# iteration, while in Python the rows are the preferred inner axis. By
# transposing the matrices we match the algorithms to the memory layout as
# intended in the original Fortran. I have no idea how much of a performance
# boost this gives, and of course we're using Python so you're deluding
# yourself if you're trying to wring out every cycle, but I suppose it helps,
# and it makes some of the code constructs nicer and feels a lot cleaner
# conceptually to me.
#
# The main operation of interest is the Q R factorization, which in the
# Fortran version involves matrices A, P, Q and R such that
#
# A P = Q R or, in Python,
# a[:,pmut] == np.dot (q, r)
#
# where A is an arbitrary m-by-n matrix, P is a permutation matrix, Q is an
# orthogonal m-by-m matrix (Q Q^T = Ident), and R is an m-by-n upper
# triangular matrix. In the transposed version,
#
# A P = R Q
#
# where A is n-by-m and R is n-by-m and lower triangular. We refer to this as
# the "transposed Q R factorization." I've tried to update the documentation
# to reflect this change, but I can't claim that I completely understand the
# mapping of the matrix algebra into code, so there are probably confusing
# mistakes in the comments and docstrings.
#
#
# == Web Links ==
#
# MINPACK-1: http://www.netlib.org/minpack/
#
# Markwardt's IDL software MPFIT.PRO: http://purl.com/net/mpfit
#
# Rivers' Python software mpfit.py: http://cars.uchicago.edu/software/python/mpfit.html
#
# nmpfit.py is part of stsci_python:
# http://www.stsci.edu/institute/software_hardware/pyraf/stsci_python
#
#
# == Academic References ==
#
# <NAME>. 1944, "A method for the solution of certain nonlinear
# problems in least squares," Quart. Appl. Math., vol. 2,
# pp. 164-168.
#
# <NAME>. 1963, "An algorithm for least squares estimation of
# nonlinear parameters," SIAM J. Appl. Math., vol. 11, pp. 431-441.
# (DOI: 10.1137/0111030 )
#
# For MINPACK-1:
#
# <NAME>. 1978, "The Levenberg-Marquardt Algorithm: Implementation
# and Theory," in Numerical Analysis, vol. 630, ed. <NAME>
# (Springer-Verlag: Berlin), p. 105 (DOI: 10.1007/BFb0067700 )
#
# <NAME> and Wright, S. 1987, "Optimization Software Guide," SIAM,
# Frontiers in Applied Mathematics, no. 14. (ISBN:
# 978-0-898713-22-0)
#
# For Markwardt's IDL software MPFIT.PRO:
#
# Markwardt, <NAME>. 2008, "Non-Linear Least Squares Fitting in IDL with
# MPFIT," in Proc. Astronomical Data Analysis Software and Systems
# XVIII, Quebec, Canada, ASP Conference Series, Vol. XXX, eds.
# <NAME>, <NAME> & <NAME> (Astronomical Society of the
# Pacific: San Francisco), pp. 251-254 (ISBN: 978-1-58381-702-5;
# arxiv:0902.2850; bibcode: 2009ASPC..411..251M)
"""pwkit.lmmin - Pythonic, Numpy-based Levenberg-Marquardt least-squares minimizer
Basic usage::
from pwkit.lmmin import Problem, ResidualProblem
def yfunc(params, vals):
vals[:] = {stuff with params}
def jfunc(params, jac):
jac[i,j] = {deriv of val[j] w.r.t. params[i]}
# i.e. jac[i] = {deriv of val wrt params[i]}
p = Problem(npar, nout, yfunc, jfunc=None)
solution = p.solve(guess)
p2 = Problem()
p2.set_npar(npar) # enables configuration of parameter meta-info
p2.set_func(nout, yfunc, jfunc)
Main Solution properties:
prob - The Problem.
status - Set of strings; presence of 'ftol', 'gtol', or 'xtol' suggests success.
params - Final parameter values.
perror - 1σ uncertainties on params.
covar - Covariance matrix of parameters.
fnorm - Final norm of function output.
fvec - Final vector of function outputs.
fjac - Final Jacobian matrix of d(fvec)/d(params).
Automatic least-squares model-fitting (subtracts "observed" Y values and
multiplies by inverse errors):
def yrfunc(params, modelyvalues):
modelyvalues[:] = {stuff with params}
def yjfunc(params, modelyjac):
jac[i,j] = {deriv of modelyvalue[j] w.r.t. params[i]}
p.set_residual_func(yobs, errinv, yrfunc, jrfunc, reckless=False)
p = ResidualProblem(npar, yobs, errinv, yrfunc, jrfunc=None, reckless=False)
Parameter meta-information:
p.p_value(paramindex, value, fixed=False)
p.p_limit(paramindex, lower=-inf, upper=+inf)
p.p_step(paramindex, stepsize, maxstep=info, isrel=False)
p.p_side(paramindex, sidedness) # one of 'auto', 'pos', 'neg', 'two'
p.p_tie(paramindex, tiefunc) # pval = tiefunc(params)
solve() status codes:
Solution.status is a set of strings. The presence of a string in the
set means that the specified condition was active when the iteration
terminated. Multiple conditions may contribute to ending the
iteration. The algorithm likely did not converge correctly if none of
'ftol', 'xtol', or 'gtol' are in status upon termination.
'ftol' (MINPACK/MPFIT equiv: 1, 3)
"Termination occurs when both the actual and predicted relative
reductions in the sum of squares are at most FTOL. Therefore, FTOL
measures the relative error desired in the sum of squares."
'xtol' (MINPACK/MPFIT equiv: 2, 3)
"Termination occurs when the relative error between two consecutive
iterates is at most XTOL. Therefore, XTOL measures the relative
error desired in the approximate solution."
'gtol' (MINPACK/MPFIT equiv: 4)
"Termination occurs when the cosine of the angle between fvec and
any column of the jacobian is at most GTOL in absolute
value. Therefore, GTOL measures the orthogonality desired between
the function vector and the columns of the jacobian."
'maxiter' (MINPACK/MPFIT equiv: 5)
Number of iterations exceeds maxiter.
'feps' (MINPACK/MPFIT equiv: 6)
"ftol is too small. no further reduction in the sum of squares is
possible."
'xeps' (MINPACK/MPFIT equiv: 7)
"xtol is too small. no further improvement in the approximate
solution x is possible."
'geps' (MINPACK/MPFIT equiv: 8)
"gtol is too small. fvec is orthogonal to the columns of the jacobian
to machine precision."
(This docstring contains only usage information. For important
information regarding provenance, license, and academic references,
see comments in the module source code.)
"""
from __future__ import absolute_import, division, print_function, unicode_literals
__all__ = '''enorm_fast enorm_mpfit_careful enorm_minpack Problem Solution
ResidualProblem check_derivative'''.split()
from six.moves import range
import numpy as np
# Quickie testing infrastructure
_testfuncs = []
def test(f): # a decorator
_testfuncs.append(f)
return f
def _runtests(namefilt=None):
for f in _testfuncs:
if namefilt is not None and f.__name__ != namefilt:
continue
n = f.__name__
if n[0] == '_':
n = n[1:]
print(n, '...')
f()
from numpy.testing import assert_array_almost_equal as Taaae
from numpy.testing import assert_almost_equal as Taae
def _timer_helper(n=100):
for i in range(n):
for f in _testfuncs:
f()
# Parameter Info attributes that can be specified
#
# Each parameter can be described by five floats:
PI_F_VALUE = 0 # specified initial value
PI_F_LLIMIT = 1 # lower bound on param value (can be -inf)
PI_F_ULIMIT = 2 # upper bound (can be +inf)
PI_F_STEP = 3 # fixed parameter step size to use (abs or rel), 0. for unspecified
PI_F_MAXSTEP = 4 # maximum step to take
PI_NUM_F = 5
# Four bits of data
PI_M_SIDE = 0x3 # sidedness of derivative - two bits
PI_M_FIXED = 0x4 # fixed value
PI_M_RELSTEP = 0x8 # whether the specified stepsize is relative
# And one object
PI_O_TIEFUNC = 0 # fixed to be a function of other parameters
PI_NUM_O = 1
# Codes for the automatic derivative sidedness
DSIDE_AUTO = 0x0
DSIDE_POS = 0x1
DSIDE_NEG = 0x2
DSIDE_TWO = 0x3
_dside_names = {
'auto': DSIDE_AUTO,
'pos': DSIDE_POS,
'neg': DSIDE_NEG,
'two': DSIDE_TWO,
}
anynotfinite = lambda x: not np.all(np.isfinite(x))
# Euclidean norm-calculating functions. The naive implementation is
# fast but can be sensitive to under/overflows. The "mpfit_careful"
# version is slower but tries to be more robust. The "minpack"
# version, which does indeed emulate the MINPACK implementation, also
# tries to be careful. I've used this last implementation a little
# bit but haven't compared it to the others thoroughly.
enorm_fast = lambda v, finfo: np.sqrt(np.dot(v, v))
def enorm_mpfit_careful(v, finfo):
# "This is hopefully a compromise between speed and robustness.
# Need to do this because of the possibility of over- or under-
# flow."
mx = max(abs(v.max()), abs(v.min()))
if mx == 0:
return v[0] * 0. # preserve type (?)
if not np.isfinite(mx):
raise ValueError('tried to compute norm of a vector with nonfinite values')
if mx > finfo.max / v.size or mx < finfo.tiny * v.size:
return mx * np.sqrt(np.dot(v / mx, v / mx))
return np.sqrt(np.dot(v, v))
def enorm_minpack(v, finfo):
rdwarf = 3.834e-20
rgiant = 1.304e19
agiant = rgiant / v.size
s1 = s2 = s3 = x1max = x3max = 0.
for i in range(v.size):
xabs = abs(v[i])
if xabs > rdwarf and xabs < agiant:
s2 += xabs**2
elif xabs <= rdwarf:
if xabs <= x3max:
if xabs != 0.:
s3 += (xabs / x3max)**2
else:
s3 = 1 + s3 * (x3max / xabs)**2
x3max = xabs
else:
if xabs <= x1max:
s1 += (xabs / x1max)**2
else:
s1 = 1. + s1 * (x1max / xabs)**2
x1max = xabs
if s1 != 0.:
return x1max * np.sqrt(s1 + (s2 / x1max) / x1max)
if s2 == 0.:
return x3max * np.sqrt(s3)
if s2 >= x3max:
return np.sqrt(s2 * (1 + (x3max / s2) * (x3max * s3)))
return np.sqrt(x3max * ((s2 / x3max) + (x3max * s3)))
# Q-R factorization.
def _qr_factor_packed(a, enorm, finfo):
"""Compute the packed pivoting Q-R factorization of a matrix.
Parameters:
a - An n-by-m matrix, m >= n. This will be *overwritten*
by this function as described below!
enorm - A Euclidian-norm-computing function.
finfo - A Numpy finfo object.
Returns:
pmut - An n-element permutation vector
rdiag - An n-element vector of the diagonal of R
acnorm - An n-element vector of the norms of the rows
of the input matrix 'a'.
Computes the transposed Q-R factorization of the matrix 'a', with
pivoting, in a packed form, in-place. The packed information can be
used to construct matrices Q and R such that
A P = R Q or, in Python,
np.dot(r, q) = a[pmut]
where q is m-by-m and q q^T = ident and r is n-by-m and is lower
triangular. The function _qr_factor_full can compute these
matrices. The packed form of output is all that is used by the main LM
fitting algorithm.
"Pivoting" refers to permuting the rows of 'a' to have their norms in
nonincreasing order. The return value 'pmut' maps the unpermuted rows
of 'a' to permuted rows. That is, the norms of the rows of a[pmut] are
in nonincreasing order.
The parameter 'a' is overwritten by this function. Its new value
should still be interpreted as an n-by-m array. It comes in two
parts. Its strict lower triangular part contains the struct lower
triangular part of R. (The diagonal of R is returned in 'rdiag' and
the strict upper trapezoidal part of R is zero.) The upper trapezoidal
part of 'a' contains Q as factorized into a series of Householder
transformation vectors. Q can be reconstructed as the matrix product
of n Householder matrices, where the i'th Householder matrix is
defined by
H_i = I - 2 (v^T v) / (v v^T)
where 'v' is the pmut[i]'th row of 'a' with its strict lower
triangular part set to zero. See _qr_factor_full for more information.
'rdiag' contains the diagonal part of the R matrix, taking into
account the permutation of 'a'. The strict lower triangular part of R
is stored in 'a' *with permutation*, so that the i'th row of R has
rdiag[i] as its diagonal and a[pmut[i],:i] as its upper part. See
_qr_factor_full for more information.
'acnorm' contains the norms of the rows of the original input
matrix 'a' without permutation.
The form of this transformation and the method of pivoting first
appeared in Linpack."""
machep = finfo.eps
n, m = a.shape
if m < n:
raise ValueError('"a" must be at least as tall as it is wide')
acnorm = np.empty(n, finfo.dtype)
for j in range(n):
acnorm[j] = enorm(a[j], finfo)
rdiag = acnorm.copy()
wa = acnorm.copy()
pmut = np.arange(n)
for i in range(n):
# Find the row of a with the i'th largest norm, and note it in
# the pivot vector.
kmax = rdiag[i:].argmax() + i
if kmax != i:
temp = pmut[i]
pmut[i] = pmut[kmax]
pmut[kmax] = temp
rdiag[kmax] = rdiag[i]
wa[kmax] = wa[i]
temp = a[i].copy()
a[i] = a[kmax]
a[kmax] = temp
# Compute the Householder transformation to reduce the i'th
# row of A to a multiple of the i'th unit vector.
ainorm = enorm(a[i,i:], finfo)
if ainorm == 0:
rdiag[i] = 0
continue
if a[i,i] < 0:
# Doing this apparently improves FP precision somehow.
ainorm = -ainorm
a[i,i:] /= ainorm
a[i,i] += 1
# Apply the transformation to the remaining rows and update
# the norms.
for j in range(i + 1, n):
a[j,i:] -= a[i,i:] * np.dot(a[i,i:], a[j,i:]) / a[i,i]
if rdiag[j] != 0:
rdiag[j] *= np.sqrt(max(1 - (a[j,i] / rdiag[j])**2, 0))
if 0.05 * (rdiag[j] / wa[j])**2 <= machep:
# What does this do???
wa[j] = rdiag[j] = enorm(a[j,i+1:], finfo)
rdiag[i] = -ainorm
return pmut, rdiag, acnorm
def _manual_qr_factor_packed(a, dtype=np.float):
# This testing function gives sensible defaults to _qr_factor_packed
# and makes a copy of its input to make comparisons easier.
a = np.array(a, dtype)
pmut, rdiag, acnorm = _qr_factor_packed(a, enorm_mpfit_careful,
np.finfo(dtype))
return a, pmut, rdiag, acnorm
def _qr_factor_full(a, dtype=np.float):
"""Compute the QR factorization of a matrix, with pivoting.
Parameters:
a - An n-by-m arraylike, m >= n.
dtype - (optional) The data type to use for computations.
Default is np.float.
Returns:
q - An m-by-m orthogonal matrix (q q^T = ident)
r - An n-by-m upper triangular matrix
pmut - An n-element permutation vector
The returned values will satisfy the equation
np.dot(r, q) == a[:,pmut]
The outputs are computed indirectly via the function
_qr_factor_packed. If you need to compute q and r matrices in
production code, there are faster ways to do it. This function is for
testing _qr_factor_packed.
The permutation vector pmut is a vector of the integers 0 through
n-1. It sorts the rows of 'a' by their norms, so that the
pmut[i]'th row of 'a' has the i'th biggest norm."""
n, m = a.shape
# Compute the packed Q and R matrix information.
packed, pmut, rdiag, acnorm = \
_manual_qr_factor_packed(a, dtype)
# Now we unpack. Start with the R matrix, which is easy: we just
# have to piece it together from the strict lower triangle of 'a'
# and the diagonal in 'rdiag'.
r = np.zeros((n, m))
for i in range(n):
r[i,:i] = packed[i,:i]
r[i,i] = rdiag[i]
# Now the Q matrix. It is the concatenation of n Householder
# transformations, each of which is defined by a row in the upper
# trapezoidal portion of 'a'. We extract the appropriate vector,
# construct the matrix for the Householder transform, and build up
# the Q matrix.
q = np.eye(m)
v = np.empty(m)
for i in range(n):
v[:] = packed[i]
v[:i] = 0
hhm = np.eye(m) - 2 * np.outer(v, v) / np.dot(v, v)
q = np.dot(hhm, q)
return q, r, pmut
@test
def _qr_examples():
# This is the sample given in the comments of <NAME>'s
# IDL MPFIT implementation.
a = np.asarray([[9., 2, 6], [4, 8, 7]])
packed, pmut, rdiag, acnorm = _manual_qr_factor_packed(a)
Taaae(packed, [[1.35218036, 0.70436073, 0.61631563],
[-8.27623852, 1.96596229, 0.25868293]])
assert pmut[0] == 1
assert pmut[1] == 0
Taaae(rdiag, [-11.35781669, 7.24595584])
| Taaae(acnorm, [11.0, 11.35781669]) | numpy.testing.assert_array_almost_equal |
import numpy as np
import pytest
import tifffile
from lxml import etree # nosec
from PartSegImage.image import Image
from PartSegImage.image_reader import TiffImageReader
from PartSegImage.image_writer import IMAGEJImageWriter, ImageWriter
@pytest.fixture(scope="module")
def ome_xml(bundle_test_dir):
return etree.XMLSchema(file=str(bundle_test_dir / "ome.xsd.xml"))
def test_scaling(tmp_path):
image = Image(np.zeros((10, 50, 50), dtype=np.uint8), (30, 0.1, 0.1), axes_order="ZYX")
ImageWriter.save(image, tmp_path / "image.tif")
read_image = TiffImageReader.read_image(tmp_path / "image.tif")
assert np.all(np.isclose(image.spacing, read_image.spacing))
def test_save_mask(tmp_path):
data = np.zeros((10, 40, 40), dtype=np.uint8)
data[1:-1, 1:-1, 1:-1] = 1
data[2:-3, 4:-4, 4:-4] = 2
mask = np.array(data > 0).astype(np.uint8)
image = Image(data, (0.4, 0.1, 0.1), mask=mask, axes_order="ZYX")
ImageWriter.save_mask(image, tmp_path / "mask.tif")
read_mask = TiffImageReader.read_image(tmp_path / "mask.tif")
assert np.all(np.isclose(read_mask.spacing, image.spacing))
@pytest.mark.parametrize("z_size", (1, 10))
def test_ome_save(tmp_path, bundle_test_dir, ome_xml, z_size):
data = | np.zeros((z_size, 20, 20, 2), dtype=np.uint8) | numpy.zeros |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 4 14:09:33 2018
@author: john
"""
#all skeleton holders used by dart_env_2bot
import numpy as np
import nlopt
from math import sqrt
from gym import error, spaces
#from gym.spaces import *
from abc import ABC, abstractmethod
from collections import defaultdict
try:
import pydart2 as pydart
from pydart2.gui.trackball import Trackball
pydart.init()
except ImportError as e:
raise error.DependencyNotInstalled("{}. (HINT: you need to install pydart2.)".format(e))
#base convenience class holding relevant info and functions for a skeleton
class skelHolder(ABC):
#env is owning environment
#skel is ref to skeleton
#widx is index in world skel array
#stIdx is starting index in force/torque array for tau calc - past root dofs that get no tau
#fTipOffset is distance in body local coords from com of reach body for constraint/grab location
def __init__(self, env, skel, widx, stIdx, fTipOffset):
print("making skel : {}".format(skel.name))
self.name=''
#ref to owning environment
self.env = env
#ref to skel object
self.skel = skel
#index in world skeleton array
self.worldIdx = widx
#start index for action application in tau array -> bypasses
#dofs that are root/world related (And do not get tau applied)
self.stTauIdx = stIdx
#base action scale multiplier
self.actionScaleBaseVal = 150.0
#preloaded initial state to return to at reset, otherwise variation of initstate is used
self.initQPos = None
self.initQVel = None
#idxs of dofs corresponding to world location of root - replace with com in observation, since x
self.rootLocDofs = np.array([3,4,5])
#number of dofs - get rid of length calc every time needed
self.ndofs = self.skel.ndofs
#number of actuated dofs : number of dofs - world dofs
self.numActDofs = self.ndofs - self.stTauIdx
#sqrt of numActuated dofs, for reward scaling
self.sqrtNumActDofs = np.sqrt(self.numActDofs)
#ground friction from environment
self.groundFric = self.env.groundFric
#gravity of this world
grav = self.env.dart_world.gravity()
#print('gravity is : {} '.format(grav))
#precalc mg for force calculations - magnitude of grav * mass
self.mg = np.linalg.norm(grav) * self.skel.mass()
#to monitor torques seen : minimum and maximum seen torques saved in arrays
self.monitorTorques = False
#self._reset_monTorques()
self.monTrqDict = {}
self._resetMinMaxMonitors(self.monTrqDict, self.ndofs)
#bound on allowable qDot for training of policy
self.qDotBnd = 10
#state flags
#use the mean state only if set to false, otherwise randomize initial state
self.randomizeInitState = True
#use these to show that we are holding preset initial states - only used if randomizeInitState is false
self.loadedInitStateSet = False
#desired force/torque has been set
self.desForceTorqueSet = False
#process actions and forward simulate (should match skel.is_mobile) - only use in prestep and poststep functions, if at all
self.isFrwrdSim = True
#whether to use linear or world jacobian for endeffector
self.useLinJacob = False
#Monitor generated force at pull point/hand contact
self.monitorGenForce = False
#display debug information for this skel holder
self.debug = True
#set baseline desired external forces and force mults
self.desExtFrcVal = np.array([0,0,0])
self.desExtFrcVal_mults = np.array([0,0,0])
#using force multiplier instead of force as observation component of force in RL training/policy consumption
self.useMultNotForce=False
#initial torques - set to 0
self.dbgResetTau()
#TODO force and torque dimensions get from env
#+/- perturb amount of intial pose and vel for random start state
self.poseDel = .005
#hand reaching to other agent - name and ref to body
self.reach_hand = ''
self.reachBody = None
#initial constraint location - pose is built/modified off this for assistant robot, and this is derived from human's eff location
self.initEffPosInWorld = None
#this is location on reach_hand in local coords of contact with constraint body
#i.e., this is constraint location on reach_hand in local coords
self.reachBodyOffset = fTipOffset
#list of body node names for feet and hand in biped
self.feetBodyNames = list()
self.handBodyNames = list()
# # of sim steps we've run (# of times tau is applied)
self.numSimSteps = 0
#timestep - do not include repeated steps
#since query sim for character state and sim state is step dependent
self.timestep = env.dart_world.dt
#tag to follow # of broken simulation steps
self.env.numBrokeSims = 0
#whether to check for best state after each reward - this is to keep around the best state from the previous rollout to use as next rollout's mean state
self.checkBestState = False#set this true in ana
#initialize to bogus vals
self.bestState = None
#moved from dart_env_2bot - this sets up the action and (initial) observation spaces for the skeleton.
# NOTE : the observation space does not initially include any external forces,
# and can be modified through external calls to setObsDim directly
# this should be called once, only upon initial construction of skel handler
def setInitialSkelParams(self, bodyNamesAra):
#clips control to be within -1 and 1
#min is idx 0, max is idx 1
self.control_bounds = (np.array([[-1.0]*self.numActDofs,[1.0]*self.numActDofs]))
self.action_dim = self.numActDofs
self.action_space = spaces.Box(self.control_bounds[0], self.control_bounds[1])
#scaling value of action multiplier (action is from policy and in the range of approx +/- 2)
action_scaleBase = np.array([self.actionScaleBaseVal]*self.numActDofs)
#individual action scaling for different bot configurations
action_scale = self._setupSkelSpecificActionSpace(action_scaleBase)
print('action scale : {}'.format(action_scale))
self.action_scale = action_scale
#set initial observation dimension - NOTE : this does not include any external forces or observations
self.setObsDim(2*self.ndofs)
if (len(bodyNamesAra) > 0):
self._setFootHandBodyNames(bodyNamesAra[0], bodyNamesAra[1], bodyNamesAra[2], bodyNamesAra[3])
else :#not relevant for KR5 arm robot
print("---- No foot/hand/head body names specified, no self.StandCOMHeight derived ----")
#called for each skeleton type, to configure multipliers for skeleton-specific action space
@abstractmethod
def _setupSkelSpecificActionSpace(self, action_scale):
pass
#called initially before any pose modification is done - pose of skel by here is pose specified in skel/urdf file
def _setFootHandBodyNames(self,lf_bdyNames, rf_bdyNames, h_bodyNames, headBodyName):
self.feetBodyNames = lf_bdyNames + rf_bdyNames
self.leftFootBodyNames = lf_bdyNames[:]
self.rightFootBodyNames = rf_bdyNames[:]
self.handBodyNames = h_bodyNames[:]
self.headBodyName = headBodyName
print('skelHolder::setFootHandBodyNames : set values for initial height above avg foot location - ASSUMES CHARACTER IS UPRIGHT IN SKEL FILE. Must be performed before desired pose is set')
#specific to instancing class - only RL-involved skel holders should have code in this
self.setInitRWDValues()
def setSkelMobile(self, val):
self.skel.set_mobile(val)
#frwrdSim is boolean whether mobile/simulated or not
self.isFrwrdSim = val
#initialize constraint locations and references to constraint bodies
def initConstraintLocs(self, cPosInWorld, cBody):
#this is initial end effector position desired in world coordinates, built relative to human pose fingertip
self.initEffPosInWorld = np.copy(cPosInWorld)
#initializing current location for finite diff velocity calc
self.trackBodyCurPos = np.copy(self.initEffPosInWorld)#self.cnstrntBody.com()
#body to be constrained to or track
self.cnstrntBody = cBody
#constraint location in ball local coords - convert to world for target location for inv dyn
self.cnstrntOnBallLoc = self.cnstrntBody.to_local(x=self.initEffPosInWorld)
#initialize best state reward
if (self.checkBestState):
self.bestStRwd = -100000000000
self.bestState = self.state_vector()
#set initial constraint location in world - called every reset and before addBallConstraint
#only called 1 time, when constraints being first built
def addBallConstraint(self):
# if(setConnect ):#set the constraint to connect these bodies
#build constraint
constraint = pydart.constraints.BallJointConstraint(self.cnstrntBody, self.reachBody, self.initEffPosInWorld)
#add to world
constraint.add_to_world(self.env.dart_world)
#print('{} is currently constrainted to ball at world location : {} corresponding to local reach body loc : {}'.format(self.skel.name, self.initEffPosInWorld,self.reachBody.to_local( self.initEffPosInWorld)))
# else : #treat as tracking body
#print('{} not currently holding constraint ball!!!'.format(self.skel.name))
#initializing current location for finite diff velocity calc
# pass
#return the world position of the constraint on the constraint body
def getWorldPosCnstrntOnCBody(self):
return self.cnstrntBody.to_world(x=self.cnstrntOnBallLoc)
#set the name of the body node reaching to other agent
#called by initial init of pose
def setReachHand(self, _rchHand):
self.reach_hand = _rchHand
self.reachBody = self.skel.body(self.reach_hand)
#set the desired external force for this skel
#(either the force applied to the human, or the force being applied by the robot)
#set reciprocal is only used for debugging/displaying efficacy of force generation method for robot
def setDesiredExtForce(self, desFrcTrqVal, desExtFrcVal_mults, setReciprocal, obsUseMultNotFrc):
self.useMultNotForce = obsUseMultNotFrc
#print('{} got force set to {}'.format(self.skel.name, desFrcTrqVal))
#self.lenFrcVec = len(desFrcTrqVal)
self.desExtFrcVal = np.copy(desFrcTrqVal)
self.desExtFrcVal_mults = np.copy(desExtFrcVal_mults)
self.desForceTorqueSet = True
#if true then apply reciprocal force to reach body
if(setReciprocal):
#counteracting force for debugging - remove when connected
self.reachBody.set_ext_force(-1 * self.desExtFrcVal, _offset=self.reachBodyOffset)
#set observation dimension
def setObsDim(self, obsDim):
self.obs_dim = obsDim
high = np.inf*np.ones(self.obs_dim)
low = -high
self.observation_space = spaces.Box(low, high)
#set what this skeleton's init pose should be
#only call this whenever initial base pose _actually chagnes_ (like upon loading)
def setStartingPose(self):
#initPose is base initial pose that gets varied upon reset if randomized - base pose is treated as constant
self.initPose = self._makeInitPoseIndiv()
self.setToInitPose()
#reset this skeleton to its initial base pose - uses preset self.initPose
def setToInitPose(self):
#priv method is so that helper bots can IK to appropriate location based on where ANA hand is
self._setToInitPose_Priv()
self.skel.set_positions(self.initPose)
#set skel velocities
self.skel.set_velocities(np.zeros(self.skel.dq.shape))
#if monitoring the force/torques at pull application point, reset minmax arrays
if(self.monitorGenForce):
self.totGenFrc = list()
self.minMaxFrcDict = {}
self._resetMinMaxMonitors(self.minMaxFrcDict, self.useForce.shape)
#self._reset_minMaxGenForceVals()
self.postPoseInit()
#will reset passed dictionary of min and max values to the given shape of initial sentinel values
def _resetMinMaxMonitors(self, minMaxDict, sizeShape):
minMaxDict['min'] = np.ones(sizeShape)*1000000000
minMaxDict['max'] = np.ones(sizeShape)*-1000000000
#set initial state externally - call before reset_model is called by training process
#Does not override initPose
def setNewInitState(self, _qpos, _qvel):
#set to false to use specified states
self.randomizeInitState = False
self.initQPos = np.asarray(_qpos, dtype=np.float64)
self.initQVel = np.asarray(_qvel, dtype=np.float64)
self.loadedInitStateSet = True
#set this skeleton's state
def state_vector(self):
return np.concatenate([
self.skel.q,
self.skel.dq
])
#sets skeleton state to be passed position and velocity
def set_state(self, qpos, qvel):
assert qpos.shape == (self.ndofs,) and qvel.shape == (self.ndofs,)
self.skel.set_positions(qpos)
self.skel.set_velocities(qvel)
#sets skeleton state to be passed state vector, split in half (for external use)
def set_state_vector(self, state):
numVals = int(len(state)/2.0)
self.set_state(state[0:numVals], state[numVals:])
#called in do_simulate if perturbation is true - adds external force to passed body nodes
def add_perturbation(self, nodes, frc):
self.skel.bodynodes[nodes].add_ext_force(frc)
#build tau from a, using control clamping, for skel, starting at stIdx and action scale for skeleton
#a is specified from RL policy, and is clamped to be within control_bounds
def setClampedTau(self, a):
self.a = np.copy(a)
#print('pre clamped cntl : {}'.format(a))
#idx 0 is min, idx 1 is max.
clamped_control = np.clip(self.a, self.control_bounds[0],self.control_bounds[1])
#print('clamped cntl : {}'.format(clamped_control))
self.tau = np.zeros(self.ndofs)
self.tau[self.stTauIdx:] = clamped_control * self.action_scale
#print('tau : {}'.format(self.tau))
return self.tau
#send torques to skeleton
def applyTau(self):
if(self.monitorTorques):
self._checkiMinMaxVals(self.tau, self.monTrqDict)
#apply torques every step since they are cleared after world steps
self.skel.set_forces(self.tau)
#record # of tau applications
self.numSimSteps += 1
#any private per-step torque application functionality - this is where the external force is applied to human skeleton during RL training to simulate robot assistant
self.applyTau_priv()
#return limits of Obs values (q, qdot, force)
def getObsLimits(self):
jtlims = {}
jtlims['lowQLims'] = | np.zeros(self.ndofs) | numpy.zeros |
import sys, os
import numpy as np
import gmpy2 as gm
from recursions import alpha_array, gamma_array
"""
This file will implement general helper functions.
"""
class HiddenPrints:
'''
This is a class that can be used to suppress stdout from function calls.
Usage:
with HiddenPrints():
>>do stuff without printing
'''
def __enter__(self):
self._original_stdout = sys.stdout
sys.stdout = open(os.devnull, 'w')
# self._original_sterr = sys.stderr
# sys.stderr = open(os.devnull, 'w')
def __exit__(self, exc_type, exc_val, exc_tb):
sys.stdout.close()
# sys.stderr.close()
sys.stdout = self._original_stdout
# sys.stderr = self._original_sterr
def bmatrix(a):
"""
Converts np.array into a LaTeX bmatrix
Args:
a: numpy array
Returns:
LaTeX bmatrix of a as a string
"""
if len(a.shape) > 2:
raise ValueError('bmatrix can at most display two dimensions')
lines = str(a).replace('[', '').replace(']', '').splitlines()
rv = [r'\begin{bmatrix}']
rv += [' ' + ' & '.join(l.split()) + r'\\' for l in lines]
rv += [r'\end{bmatrix}']
for i in rv:
print(i)
return
def address_from_index(level, index):
"""Computes address vector from the index.
Returns the address vector of a point with certain TLR index in
a graph of SG at some fixed level.
For point F_{w1} F_{w2} ... F_{wm} q_{k} (0<=wi<=2, 0<=k<=2), we can
represent it in two ways:
1. Address Vector: [wm, ..., w1, k] (Note that this represents
picking transform F_{wm}, ..., F_{w1} in this sequence and then
finding vertex q_{k} in the final triangle. This order is weird
but will prove to be useful)
2. TLR Index: k = wm * 3^m + ... + w1 * 3 + k + 1
This function provides transform 2 -> 1.
Args:
level: A nonnegative integer representing the level of SG we're
working with.
index: A number in the range [1, 3^(level+1)] representing the
TLR index of some point in level m.
Returns:
address: np.array of length (level+1) representing the address
of the point specified by index in a particular level of SG.
Example:
address_from_index(1, 4) = [1, 0]
address_from_index(2, 21) = [2, 1, 2]
"""
# Initialize the vector to store the address
v = np.zeros(level+1)
# First decide the last term of the vector
index = index - 1
v[level] = index % 3
index = int(index / 3)
# Perform transformation similar to base 10 -> base 3
for i in range(level):
v[level - 1 - i] = index % 3
index = int(index / 3)
return v
def index_from_address(level, address):
"""Computes TLR Index from Address vector.
Returns the TLR index of a point with certain address vector in
a graph of SG at some fixed level.
For point F_{w1} F_{w2} ... F_{wm} q_{k} (0<=wi<=2, 0<=k<=2), we
can represent it in two ways:
1. Address Vector: [wm, ..., w1, k] (Note that this represents
picking transform F_{wm}, ..., F_{w1} in this sequence and then
finding vertex q_{l} in the final triangle)
2. TLR Index: k = wm * 3^m + ... + w1 * 3 + k + 1
This function provides transform 1 -> 2.
Args:
level: A nonnegative integer representing the level of SG we're
working with.
address: np.array of size (level+1) representing the address
vector of a point in some SG graph.
Returns:
index: A number in the range [1, 3^(level+1)] representing the
TLR index of some point in level m.
"""
# Initialize index with additional 1 added
index = 1
# Perform transformation similar to base 3 -> base 10
for i in range(level+1):
index += address[i] * (3 ** (level - i))
return int(index)
def q_contract(orig_mat, base_point):
"""Computes the image of points under some contraction.
Contracts all points represented in rows of v toward the base_point
with a contraction ratio of 1/2.
Args:
orig_mat: A np.array of size (t, 2) for some integer t, with
each row representing the coordinate of a point
base_point: A np.array of length 2 representing the coordinates
of the point we're contracting toward.
Returns:
contract_mat: A np.array of size (t, 2) for some integer t, with
each row the contracted version of that in orig_mat.
"""
# Use broadcasting to find the average points
contract_mat = 0.5 * orig_mat + 0.5 * base_point
return contract_mat
def sg_coordinates(level):
"""Computes the coordinates of points for SG at some level.
Given base points q0 = [cos(5*pi/12) sin(5*pi/12)], q1=[0 0],
q2=[cos(pi/12) sin(pi/12)], we calculate the coordinates of all
points up to some level of the SG graph.
Args:
level: A nonnegative integer representing the level of SG we're
working with.
Returns:
coord_mat: A matrix with dimension (3^(level+1), 2), with each
row representing coordinate of one point in V_m
"""
# Initialize the boundary points of V_0
q0 = np.array([np.cos(np.pi * 5 / 12), np.sin(np.pi * 5 / 12)])
print(q0)
q1 = np.array([0, 0])
print(q1)
q2 = np.array([np.cos(np.pi / 12), np.sin(np.pi / 12)])
print(q2)
# Stack the first three coordinates into a matrix
coord_mat = np.stack((q0, q1, q2))
# Each iteration produces a matrix of coordinates in the next level
for _ in range(level):
coord_mat = np.vstack((q_contract(coord_mat, q0),
q_contract(coord_mat, q1), q_contract(coord_mat, q2)))
return coord_mat
def alternate_address(level, address):
"""Computes the alternate address of a point.
Args:
level: A nonnegative integer representing the level of SG we're
working with.
address: np.array of size (level+1) representing the address
vector of a point in some SG graph.
Returns:
alt_address: np.array of size (level+1) representing the
alternate address of the same point in some SG graph.
Example:
alternate_address(2, [0, 1, 2]) = [0, 2, 1] (F1F0q2 = F2F0q1)
alternate_address(2, [1, 0, 0]) = [0, 1, 1] (F0F1q1 = F1F1q0)
"""
# Make a copy of the address
alt_address = np.copy(address)
if (level > 0):
# Find the index of the last address entry that is not equal
# to the final value
last_val = alt_address[level]
temp_index = level - 1
while (last_val == address[temp_index] and temp_index > 0):
temp_index = temp_index - 1
# If there is such an entry, interchange it with the final value
temp = alt_address[temp_index]
alt_address[temp_index] = alt_address[level]
alt_address[level] = temp
return alt_address
def alternate_index(level, index):
"""Compute the alternate TLR index of a point
Args:
level: A nonnegative integer representing the level of SG we're
working with.
index: A number in the range [1, 3^(level+1)] representing the
TLR index of some point in level m.
Returns:
alt_index: A number in the range [1, 3^(level+1)] representing
the alternate TLR index of the point in level m.
Example:
alternate_index(1, 2) = 4
alternate_index(1, 3) = 7
"""
current_address = address_from_index(level, index)
alt_address = alternate_address(level, current_address)
alt_index = index_from_address(level, alt_address)
return alt_index
def get_neighbors(level, address):
"""Compute the addresses of the 4 neighbors of a point
Args:
level: A nonnegative integer representing the level of SG we're
working with.
address: np.array of size (level+1) representing the address
vector of a point in some SG graph.
Returns:
nbhd_mat: np.array of size (4, level+1) representing the
address of the 4 neighbors of the point.
"""
# Find alternate address of the point
alt_address = alternate_address(level, address)
# ones has all coordinates 1
# di has only the (m+1)-th term 1, others 0
di = np.zeros(level + 1)
di[level] = 1
# Initialize space for nbhd matrix
nbhd_mat = np.zeros((4, level+1))
# The only update happens on the last term, where q_i is replaced by
# q_(i-1) and q_(i+1). Both cases reduce to mod 3 operations.
nbhd_mat[0, :] = np.mod(address - di, 3)
nbhd_mat[1, :] = np.mod(address + di, 3)
nbhd_mat[2, :] = np.mod(alt_address - di, 3)
nbhd_mat[3, :] = np.mod(alt_address + di, 3)
return nbhd_mat
def index_alternate_level(current_level, target_level, address):
"""Finds the index of a point in another level of SG
Args:
current_level: A nonnegative integer representing the current
level of SG we're working with.
target_level: A nonnegative integer representing the target
level of SG we're moving our point to. This should be larger
than the current level.
address: np.array of size (current_level+1) representing the
address vector of a point in some SG graph.
Returns:
target_index: A number in the range [1, 3^(target_level+1)]
representing the TLR index of the point in target_level.
Example:
index_alternate_level(1, 1, [0, 1]) = 2
index_alternate_level(1, 2, [0, 1]) = 5
index_alternate_level(1, 3, [0, 1]) = 14
"""
target_address = | np.zeros(target_level+1) | numpy.zeros |
import numpy as np
import itertools as it
import scipy as sp
from mallows_model import *
def weighted_median(sample, ws):
"""
Parameters
----------
sample: numpy array
RANKINGS
ws: float
weight of each permutation
Returns
-------
ranking
weigthed median ranking
"""
return borda(sample * ws[:, None])
def max_dist(n):
"""
Parameters
----------
n: int
length of permutations
Returns
-------
int
Maximum distance between permutations of given n length
"""
return n * (n - 1) // 2 # Integer division
def compose(s, p):
"""This function composes two given permutations
Parameters
----------
s: ndarray
The first permutation array
p: ndarray
The second permutation array
Returns
-------
ndarray
The composition of the permutations
"""
return np.array(s[p])
def compose_partial(partial, full):
"""This function composes a partial permutation with an other (full)
Parameters
----------
partial: ndarray
The partial permutation (should be filled with float)
full:
The full permutation (should be filled with integers)
Returns
-------
ndarray
The composition of the permutations
"""
# MANUEL: If full contains np.nan, then it cannot be filled with integers, because np.nan is float.
return [partial[i] if not np.isnan(i) else np.nan for i in full]
def inverse_partial(sigma):
"""This function computes the inverse of a given partial permutation
Parameters
----------
sigma: ndarray
A partial permutation array (filled with float)
Returns
-------
ndarray
The inverse of given partial permutation
"""
inv = np.full(len(sigma), np.nan)
for i,j in enumerate(sigma):
if not np.isnan(j):
inv[int(j)] = i
return inv
def inverse(s):
"""This function computes the inverse of a given permutation
Parameters
----------
s: ndarray
A permutation array
Returns
-------
ndarray
The inverse of given permutation
"""
return np.argsort(s)
def borda(rankings):
"""This function computes an average permutation given several permutations
Parameters
----------
rankings: ndarray
Matrix of several permutations
Returns
-------
ndarray
The 'average' permutation of permutations given
"""
# MANUEL: Using inverse instead of np.argsort clarifies the intention
consensus = inverse( # give the inverse of result --> sigma_0
inverse( # give the indexes to sort the sum vector --> sigma_0^-1
rankings.sum(axis=0) # sum the indexes of all permutations
)
) #borda
return consensus
def borda_partial(rankings, w, k):
"""
Parameters
----------
Returns
-------
"""
a, b = rankings, w
a, b = np.nan_to_num(rankings,nan=k), w
aux = a * b
borda = np.argsort(np.argsort(np.nanmean(aux, axis=0))).astype(float)
mask = np.isnan(rankings).all(axis=0)
borda[mask]=np.nan
return borda
def expected_dist_mm(n, theta=None, phi=None):
"""Compute the expected distance, MM under the Kendall's-tau distance
Parameters
----------
n: int
Length of the permutation in the considered model
theta: float
Real dispersion parameter (optionnal if phi is given)
phi: float
Real dispersion parameter (optionnal if theta is given)
Returns
-------
float
The expected disance under the MMs
"""
theta, phi = check_theta_phi(theta, phi)
# MANUEL:
# rnge = np.array(range(1,n+1))
rnge = np.arange(1, n + 1)
# exp_j_theta = np.exp(-j * theta)
# exp_dist = (n * n.exp(-theta) / (1 - n.exp(-theta))) - np.sum(j * exp_j_theta / (1 - exp_j_theta)
expected_dist = n * np.exp(-theta) / (1-np.exp(-theta)) - np.sum(rnge * np.exp(-rnge*theta) / (1 - np.exp(-rnge*theta)))
return expected_dist
def variance_dist_mm(n, theta=None, phi=None):
"""
Parameters
----------
Returns
-------
"""
theta, phi = check_theta_phi(theta, phi)
rnge = np.array(range(1,n+1))
variance = (phi*n)/(1-phi)**2 - np.sum((pow(phi,rnge) * rnge**2)/(1-pow(phi,rnge))**2)
return variance
def expected_v(n, theta=None, phi=None, k=None):#txapu integrar
"""This function computes the expected decomposition vector
Parameters
----------
n: int
Length of the permutation in the considered model
theta: float
Real dispersion parameter (optionnal if phi is given)
phi: float
Real dispersion parameter (optionnal if theta is given)
k: int
Index to which the decomposition vector is needed ???
Returns
-------
ndarray
The expected decomposition vector
"""
theta, phi = check_theta_phi(theta, phi)
if k is None: k = n-1
if type(theta)!=list: theta = np.full(k, theta)
rnge = np.array(range(k))
expected_v = np.exp(-theta[rnge]) / (1- | np.exp(-theta[rnge]) | numpy.exp |
# coding: utf-8
# Copyright (c) Pymatgen Development Team.
# Distributed under the terms of the MIT License.
"""
Magnetic space groups.
"""
import os
import sqlite3
import textwrap
from array import array
from fractions import Fraction
import numpy as np
from monty.design_patterns import cached_class
from pymatgen.core.operations import MagSymmOp
from pymatgen.electronic_structure.core import Magmom
from pymatgen.symmetry.groups import SymmetryGroup, in_array_list
from pymatgen.symmetry.settings import JonesFaithfulTransformation
from pymatgen.util.string import transformation_to_string
__author__ = "<NAME>, <NAME>"
__copyright__ = "Copyright 2017, The Materials Project"
__version__ = "0.1"
__maintainer__ = "<NAME>"
__email__ = "<EMAIL>"
__status__ = "Beta"
__date__ = "Feb 2017"
MAGSYMM_DATA = os.path.join(os.path.dirname(__file__), "symm_data_magnetic.sqlite")
@cached_class
class MagneticSpaceGroup(SymmetryGroup):
"""
Representation of a magnetic space group.
"""
def __init__(self, id, setting_transformation="a,b,c;0,0,0"):
"""
Initializes a MagneticSpaceGroup from its Belov, Neronova and
Smirnova (BNS) number supplied as a list or its label supplied
as a string. To create a magnetic structure in pymatgen, the
Structure.from_magnetic_spacegroup() method can be used, which
relies on this class.
The main difference between magnetic space groups and normal
crystallographic space groups is the inclusion of a time reversal
operator that acts on an atom's magnetic moment. This is
indicated by a prime symbol (') next to the respective symmetry
operation in its label, e.g. the standard crystallographic
space group Pnma has magnetic subgroups Pn'ma, Pnm'a, Pnma',
Pn'm'a, Pnm'a', Pn'ma', Pn'm'a'.
The magnetic space groups are classified as one of 4 types
where G = magnetic space group, and F = parent crystallographic
space group:
1. G=F no time reversal, i.e. the same as corresponding
crystallographic group
2. G=F+F1', "grey" groups, where avg. magnetic moment is zero,
e.g. a paramagnet in zero ext. mag. field
3. G=D+(F-D)1', where D is an equi-translation subgroup of F of
index 2, lattice translations do not include time reversal
4. G=D+(F-D)1', where D is an equi-class subgroup of F of index 2
There are two common settings for magnetic space groups, BNS
and OG. In case 4, the BNS setting != OG setting, and so a
transformation to go between the two settings is required:
specifically, the BNS setting is derived from D, and the OG
setting is derived from F.
This means that the OG setting refers to the unit cell if magnetic
order is neglected, and requires multiple unit cells to reproduce
the full crystal periodicity when magnetic moments are present.
This does not make the OG setting, in general, useful for
electronic structure calculations and the BNS setting is preferred.
However, this class does contain information on the OG setting and
can be initialized from OG labels or numbers if required.
Conventions: ITC monoclinic unique axis b, monoclinic cell choice 1,
hexagonal axis for trigonal groups, origin choice 2 for groups with
more than one origin choice (ISO-MAG).
Raw data comes from ISO-MAG, ISOTROPY Software Suite, iso.byu.edu
http://stokes.byu.edu/iso/magnetic_data.txt
with kind permission from Professor <NAME>, BYU
Data originally compiled from:
(1) <NAME>, Magnetic Group Tables (International Union
of Crystallography, 2013) www.iucr.org/publ/978-0-9553602-2-0.
(2) <NAME> and <NAME>, The Mathematical Theory of
Symmetry in Solids (Clarendon Press, Oxford, 1972).
See http://stokes.byu.edu/iso/magneticspacegroupshelp.php for more
information on magnetic symmetry.
:param id: BNS number supplied as list of 2 ints or BNS label as
str or index as int (1-1651) to iterate over all space groups"""
self._data = {}
# Datafile is stored as sqlite3 database since (a) it can be easily
# queried for various different indexes (BNS/OG number/labels) and (b)
# allows binary data to be stored in a compact form similar to that in
# the source data file, significantly reducing file size.
# Note that a human-readable JSON format was tested first but was 20x
# larger and required *much* longer initial loading times.
# retrieve raw data
db = sqlite3.connect(MAGSYMM_DATA)
c = db.cursor()
if isinstance(id, str):
id = "".join(id.split()) # remove any white space
c.execute("SELECT * FROM space_groups WHERE BNS_label=?;", (id,))
elif isinstance(id, list):
c.execute("SELECT * FROM space_groups WHERE BNS1=? AND BNS2=?;", (id[0], id[1]))
elif isinstance(id, int):
# OG3 index is a 'master' index, going from 1 to 1651
c.execute("SELECT * FROM space_groups WHERE OG3=?;", (id,))
raw_data = list(c.fetchone())
# Jones Faithful transformation
self.jf = JonesFaithfulTransformation.from_transformation_string("a,b,c;0,0,0")
if isinstance(setting_transformation, str):
if setting_transformation != "a,b,c;0,0,0":
self.jf = JonesFaithfulTransformation.from_transformation_string(setting_transformation)
elif isinstance(setting_transformation, JonesFaithfulTransformation):
if setting_transformation != self.jf:
self.jf = setting_transformation
self._data["magtype"] = raw_data[0] # int from 1 to 4
self._data["bns_number"] = [raw_data[1], raw_data[2]]
self._data["bns_label"] = raw_data[3]
self._data["og_number"] = [raw_data[4], raw_data[5], raw_data[6]]
self._data["og_label"] = raw_data[7] # can differ from BNS_label
def _get_point_operator(idx):
"""Retrieve information on point operator (rotation matrix and Seitz label)."""
hex = self._data["bns_number"][0] >= 143 and self._data["bns_number"][0] <= 194
c.execute(
"SELECT symbol, matrix FROM point_operators WHERE idx=? AND hex=?;",
(idx - 1, hex),
)
op = c.fetchone()
op = {
"symbol": op[0],
"matrix": np.array(op[1].split(","), dtype="f").reshape(3, 3),
}
return op
def _parse_operators(b):
"""Parses compact binary representation into list of MagSymmOps."""
if len(b) == 0: # e.g. if magtype != 4, OG setting == BNS setting, and b == [] for OG symmops
return None
raw_symops = [b[i : i + 6] for i in range(0, len(b), 6)]
symops = []
for r in raw_symops:
point_operator = _get_point_operator(r[0])
translation_vec = [r[1] / r[4], r[2] / r[4], r[3] / r[4]]
time_reversal = r[5]
op = MagSymmOp.from_rotation_and_translation_and_time_reversal(
rotation_matrix=point_operator["matrix"],
translation_vec=translation_vec,
time_reversal=time_reversal,
)
# store string representation, e.g. (2x|1/2,1/2,1/2)'
seitz = "({0}|{1},{2},{3})".format(
point_operator["symbol"],
Fraction(translation_vec[0]),
Fraction(translation_vec[1]),
Fraction(translation_vec[2]),
)
if time_reversal == -1:
seitz += "'"
symops.append({"op": op, "str": seitz})
return symops
def _parse_wyckoff(b):
"""Parses compact binary representation into list of Wyckoff sites."""
if len(b) == 0:
return None
wyckoff_sites = []
def get_label(idx):
if idx <= 25:
return chr(97 + idx) # returns a-z when idx 0-25
return "alpha" # when a-z labels exhausted, use alpha, only relevant for a few space groups
o = 0 # offset
n = 1 # nth Wyckoff site
num_wyckoff = b[0]
while len(wyckoff_sites) < num_wyckoff:
m = b[1 + o] # multiplicity
label = str(b[2 + o] * m) + get_label(num_wyckoff - n)
sites = []
for j in range(m):
s = b[3 + o + (j * 22) : 3 + o + (j * 22) + 22] # data corresponding to specific Wyckoff position
translation_vec = [s[0] / s[3], s[1] / s[3], s[2] / s[3]]
matrix = [
[s[4], s[7], s[10]],
[s[5], s[8], s[11]],
[s[6], s[9], s[12]],
]
matrix_magmom = [
[s[13], s[16], s[19]],
[s[14], s[17], s[20]],
[s[15], s[18], s[21]],
]
# store string representation, e.g. (x,y,z;mx,my,mz)
wyckoff_str = "({};{})".format(
transformation_to_string(matrix, translation_vec),
transformation_to_string(matrix_magmom, c="m"),
)
sites.append(
{
"translation_vec": translation_vec,
"matrix": matrix,
"matrix_magnetic": matrix_magmom,
"str": wyckoff_str,
}
)
# only keeping string representation of Wyckoff sites for now
# could do something else with these in future
wyckoff_sites.append({"label": label, "str": " ".join([s["str"] for s in sites])})
n += 1
o += m * 22 + 2
return wyckoff_sites
def _parse_lattice(b):
"""Parses compact binary representation into list of lattice vectors/centerings."""
if len(b) == 0:
return None
raw_lattice = [b[i : i + 4] for i in range(0, len(b), 4)]
lattice = []
for r in raw_lattice:
lattice.append(
{
"vector": [r[0] / r[3], r[1] / r[3], r[2] / r[3]],
"str": "({0},{1},{2})+".format(
Fraction(r[0] / r[3]).limit_denominator(),
Fraction(r[1] / r[3]).limit_denominator(),
Fraction(r[2] / r[3]).limit_denominator(),
),
}
)
return lattice
def _parse_transformation(b):
"""Parses compact binary representation into transformation between OG and BNS settings."""
if len(b) == 0:
return None
# capital letters used here by convention,
# IUCr defines P and p specifically
P = [[b[0], b[3], b[6]], [b[1], b[4], b[7]], [b[2], b[5], b[8]]]
p = [b[9] / b[12], b[10] / b[12], b[11] / b[12]]
P = np.array(P).transpose()
P_string = transformation_to_string(P, components=("a", "b", "c"))
p_string = "{},{},{}".format(
Fraction(p[0]).limit_denominator(),
Fraction(p[1]).limit_denominator(),
Fraction(p[2]).limit_denominator(),
)
return P_string + ";" + p_string
for i in range(8, 15):
try:
raw_data[i] = array("b", raw_data[i]) # construct array from sql binary blobs
except Exception:
# array() behavior changed, need to explicitly convert buffer to str in earlier Python
raw_data[i] = array("b", str(raw_data[i]))
self._data["og_bns_transform"] = _parse_transformation(raw_data[8])
self._data["bns_operators"] = _parse_operators(raw_data[9])
self._data["bns_lattice"] = _parse_lattice(raw_data[10])
self._data["bns_wyckoff"] = _parse_wyckoff(raw_data[11])
self._data["og_operators"] = _parse_operators(raw_data[12])
self._data["og_lattice"] = _parse_lattice(raw_data[13])
self._data["og_wyckoff"] = _parse_wyckoff(raw_data[14])
db.close()
@classmethod
def from_og(cls, id):
"""
Initialize from Opechowski and Guccione (OG) label or number.
:param id: OG number supplied as list of 3 ints or
or OG label as str
:return:
"""
db = sqlite3.connect(MAGSYMM_DATA)
c = db.cursor()
if isinstance(id, str):
c.execute("SELECT BNS_label FROM space_groups WHERE OG_label=?", (id,))
elif isinstance(id, list):
c.execute(
"SELECT BNS_label FROM space_groups WHERE OG1=? and OG2=? and OG3=?",
(id[0], id[1], id[2]),
)
bns_label = c.fetchone()[0]
db.close()
return cls(bns_label)
def __eq__(self, other):
return self._data == other._data
@property
def crystal_system(self):
"""
:return: Crystal system, e.g., cubic, hexagonal, etc.
"""
i = self._data["bns_number"][0]
if i <= 2:
return "triclinic"
if i <= 15:
return "monoclinic"
if i <= 74:
return "orthorhombic"
if i <= 142:
return "tetragonal"
if i <= 167:
return "trigonal"
if i <= 194:
return "hexagonal"
return "cubic"
@property
def sg_symbol(self):
"""
:return: Space group symbol
"""
return self._data["bns_label"]
@property
def symmetry_ops(self):
"""
Retrieve magnetic symmetry operations of the space group.
:return: List of :class:`pymatgen.core.operations.MagSymmOp`
"""
ops = [op_data["op"] for op_data in self._data["bns_operators"]]
# add lattice centerings
centered_ops = []
lattice_vectors = [l["vector"] for l in self._data["bns_lattice"]]
for vec in lattice_vectors:
if not (np.array_equal(vec, [1, 0, 0]) or np.array_equal(vec, [0, 1, 0]) or | np.array_equal(vec, [0, 0, 1]) | numpy.array_equal |
import tracemalloc
import numpy as np
import quantities as pq
from elephant.spike_train_generation import homogeneous_poisson_process
import matplotlib.pyplot as plt
from online_statistics import OnlineMeanFiringRate, OnlineInterSpikeInterval, \
OnlinePearsonCorrelationCoefficient
def omfr_plot_memory_benchmark_for_instantiation(buffer_sizes, used_memory,
std_error_memory):
fig, ax1 = plt.subplots(1, 1, figsize=(8, 5))
fig.suptitle(f"Memory Usage for Instancing Online MFR",
y=0.93, fontsize=18)
# rescale to MB
current = np.divide(used_memory[:, 0], 10 ** 6)
peak = np.divide(used_memory[:, 1], 10 ** 6)
std_error_memory = np.divide(std_error_memory, 10 ** 6)
ax1.errorbar(buffer_sizes, current, yerr=std_error_memory[:, 0],
ecolor='red', color="blue", marker="o", markerfacecolor="blue",
markeredgecolor='black',
label="current memory usage after instantiation")
ax1.errorbar(buffer_sizes, peak, yerr=std_error_memory[:, 1], ecolor='red',
color="orange", marker="o", markerfacecolor="orange",
markeredgecolor='black',
label="peak memory usage while instantiation")
ax1.set_xlabel(f"Buffer Size [s]", fontsize=16)
ax1.set_ylabel(f"Memory Usage [MB]", fontsize=16)
plt.legend(fontsize=16)
plt.savefig(f"plots/omfr_investigate_memory_usage_at_instantiation.pdf")
plt.show()
def omfr_benchmark_memory_at_instantiation(num_repetitions=100):
buffer_sizes = [0.1, 0.25, 0.5, 0.75, 1, 2, 4, 6, 8, 10] # in s
memory_for_instantiation = []
for rep in range(num_repetitions):
mem_for_inst_within_rep = []
for j, bs in enumerate(buffer_sizes):
# measure memory usage for instantiation
tracemalloc.start()
omfr = OnlineMeanFiringRate(buffer_size=bs)
current_i, peak_i = tracemalloc.get_traced_memory()
tracemalloc.stop()
mem_for_inst_within_rep.append((current_i, peak_i))
memory_for_instantiation.append(mem_for_inst_within_rep)
# calculating mean and standard error for memory usage at instantiation
mean_memory_for_instantiation = np.mean(memory_for_instantiation, axis=0)
std_error_of_memory_for_instantiation = \
np.std(memory_for_instantiation, axis=0) / np.sqrt(num_repetitions)
omfr_plot_memory_benchmark_for_instantiation(
buffer_sizes=buffer_sizes, used_memory=mean_memory_for_instantiation,
std_error_memory=std_error_of_memory_for_instantiation)
def trace_memory_usage_during_simulation_of_MFR_ISI_PCC(
num_buffers=100, buffer_size=1, firing_rate=50):
omfr_memory_usage = []
oisi_memory_usage = []
opcc_memory_usage = []
st_list = [homogeneous_poisson_process(
firing_rate*pq.Hz, t_start=buffer_size*i*pq.s,
t_stop=(buffer_size*i+buffer_size)*pq.s).magnitude
for i in range(num_buffers)]
tracemalloc.start()
omfr = OnlineMeanFiringRate()
oisi = OnlineInterSpikeInterval()
opcc = OnlinePearsonCorrelationCoefficient()
for i in range(num_buffers):
omfr.update_mfr(spike_buffer=st_list[i])
oisi.update_isi(spike_buffer=st_list[i])
opcc.update_pcc(spike_buffer1=st_list[i], spike_buffer2=st_list[i])
snapshot = tracemalloc.take_snapshot()
# filter OMFR trace
omfr_filter_instantiation = tracemalloc.Filter(
inclusive=True, filename_pattern="*/benchmark_memory.py",
lineno=_get_line_number(omfr))
omfr_filter_update = tracemalloc.Filter(
inclusive=True, filename_pattern="*/benchmark_memory.py",
lineno=_get_line_number(omfr)+4)
omfr_snapshot_filtered = snapshot.filter_traces(
filters=[omfr_filter_instantiation, omfr_filter_update])
omfr_filterd_stats = omfr_snapshot_filtered.statistics("lineno")
omfr_memory_usage.append((omfr_filterd_stats[0].size,
omfr_filterd_stats[1].size))
# filter OISI trace
oisi_filter_instantiation = tracemalloc.Filter(
inclusive=True, filename_pattern="*/benchmark_memory.py",
lineno=_get_line_number(oisi))
oisi_filter_update = tracemalloc.Filter(
inclusive=True, filename_pattern="*/benchmark_memory.py",
lineno=_get_line_number(oisi)+4)
oisi_snapshot_filtered = snapshot.filter_traces(
filters=[oisi_filter_instantiation, oisi_filter_update])
oisi_filterd_stats = oisi_snapshot_filtered.statistics("lineno")
oisi_memory_usage.append((oisi_filterd_stats[0].size,
oisi_filterd_stats[1].size))
# filter OPCC trace
opcc_filter_instantiation = tracemalloc.Filter(
inclusive=True, filename_pattern="*/benchmark_memory.py",
lineno=_get_line_number(opcc))
opcc_filter_update = tracemalloc.Filter(
inclusive=True, filename_pattern="*/benchmark_memory.py",
lineno=_get_line_number(opcc)+4)
opcc_snapshot_filtered = snapshot.filter_traces(
filters=[opcc_filter_instantiation, opcc_filter_update])
opcc_filterd_stats = opcc_snapshot_filtered.statistics("lineno")
opcc_memory_usage.append((opcc_filterd_stats[0].size,
opcc_filterd_stats[1].size))
tracemalloc.stop()
fig, ax1 = plt.subplots(1, 1, figsize=(10, 6))
fig.suptitle(f"Memory Usage of Online MFR, ISI and PCC",
y=0.93, fontsize=22)
# plot MFR memory usage results
ax1.plot(np.arange(0, num_buffers), np.asarray(omfr_memory_usage)[:, 0],
color="lightblue", marker="o", markerfacecolor="lightblue",
markeredgecolor='black', label="OMFR @ instance")
ax1.plot(np.arange(0, num_buffers), np.asarray(omfr_memory_usage)[:, 1],
color="blue", marker="o", markerfacecolor="blue",
markeredgecolor='black', label="OMFR @ update")
# plot ISI memory usage results
ax1.plot(np.arange(0, num_buffers), np.asarray(oisi_memory_usage)[:, 0],
color="lightcoral", marker="o", markerfacecolor="lightcoral",
markeredgecolor='black', label="OISI @ instance")
ax1.plot( | np.arange(0, num_buffers) | numpy.arange |
import numpy as np
import matplotlib.pyplot as plt
from sklearn.cluster import AgglomerativeClustering
from sklearn.neighbors import kneighbors_graph
def add_noise(x, y, amplitude):
X = np.concatenate((x, y))
X += amplitude * np.random.randn(2, X.shape[1])
return X.T
def get_spiral(t, noise_amplitude=0.5):
r = t
x = r * np.cos(t)
y = r * np.sin(t)
return add_noise(x, y, noise_amplitude)
def get_rose(t, noise_amplitude=0.02):
# Equation for "rose" (or rhodonea curve); if k is odd, then
# the curve will have k petals, else it will have 2k petals
k = 5
r = np.cos(k*t) + 0.25
x = r * np.cos(t)
y = r * np.sin(t)
return add_noise(x, y, noise_amplitude)
def get_hypotrochoid(t, noise_amplitude=0):
a, b, h = 10.0, 2.0, 4.0
x = (a - b) * np.cos(t) + h * np.cos((a - b) / b * t)
y = (a - b) * np.sin(t) - h * np.sin((a - b) / b * t)
return add_noise(x, y, 0)
def perform_clustering(X, connectivity, title, num_clusters=3, linkage='ward'):
plt.figure()
model = AgglomerativeClustering(linkage=linkage,
connectivity=connectivity, n_clusters=num_clusters)
model.fit(X)
# extract labels
labels = model.labels_
# specify marker shapes for different clusters
markers = '.vx'
for i, marker in zip(range(num_clusters), markers):
# plot the points belong to the current cluster
plt.scatter(X[labels==i, 0], X[labels==i, 1], s=50,
marker=marker, color='k', facecolors='none')
plt.title(title)
if __name__=='__main__':
# Generate sample data
n_samples = 500
np.random.seed(2)
t = 2.5 * np.pi * (1 + 2 * | np.random.rand(1, n_samples) | numpy.random.rand |
import numpy as np
def clip(val, min, max):
if val < min:
return min
elif val > max:
return max
else:
return val
def count_overlaps(segments, seglen):
def helper(segments):
maxlen= segments[-1][1]
zeros = np.zeros(maxlen)
for seg in segments:
zeros[seg[0]:seg[-1]] += 1
return zeros
zeros = helper(segments)
speech = len(np.where(zeros==1)[0])
return seglen-speech, speech, len( | np.where(zeros==2) | numpy.where |
import gc
import lightgbm as lgb
import numpy as np
import pandas as pd
from tqdm import tqdm
def get_expectations(P, pNone=None):
expectations = []
P = np.sort(P)[::-1]
n = np.array(P).shape[0]
DP_C = np.zeros((n + 2, n + 1))
if pNone is None:
pNone = (1.0 - P).prod()
DP_C[0][0] = 1.0
for j in range(1, n):
DP_C[0][j] = (1.0 - P[j - 1]) * DP_C[0, j - 1]
for i in range(1, n + 1):
DP_C[i, i] = DP_C[i - 1, i - 1] * P[i - 1]
for j in range(i + 1, n + 1):
DP_C[i, j] = P[j - 1] * DP_C[i - 1, j - 1] + (1.0 - P[j - 1]) * DP_C[i, j - 1]
DP_S = np.zeros((2 * n + 1,))
DP_SNone = | np.zeros((2 * n + 1,)) | numpy.zeros |
import numpy as np
import scipy.stats
import os
import logging
from astropy.tests.helper import pytest, catch_warnings
from astropy.modeling import models
from astropy.modeling.fitting import _fitter_to_model_params
from stingray import Powerspectrum
from stingray.modeling import ParameterEstimation, PSDParEst, \
OptimizationResults, SamplingResults
from stingray.modeling import PSDPosterior, set_logprior, PSDLogLikelihood, \
LogLikelihood
try:
from statsmodels.tools.numdiff import approx_hess
comp_hessian = True
except ImportError:
comp_hessian = False
try:
import emcee
can_sample = True
except ImportError:
can_sample = False
try:
import matplotlib.pyplot as plt
can_plot = True
except ImportError:
can_plot = False
class LogLikelihoodDummy(LogLikelihood):
def __init__(self, x, y, model):
LogLikelihood.__init__(self, x, y, model)
def evaluate(self, parse, neg=False):
return np.nan
class OptimizationResultsSubclassDummy(OptimizationResults):
def __init__(self, lpost, res, neg, log=None):
if log is None:
self.log = logging.getLogger('Fitting summary')
self.log.setLevel(logging.DEBUG)
if not self.log.handlers:
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
self.log.addHandler(ch)
self.neg = neg
if res is not None:
self.result = res.fun
self.p_opt = res.x
else:
self.result = None
self.p_opt = None
self.model = lpost.model
class TestParameterEstimation(object):
@classmethod
def setup_class(cls):
| np.random.seed(100) | numpy.random.seed |
from .. import util
from ..probabilities import pulsars, mass
from ..core.data import Observations, Model
import h5py
import numpy as np
import astropy.units as u
import matplotlib.pyplot as plt
import matplotlib.colors as mpl_clr
import astropy.visualization as astroviz
__all__ = ['ModelVisualizer', 'CIModelVisualizer', 'ObservationsVisualizer']
class _ClusterVisualizer:
_MARKERS = ('o', '^', 'D', '+', 'x', '*', 's', 'p', 'h', 'v', '1', '2')
# Default xaxis limits for all profiles. Set by inits, can be reset by user
rlims = None
# -----------------------------------------------------------------------
# Artist setups
# -----------------------------------------------------------------------
def _setup_artist(self, fig, ax, *, use_name=True):
'''setup a plot (figure and ax) with one single ax'''
if ax is None:
if fig is None:
# no figure or ax provided, make one here
fig, ax = plt.subplots()
else:
# Figure provided, no ax provided. Try to grab it from the fig
# if that doens't work, create it
cur_axes = fig.axes
if len(cur_axes) > 1:
raise ValueError(f"figure {fig} already has too many axes")
elif len(cur_axes) == 1:
ax = cur_axes[0]
else:
ax = fig.add_subplot()
else:
if fig is None:
# ax is provided, but no figure. Grab it's figure from it
fig = ax.get_figure()
if hasattr(self, 'name') and use_name:
fig.suptitle(self.name)
return fig, ax
def _setup_multi_artist(self, fig, shape, *, allow_blank=True,
use_name=True, constrained_layout=True,
subfig_kw=None, **sub_kw):
'''setup a subplot with multiple axes'''
if subfig_kw is None:
subfig_kw = {}
def create_axes(base, shape):
'''create the axes of `shape` on this base (fig)'''
# make sure shape is a tuple of atleast 1d, at most 2d
if not isinstance(shape, tuple):
# TODO doesnt work on an int
shape = tuple(shape)
if len(shape) == 1:
shape = (shape, 1)
elif len(shape) > 2:
mssg = f"Invalid `shape` for subplots {shape}, must be 2D"
raise ValueError(mssg)
# split into dict of nrows, ncols
shape = dict(zip(("nrows", "ncols"), shape))
# if either of them is also a tuple, means we want columns or rows
# of varying sizes, switch to using subfigures
# TODO what are the chances stuff like `sharex` works correctly?
if isinstance(shape['nrows'], tuple):
subfigs = base.subfigures(ncols=shape['ncols'], nrows=1,
squeeze=False, **subfig_kw)
for ind, sf in enumerate(subfigs.flatten()):
try:
nr = shape['nrows'][ind]
except IndexError:
if allow_blank:
continue
mssg = (f"Number of row entries {shape['nrows']} must "
f"match number of columns ({shape['ncols']})")
raise ValueError(mssg)
sf.subplots(ncols=1, nrows=nr, **sub_kw)
elif isinstance(shape['ncols'], tuple):
subfigs = base.subfigures(nrows=shape['nrows'], ncols=1,
squeeze=False, **subfig_kw)
for ind, sf in enumerate(subfigs.flatten()):
try:
nc = shape['ncols'][ind]
except IndexError:
if allow_blank:
continue
mssg = (f"Number of col entries {shape['ncols']} must "
f"match number of rows ({shape['nrows']})")
raise ValueError(mssg)
sf.subplots(nrows=1, ncols=nc, **sub_kw)
# otherwise just make a simple subplots and return that
else:
base.subplots(**shape, **sub_kw)
return base, base.axes
# ------------------------------------------------------------------
# Create figure, if necessary
# ------------------------------------------------------------------
if fig is None:
fig = plt.figure(constrained_layout=constrained_layout)
# ------------------------------------------------------------------
# If no shape is provided, just return the figure, probably empty
# ------------------------------------------------------------------
if shape is None:
axarr = []
# ------------------------------------------------------------------
# Otherwise attempt to first grab this figures axes, or create them
# ------------------------------------------------------------------
else:
# this fig has axes, check that they match shape
if axarr := fig.axes:
# TODO this won't actually work, cause fig.axes is just a list
if axarr.shape != shape:
mssg = (f"figure {fig} already contains axes with "
f"mismatched shape ({axarr.shape} != {shape})")
raise ValueError(mssg)
else:
fig, axarr = create_axes(fig, shape)
# ------------------------------------------------------------------
# If desired, default to titling the figure based on it's "name"
# ------------------------------------------------------------------
if hasattr(self, 'name') and use_name:
fig.suptitle(self.name)
# ------------------------------------------------------------------
# Ensure the axes are always returned in an array
# ------------------------------------------------------------------
return fig, np.atleast_1d(axarr)
# -----------------------------------------------------------------------
# Unit support
# -----------------------------------------------------------------------
def _support_units(method):
import functools
@functools.wraps(method)
def _unit_decorator(self, *args, **kwargs):
# convert based on median distance parameter
eqvs = util.angular_width(self.d)
with astroviz.quantity_support(), u.set_enabled_equivalencies(eqvs):
return method(self, *args, **kwargs)
return _unit_decorator
# -----------------------------------------------------------------------
# Plotting functionality
# -----------------------------------------------------------------------
def _get_median(self, percs):
'''from an array of data percentiles, return the median array'''
return percs[percs.shape[0] // 2] if percs.ndim > 1 else percs
def _get_err(self, dataset, key):
'''gather the error variables corresponding to `key` from `dataset`'''
try:
return dataset[f'Δ{key}']
except KeyError:
try:
return (dataset[f'Δ{key},down'], dataset[f'Δ{key},up'])
except KeyError:
return None
def _plot_model(self, ax, data, intervals=None, *,
x_data=None, x_unit='pc', y_unit=None,
CI_kwargs=None, **kwargs):
CI_kwargs = dict() if CI_kwargs is None else CI_kwargs
# ------------------------------------------------------------------
# Evaluate the shape of the data array to determine confidence
# intervals, if applicable
# ------------------------------------------------------------------
if data is None or data.ndim == 0:
return
elif data.ndim == 1:
data = data.reshape((1, data.size))
if not (data.shape[0] % 2):
mssg = 'Invalid `data`, must have odd-numbered zeroth axis shape'
raise ValueError(mssg)
midpoint = data.shape[0] // 2
if intervals is None:
intervals = midpoint
elif intervals > midpoint:
mssg = f'{intervals}σ is outside stored range of {midpoint}σ'
raise ValueError(mssg)
# ------------------------------------------------------------------
# Convert any units desired
# ------------------------------------------------------------------
x_domain = self.r if x_data is None else x_data
if x_unit:
x_domain = x_domain.to(x_unit)
if y_unit:
data = data.to(y_unit)
# ------------------------------------------------------------------
# Plot the median (assumed to be the middle axis of the intervals)
# ------------------------------------------------------------------
median = data[midpoint]
med_plot, = ax.plot(x_domain, median, **kwargs)
# ------------------------------------------------------------------
# Plot confidence intervals successively from the midpoint
# ------------------------------------------------------------------
output = [med_plot]
CI_kwargs.setdefault('color', med_plot.get_color())
alpha = 0.8 / (intervals + 1)
for sigma in range(1, intervals + 1):
CI = ax.fill_between(
x_domain, data[midpoint + sigma], data[midpoint - sigma],
alpha=(1 - alpha), **CI_kwargs
)
output.append(CI)
alpha += alpha
return output
def _plot_data(self, ax, dataset, y_key, *,
x_key='r', x_unit='pc', y_unit=None,
err_transform=None, **kwargs):
# TODO need to handle colours better
defaultcolour = None
# ------------------------------------------------------------------
# Get data and relevant errors for plotting
# ------------------------------------------------------------------
xdata = dataset[x_key]
ydata = dataset[y_key]
xerr = self._get_err(dataset, x_key)
yerr = self._get_err(dataset, y_key)
# ------------------------------------------------------------------
# Convert any units desired
# ------------------------------------------------------------------
if x_unit is not None:
xdata = xdata.to(x_unit)
if y_unit is not None:
ydata = ydata.to(y_unit)
# ------------------------------------------------------------------
# If given, transform errors based on `err_transform` function
# ------------------------------------------------------------------
if err_transform is not None:
yerr = err_transform(yerr)
# ------------------------------------------------------------------
# Setup default plotting details, style, labels
# ------------------------------------------------------------------
kwargs.setdefault('marker', '.')
kwargs.setdefault('linestyle', 'None')
kwargs.setdefault('color', defaultcolour)
# TODO should try to cite, but if that fails just use raw bibcode?
label = dataset.cite()
if 'm' in dataset.mdata:
label += fr' ($m={dataset.mdata["m"]}\ M_\odot$)'
# ------------------------------------------------------------------
# Plot
# ------------------------------------------------------------------
# TODO not sure if I like the mfc=none style,
# mostly due to https://github.com/matplotlib/matplotlib/issues/3400
return ax.errorbar(xdata, ydata, xerr=xerr, yerr=yerr, mfc='none',
label=label, **kwargs)
def _plot_profile(self, ax, ds_pattern, y_key, model_data, *,
residuals=False, err_transform=None,
**kwargs):
'''figure out what needs to be plotted and call model/data plotters
all **kwargs passed to both _plot_model and _plot_data
model_data dimensions *must* be (mass bins, intervals, r axis)
'''
# TODO we might still want to allow for specific model/data kwargs?
ds_pattern = ds_pattern or ''
strict = kwargs.pop('strict', False)
# Restart marker styles each plotting call
markers = iter(self._MARKERS)
# TODO need to figure out how we handle passed kwargs better
default_clr = kwargs.pop('color', None)
# ------------------------------------------------------------------
# Determine the relevant datasets to the given pattern
# ------------------------------------------------------------------
datasets = self.obs.filter_datasets(ds_pattern)
if strict and ds_pattern and not datasets:
mssg = f"Dataset matching '{ds_pattern}' do not exist in {self.obs}"
# raise DataError
raise KeyError(mssg)
# ------------------------------------------------------------------
# Iterate over the datasets, keeping track of all relevant masses
# and calling `_plot_data`
# ------------------------------------------------------------------
masses = {}
for key, dset in datasets.items():
mrk = next(markers)
# get mass bin of this dataset, for later model plotting
if 'm' in dset.mdata:
m = dset.mdata['m'] * u.Msun
mass_bin = np.where(self.mj == m)[0][0]
else:
mass_bin = self.star_bin
if mass_bin in masses:
clr = masses[mass_bin][0][0].get_color()
else:
clr = default_clr
# plot the data
try:
line = self._plot_data(ax, dset, y_key, marker=mrk, color=clr,
err_transform=err_transform, **kwargs)
except KeyError as err:
if strict:
raise err
else:
# warnings.warn(err.args[0])
continue
masses.setdefault(mass_bin, [])
masses[mass_bin].append(line)
# ------------------------------------------------------------------
# Based on the masses of data plotted, plot the corresponding axes of
# the model data, calling `_plot_model`
# ------------------------------------------------------------------
if model_data is not None:
# ensure that the data is (mass bin, intervals, r domain)
if len(model_data.shape) != 3:
raise ValueError("invalid model data shape")
# No data plotted, use the star_bin
if not masses:
if model_data.shape[0] > 1:
masses = {self.star_bin: None}
else:
masses = {0: None}
res_ax = None
for mbin, errbars in masses.items():
ymodel = model_data[mbin, :, :]
# TODO having model/data be same color is kinda hard to read
# this is why I added mfc=none, but I dont like that either
if errbars is not None:
clr = errbars[0][0].get_color()
else:
clr = default_clr
self._plot_model(ax, ymodel, color=clr, **kwargs)
if residuals:
res_ax = self._add_residuals(ax, ymodel, errbars,
res_ax=res_ax, **kwargs)
if self.rlims is not None:
ax.set_xlim(*self.rlims)
# -----------------------------------------------------------------------
# Plot extras
# -----------------------------------------------------------------------
def _add_residuals(self, ax, ymodel, errorbars, *,
xmodel=None, y_unit=None, res_ax=None, **kwargs):
'''
errorbars : a list of outputs from calls to plt.errorbars
'''
from mpl_toolkits.axes_grid1 import make_axes_locatable
if not errorbars:
mssg = "Cannot compute residuals, no observables data provided"
raise ValueError(mssg)
# ------------------------------------------------------------------
# Get model data and spline
# ------------------------------------------------------------------
if xmodel is None:
xmodel = self.r
if y_unit is not None:
ymodel = ymodel.to(y_unit)
ymedian = self._get_median(ymodel)
yspline = util.QuantitySpline(xmodel, ymedian)
# ------------------------------------------------------------------
# Setup axes, adding a new smaller axe for the residual underneath,
# if it hasn't already been created (and passed to `res_ax`)
# ------------------------------------------------------------------
if res_ax is None:
divider = make_axes_locatable(ax)
res_ax = divider.append_axes('bottom', size="15%", pad=0, sharex=ax)
res_ax.grid()
res_ax.set_xscale(ax.get_xscale())
# ------------------------------------------------------------------
# Plot the model line, hopefully centred on zero
# ------------------------------------------------------------------
self._plot_model(res_ax, ymodel - ymedian, color='k')
# ------------------------------------------------------------------
# Get data from the plotted errorbars
# ------------------------------------------------------------------
for errbar in errorbars:
# --------------------------------------------------------------
# Get the actual datapoints, and the hopefully correct units
# --------------------------------------------------------------
xdata, ydata = errbar[0].get_data()
ydata = ydata.to(ymedian.unit)
# --------------------------------------------------------------
# Grab relevant formatting (colours and markers)
# --------------------------------------------------------------
clr = errbar[0].get_color()
mrk = errbar[0].get_marker()
# --------------------------------------------------------------
# Parse the errors from the size of the errorbar lines (messy)
# --------------------------------------------------------------
xerr = yerr = None
if errbar.has_xerr:
xerr_lines = errbar[2][0]
yerr_lines = errbar[2][1] if errbar.has_yerr else None
elif errbar.has_yerr:
xerr_lines, yerr_lines = None, errbar[2][0]
else:
xerr_lines = yerr_lines = None
if xerr_lines:
xerr = np.array([(np.diff(seg, axis=0) / 2)[..., -1]
for seg in xerr_lines.get_segments()]).T[0]
xerr <<= xdata.unit
if yerr_lines:
yerr = np.array([(np.diff(seg, axis=0) / 2)[..., -1]
for seg in yerr_lines.get_segments()]).T[0]
yerr <<= ydata.unit
# --------------------------------------------------------------
# Compute the residuals and plot them
# --------------------------------------------------------------
res = yspline(xdata) - ydata
res_ax.errorbar(xdata, res, xerr=xerr, yerr=yerr,
color=clr, marker=mrk, linestyle='none')
return res_ax
def _add_hyperparam(self, ax, ymodel, xdata, ydata, yerr):
# TODO this is still a complete mess
yspline = util.QuantitySpline(self.r, ymodel)
if hasattr(ax, 'aeff_text'):
aeff_str = ax.aeff_text.get_text()
aeff = float(aeff_str[aeff_str.rfind('$') + 1:])
else:
# TODO figure out best place to place this at
ax.aeff_text = ax.text(0.1, 0.3, '')
aeff = 0.
aeff += util.hyperparam_effective(ydata, yspline(xdata), yerr)
ax.aeff_text.set_text(fr'$\alpha_{{eff}}=${aeff:.4e}')
# -----------------------------------------------------------------------
# Observables plotting
# -----------------------------------------------------------------------
@_support_units
def plot_LOS(self, fig=None, ax=None,
show_obs=True, residuals=False, *,
x_unit='pc', y_unit='km/s'):
fig, ax = self._setup_artist(fig, ax)
ax.set_title('Line-of-Sight Velocity Dispersion')
ax.set_xscale("log")
if show_obs:
pattern, var = '*velocity_dispersion*', 'σ'
strict = show_obs == 'strict'
else:
pattern = var = None
strict = False
self._plot_profile(ax, pattern, var, self.LOS,
strict=strict, residuals=residuals,
x_unit=x_unit, y_unit=y_unit)
ax.legend()
return fig
@_support_units
def plot_pm_tot(self, fig=None, ax=None,
show_obs=True, residuals=False, *,
x_unit='pc', y_unit='mas/yr'):
fig, ax = self._setup_artist(fig, ax)
ax.set_title("Total Proper Motion")
ax.set_xscale("log")
if show_obs:
pattern, var = '*proper_motion*', 'PM_tot'
strict = show_obs == 'strict'
else:
pattern = var = None
strict = False
self._plot_profile(ax, pattern, var, self.pm_tot,
strict=strict, residuals=residuals,
x_unit=x_unit, y_unit=y_unit)
ax.legend()
return fig
@_support_units
def plot_pm_ratio(self, fig=None, ax=None,
show_obs=True, residuals=False, *,
x_unit='pc'):
fig, ax = self._setup_artist(fig, ax)
ax.set_title("Proper Motion Anisotropy")
ax.set_xscale("log")
if show_obs:
pattern, var = '*proper_motion*', 'PM_ratio'
strict = show_obs == 'strict'
else:
pattern = var = None
strict = False
self._plot_profile(ax, pattern, var, self.pm_ratio,
strict=strict, residuals=residuals,
x_unit=x_unit)
ax.legend()
return fig
@_support_units
def plot_pm_T(self, fig=None, ax=None,
show_obs=True, residuals=False, *,
x_unit='pc', y_unit='mas/yr'):
fig, ax = self._setup_artist(fig, ax)
ax.set_title("Tangential Proper Motion")
ax.set_xscale("log")
if show_obs:
pattern, var = '*proper_motion*', 'PM_T'
strict = show_obs == 'strict'
else:
pattern = var = None
strict = False
# pm_T = self.pm_T.to('mas/yr')
self._plot_profile(ax, pattern, var, self.pm_T,
strict=strict, residuals=residuals,
x_unit=x_unit, y_unit=y_unit)
ax.legend()
return fig
@_support_units
def plot_pm_R(self, fig=None, ax=None,
show_obs=True, residuals=False, *,
x_unit='pc', y_unit='mas/yr'):
fig, ax = self._setup_artist(fig, ax)
ax.set_title("Radial Proper Motion")
ax.set_xscale("log")
if show_obs:
pattern, var = '*proper_motion*', 'PM_R'
strict = show_obs == 'strict'
else:
pattern = var = None
strict = False
# pm_R = self.pm_R.to('mas/yr')
self._plot_profile(ax, pattern, var, self.pm_R,
strict=strict, residuals=residuals,
x_unit=x_unit, y_unit=y_unit)
ax.legend()
return fig
@_support_units
def plot_number_density(self, fig=None, ax=None,
show_obs=True, residuals=False, *,
x_unit='pc'):
def quad_nuisance(err):
return np.sqrt(err**2 + (self.s2 << err.unit**2))
fig, ax = self._setup_artist(fig, ax)
ax.set_title('Number Density')
ax.loglog()
if show_obs:
pattern, var = '*number_density*', 'Σ'
strict = show_obs == 'strict'
kwargs = {'err_transform': quad_nuisance}
else:
pattern = var = None
strict = False
kwargs = {}
self._plot_profile(ax, pattern, var, self.numdens,
strict=strict, residuals=residuals,
x_unit=x_unit, **kwargs)
# bit arbitrary, but probably fine for the most part
ax.set_ylim(bottom=1e-4)
ax.legend()
return fig
@_support_units
def plot_pulsar(self, fig=None, ax=None, show_obs=True):
# TODO this is out of date with the new pulsar probability code
# TODO I dont even think this is what we should use anymore, but the
# new convolved distributions peak
fig, ax = self._setup_artist(fig, ax)
ax.set_title('Pulsar LOS Acceleration')
ax.set_xlabel('R')
ax.set_ylabel(r'$a_{los}$')
maz = u.Quantity(np.empty(self.model.nstep - 1), '1/s')
for i in range(self.model.nstep - 1):
a_domain, Paz = pulsars.cluster_component(self.model, self.model.r[i], -1)
maz[i] = a_domain[Paz.argmax()] << maz.unit
maz = (self.obs['pulsar/P'] * maz).decompose()
if show_obs:
try:
obs_pulsar = self.obs['pulsar']
ax.errorbar(obs_pulsar['r'],
self.obs['pulsar/Pdot'],
yerr=self.obs['pulsar/ΔPdot'],
fmt='k.')
except KeyError as err:
if show_obs != 'attempt':
raise err
model_r = self.model.r.to(u.arcmin, util.angular_width(self.model.d))
upper_az, = ax.plot(model_r[:-1], maz)
ax.plot(model_r[:-1], -maz, c=upper_az.get_color())
return fig
@_support_units
def plot_pulsar_spin_dist(self, fig=None, ax=None, pulsar_ind=0,
show_obs=True, show_conv=False):
import scipy.interpolate as interp
fig, ax = self._setup_artist(fig, ax)
# pulsars = self.obs['pulsar']
puls_obs = self.obs['pulsar/spin']
id_ = puls_obs['id'][pulsar_ind].value.decode()
ax.set_title(f'Pulsar "{id_}" Period Derivative Likelihood')
ax.set_ylabel('Probability')
ax.set_xlabel(r'$\dot{P}/P$ $\left[s^{-1}\right]$')
mass_bin = -1
kde = pulsars.field_Pdot_KDE()
Pdot_min, Pdot_max = kde.dataset[1].min(), kde.dataset[1].max()
R = puls_obs['r'][pulsar_ind].to(u.pc)
P = puls_obs['P'][pulsar_ind].to('s')
Pdot_meas = puls_obs['Pdot'][pulsar_ind]
ΔPdot_meas = np.abs(puls_obs['ΔPdot'][pulsar_ind])
PdotP_domain, PdotP_c_prob = pulsars.cluster_component(self.model,
R, mass_bin)
Pdot_domain = (P * PdotP_domain).decompose()
# linear to avoid effects around asymptote
Pdot_c_spl = interp.UnivariateSpline(
Pdot_domain, PdotP_c_prob, k=1, s=0, ext=1
)
err = util.gaussian(x=Pdot_domain, sigma=ΔPdot_meas, mu=0)
err_spl = interp.UnivariateSpline(Pdot_domain, err, k=3, s=0, ext=1)
lg_P = np.log10(P / P.unit)
P_grid, Pdot_int_domain = np.mgrid[lg_P:lg_P:1j, Pdot_min:Pdot_max:200j]
P_grid, Pdot_int_domain = P_grid.ravel(), Pdot_int_domain.ravel()
Pdot_int_prob = kde(np.vstack([P_grid, Pdot_int_domain]))
Pdot_int_spl = interp.UnivariateSpline(
Pdot_int_domain, Pdot_int_prob, k=3, s=0, ext=1
)
Pdot_int_prob = util.RV_transform(
domain=10**Pdot_int_domain, f_X=Pdot_int_spl,
h=np.log10, h_prime=lambda y: (1 / (np.log(10) * y))
)
Pdot_int_spl = interp.UnivariateSpline(
10**Pdot_int_domain, Pdot_int_prob, k=3, s=0, ext=1
)
lin_domain = np.linspace(0., 1e-18, 5_000 // 2)
lin_domain = np.concatenate((np.flip(-lin_domain[1:]), lin_domain))
conv1 = np.convolve(err_spl(lin_domain), Pdot_c_spl(lin_domain), 'same')
conv2 = np.convolve(conv1, Pdot_int_spl(lin_domain), 'same')
# Normalize
conv2 /= interp.UnivariateSpline(
lin_domain, conv2, k=3, s=0, ext=1
).integral(-np.inf, np.inf)
cluster_μ = self.obs.mdata['μ'] << u.Unit("mas/yr")
PdotP_pm = pulsars.shklovskii_component(cluster_μ, self.model.d)
cluster_coords = (self.obs.mdata['b'], self.obs.mdata['l']) * u.deg
PdotP_gal = pulsars.galactic_component(*cluster_coords, D=self.model.d)
x_total = (lin_domain / P) + PdotP_pm + PdotP_gal
ax.plot(x_total, conv2)
if show_conv:
# Will really mess the scaling up, usually
ax.plot(x_total, Pdot_c_spl(lin_domain))
ax.plot(x_total, conv1)
if show_obs:
ax.axvline((Pdot_meas / P).decompose(), c='r', ls=':')
prob_dist = interp.interp1d(
(lin_domain / P) + PdotP_pm + PdotP_gal, conv2,
assume_sorted=True, bounds_error=False, fill_value=0.0
)
print('prob=', prob_dist((Pdot_meas / P).decompose()))
return fig
@_support_units
def plot_pulsar_orbital_dist(self, fig=None, ax=None, pulsar_ind=0,
show_obs=True, show_conv=False):
import scipy.interpolate as interp
fig, ax = self._setup_artist(fig, ax)
# pulsars = self.obs['pulsar']
puls_obs = self.obs['pulsar/orbital']
id_ = puls_obs['id'][pulsar_ind].value.decode()
ax.set_title(f'Pulsar "{id_}" Period Derivative Likelihood')
ax.set_ylabel('Probability')
ax.set_xlabel(r'$\dot{P}/P$ $\left[s^{-1}\right]$')
mass_bin = -1
R = puls_obs['r'][pulsar_ind].to(u.pc)
P = puls_obs['Pb'][pulsar_ind].to('s')
Pdot_meas = puls_obs['Pbdot'][pulsar_ind]
ΔPdot_meas = np.abs(puls_obs['ΔPbdot'][pulsar_ind])
PdotP_domain, PdotP_c_prob = pulsars.cluster_component(self.model,
R, mass_bin)
Pdot_domain = (P * PdotP_domain).decompose()
Pdot_c_spl = interp.UnivariateSpline(
Pdot_domain, PdotP_c_prob, k=1, s=0, ext=1
)
err = util.gaussian(x=Pdot_domain, sigma=ΔPdot_meas, mu=0)
err_spl = interp.UnivariateSpline(Pdot_domain, err, k=3, s=0, ext=1)
lin_domain = np.linspace(0., 1e-11, 5_000 // 2)
lin_domain = np.concatenate((np.flip(-lin_domain[1:]), lin_domain))
conv = np.convolve(err_spl(lin_domain), Pdot_c_spl(lin_domain), 'same')
# conv = np.convolve(err, PdotP_c_prob, 'same')
# Normalize
conv /= interp.UnivariateSpline(
lin_domain, conv, k=3, s=0, ext=1
).integral(-np.inf, np.inf)
cluster_μ = self.obs.mdata['μ'] << u.Unit("mas/yr")
PdotP_pm = pulsars.shklovskii_component(cluster_μ, self.model.d)
cluster_coords = (self.obs.mdata['b'], self.obs.mdata['l']) * u.deg
PdotP_gal = pulsars.galactic_component(*cluster_coords, D=self.model.d)
x_total = (lin_domain / P) + PdotP_pm + PdotP_gal
ax.plot(x_total, conv)
if show_conv:
# Will really mess the scaling up, usually
ax.plot(x_total, PdotP_c_prob)
ax.plot(x_total, conv)
if show_obs:
ax.axvline((Pdot_meas / P).decompose(), c='r', ls=':')
prob_dist = interp.interp1d(
x_total, conv,
assume_sorted=True, bounds_error=False, fill_value=0.0
)
print('prob=', prob_dist((Pdot_meas / P).decompose()))
return fig
@_support_units
def plot_all(self, fig=None, show_obs='attempt'):
'''Plots all the primary profiles (numdens, LOS, PM)
but *not* the mass function, pulsars, or any secondary profiles
(cum-mass, remnants, etc)
'''
fig, axes = self._setup_multi_artist(fig, (3, 2))
axes = axes.reshape((3, 2))
fig.suptitle(str(self.obs))
kw = {}
self.plot_number_density(fig=fig, ax=axes[0, 0], **kw)
self.plot_LOS(fig=fig, ax=axes[1, 0], **kw)
self.plot_pm_ratio(fig=fig, ax=axes[2, 0], **kw)
self.plot_pm_tot(fig=fig, ax=axes[0, 1], **kw)
self.plot_pm_T(fig=fig, ax=axes[1, 1], **kw)
self.plot_pm_R(fig=fig, ax=axes[2, 1], **kw)
for ax in axes.flatten():
ax.set_xlabel('')
return fig
# ----------------------------------------------------------------------
# Mass Function Plotting
# ----------------------------------------------------------------------
@_support_units
def plot_mass_func(self, fig=None, show_obs=True, show_fields=False, *,
colours=None, PI_legend=False, logscaled=False,
field_kw=None):
# ------------------------------------------------------------------
# Setup axes, splitting into two columns if necessary and adding the
# extra ax for the field plot if desired
# ------------------------------------------------------------------
N_rbins = sum([len(d) for d in self.mass_func.values()])
shape = ((int(np.ceil(N_rbins / 2)), int(np.floor(N_rbins / 2))), 2)
# If adding the fields, include an extra column on the left for it
if show_fields:
shape = ((1, *shape[0]), shape[1] + 1)
fig, axes = self._setup_multi_artist(fig, shape, sharex=True)
axes = axes.T.flatten()
ax_ind = 0
# ------------------------------------------------------------------
# If desired, use the `plot_MF_fields` method to show the fields
# ------------------------------------------------------------------
if show_fields:
ax = axes[ax_ind]
if field_kw is None:
field_kw = {}
field_kw.setdefault('radii', [])
# TODO need to figure out a good size and how to do it, for this ax
self.plot_MF_fields(fig, ax, **field_kw)
ax_ind += 1
# ------------------------------------------------------------------
# Iterate over each PI, gathering data to plot
# ------------------------------------------------------------------
for PI in sorted(self.mass_func,
key=lambda k: self.mass_func[k][0]['r1']):
bins = self.mass_func[PI]
# Get data for this PI
mf = self.obs[PI]
mbin_mean = (mf['m1'] + mf['m2']) / 2.
mbin_width = mf['m2'] - mf['m1']
N = mf['N'] / mbin_width
ΔN = mf['ΔN'] / mbin_width
# --------------------------------------------------------------
# Iterate over radial bin dicts for this PI
# --------------------------------------------------------------
for rind, rbin in enumerate(bins):
ax = axes[ax_ind]
clr = rbin.get('colour', None)
# ----------------------------------------------------------
# Plot observations
# ----------------------------------------------------------
if show_obs:
r_mask = ((mf['r1'] == rbin['r1'])
& (mf['r2'] == rbin['r2']))
N_data = N[r_mask].value
err_data = ΔN[r_mask].value
err = self.F * err_data
pnts = ax.errorbar(mbin_mean[r_mask], N_data, yerr=err,
fmt='o', color=clr)
clr = pnts[0].get_color()
# ----------------------------------------------------------
# Plot model. Doesn't utilize the `_plot_profile` method, as
# this is *not* a profile, but does use similar, but simpler,
# logic
# ----------------------------------------------------------
dNdm = rbin['dNdm']
midpoint = dNdm.shape[0] // 2
m_domain = self.mj[:dNdm.shape[-1]]
median = dNdm[midpoint]
med_plot, = ax.plot(m_domain, median, '--', c=clr)
alpha = 0.8 / (midpoint + 1)
for sigma in range(1, midpoint + 1):
ax.fill_between(
m_domain,
dNdm[midpoint + sigma],
dNdm[midpoint - sigma],
alpha=1 - alpha, color=clr
)
alpha += alpha
if logscaled:
ax.set_xscale('log')
ax.set_xlabel(None)
# ----------------------------------------------------------
# "Label" each bin with it's radial bounds.
# Uses fake text to allow for using loc='best' from `legend`.
# Really this should be a part of plt (see matplotlib#17946)
# ----------------------------------------------------------
r1 = rbin['r1'].to_value('arcmin')
r2 = rbin['r2'].to_value('arcmin')
fake = plt.Line2D([], [], label=f"r = {r1:.2f}'-{r2:.2f}'")
handles = [fake]
leg_kw = {'handlelength': 0, 'handletextpad': 0}
# If this is the first bin, also add a PI tag
if PI_legend and not rind and not show_fields:
pi_fake = plt.Line2D([], [], label=PI)
handles.append(pi_fake)
leg_kw['labelcolor'] = ['k', clr]
ax.legend(handles=handles, **leg_kw)
ax_ind += 1
# ------------------------------------------------------------------
# Put labels on subfigs
# ------------------------------------------------------------------
for sf in fig.subfigs[show_fields:]:
sf.supxlabel(r'Mass [$M_\odot$]')
fig.subfigs[show_fields].supylabel('dN/dm')
return fig
@_support_units
def plot_MF_fields(self, fig=None, ax=None, *, radii=("rh",),
cmap=None, grid=True):
'''plot all mass function fields in this observation
'''
import shapely.geometry as geom
fig, ax = self._setup_artist(fig, ax)
# Centre dot
ax.plot(0, 0, 'kx')
# ------------------------------------------------------------------
# Iterate over each PI and it's radial bins
# ------------------------------------------------------------------
for PI, bins in self.mass_func.items():
for rbin in bins:
# ----------------------------------------------------------
# Plot the field using this `Field` slice's own plotting method
# ----------------------------------------------------------
clr = rbin.get("colour", None)
rbin['field'].plot(ax, fc=clr, alpha=0.7, ec='k', label=PI)
# make this label private so it's only added once to legend
PI = f'_{PI}'
# ------------------------------------------------------------------
# If desired, add a "pseudo" grid in the polar projection, at 2
# arcmin intervals, up to the rt
# ------------------------------------------------------------------
# Ensure the gridlines don't affect the axes scaling
ax.autoscale(False)
if grid:
rt = self.rt if hasattr(self, 'rt') else (20 << u.arcmin)
ticks = np.arange(2, rt.to_value('arcmin'), 2)
# make sure this grid matches normal grids
grid_kw = {
'color': plt.rcParams.get('grid.color'),
'linestyle': plt.rcParams.get('grid.linestyle'),
'linewidth': plt.rcParams.get('grid.linewidth'),
'alpha': plt.rcParams.get('grid.alpha'),
'zorder': 0.5
}
for gr in ticks:
circle = np.array(geom.Point(0, 0).buffer(gr).exterior).T
gr_line, = ax.plot(*circle, **grid_kw)
ax.annotate(f'{gr:.0f}"', xy=(circle[0].max(), 0),
color=grid_kw['color'])
# ------------------------------------------------------------------
# Try to plot the various radii quantities from this model, if desired
# ------------------------------------------------------------------
# TODO for CI this could be a CI of rh, ra, rt actually (60)
for r_type in radii:
# This is to explicitly avoid very ugly exceptions from geom
if r_type not in {'rh', 'ra', 'rt'}:
mssg = f'radii must be one of {{rh, ra, rt}}, not `{r_type}`'
raise TypeError(mssg)
radius = getattr(self, r_type).to_value('arcmin')
circle = np.array(geom.Point(0, 0).buffer(radius).exterior).T
ax.plot(*circle, ls='--')
ax.text(0, circle[1].max(), r_type)
# ------------------------------------------------------------------
# Add plot labels and legends
# ------------------------------------------------------------------
ax.set_xlabel('RA [arcmin]')
ax.set_ylabel('DEC [arcmin]')
# TODO figure out a better way of handling this always using best? (75)
ax.legend(loc='upper left' if grid else 'best')
return fig
# -----------------------------------------------------------------------
# Model plotting
# -----------------------------------------------------------------------
@_support_units
def plot_density(self, fig=None, ax=None, kind='all', *,
x_unit='pc'):
if kind == 'all':
kind = {'MS', 'tot', 'BH', 'WD', 'NS'}
fig, ax = self._setup_artist(fig, ax)
# ax.set_title('Surface Mass Density')
# Total density
if 'tot' in kind:
kw = {"label": "Total", "color": "tab:cyan"}
self._plot_profile(ax, None, None, self.rho_tot,
x_unit=x_unit, **kw)
# Total Remnant density
if 'rem' in kind:
kw = {"label": "Remnants", "color": "tab:purple"}
self._plot_profile(ax, None, None, self.rho_rem,
x_unit=x_unit, **kw)
# Main sequence density
if 'MS' in kind:
kw = {"label": "Main-sequence stars", "color": "tab:orange"}
self._plot_profile(ax, None, None, self.rho_MS,
x_unit=x_unit, **kw)
if 'WD' in kind:
kw = {"label": "White Dwarfs", "color": "tab:green"}
self._plot_profile(ax, None, None, self.rho_WD,
x_unit=x_unit, **kw)
if 'NS' in kind:
kw = {"label": "Neutron Stars", "color": "tab:red"}
self._plot_profile(ax, None, None, self.rho_NS,
x_unit=x_unit, **kw)
# Black hole density
if 'BH' in kind:
kw = {"label": "Black Holes", "color": "tab:gray"}
self._plot_profile(ax, None, None, self.rho_BH,
x_unit=x_unit, **kw)
ax.set_yscale("log")
ax.set_xscale("log")
ax.set_ylabel(rf'Surface Density $[M_\odot / pc^3]$')
# ax.set_xlabel('arcsec')
# ax.legend()
fig.legend(loc='upper center', ncol=6,
bbox_to_anchor=(0.5, 1.), fancybox=True)
return fig
@_support_units
def plot_surface_density(self, fig=None, ax=None, kind='all', *,
x_unit='pc'):
if kind == 'all':
kind = {'MS', 'tot', 'BH', 'WD', 'NS'}
fig, ax = self._setup_artist(fig, ax)
# ax.set_title('Surface Mass Density')
# Total density
if 'tot' in kind:
kw = {"label": "Total", "color": "tab:cyan"}
self._plot_profile(ax, None, None, self.Sigma_tot,
x_unit=x_unit, **kw)
# Total Remnant density
if 'rem' in kind:
kw = {"label": "Remnants", "color": "tab:purple"}
self._plot_profile(ax, None, None, self.Sigma_rem,
x_unit=x_unit, **kw)
# Main sequence density
if 'MS' in kind:
kw = {"label": "Main-sequence stars", "color": "tab:orange"}
self._plot_profile(ax, None, None, self.Sigma_MS,
x_unit=x_unit, **kw)
if 'WD' in kind:
kw = {"label": "White Dwarfs", "color": "tab:green"}
self._plot_profile(ax, None, None, self.Sigma_WD,
x_unit=x_unit, **kw)
if 'NS' in kind:
kw = {"label": "Neutron Stars", "color": "tab:red"}
self._plot_profile(ax, None, None, self.Sigma_NS,
x_unit=x_unit, **kw)
# Black hole density
if 'BH' in kind:
kw = {"label": "Black Holes", "color": "tab:gray"}
self._plot_profile(ax, None, None, self.Sigma_BH,
x_unit=x_unit, **kw)
ax.set_yscale("log")
ax.set_xscale("log")
ax.set_ylabel(rf'Surface Density $[M_\odot / pc^2]$')
# ax.set_xlabel('arcsec')
# ax.legend()
fig.legend(loc='upper center', ncol=6,
bbox_to_anchor=(0.5, 1.), fancybox=True)
return fig
@_support_units
def plot_cumulative_mass(self, fig=None, ax=None, kind='all', *,
x_unit='pc'):
if kind == 'all':
kind = {'MS', 'tot', 'BH', 'WD', 'NS'}
fig, ax = self._setup_artist(fig, ax)
# ax.set_title('Cumulative Mass')
# Total density
if 'tot' in kind:
kw = {"label": "Total", "color": "tab:cyan"}
self._plot_profile(ax, None, None, self.cum_M_tot,
x_unit=x_unit, **kw)
# Main sequence density
if 'MS' in kind:
kw = {"label": "Main-sequence stars", "color": "tab:orange"}
self._plot_profile(ax, None, None, self.cum_M_MS,
x_unit=x_unit, **kw)
if 'WD' in kind:
kw = {"label": "White Dwarfs", "color": "tab:green"}
self._plot_profile(ax, None, None, self.cum_M_WD,
x_unit=x_unit, **kw)
if 'NS' in kind:
kw = {"label": "Neutron Stars", "color": "tab:red"}
self._plot_profile(ax, None, None, self.cum_M_NS,
x_unit=x_unit, **kw)
# Black hole density
if 'BH' in kind:
kw = {"label": "Black Holes", "color": "tab:gray"}
self._plot_profile(ax, None, None, self.cum_M_BH,
x_unit=x_unit, **kw)
ax.set_yscale("log")
ax.set_xscale("log")
# ax.set_ylabel(rf'$M_{{enc}} ({self.cum_M_tot.unit})$')
ax.set_ylabel(rf'$M_{{enc}}$ $[M_\odot]$')
# ax.set_xlabel('arcsec')
# ax.legend()
fig.legend(loc='upper center', ncol=5,
bbox_to_anchor=(0.5, 1.), fancybox=True)
return fig
@_support_units
def plot_remnant_fraction(self, fig=None, ax=None, *, x_unit='pc'):
'''Fraction of mass in remnants vs MS stars, like in baumgardt'''
fig, ax = self._setup_artist(fig, ax)
ax.set_title("Remnant Fraction")
ax.set_xscale("log")
self._plot_profile(ax, None, None, self.frac_M_MS,
x_unit=x_unit, label="Main-sequence stars")
self._plot_profile(ax, None, None, self.frac_M_rem,
x_unit=x_unit, label="Remnants")
ax.set_ylabel(r"Mass fraction $M_{MS}/M_{tot}$, $M_{remn.}/M_{tot}$")
ax.set_ylim(0.0, 1.0)
ax.legend()
return fig
# --------------------------------------------------------------------------
# Visualizers
# --------------------------------------------------------------------------
class ModelVisualizer(_ClusterVisualizer):
'''
class for making, showing, saving all the plots related to a single model
'''
@classmethod
def from_chain(cls, chain, observations, method='median'):
'''
create a Visualizer instance based on a chain, y taking the median
of the chain parameters
'''
reduc_methods = {'median': np.median, 'mean': np.mean}
# if 3d (Niters, Nwalkers, Nparams)
# if 2d (Nwalkers, Nparams)
# if 1d (Nparams)
chain = chain.reshape((-1, chain.shape[-1]))
theta = reduc_methods[method](chain, axis=0)
return cls(Model(theta, observations), observations)
@classmethod
def from_theta(cls, theta, observations):
'''
create a Visualizer instance based on a theta, see `Model` for allowed
theta types
'''
return cls(Model(theta, observations), observations)
def __init__(self, model, observations=None):
self.model = model
self.obs = observations if observations else model.observations
self.rh = model.rh
self.ra = model.ra
self.rt = model.rt
self.F = model.F
self.s2 = model.s2
self.d = model.d
self.r = model.r
self.rlims = (9e-3, self.r.max() + (5 << self.r.unit))
self._2πr = 2 * np.pi * model.r
self.star_bin = model.nms - 1
self.mj = model.mj
self.LOS = np.sqrt(self.model.v2pj)[:, np.newaxis, :]
self.pm_T = np.sqrt(model.v2Tj)[:, np.newaxis, :]
self.pm_R = np.sqrt(model.v2Rj)[:, np.newaxis, :]
self.pm_tot = np.sqrt(0.5 * (self.pm_T**2 + self.pm_R**2))
self.pm_ratio = self.pm_T / self.pm_R
self._init_numdens(model, observations)
self._init_massfunc(model, observations)
self._init_surfdens(model, observations)
self._init_dens(model, observations)
self._init_mass_frac(model, observations)
self._init_cum_mass(model, observations)
# TODO alot of these init functions could be more homogenous
@_ClusterVisualizer._support_units
def _init_numdens(self, model, observations):
# TODO make this more robust and cleaner
model_nd = model.Sigmaj / model.mj[:, np.newaxis]
nd = np.empty(model_nd.shape)[:, np.newaxis, :] << model_nd.unit
# If have nd obs, apply scaling factor K
for mbin in range(model_nd.shape[0]):
try:
obs_nd = observations['number_density']
obs_r = obs_nd['r'].to(model.r.unit)
nd_interp = util.QuantitySpline(model.r, model_nd[mbin, :])
K = (np.nansum(obs_nd['Σ'] * nd_interp(obs_r) / obs_nd['Σ']**2)
/ np.nansum(nd_interp(obs_r)**2 / obs_nd['Σ']**2))
except KeyError:
K = 1
nd[mbin, 0, :] = K * model_nd[mbin, :]
self.numdens = nd
@_ClusterVisualizer._support_units
def _init_massfunc(self, model, observations, *, cmap=None):
'''
sets self.mass_func as a dict of PI's, where each PI has a list of
subdicts. Each subdict represents a single radial slice (within this PI)
and contains the radii, the mass func values, and the field slice
'''
cmap = cmap or plt.cm.rainbow
self.mass_func = {}
cen = (observations.mdata['RA'], observations.mdata['DEC'])
PI_list = observations.filter_datasets('*mass_function*')
densityj = [util.QuantitySpline(model.r, model.Sigmaj[j])
for j in range(model.nms)]
for i, (key, mf) in enumerate(PI_list.items()):
self.mass_func[key] = []
# TODO same colour for each PI or different for each slice?
clr = cmap(i / len(PI_list))
field = mass.Field.from_dataset(mf, cen=cen)
rbins = np.unique(np.c_[mf['r1'], mf['r2']], axis=0)
rbins.sort(axis=0)
for r_in, r_out in rbins:
this_slc = {'r1': r_in, 'r2': r_out}
field_slice = field.slice_radially(r_in, r_out)
this_slc['field'] = field_slice
this_slc['colour'] = clr
this_slc['dNdm'] = np.empty((1, model.nms))
sample_radii = field_slice.MC_sample(300).to(u.pc)
for j in range(model.nms):
Nj = field_slice.MC_integrate(densityj[j], sample_radii)
widthj = (model.mj[j] * model.mes_widths[j])
this_slc['dNdm'][0, j] = (Nj / widthj).value
self.mass_func[key].append(this_slc)
@_ClusterVisualizer._support_units
def _init_dens(self, model, observations):
shp = (np.newaxis, np.newaxis, slice(None))
self.rho_tot = np.sum(model.rhoj, axis=0)[shp]
self.rho_MS = np.sum(model.rhoj[model._star_bins], axis=0)[shp]
self.rho_rem = np.sum(model.rhoj[model._remnant_bins], axis=0)[shp]
self.rho_BH = np.sum(model.BH_rhoj, axis=0)[shp]
self.rho_WD = np.sum(model.WD_rhoj, axis=0)[shp]
self.rho_NS = np.sum(model.NS_rhoj, axis=0)[shp]
@_ClusterVisualizer._support_units
def _init_surfdens(self, model, observations):
shp = (np.newaxis, np.newaxis, slice(None))
self.Sigma_tot = np.sum(model.Sigmaj, axis=0)[shp]
self.Sigma_MS = np.sum(model.Sigmaj[model._star_bins], axis=0)[shp]
self.Sigma_rem = np.sum(model.Sigmaj[model._remnant_bins], axis=0)[shp]
self.Sigma_BH = np.sum(model.BH_Sigmaj, axis=0)[shp]
self.Sigma_WD = np.sum(model.WD_Sigmaj, axis=0)[shp]
self.Sigma_NS = np.sum(model.NS_Sigmaj, axis=0)[shp]
@_ClusterVisualizer._support_units
def _init_mass_frac(self, model, observations):
int_MS = util.QuantitySpline(self.r, self._2πr * self.Sigma_MS)
int_rem = util.QuantitySpline(self.r, self._2πr * self.Sigma_rem)
int_tot = util.QuantitySpline(self.r, self._2πr * self.Sigma_tot)
mass_MS = np.empty((1, 1, self.r.size))
mass_rem = np.empty((1, 1, self.r.size))
mass_tot = np.empty((1, 1, self.r.size))
# TODO the rbins at the end always mess up fractional stuff, drop to 0
mass_MS[0, 0, 0] = mass_rem[0, 0, 0] = mass_tot[0, 0, 0] = np.nan
for i in range(1, self.r.size - 2):
mass_MS[0, 0, i] = int_MS.integral(self.r[i], self.r[i + 1]).value
mass_rem[0, 0, i] = int_rem.integral(self.r[i], self.r[i + 1]).value
mass_tot[0, 0, i] = int_tot.integral(self.r[i], self.r[i + 1]).value
self.frac_M_MS = mass_MS / mass_tot
self.frac_M_rem = mass_rem / mass_tot
@_ClusterVisualizer._support_units
def _init_cum_mass(self, model, observations):
int_tot = util.QuantitySpline(self.r, self._2πr * self.Sigma_tot)
int_MS = util.QuantitySpline(self.r, self._2πr * self.Sigma_MS)
int_BH = util.QuantitySpline(self.r, self._2πr * self.Sigma_BH)
int_WD = util.QuantitySpline(self.r, self._2πr * self.Sigma_WD)
int_NS = util.QuantitySpline(self.r, self._2πr * self.Sigma_NS)
cum_tot = np.empty((1, 1, self.r.size)) << u.Msun
cum_MS = np.empty((1, 1, self.r.size)) << u.Msun
cum_BH = np.empty((1, 1, self.r.size)) << u.Msun
cum_WD = np.empty((1, 1, self.r.size)) << u.Msun
cum_NS = np.empty((1, 1, self.r.size)) << u.Msun
for i in range(0, self.r.size):
cum_tot[0, 0, i] = int_tot.integral(model.r[0], model.r[i])
cum_MS[0, 0, i] = int_MS.integral(model.r[0], model.r[i])
cum_BH[0, 0, i] = int_BH.integral(model.r[0], model.r[i])
cum_WD[0, 0, i] = int_WD.integral(model.r[0], model.r[i])
cum_NS[0, 0, i] = int_NS.integral(model.r[0], model.r[i])
self.cum_M_tot = cum_tot
self.cum_M_MS = cum_MS
self.cum_M_WD = cum_WD
self.cum_M_NS = cum_NS
self.cum_M_BH = cum_BH
class CIModelVisualizer(_ClusterVisualizer):
'''
class for making, showing, saving all the plots related to a bunch of models
in the form of confidence intervals
'''
@_ClusterVisualizer._support_units
def plot_BH_mass(self, fig=None, ax=None, bins='auto', color='b'):
fig, ax = self._setup_artist(fig, ax)
color = mpl_clr.to_rgb(color)
facecolor = color + (0.33, )
ax.hist(self.BH_mass, histtype='stepfilled',
bins=bins, ec=color, fc=facecolor, lw=2)
return fig
@_ClusterVisualizer._support_units
def plot_BH_num(self, fig=None, ax=None, bins='auto', color='b'):
fig, ax = self._setup_artist(fig, ax)
color = mpl_clr.to_rgb(color)
facecolor = color + (0.33, )
ax.hist(self.BH_num, histtype='stepfilled',
bins=bins, ec=color, fc=facecolor, lw=2)
return fig
@classmethod
def from_chain(cls, chain, observations, N=100, *, verbose=True, pool=None):
import functools
viz = cls()
viz.N = N
viz.obs = observations
# ------------------------------------------------------------------
# Get info about the chain and set of models
# ------------------------------------------------------------------
# Flatten walkers, if not already
chain = chain.reshape((-1, chain.shape[-1]))[-N:]
median_chain = np.median(chain, axis=0)
# TODO get these indices more dynamically
viz.F = median_chain[7]
viz.s2 = median_chain[6]
viz.d = median_chain[12] << u.kpc
# Setup the radial domain to interpolate everything onto
# We estimate the maximum radius needed will be given by the model with
# the largest value of the truncation parameter "g". This should be a
# valid enough assumption for our needs. While we have it, we'll also
# use this model to grab the other values we need, which shouldn't
# change much between models, so using this extreme model is okay.
# warning: in very large N samples, this g might be huge, and lead to a
# very large rt. I'm not really sure yet how that might affect the CIs
# or plots
huge_model = Model(chain[np.argmax(chain[:, 4])], viz.obs)
viz.rt = huge_model.rt
viz.r = np.r_[0, np.geomspace(1e-5, viz.rt.value, num=99)] << u.pc
viz.rlims = (9e-3, viz.r.max() + (5 << viz.r.unit))
# Assume that this example model has same nms, mj[:nms] as all models
# This approximation isn't exactly correct, but close enough for plots
# viz.star_bin = huge_model.nms - 1
viz.star_bin = 0
mj_MS = huge_model.mj[:huge_model.nms]
mj_tracer = huge_model.mj[huge_model._tracer_bins]
viz.mj = np.r_[mj_MS, mj_tracer]
# ------------------------------------------------------------------
# Setup the final full parameters arrays with dims of
# [mass bins, intervals (from percentile of models), radial bins] for
# all "profile" datasets
# ------------------------------------------------------------------
# velocities
vel_unit = np.sqrt(huge_model.v2Tj).unit
Nm = 1 + len(mj_tracer)
vpj = np.empty((Nm, N, viz.r.size)) << vel_unit
vTj, vRj, vtotj = vpj.copy(), vpj.copy(), vpj.copy()
vaj = np.empty((Nm, N, viz.r.size)) << u.dimensionless_unscaled
# mass density
rho_unit = huge_model.rhoj.unit
rho_tot = np.empty((1, N, viz.r.size)) << rho_unit
rho_MS, rho_BH = rho_tot.copy(), rho_tot.copy()
rho_WD, rho_NS = rho_tot.copy(), rho_tot.copy()
# surface density
Sigma_unit = huge_model.Sigmaj.unit
Sigma_tot = np.empty((1, N, viz.r.size)) << Sigma_unit
Sigma_MS, Sigma_BH = Sigma_tot.copy(), Sigma_tot.copy()
Sigma_WD, Sigma_NS = Sigma_tot.copy(), Sigma_tot.copy()
# Cumulative mass
mass_unit = huge_model.M.unit
cum_M_tot = np.empty((1, N, viz.r.size)) << mass_unit
cum_M_MS, cum_M_BH = cum_M_tot.copy(), cum_M_tot.copy()
cum_M_WD, cum_M_NS = cum_M_tot.copy(), cum_M_tot.copy()
# Mass Fraction
frac_M_MS = np.empty((1, N, viz.r.size)) << u.dimensionless_unscaled
frac_M_rem = frac_M_MS.copy()
# number density
numdens = np.empty((1, N, viz.r.size)) << u.arcmin**-2
# mass function
massfunc = viz._prep_massfunc(viz.obs)
# massfunc = np.empty((N, N_rbins, huge_model.nms))
for rbins in massfunc.values():
for rslice in rbins:
rslice['dNdm'] = np.empty((N, huge_model.nms))
# BH mass
BH_mass = np.empty(N) << u.Msun
BH_num = np.empty(N) << u.dimensionless_unscaled
# ------------------------------------------------------------------
# Setup iteration and pooling
# ------------------------------------------------------------------
# TODO currently does nothing
# if verbose:
# import tqdm
# chain_loader = tqdm.tqdm(chain)
# else:
# chain_loader = chain
# TODO assuming that chain always converges, might err if not the case
get_model = functools.partial(Model, observations=viz.obs)
try:
_map = map if pool is None else pool.imap_unordered
except AttributeError:
mssg = ("Invalid pool, currently only support pools with an "
"`imap_unordered` method")
raise ValueError(mssg)
# ------------------------------------------------------------------
# iterate over all models in the sample and compute/store their
# relevant parameters
# ------------------------------------------------------------------
for model_ind, model in enumerate(_map(get_model, chain)):
equivs = util.angular_width(model.d)
# Velocities
# convoluted way of going from a slice to a list of indices
tracers = list(range(len(model.mj))[model._tracer_bins])
for i, mass_bin in enumerate([model.nms - 1] + tracers):
slc = (i, model_ind, slice(None))
vTj[slc], vRj[slc], vtotj[slc], \
vaj[slc], vpj[slc] = viz._init_velocities(model, mass_bin)
slc = (0, model_ind, slice(None))
# Mass Densities
rho_MS[slc], rho_tot[slc], rho_BH[slc], \
rho_WD[slc], rho_NS[slc] = viz._init_dens(model)
# Surface Densities
Sigma_MS[slc], Sigma_tot[slc], Sigma_BH[slc], \
Sigma_WD[slc], Sigma_NS[slc] = viz._init_surfdens(model)
# Cumulative Mass distribution
cum_M_MS[slc], cum_M_tot[slc], cum_M_BH[slc], \
cum_M_WD[slc], cum_M_NS[slc] = viz._init_cum_mass(model)
# Number Densities
numdens[slc] = viz._init_numdens(model, equivs=equivs)
# Mass Functions
for rbins in massfunc.values():
for rslice in rbins:
mf = rslice['dNdm']
mf[model_ind, ...] = viz._init_dNdm(model, rslice, equivs)
# Mass Fractions
frac_M_MS[slc], frac_M_rem[slc] = viz._init_mass_frac(model)
# Black holes
BH_mass[model_ind] = | np.sum(model.BH_Mj) | numpy.sum |
# pylint: disable=protected-access
"""
Test the wrappers for the C API.
"""
import os
from contextlib import contextmanager
import numpy as np
import numpy.testing as npt
import pandas as pd
import pytest
import xarray as xr
from packaging.version import Version
from pygmt import Figure, clib
from pygmt.clib.conversion import dataarray_to_matrix
from pygmt.clib.session import FAMILIES, VIAS
from pygmt.exceptions import (
GMTCLibError,
GMTCLibNoSessionError,
GMTInvalidInput,
GMTVersionError,
)
from pygmt.helpers import GMTTempFile
TEST_DATA_DIR = os.path.join(os.path.dirname(__file__), "data")
with clib.Session() as _lib:
gmt_version = Version(_lib.info["version"])
@contextmanager
def mock(session, func, returns=None, mock_func=None):
"""
Mock a GMT C API function to make it always return a given value.
Used to test that exceptions are raised when API functions fail by
producing a NULL pointer as output or non-zero status codes.
Needed because it's not easy to get some API functions to fail without
inducing a Segmentation Fault (which is a good thing because libgmt usually
only fails with errors).
"""
if mock_func is None:
def mock_api_function(*args): # pylint: disable=unused-argument
"""
A mock GMT API function that always returns a given value.
"""
return returns
mock_func = mock_api_function
get_libgmt_func = session.get_libgmt_func
def mock_get_libgmt_func(name, argtypes=None, restype=None):
"""
Return our mock function.
"""
if name == func:
return mock_func
return get_libgmt_func(name, argtypes, restype)
setattr(session, "get_libgmt_func", mock_get_libgmt_func)
yield
setattr(session, "get_libgmt_func", get_libgmt_func)
def test_getitem():
"""
Test that I can get correct constants from the C lib.
"""
ses = clib.Session()
assert ses["GMT_SESSION_EXTERNAL"] != -99999
assert ses["GMT_MODULE_CMD"] != -99999
assert ses["GMT_PAD_DEFAULT"] != -99999
assert ses["GMT_DOUBLE"] != -99999
with pytest.raises(GMTCLibError):
ses["A_WHOLE_LOT_OF_JUNK"] # pylint: disable=pointless-statement
def test_create_destroy_session():
"""
Test that create and destroy session are called without errors.
"""
# Create two session and make sure they are not pointing to the same memory
session1 = clib.Session()
session1.create(name="test_session1")
assert session1.session_pointer is not None
session2 = clib.Session()
session2.create(name="test_session2")
assert session2.session_pointer is not None
assert session2.session_pointer != session1.session_pointer
session1.destroy()
session2.destroy()
# Create and destroy a session twice
ses = clib.Session()
for __ in range(2):
with pytest.raises(GMTCLibNoSessionError):
ses.session_pointer # pylint: disable=pointless-statement
ses.create("session1")
assert ses.session_pointer is not None
ses.destroy()
with pytest.raises(GMTCLibNoSessionError):
ses.session_pointer # pylint: disable=pointless-statement
def test_create_session_fails():
"""
Check that an exception is raised when failing to create a session.
"""
ses = clib.Session()
with mock(ses, "GMT_Create_Session", returns=None):
with pytest.raises(GMTCLibError):
ses.create("test-session-name")
# Should fail if trying to create a session before destroying the old one.
ses.create("test1")
with pytest.raises(GMTCLibError):
ses.create("test2")
def test_destroy_session_fails():
"""
Fail to destroy session when given bad input.
"""
ses = clib.Session()
with pytest.raises(GMTCLibNoSessionError):
ses.destroy()
ses.create("test-session")
with mock(ses, "GMT_Destroy_Session", returns=1):
with pytest.raises(GMTCLibError):
ses.destroy()
ses.destroy()
def test_call_module():
"""
Run a command to see if call_module works.
"""
data_fname = os.path.join(TEST_DATA_DIR, "points.txt")
out_fname = "test_call_module.txt"
with clib.Session() as lib:
with GMTTempFile() as out_fname:
lib.call_module("info", "{} -C ->{}".format(data_fname, out_fname.name))
assert os.path.exists(out_fname.name)
output = out_fname.read().strip()
assert output == "11.5309 61.7074 -2.9289 7.8648 0.1412 0.9338"
def test_call_module_invalid_arguments():
"""
Fails for invalid module arguments.
"""
with clib.Session() as lib:
with pytest.raises(GMTCLibError):
lib.call_module("info", "bogus-data.bla")
def test_call_module_invalid_name():
"""
Fails when given bad input.
"""
with clib.Session() as lib:
with pytest.raises(GMTCLibError):
lib.call_module("meh", "")
def test_call_module_error_message():
"""
Check is the GMT error message was captured.
"""
with clib.Session() as lib:
try:
lib.call_module("info", "bogus-data.bla")
except GMTCLibError as error:
assert "Module 'info' failed with status code" in str(error)
assert "gmtinfo [ERROR]: Cannot find file bogus-data.bla" in str(error)
def test_method_no_session():
"""
Fails when not in a session.
"""
# Create an instance of Session without "with" so no session is created.
lib = clib.Session()
with pytest.raises(GMTCLibNoSessionError):
lib.call_module("gmtdefaults", "")
with pytest.raises(GMTCLibNoSessionError):
lib.session_pointer # pylint: disable=pointless-statement
def test_parse_constant_single():
"""
Parsing a single family argument correctly.
"""
lib = clib.Session()
for family in FAMILIES:
parsed = lib._parse_constant(family, valid=FAMILIES)
assert parsed == lib[family]
def test_parse_constant_composite():
"""
Parsing a composite constant argument (separated by |) correctly.
"""
lib = clib.Session()
test_cases = ((family, via) for family in FAMILIES for via in VIAS)
for family, via in test_cases:
composite = "|".join([family, via])
expected = lib[family] + lib[via]
parsed = lib._parse_constant(composite, valid=FAMILIES, valid_modifiers=VIAS)
assert parsed == expected
def test_parse_constant_fails():
"""
Check if the function fails when given bad input.
"""
lib = clib.Session()
test_cases = [
"SOME_random_STRING",
"GMT_IS_DATASET|GMT_VIA_MATRIX|GMT_VIA_VECTOR",
"GMT_IS_DATASET|NOT_A_PROPER_VIA",
"NOT_A_PROPER_FAMILY|GMT_VIA_MATRIX",
"NOT_A_PROPER_FAMILY|ALSO_INVALID",
]
for test_case in test_cases:
with pytest.raises(GMTInvalidInput):
lib._parse_constant(test_case, valid=FAMILIES, valid_modifiers=VIAS)
# Should also fail if not given valid modifiers but is using them anyway.
# This should work...
lib._parse_constant(
"GMT_IS_DATASET|GMT_VIA_MATRIX", valid=FAMILIES, valid_modifiers=VIAS
)
# But this shouldn't.
with pytest.raises(GMTInvalidInput):
lib._parse_constant(
"GMT_IS_DATASET|GMT_VIA_MATRIX", valid=FAMILIES, valid_modifiers=None
)
def test_create_data_dataset():
"""
Run the function to make sure it doesn't fail badly.
"""
with clib.Session() as lib:
# Dataset from vectors
data_vector = lib.create_data(
family="GMT_IS_DATASET|GMT_VIA_VECTOR",
geometry="GMT_IS_POINT",
mode="GMT_CONTAINER_ONLY",
dim=[10, 20, 1, 0], # columns, rows, layers, dtype
)
# Dataset from matrices
data_matrix = lib.create_data(
family="GMT_IS_DATASET|GMT_VIA_MATRIX",
geometry="GMT_IS_POINT",
mode="GMT_CONTAINER_ONLY",
dim=[10, 20, 1, 0],
)
assert data_vector != data_matrix
def test_create_data_grid_dim():
"""
Create a grid ignoring range and inc.
"""
with clib.Session() as lib:
# Grids from matrices using dim
lib.create_data(
family="GMT_IS_GRID|GMT_VIA_MATRIX",
geometry="GMT_IS_SURFACE",
mode="GMT_CONTAINER_ONLY",
dim=[10, 20, 1, 0],
)
def test_create_data_grid_range():
"""
Create a grid specifying range and inc instead of dim.
"""
with clib.Session() as lib:
# Grids from matrices using range and int
lib.create_data(
family="GMT_IS_GRID|GMT_VIA_MATRIX",
geometry="GMT_IS_SURFACE",
mode="GMT_CONTAINER_ONLY",
ranges=[150.0, 250.0, -20.0, 20.0],
inc=[0.1, 0.2],
)
def test_create_data_fails():
"""
Check that create_data raises exceptions for invalid input and output.
"""
# Passing in invalid mode
with pytest.raises(GMTInvalidInput):
with clib.Session() as lib:
lib.create_data(
family="GMT_IS_DATASET",
geometry="GMT_IS_SURFACE",
mode="Not_a_valid_mode",
dim=[0, 0, 1, 0],
ranges=[150.0, 250.0, -20.0, 20.0],
inc=[0.1, 0.2],
)
# Passing in invalid geometry
with pytest.raises(GMTInvalidInput):
with clib.Session() as lib:
lib.create_data(
family="GMT_IS_GRID",
geometry="Not_a_valid_geometry",
mode="GMT_CONTAINER_ONLY",
dim=[0, 0, 1, 0],
ranges=[150.0, 250.0, -20.0, 20.0],
inc=[0.1, 0.2],
)
# If the data pointer returned is None (NULL pointer)
with pytest.raises(GMTCLibError):
with clib.Session() as lib:
with mock(lib, "GMT_Create_Data", returns=None):
lib.create_data(
family="GMT_IS_DATASET",
geometry="GMT_IS_SURFACE",
mode="GMT_CONTAINER_ONLY",
dim=[11, 10, 2, 0],
)
def test_virtual_file():
"""
Test passing in data via a virtual file with a Dataset.
"""
dtypes = "float32 float64 int32 int64 uint32 uint64".split()
shape = (5, 3)
for dtype in dtypes:
with clib.Session() as lib:
family = "GMT_IS_DATASET|GMT_VIA_MATRIX"
geometry = "GMT_IS_POINT"
dataset = lib.create_data(
family=family,
geometry=geometry,
mode="GMT_CONTAINER_ONLY",
dim=[shape[1], shape[0], 1, 0], # columns, rows, layers, dtype
)
data = np.arange(shape[0] * shape[1], dtype=dtype).reshape(shape)
lib.put_matrix(dataset, matrix=data)
# Add the dataset to a virtual file and pass it along to gmt info
vfargs = (family, geometry, "GMT_IN|GMT_IS_REFERENCE", dataset)
with lib.open_virtual_file(*vfargs) as vfile:
with GMTTempFile() as outfile:
lib.call_module("info", "{} ->{}".format(vfile, outfile.name))
output = outfile.read(keep_tabs=True)
bounds = "\t".join(
["<{:.0f}/{:.0f}>".format(col.min(), col.max()) for col in data.T]
)
expected = "<matrix memory>: N = {}\t{}\n".format(shape[0], bounds)
assert output == expected
def test_virtual_file_fails():
"""
Check that opening and closing virtual files raises an exception for non-
zero return codes.
"""
vfargs = (
"GMT_IS_DATASET|GMT_VIA_MATRIX",
"GMT_IS_POINT",
"GMT_IN|GMT_IS_REFERENCE",
None,
)
# Mock Open_VirtualFile to test the status check when entering the context.
# If the exception is raised, the code won't get to the closing of the
# virtual file.
with clib.Session() as lib, mock(lib, "GMT_Open_VirtualFile", returns=1):
with pytest.raises(GMTCLibError):
with lib.open_virtual_file(*vfargs):
print("Should not get to this code")
# Test the status check when closing the virtual file
# Mock the opening to return 0 (success) so that we don't open a file that
# we won't close later.
with clib.Session() as lib, mock(lib, "GMT_Open_VirtualFile", returns=0), mock(
lib, "GMT_Close_VirtualFile", returns=1
):
with pytest.raises(GMTCLibError):
with lib.open_virtual_file(*vfargs):
pass
print("Shouldn't get to this code either")
def test_virtual_file_bad_direction():
"""
Test passing an invalid direction argument.
"""
with clib.Session() as lib:
vfargs = (
"GMT_IS_DATASET|GMT_VIA_MATRIX",
"GMT_IS_POINT",
"GMT_IS_GRID", # The invalid direction argument
0,
)
with pytest.raises(GMTInvalidInput):
with lib.open_virtual_file(*vfargs):
print("This should have failed")
def test_virtualfile_from_vectors():
"""
Test the automation for transforming vectors to virtual file dataset.
"""
dtypes = "float32 float64 int32 int64 uint32 uint64".split()
size = 10
for dtype in dtypes:
x = np.arange(size, dtype=dtype)
y = np.arange(size, size * 2, 1, dtype=dtype)
z = np.arange(size * 2, size * 3, 1, dtype=dtype)
with clib.Session() as lib:
with lib.virtualfile_from_vectors(x, y, z) as vfile:
with GMTTempFile() as outfile:
lib.call_module("info", "{} ->{}".format(vfile, outfile.name))
output = outfile.read(keep_tabs=True)
bounds = "\t".join(
["<{:.0f}/{:.0f}>".format(i.min(), i.max()) for i in (x, y, z)]
)
expected = "<vector memory>: N = {}\t{}\n".format(size, bounds)
assert output == expected
@pytest.mark.parametrize("dtype", [str, object])
def test_virtualfile_from_vectors_one_string_or_object_column(dtype):
"""
Test passing in one column with string or object dtype into virtual file
dataset.
"""
size = 5
x = np.arange(size, dtype=np.int32)
y = np.arange(size, size * 2, 1, dtype=np.int32)
strings = np.array(["a", "bc", "defg", "hijklmn", "opqrst"], dtype=dtype)
with clib.Session() as lib:
with lib.virtualfile_from_vectors(x, y, strings) as vfile:
with GMTTempFile() as outfile:
lib.call_module("convert", f"{vfile} ->{outfile.name}")
output = outfile.read(keep_tabs=True)
expected = "".join(f"{i}\t{j}\t{k}\n" for i, j, k in zip(x, y, strings))
assert output == expected
@pytest.mark.parametrize("dtype", [str, object])
def test_virtualfile_from_vectors_two_string_or_object_columns(dtype):
"""
Test passing in two columns of string or object dtype into virtual file
dataset.
"""
size = 5
x = np.arange(size, dtype=np.int32)
y = np.arange(size, size * 2, 1, dtype=np.int32)
strings1 = np.array(["a", "bc", "def", "ghij", "klmno"], dtype=dtype)
strings2 = np.array(["pqrst", "uvwx", "yz!", "@#", "$"], dtype=dtype)
with clib.Session() as lib:
with lib.virtualfile_from_vectors(x, y, strings1, strings2) as vfile:
with GMTTempFile() as outfile:
lib.call_module("convert", f"{vfile} ->{outfile.name}")
output = outfile.read(keep_tabs=True)
expected = "".join(
f"{h}\t{i}\t{j} {k}\n" for h, i, j, k in zip(x, y, strings1, strings2)
)
assert output == expected
def test_virtualfile_from_vectors_transpose():
"""
Test transforming matrix columns to virtual file dataset.
"""
dtypes = "float32 float64 int32 int64 uint32 uint64".split()
shape = (7, 5)
for dtype in dtypes:
data = np.arange(shape[0] * shape[1], dtype=dtype).reshape(shape)
with clib.Session() as lib:
with lib.virtualfile_from_vectors(*data.T) as vfile:
with GMTTempFile() as outfile:
lib.call_module("info", "{} -C ->{}".format(vfile, outfile.name))
output = outfile.read(keep_tabs=True)
bounds = "\t".join(
["{:.0f}\t{:.0f}".format(col.min(), col.max()) for col in data.T]
)
expected = "{}\n".format(bounds)
assert output == expected
def test_virtualfile_from_vectors_diff_size():
"""
Test the function fails for arrays of different sizes.
"""
x = np.arange(5)
y = np.arange(6)
with clib.Session() as lib:
with pytest.raises(GMTInvalidInput):
with lib.virtualfile_from_vectors(x, y):
print("This should have failed")
def test_virtualfile_from_matrix():
"""
Test transforming a matrix to virtual file dataset.
"""
dtypes = "float32 float64 int32 int64 uint32 uint64".split()
shape = (7, 5)
for dtype in dtypes:
data = np.arange(shape[0] * shape[1], dtype=dtype).reshape(shape)
with clib.Session() as lib:
with lib.virtualfile_from_matrix(data) as vfile:
with GMTTempFile() as outfile:
lib.call_module("info", "{} ->{}".format(vfile, outfile.name))
output = outfile.read(keep_tabs=True)
bounds = "\t".join(
["<{:.0f}/{:.0f}>".format(col.min(), col.max()) for col in data.T]
)
expected = "<matrix memory>: N = {}\t{}\n".format(shape[0], bounds)
assert output == expected
def test_virtualfile_from_matrix_slice():
"""
Test transforming a slice of a larger array to virtual file dataset.
"""
dtypes = "float32 float64 int32 int64 uint32 uint64".split()
shape = (10, 6)
for dtype in dtypes:
full_data = np.arange(shape[0] * shape[1], dtype=dtype).reshape(shape)
rows = 5
cols = 3
data = full_data[:rows, :cols]
with clib.Session() as lib:
with lib.virtualfile_from_matrix(data) as vfile:
with GMTTempFile() as outfile:
lib.call_module("info", "{} ->{}".format(vfile, outfile.name))
output = outfile.read(keep_tabs=True)
bounds = "\t".join(
["<{:.0f}/{:.0f}>".format(col.min(), col.max()) for col in data.T]
)
expected = "<matrix memory>: N = {}\t{}\n".format(rows, bounds)
assert output == expected
def test_virtualfile_from_vectors_pandas():
"""
Pass vectors to a dataset using pandas Series.
"""
dtypes = "float32 float64 int32 int64 uint32 uint64".split()
size = 13
for dtype in dtypes:
data = pd.DataFrame(
data=dict(
x=np.arange(size, dtype=dtype),
y=np.arange(size, size * 2, 1, dtype=dtype),
z=np.arange(size * 2, size * 3, 1, dtype=dtype),
)
)
with clib.Session() as lib:
with lib.virtualfile_from_vectors(data.x, data.y, data.z) as vfile:
with GMTTempFile() as outfile:
lib.call_module("info", "{} ->{}".format(vfile, outfile.name))
output = outfile.read(keep_tabs=True)
bounds = "\t".join(
[
"<{:.0f}/{:.0f}>".format(i.min(), i.max())
for i in (data.x, data.y, data.z)
]
)
expected = "<vector memory>: N = {}\t{}\n".format(size, bounds)
assert output == expected
def test_virtualfile_from_vectors_arraylike():
"""
Pass array-like vectors to a dataset.
"""
size = 13
x = list(range(0, size, 1))
y = tuple(range(size, size * 2, 1))
z = range(size * 2, size * 3, 1)
with clib.Session() as lib:
with lib.virtualfile_from_vectors(x, y, z) as vfile:
with GMTTempFile() as outfile:
lib.call_module("info", "{} ->{}".format(vfile, outfile.name))
output = outfile.read(keep_tabs=True)
bounds = "\t".join(
["<{:.0f}/{:.0f}>".format(min(i), max(i)) for i in (x, y, z)]
)
expected = "<vector memory>: N = {}\t{}\n".format(size, bounds)
assert output == expected
def test_extract_region_fails():
"""
Check that extract region fails if nothing has been plotted.
"""
Figure()
with pytest.raises(GMTCLibError):
with clib.Session() as lib:
lib.extract_region()
def test_extract_region_two_figures():
"""
Extract region should handle multiple figures existing at the same time.
"""
# Make two figures before calling extract_region to make sure that it's
# getting from the current figure, not the last figure.
fig1 = Figure()
region1 = np.array([0, 10, -20, -10])
fig1.coast(region=region1, projection="M6i", frame=True, land="black")
fig2 = Figure()
fig2.basemap(region="US.HI+r5", projection="M6i", frame=True)
# Activate the first figure and extract the region from it
# Use in a different session to avoid any memory problems.
with clib.Session() as lib:
lib.call_module("figure", "{} -".format(fig1._name))
with clib.Session() as lib:
wesn1 = lib.extract_region()
npt.assert_allclose(wesn1, region1)
# Now try it with the second one
with clib.Session() as lib:
lib.call_module("figure", "{} -".format(fig2._name))
with clib.Session() as lib:
wesn2 = lib.extract_region()
npt.assert_allclose(wesn2, np.array([-165.0, -150.0, 15.0, 25.0]))
def test_write_data_fails():
"""
Check that write data raises an exception for non-zero return codes.
"""
# It's hard to make the C API function fail without causing a Segmentation
# Fault. Can't test this if by giving a bad file name because if
# output=='', GMT will just write to stdout and spaces are valid file
# names. Use a mock instead just to exercise this part of the code.
with clib.Session() as lib:
with mock(lib, "GMT_Write_Data", returns=1):
with pytest.raises(GMTCLibError):
lib.write_data(
"GMT_IS_VECTOR",
"GMT_IS_POINT",
"GMT_WRITE_SET",
[1] * 6,
"some-file-name",
None,
)
def test_dataarray_to_matrix_works():
"""
Check that dataarray_to_matrix returns correct output.
"""
data = np.diag(v=np.arange(3))
x = np.linspace(start=0, stop=4, num=3)
y = np.linspace(start=5, stop=9, num=3)
grid = xr.DataArray(data, coords=[("y", y), ("x", x)])
matrix, region, inc = dataarray_to_matrix(grid)
npt.assert_allclose(actual=matrix, desired=np.flipud(data))
npt.assert_allclose(actual=region, desired=[x.min(), x.max(), y.min(), y.max()])
npt.assert_allclose(actual=inc, desired=[x[1] - x[0], y[1] - y[0]])
def test_dataarray_to_matrix_negative_x_increment():
"""
Check if dataarray_to_matrix returns correct output with flipped x.
"""
data = np.diag(v=np.arange(3))
x = np.linspace(start=4, stop=0, num=3)
y = np.linspace(start=5, stop=9, num=3)
grid = xr.DataArray(data, coords=[("y", y), ("x", x)])
matrix, region, inc = dataarray_to_matrix(grid)
npt.assert_allclose(actual=matrix, desired= | np.flip(data, axis=(0, 1)) | numpy.flip |
from astropy.io import fits
from astropy.stats import sigma_clipped_stats
from astropy.wcs import WCS
from astropy.coordinates import SkyCoord
from scipy.optimize import curve_fit
from scipy.integrate import quad
from scipy.interpolate import interp2d
from photutils import CircularAnnulus,CircularAperture,aperture_photometry
from photutils.utils import calc_total_error
from photutils import centroid_sources,centroid_2dg,centroid_com
from kbastroutils.grismconf import GrismCONF
from kbastroutils.grismsens import GrismSens
from kbastroutils.grismapcorr import GrismApCorr
from kbastroutils.dqmask import DQMask
from kbastroutils.make_sip import make_SIP
from kbastroutils.photapcorr import PhotApCorr
from kbastroutils.grismmeta import GrismMeta
from kbastroutils.grismmodel import GrismModel
from kbastroutils.grismcrclean import GrismCRClean
from kbastroutils.grismcalibpath import GrismCalibPath
from kbastroutils.grismdrz import GrismDRZ
import copy,os,pickle,sys,re,shutil
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
class GND:
def __init__(self,files):
meta = GrismMeta(files)
self.files = copy.deepcopy(meta.files)
self.meta = copy.deepcopy(meta.meta)
####################
####################
####################
def make_pair(self,pairs=None):
if pairs:
self.pairs = copy.deepcopy(pairs)
gid,did = [],[]
for i in pairs:
did.append(i)
for j in pairs[i]:
gid.append(j)
self.meta[j]['DIRECT'] = (i,(self.meta[j]['FILTER'],self.meta[i]['FILTER']))
self.did = copy.deepcopy(did)
self.gid = copy.deepcopy(gid)
else:
self.gid,self.did = self.make_pair_id()
pairs = self.make_pair_auto()
self.make_pair(pairs)
def make_pair_id(self):
KEYS = {
'DIRECT': ['F.+'],
'GRISM': ['G.+']
}
gid,did = [],[]
for i in self.meta:
filt = self.meta[i]['FILTER']
y = None
for j in KEYS:
for k in KEYS[j]:
if re.search(k,filt):
y = j
if y=='DIRECT':
did.append(i)
elif y=='GRISM':
gid.append(i)
else:
print('Warning: cannot assign DIRECT or GRISM. {0} {1}'.format(i,self.meta[i]['FILE']))
return gid,did
def make_pair_auto(self):
KEY = 'EXPSTART'
out = {}
dmeta = {}
for i in self.did:
dmeta[i] = self.meta[i]
dtab = pd.DataFrame(dmeta).T
did,dval = dtab['ID'].values,dtab[KEY].values
tmp = []
for i in self.gid:
gval = self.meta[i][KEY]
tmpp = np.abs(dval-gval)
tmppp = np.where(tmpp == np.min(tmpp))[0][0]
tmp.append((did[tmppp],i))
for i in tmp:
if i[0] not in out.keys():
out[i[0]] = [i[1]]
else:
tmpppp = out[i[0]]
tmpppp.append(i[1])
return out
####################
####################
####################
def make_calibpath(self,
keysconf=['DQMASK','DRZSCALE','BEAMA','DYDX_ORDER_A','XOFF_A','YOFF_A','DISP_ORDER_A'],
keyssens=None
):
self.calibpath = GrismCalibPath()
self.make_calibpath_conf(keysconf)
self.make_calibpath_sens(keyssens)
def make_calibpath_conf(self,keysconf):
for i in self.gid:
self.meta[i]['CONF'] = GrismCONF(keysconf,self.meta[i],self.calibpath.table)
self.meta[i]['CONF'].fetch(self.meta[i]['CONF'].keysconf)
self.meta[i]['CONF'].value['DQMASK'] = int(self.meta[i]['CONF'].value['DQMASK'][0])
def make_calibpath_sens(self,keyssens):
for i in self.gid:
self.meta[i]['SENS'] = GrismSens(keyssens,self.meta[i],self.calibpath.table)
####################
####################
####################
def make_crclean(self,identifier,group=None,params=None,run=False,outpath=None):
pairs = self.pairs
meta = self.meta
self.crclean = GrismCRClean(identifier,pairs,group,params,run,outpath,meta)
if run:
for i in self.crclean.meta:
self.meta[i]['CRCLEAN'] = self.crclean.meta[i]
####################
####################
####################
def make_xyref(self):
self.make_xyoff()
self.make_xydif()
for j in self.gid:
xyoff = self.meta[j]['XYOFF']
xydif = self.meta[j]['XYDIF']
direct = self.meta[j]['DIRECT'][0]
xyd = self.meta[direct]['XYD']
xref = xyd[0] + xyoff[0] + xydif[0]
yref = xyd[1] + xyoff[1] + xydif[1]
xyref = (xref,yref)
self.meta[j]['XYREF'] = xyref
def make_xyoff(self):
for i in self.gid:
coefxoff = self.meta[i]['CONF'].value['XOFF_A']
coefyoff = self.meta[i]['CONF'].value['YOFF_A']
orderx,ordery = self.make_xyofforder(coefxoff),self.make_xyofforder(coefyoff)
direct = self.meta[i]['DIRECT'][0]
xyd = self.meta[direct]['XYD']
if self.meta[i]['SUBARRAY']:
corner = self.meta[i]['SUBARRAY_PARAMS']['CORNER']
naxis1 = xyd[0] + corner[0]
naxis2 = xyd[1] + corner[1]
xoff = make_SIP(coefxoff,naxis1,naxis2,startx=True)
yoff = make_SIP(coefyoff,naxis2,naxis2,startx=True)
else:
xoff = make_SIP(coefxoff,xyd[0],xyd[1],startx=True)
yoff = make_SIP(coefyoff,xyd[0],xyd[1],startx=True)
self.meta[i]['XYOFF'] = (xoff[0],yoff[0])
def make_xyofforder(self,coef):
ncoef = len(coef)
out,n = 0,1
while n!=ncoef:
out += 1
n += out+1
return out
def make_xydif(self):
for i in self.gid:
post1g,post2g = self.meta[i]['POSTARG1'],self.meta[i]['POSTARG2']
direct = self.meta[i]['DIRECT'][0]
post1d,post2d = self.meta[direct]['POSTARG1'],self.meta[direct]['POSTARG2']
scaleg,scaled = self.meta[i]["IDCSCALE"],self.meta[direct]['IDCSCALE']
dx = post1g/scaleg - post1d/scaled
dy = post2g/scaleg - post2d/scaled
xydif = (dx,dy)
self.meta[i]['XYDIF'] = copy.deepcopy(xydif)
####################
####################
####################
def make_xyd(self,XYD=None
,inittype='header'
,adjust=True,box_size=25,maskin=[0]
):
if XYD:
for i in XYD:
self.meta[i]['XYD'] = XYD[i]
else:
init = self.make_xydinit(inittype)
if not init:
print('Error: cannot initiate. Terminate')
sys.exit()
if adjust:
xyd = self.make_xydadjust(init,box_size,maskin)
self.make_xyd(xyd)
else:
self.make_xyd(init)
def make_xydinit(self,inittype):
out = {}
if inittype=='header':
for i in self.did:
try:
tmp = self.meta[i]['XYD']
continue
except:
pass
ra,dec = self.meta[i]['RA_TARG'],self.meta[i]['DEC_TARG']
w = WCS(header=fits.open(self.files[i])[self.meta[i]['EXT']]
,fobj=fits.open(self.files[i])
)
coord = SkyCoord(ra,dec,unit='deg')
xx,yy = w.all_world2pix(coord.ra,coord.dec,1)
out[i] = copy.deepcopy((xx,yy))
return out
else:
print("Error: only inittype='header' is available. Terminate")
return False
def make_xydadjust(self,init,box_size,maskin):
out = {}
for i in self.did:
try:
tmp = self.meta[i]['XYD']
continue
except:
pass
x = fits.open(self.files[i])
xdata = x[self.meta[i]['EXT']].data
xdq = x['DQ',self.meta[i]['EXT'][1]].data
xi,yi = int(init[i][0]),int(init[i][1])
mask = DQMask(maskin)
mask.make_mask(xdq)
try:
xx,yy = centroid_sources(xdata,xi,yi,box_size=box_size,mask=~mask.mask)
tmp = np.full_like(xdata,False,dtype=bool)
xi,yi = int(xx[0]),int(yy[0])
tmp[yi-box_size:yi+box_size+1,xi-box_size:xi+box_size+1] = True
newmask = (mask.mask & tmp)
xx,yy = centroid_2dg(xdata,mask=~newmask)
except:
print('Error: cannot make_xydadjust. {0} {1}. Set to inits'.format(i,self.files[i].split('/')[-1]))
xx,yy = copy.deepcopy(init[i][0]),copy.deepcopy(init[i][1])
out[i] = copy.deepcopy((xx,yy))
return out
####################
####################
####################
def make_traceNwavelength(self):
self.make_trace()
self.make_wavelength()
def make_trace(self):
for j in self.gid:
xhbound = self.meta[j]['CONF'].value['BEAMA']
xh = np.arange(xhbound[0],xhbound[1]+1,step=1)
xyref = self.meta[j]['XYREF']
order = self.meta[j]['CONF'].value['DYDX_ORDER_A']
sip = []
for k in np.arange(order+1):
string = 'DYDX_A_' + str(int(k))
coef = self.meta[j]['CONF'].value[string]
x = make_SIP(coef,*xyref,startx=True)
sip.append(x)
yh = np.full_like(xh,0.,dtype=float)
for k,kk in enumerate(sip):
yh += kk*xh**k
xg = xh + xyref[0]
yg = yh + xyref[1]
self.meta[j]['XG'] = xg
self.meta[j]['YG'] = yg
self.meta[j]['DYDX'] = sip
def make_wavelength(self):
varclength = np.vectorize(self.arclength)
for j in self.gid:
xhbound = self.meta[j]['CONF'].value['BEAMA']
xh = np.arange(xhbound[0],xhbound[1]+1,step=1)
xyref = self.meta[j]['XYREF']
order = self.meta[j]['CONF'].value['DISP_ORDER_A'].astype(int)
dydx = self.meta[j]['DYDX']
d = []
sip = []
for k in np.arange(order+1):
string = 'DLDP_A_' + str(int(k))
coef = self.meta[j]['CONF'].value[string]
x = make_SIP(coef,*xyref,startx=True)
sip.append(x)
arc,earc = np.array(varclength(xh,*dydx))
ww = np.full_like(xh,0.,dtype=float)
for k,kk in enumerate(sip):
ww += kk*arc**k
self.meta[j]['WW'] = ww
self.meta[j]['WWUNIT'] = r'$\AA$'
def arclength_integrand(self,Fa,*coef):
s = 0
for i,ii in enumerate(coef):
if i==0:
continue
s += i * ii * (Fa**(i-1))
return np.sqrt(1. + np.power(s,2))
def arclength(self,Fa,*coef):
integral,err = quad(self.arclength_integrand, 0., Fa, args=coef)
return integral,err
####################
####################
####################
def make_bkg(self,method='median',sigma=3.,iters=5,usecrclean=True,maskin=None):
for j in self.gid:
x = fits.open(self.files[j])
ext = self.meta[j]['EXT']
identifier = self.meta[j]['IDENTIFIER']
filt = self.meta[j]['FILTER']
try:
xdq = fits.open(self.meta[j]['CRCLEAN'])[('DQ',ext[1])].data
except:
xdq = x[('DQ',ext[1])].data
xdata = x[ext].data
if not maskin:
maskin = [self.meta[j]['CONF'].value['DQMASK']]
a = DQMask(value=maskin,declass=True,makeclass=True)
a.make_mask(xdq)
mean,median,std = sigma_clipped_stats(xdata,mask=~a.mask,sigma=sigma,maxiters=iters)
self.meta[j]['BKG'] = None
self.meta[j]['BKG_FILE'] = None
if method=='median':
bkgim = np.full_like(xdata,median,dtype=float)
self.meta[j]['BKG'] = bkgim
self.meta[j]['BKG_FILE'] = (method,median,'No file')
elif method=='master':
if identifier==('HST','WFC3','IR'):
bkg = self.calibpath.table['BKG'][identifier][filt]
elif identifier==('HST','ACS','WFC'):
bkg = self.calibpath.table['BKG'][identifier][(self.meta[j]['CCDCHIP'])]
if not bkg:
print('Error: bkg file is required. Terminate')
sys.exit()
elif bkg:
mask = np.full_like(a.mask,True,dtype=bool)
mask[np.where(np.abs((xdata - median)/std) > sigma)] = False
mask = copy.deepcopy(mask & a.mask)
bkgdata = fits.open(bkg)[0].data
if self.meta[j]['SUBARRAY']:
shape = mask.shape
corner = self.meta[j]['SUBARRAY_PARAMS']['CORNER']
naxis1 = corner[0] + shape[1]
naxis2 = corner[1] + shape[0]
tmp = bkgdata[corner[1]:naxis2,corner[0]:naxis1]
bkgdata = copy.deepcopy(tmp)
masktmp = np.full_like(mask,False,dtype=bool)
m = np.where(bkgdata>0.)
masktmp[m] = True
mask = copy.deepcopy(mask & masktmp)
scale = self.make_mastersky(xdata,mask,bkgdata)
self.meta[j]['BKG'] = scale[0] * bkgdata
self.meta[j]['BKG_FILE'] = (method,scale,bkg)
def make_mastersky(self,xdata,xmask,bkgdata):
x,y = bkgdata[xmask],xdata[xmask]
popt,pcov = curve_fit(lambda x, *p: p[0]*x, x,y,p0=[1.])
return (popt,pcov)
####################
####################
####################
def make_flat(self,method='uniform'):
for j in self.gid:
x = fits.open(self.files[j])
ext = self.meta[j]['EXT']
xdata = x[ext].data
identifier = self.meta[j]['IDENTIFIER']
filt = self.meta[j]['FILTER']
self.meta[j]['FLAT'] = None
self.meta[j]['FLAT_FILE'] = None
if method=='uniform':
flatim = np.full_like(xdata,1.,dtype=float)
self.meta[j]['FLAT'] = flatim
self.meta[j]['FLAT_FILE'] = (method,'No file')
elif method=='master':
if identifier==('HST','WFC3','IR'):
flatfile = self.calibpath.table['FLAT'][identifier][filt]
elif identifier==('HST','ACS','WFC'):
flatfile = self.calibpath.table['FLAT'][identifier][(self.meta[j]['CCDCHIP'])]
if not flatfile:
print('Error: flat file is required. Set to None')
else:
flatim = np.full_like(xdata,np.nan,dtype=float)
nrow,ncol = xdata.shape[0],xdata.shape[1]
y = fits.open(flatfile)
wmin,wmax = y[0].header['WMIN'],y[0].header['WMAX']
a = {}
for k,kk in enumerate(y):
if self.meta[j]['SUBARRAY']:
shape = xdata.shape
corner = self.meta[j]['SUBARRAY_PARAMS']['CORNER']
naxis1 = corner[0] + shape[1]
naxis2 = corner[1] + shape[0]
a[k] = y[k].data[corner[1]:naxis2,corner[0]:naxis1]
else:
a[k] = y[k].data
x1 = np.copy(self.meta[j]['XG'].astype(int))
w1 = np.copy(self.meta[j]['WW'])
w1[np.where(w1<=wmin)],w1[np.where(w1>=wmax)] = wmin,wmax
x1min,x1max = np.min(x1),np.max(x1)
x0,x2 = np.arange(0,x1min), | np.arange(x1max+1,ncol) | numpy.arange |
# coding: utf-8
#details of awesome oscillator can be found here
# https://www.tradingview.com/wiki/Awesome_Oscillator_(AO)
#basically i use awesome oscillator to compare with macd oscillator
#lets see which one makes more money
#there is not much difference between two of em
#this time i use exponential smoothing on macd
#for awesome oscillator, i use simple moving average instead
#the rules are quite simple
#these two are momentum trading strategy
#they compare the short moving average with long moving average
#if the difference is positive
#we long the asset, vice versa
#awesome oscillator has slightly more conditions for signals
#we will see about it later
#for more details about macd
# https://github.com/tattooday/quant-trading/blob/master/MACD%20oscillator%20backtest.py
# In[1]:
#need to get fix yahoo finance package first
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import fix_yahoo_finance as yf
# In[2]:
#this part is macd
#i will not go into details as i have another session called macd
#the only difference is that i use ewma function to apply exponential smoothing technique
def ewmacd(signals,ma1,ma2):
signals['macd ma1']=signals['Close'].ewm(span=ma1).mean()
signals['macd ma2']=signals['Close'].ewm(span=ma2).mean()
return signals
def signal_generation(df,method,ma1,ma2):
signals=method(df,ma1,ma2)
signals['macd positions']=0
signals['macd positions'][ma1:]=np.where(signals['macd ma1'][ma1:]>=signals['macd ma2'][ma1:],1,0)
signals['macd signals']=signals['macd positions'].diff()
signals['macd oscillator']=signals['macd ma1']-signals['macd ma2']
return signals
# In[3]:
#for awesome oscillator
#moving average is based on the mean of high and low instead of close price
def awesome_ma(signals):
signals['awesome ma1'],signals['awesome ma2']=0,0
signals['awesome ma1']=((signals['High']+signals['Low'])/2).rolling(window=5).mean()
signals['awesome ma2']=((signals['High']+signals['Low'])/2).rolling(window=34).mean()
return signals
#awesome signal generation,AWESOME!
def awesome_signal_generation(df,method):
signals=method(df)
signals.reset_index(inplace=True)
signals['awesome signals']=0
signals['awesome oscillator']=signals['awesome ma1']-signals['awesome ma2']
signals['cumsum']=0
for i in range(2,len(signals)):
#awesome oscillator has an extra way to generate signals
#its called saucer
#A Bearish Saucer setup occurs when the AO is below the Zero Line
#in another word, awesome oscillator is negative
#A Bearish Saucer entails two consecutive green bars (with the second bar being higher than the first bar) being followed by a red bar.
#in another word, green bar refers to open price is higher than close price
if (signals['Open'][i]>signals['Close'][i] and
signals['Open'][i-1]<signals['Close'][i-1] and
signals['Open'][i-2]<signals['Close'][i-2] and
signals['awesome oscillator'][i-1]>signals['awesome oscillator'][i-2] and
signals['awesome oscillator'][i-1]<0 and
signals['awesome oscillator'][i]<0):
signals.at[i,'awesome signals']=1
#this is bullish saucer
#vice versa
if (signals['Open'][i]<signals['Close'][i] and
signals['Open'][i-1]>signals['Close'][i-1] and
signals['Open'][i-2]>signals['Close'][i-2] and
signals['awesome oscillator'][i-1]<signals['awesome oscillator'][i-2] and
signals['awesome oscillator'][i-1]>0 and
signals['awesome oscillator'][i]>0):
signals.at[i,'awesome signals']=-1
#this part is the same as macd signal generation
#nevertheless, we have extra rules to get signals ahead of moving average
#if we get signals before moving average generate any signal
#we will ignore signals generated by moving average then
#as it is delayed and probably deliver fewer profit than previous signals
#we use cumulated sum to see if there has been created any open positions
#if so, we will take a pass
if signals['awesome ma1'][i]>signals['awesome ma2'][i]:
signals.at[i,'awesome signals']=1
signals['cumsum']=signals['awesome signals'].cumsum()
if signals['cumsum'][i]>1:
signals.at[i,'awesome signals']=0
if signals['awesome ma1'][i]<signals['awesome ma2'][i]:
signals.at[i,'awesome signals']=-1
signals['cumsum']=signals['awesome signals'].cumsum()
if signals['cumsum'][i]<0:
signals.at[i,'awesome signals']=0
signals['cumsum']=signals['awesome signals'].cumsum()
return signals
# In[4]:
#we plot the results to compare
#basically the same as macd
#im not gonna explain much
def plot(new,ticker):
#positions
fig=plt.figure()
ax=fig.add_subplot(211)
new['Close'].plot(label=ticker)
ax.plot(new.loc[new['awesome signals']==1].index,new['Close'][new['awesome signals']==1],label='AWESOME LONG',lw=0,marker='^',c='g')
ax.plot(new.loc[new['awesome signals']==-1].index,new['Close'][new['awesome signals']==-1],label='AWESOME SHORT',lw=0,marker='v',c='r')
plt.legend(loc='best')
plt.grid(True)
plt.title('Positions')
bx=fig.add_subplot(212,sharex=ax)
new['Close'].plot(label=ticker)
bx.plot(new.loc[new['macd signals']==1].index,new['Close'][new['macd signals']==1],label='MACD LONG',lw=0,marker='^',c='g')
bx.plot(new.loc[new['macd signals']==-1].index,new['Close'][new['macd signals']==-1],label='MACD SHORT',lw=0,marker='v',c='r')
plt.legend(loc='best')
plt.grid(True)
plt.show()
#oscillator
fig=plt.figure()
cx=fig.add_subplot(211)
c= | np.where(new['Open']>new['Close'],'r','g') | numpy.where |
from RNNs import QIFExpAddNoiseSyns
import numpy as np
import pickle
import matplotlib.pyplot as plt
from scipy.ndimage import gaussian_filter1d
# STEP 0: Define simulation condition
#####################################
# parse worker indices from script arguments
idx_cond = 570
# STEP 1: Load pre-generated RNN parameters
###########################################
path = "/home/rgast/PycharmProjects/BrainNetworks/RC/results"
config = pickle.load(open(f"{path}/qif_micro_config.pkl", 'rb'))
# connectivity matrix
C = config['C']
# input
inp = config['inp']
# input weights
W_in = config['W_in']
# simulation config
T = config['T']
dt = config['dt']
dts = config['dts']
cutoff = config['cutoff']
# target values
targets = config['targets']
# adaptation strength
alpha = 0.5 # config['alphas'][idx_cond]
# eta
eta = -3.8 # config['etas'][idx_cond]
# STEP 2: define remaining network parameters
#############################################
# general parameters
N = C.shape[0]
m = W_in.shape[0]
n_folds = 5
ridge_alpha = 1e-3
# qif parameters
Delta = 2.0
J = 15.0*np.sqrt(Delta)
D = 0.0
tau_a = 10.0
tau_s = 0.8
# STEP 3: Evaluate classification performance of RNN
####################################################
# setup QIF RNN
qif_rnn = QIFExpAddNoiseSyns(C, eta, J, Delta=Delta, alpha=alpha, D=D, tau_s=tau_s, tau_a=tau_a)
# perform simulation
W_in[:, :] = 0.0
X = qif_rnn.run(T, dt, dts, inp=inp, W_in=W_in, state_record_key='t1', cutoff=cutoff)
r_qif = np.mean(X, axis=1)
# prepare training data
buffer_val = 0
for i in range(X.shape[1]):
X[:, i] = gaussian_filter1d(X[:, i], 0.05 / dts, mode='constant', cval=buffer_val)
y = targets
r_qif2 = np.mean(X, axis=1)
# split into test and training data
split = int(np.round(X.shape[0]*0.75, decimals=0))
X_train = X[:split, :]
y_train = y[:split]
X_test = X[split:, :]
y_test = y[split:]
# train RNN
key, scores, coefs = qif_rnn.ridge_fit(X=X_train, y=y_train, alpha=ridge_alpha, k=n_folds, fit_intercept=False, copy_X=True,
solver='lsqr')
score, _ = qif_rnn.test(X=X_test, y=y_test, readout_key=key)
y_predict = qif_rnn.predict(X=X, readout_key=key)
print(f"Classification performance on test data: {score}")
# plotting
fig, axes = plt.subplots(nrows=4)
ax1 = axes[0]
ax1.plot(np.mean(X, axis=1))
ax2 = axes[1]
im = ax2.imshow(X.T, aspect='auto', cmap="plasma", vmin=0, vmax=0.005)
#plt.colorbar(im, ax=ax2, shrink=0.5)
ax3 = axes[2]
ax3.plot(y)
ax3.plot(y_predict)
plt.legend(['target', 'output'])
ax4 = axes[3]
start = int(cutoff/dt)
ax4.plot(inp[0, start:])
ax4.plot(inp[1, start:])
plt.legend(['lorenz', 'stula'])
plt.tight_layout()
# plot connectivity
fig2, ax = plt.subplots()
im1 = ax.imshow(C, aspect='auto', cmap="plasma", vmin=0, vmax=np.max(C[:]))
plt.colorbar(im1, ax=ax, shrink=0.5)
plt.title('C')
plt.tight_layout()
print(f'Synaptic sparseness: { | np.sum(C[:] == 0) | numpy.sum |
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import numpy as np
class Scaler(object):
"""
Iterative estimation of row and column centering/scaling
using the algorithm from page 31 of:
Matrix Completion and Low-Rank SVD via Fast Alternating Least Squares
"""
def __init__(
self,
center_columns=True,
scale_columns=True,
min_value=None,
max_value=None,
verbose=True):
self.center_columns = center_columns
self.scale_columns = scale_columns
self.min_value = min_value
self.max_value = max_value
self.verbose = verbose
self.column_centers = None
self.column_scales = None
def fit(self, X):
if self.center_columns:
self.column_centers = np.nanmean(X, axis=0)
if self.scale_columns:
self.column_scales = np.nanstd(X, axis=0)
self.column_scales[self.column_scales == 0] = 1.0
return self
def transform(self, X):
X = np.asarray(X).copy()
if self.center_columns:
X -= self.column_centers
if self.scale_columns:
X /= self.column_scales
return X
def fit_transform(self, X):
self.fit(X)
return self.transform(X)
def inverse_transform(self, X):
X = np.asarray(X).copy()
if self.scale_columns:
X *= self.column_scales
if self.center_columns:
X += self.column_centers
return X
class BiScaler(object):
"""
Iterative estimation of row and column centering/scaling
using the algorithm from page 31 of:
Matrix Completion and Low-Rank SVD via Fast Alternating Least Squares
"""
def __init__(
self,
center_rows=True,
center_columns=True,
scale_rows=True,
scale_columns=True,
min_value=None,
max_value=None,
max_iters=100,
tolerance=0.001,
verbose=True):
self.center_rows = center_rows
self.center_columns = center_columns
self.scale_rows = scale_rows
self.scale_columns = scale_columns
self.min_value = min_value
self.max_value = max_value
self.max_iters = max_iters
self.tolerance = tolerance
self.verbose = verbose
def estimate_row_means(
self,
X,
observed,
column_means,
column_scales):
"""
row_center[i] =
sum{j in observed[i, :]}{
(1 / column_scale[j]) * (X[i, j] - column_center[j])
}
------------------------------------------------------------
sum{j in observed[i, :]}{1 / column_scale[j]}
"""
n_rows, n_cols = X.shape
column_means = np.asarray(column_means)
if len(column_means) != n_cols:
raise ValueError("Expected length %d but got shape %s" % (
n_cols, column_means.shape))
X = X - column_means.reshape((1, n_cols))
column_weights = 1.0 / column_scales
X *= column_weights.reshape((1, n_cols))
row_means = np.zeros(n_rows, dtype=X.dtype)
row_residual_sums = np.nansum(X, axis=1)
for i in range(n_rows):
row_mask = observed[i, :]
sum_weights = column_weights[row_mask].sum()
row_means[i] = row_residual_sums[i] / sum_weights
return row_means
def estimate_column_means(
self,
X,
observed,
row_means,
row_scales):
"""
column_center[j] =
sum{i in observed[:, j]}{
(1 / row_scale[i]) * (X[i, j]) - row_center[i])
}
------------------------------------------------------------
sum{i in observed[:, j]}{1 / row_scale[i]}
"""
n_rows, n_cols = X.shape
row_means = np.asarray(row_means)
if len(row_means) != n_rows:
raise ValueError("Expected length %d but got shape %s" % (
n_rows, row_means.shape))
column_means = np.zeros(n_cols, dtype=X.dtype)
X = X - row_means.reshape((n_rows, 1))
row_weights = 1.0 / row_scales
X *= row_weights.reshape((n_rows, 1))
col_residual_sums = np.nansum(X, axis=0)
for j in range(n_cols):
col_mask = observed[:, j]
sum_weights = row_weights[col_mask].sum()
column_means[j] = col_residual_sums[j] / sum_weights
return column_means
def center(self, X, row_means, column_means, inplace=False):
n_rows, n_cols = X.shape
row_means = np.asarray(row_means)
column_means = np.asarray(column_means)
if len(row_means) != n_rows:
raise ValueError("Expected length %d but got shape %s" % (
n_rows, row_means.shape))
if len(column_means) != n_cols:
raise ValueError("Expected length %d but got shape %s" % (
n_cols, column_means.shape))
if not inplace:
X = X.copy()
X -= row_means.reshape((n_rows, 1))
X -= column_means.reshape((1, n_cols))
return X
def rescale(self, X, row_scales, column_scales, inplace=False):
if not inplace:
X = X.copy()
n_rows, n_cols = X.shape
X /= row_scales.reshape((n_rows, 1))
X /= column_scales.reshape((1, n_cols))
return X
def estimate_row_scales(
self,
X_centered,
column_scales):
"""
row_scale[i]**2 =
mean{j in observed[i, :]}{
(X[i, j] - row_center[i] - column_center[j]) ** 2
--------------------------------------------------
column_scale[j] ** 2
}
"""
n_rows, n_cols = X_centered.shape
column_scales = np.asarray(column_scales)
if len(column_scales) != n_cols:
raise ValueError("Expected length %d but got shape %s" % (
n_cols, column_scales))
row_variances = np.nanmean(
X_centered ** 2 / (column_scales ** 2).reshape((1, n_cols)),
axis=1)
row_variances[row_variances == 0] = 1.0
assert len(row_variances) == n_rows, "%d != %d" % (
len(row_variances),
n_rows)
return np.sqrt(row_variances)
def estimate_column_scales(
self,
X_centered,
row_scales):
"""
column_scale[j] ** 2 =
mean{i in observed[:, j]}{
(X[i, j] - row_center[i] - column_center[j]) ** 2
-------------------------------------------------
row_scale[i] ** 2
}
"""
n_rows, n_cols = X_centered.shape
row_scales = np.asarray(row_scales)
if len(row_scales) != n_rows:
raise ValueError("Expected length %s, got shape %s" % (
n_rows, row_scales.shape,))
column_variances = np.nanmean(
X_centered ** 2 / (row_scales ** 2).reshape((n_rows, 1)),
axis=0)
column_variances[column_variances == 0] = 1.0
assert len(column_variances) == n_cols, "%d != %d" % (
len(column_variances),
n_cols)
return np.sqrt(column_variances)
def residual(self, X_normalized):
total = 0
if self.center_rows:
row_means = np.nanmean(X_normalized, axis=1)
total += (row_means ** 2).sum()
if self.center_columns:
column_means = np.nanmean(X_normalized, axis=0)
total += (column_means ** 2).sum()
if self.scale_rows:
row_variances = np.nanvar(X_normalized, axis=1)
row_variances[row_variances == 0] = 1.0
total += (np.log(row_variances) ** 2).sum()
if self.scale_columns:
column_variances = np.nanvar(X_normalized, axis=0)
column_variances[column_variances == 0] = 1.0
total += (np.log(column_variances) ** 2).sum()
return total
def clamp(self, X, inplace=False):
if not inplace:
X = X.copy()
if self.min_value is not None:
X[X < self.min_value] = self.min_value
if self.max_value is not None:
X[X > self.max_value] = self.max_value
return X
def fit(self, X):
X = self.clamp(X)
n_rows, n_cols = X.shape
dtype = X.dtype
# To avoid inefficient memory access we keep around two copies
# of the array, one contiguous in the rows and the other
# contiguous in the columns
X_row_major = np.asarray(X, order="C")
X_column_major = | np.asarray(X, order="F") | numpy.asarray |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.