prompt
stringlengths 19
879k
| completion
stringlengths 3
53.8k
| api
stringlengths 8
59
|
---|---|---|
# -*- coding: utf-8 -*-
"""
Created on Tue Dec 10 14:26:54 2019
@author: Mnemosyne
Functions to compute the features of the song
"""
import os
import shutil
import glob
import sys
import random
import re
import numpy as np
import scipy as sp
import scipy.io.wavfile as wav
from scipy.fftpack import fft, rfft
from scipy.optimize import curve_fit
import scipy.signal as signal
from scipy.stats.mstats import gmean
from sklearn.cluster import KMeans
from pydub import AudioSegment
from pydub import silence
import matplotlib.pyplot as plt
import matplotlib.colors as colors
from mpl_toolkits.mplot3d import axes3d
import matplotlib.colors as colors
from threading import Thread
import librosa.feature
import librosa.effects
from songbird_data_analysis import Song_functions
# Onset and offset of the syllables: to compute duration of syllables and gaps
def cut(rawsong, sr, threshold, min_syl_dur, min_silent_dur, f_cut_min, f_cut_max):
"""
This function is meant to be used on a single recording, create an external loop
to apply on several recordings (see function distribution).
VARIABLES:
- rawsong: the wav file a song
- sr: sampling rate
OUTPUT:
- onset and offset of each syllable of the song
So for syllable 1 of a song, its onset is onsets[0] and its offset is offsets[0].
To get that segment of the spectrogram, you'd take spect[:,onsets[0]:offsets[0]]
"""
# parameters that might be adjusted dependending on the bird
rawsong = rawsong.astype(float)
rawsong = rawsong.flatten()
amp = Song_functions.smooth_data(rawsong,sr,freq_cutoffs=(f_cut_min, f_cut_max))
(onsets, offsets) = Song_functions.segment_song(amp,segment_params={'threshold': threshold, 'min_syl_dur': min_syl_dur, 'min_silent_dur': min_silent_dur},samp_freq=sr) # Detects syllables according to the threshold you set
return amp, onsets, offsets
def test_features(songfile, args):
"""
A function to tune the parameter depending on the dataset and test the feature extraction
INPUT:
One recording.
OUTPUT
- plot of the spectrogram, onset & offset and amplitude of the selected syllables
- plot the pitches
- plot the coupling of the features two by two
"""
# read the data
sr, samples = wav.read(songfile[0])
y, sr = librosa.load(songfile[0], sr=16000)
# determine onset and offset of the syllables for this song
amp, onsets, offsets = cut(samples, sr, args.threshold, args.min_syl_dur, args.min_silent_dur, args.f_cut_min, args.f_cut_max)
# Make output directory
aux_output_dir = os.path.join(args.data_dir,args.output_dir)
if not os.path.isdir(aux_output_dir):
os.makedirs(aux_output_dir)
os.chdir(aux_output_dir)
# Spectrogram with librosa
X = librosa.stft(y, n_fft=args.N, hop_length=args.H, win_length=args.N, window='hann', pad_mode='constant', center=True)
Y = np.log(1 + 100 * np.abs(X) ** 2)
T_coef = np.arange(X.shape[1]) * args.H / sr
K = args.N // 2
F_coef = np.arange(K + 1) * sr / args.N
# Plot
noverlap = args.nperseg - args.overlap
fig, (ax1, ax2, ax3) = plt.subplots(nrows=3, sharex=True)
# Plots spectrogram
#(f,t,spect)=sp.signal.spectrogram(samples, sr, args.window, args.nperseg, noverlap, mode='complex')
#ax1.imshow(10*np.log10(np.square(abs(spect))), origin="lower", aspect="auto", interpolation="none", extent=[0, max(t)*1000, min(f), max(f)], cmap = 'inferno')
extent = [T_coef[0], T_coef[-1], F_coef[0], 8000]
ax1.imshow(Y, cmap=args.color, aspect='auto', origin='lower', extent=extent, norm=colors.PowerNorm(gamma=0.2))
ax1.set_ylabel('Frequency (Hz)')
# Plots song signal amplitude
x_amp=np.arange(len(amp))
ax2.plot(x_amp/sr*1000,samples,color='grey')
for i in range(0,len(onsets)):
ax2.axvline(x=onsets[i]/sr*1000,color='olivedrab',linestyle='dashed')
ax2.axvline(x=offsets[i]/sr*1000,color='darkslategrey',linestyle='dashed')
ax2.set_ylabel('Amplitude (V)')
# Plot smoothed amplitude of the song as per spectrogram index
ax3.plot(x_amp/sr*1000, amp,color='grey')
for i in range(0,len(onsets)):
ax3.axvline(x=onsets[i]/sr*1000,color='olivedrab',linestyle='dashed')
ax3.axvline(x=offsets[i]/sr*1000,color='darkslategrey',linestyle='dashed')
ax3.axhline(y=args.threshold,color='black',label='Threshold')
ax3.legend()
ax3.set_ylabel('Amplitude (V)')
ax3.set_xlabel('Time (ms)')
ax1.spines['right'].set_visible(False)
ax1.spines['top'].set_visible(False)
ax1.spines['bottom'].set_visible(False)
ax2.spines['right'].set_visible(False)
ax2.spines['top'].set_visible(False)
ax2.spines['bottom'].set_visible(False)
ax3.spines['right'].set_visible(False)
ax3.spines['top'].set_visible(False)
ax3.spines['bottom'].set_visible(False)
ax1.tick_params(axis='x', labelbottom=False, bottom=False)
ax2.tick_params(axis='x', labelbottom=False, bottom=False)
ax3.tick_params(axis='x', labelbottom=True, bottom=True)
plt.savefig(args.data_dir + '/' + args.output_dir + '/' + 'Test_selection_0' + '.' + args.format)
# Duration, spectral flatness, mean pitch
dur_syll = np.zeros((np.size(onsets),))
dur_gap = np.zeros((np.size(onsets),))
wiener = np.zeros((np.size(onsets),))
mean_pitch = np.zeros((np.size(onsets),))
max_pitch = np.zeros((np.size(onsets),))
min_pitch = np.zeros((np.size(onsets),))
direction_pitch = np.zeros((np.size(onsets),))
for j in range(0,np.size(onsets)):
# Syllable duration
dur_syll[j] = offsets[j] - onsets[j]
if j<(np.size(onsets)-1):
dur_gap[j] = onsets[j+1] - offsets[j]
# Spectral flatness/wiener entropy
wiener[j] = np.mean(librosa.feature.spectral_flatness(samples[onsets[j]:offsets[j]].astype(np.float)))
# Pitch detection, max and min frequency
pitches, magnitudes = librosa.core.piptrack(samples[onsets[j]:offsets[j]].astype(np.float), sr=sr, n_fft=256, fmin=1000, fmax=8000) #, win_length=100)
pitches_all = 0
for interval in range(0,magnitudes.shape[1]):
index = magnitudes[:,interval].argmax()
pitches_all = np.append(pitches_all,pitches[index,interval])
pitches_all = pitches_all[np.nonzero(pitches_all)]
mean_pitch[j] = np.mean(pitches_all)
max_pitch[j] = np.max(pitches_all)
min_pitch[j] = np.min(pitches_all)
if pitches_all[0]<pitches_all[-1]:
direction_pitch[j] = 1
else:
direction_pitch[j] = -1
np.save('pitches_syll_' + str(j) + '.npy', pitches_all)
# Plot all the pitches
colors_list = list(colors._colors_full_map.values())[0::5]
fig, ax = plt.subplots()
#(f, t, spect) = sp.signal.spectrogram(samples, sr, args.window, args.nperseg, noverlap, mode='complex')
#ax.imshow(10 * np.log10(np.square(abs(spect))), origin="lower", aspect="auto", interpolation="none", extent=[0, max(t) * 1000, min(f), max(f)], cmap='inferno')
extent = [T_coef[0], T_coef[-1], F_coef[0], 8000]
ax.imshow(Y, cmap=args.color, aspect='auto', origin='lower', extent=extent, norm=colors.PowerNorm(gamma=0.2))
for j in range(0, np.size(onsets)):
pitches_all= np.load('pitches_syll_' + str(j) + '.npy')
x = np.linspace(onsets[j]/sr*1000, offsets[j]/sr*1000 - 25, np.size(pitches_all))
ax.plot(x, pitches_all, 'o', c=colors_list[j])
plt.ylabel('Frequency(Hz)')
plt.xlabel('Time(ms)')
plt.title('Pitch')
plt.savefig(args.data_dir + '/' + args.output_dir + '/' + 'syll_pitch.' + args.format)
# Mean pitch over the interval of computation
x_axis_pitches = np.zeros((np.size(samples),))
for j in range(0, np.size(onsets)):
x_axis_pitches[int(np.mean([onsets[j], offsets[j]]) / sr * 1000)] = mean_pitch[j]
x_axis_pitches_max = np.zeros((np.size(samples),))
for j in range(0, np.size(onsets)):
x_axis_pitches_max[int(np.mean([onsets[j], offsets[j]]) / sr * 1000)] = max_pitch[j]
x_axis_pitches_min = np.zeros((np.size(samples),))
for j in range(0, np.size(onsets)):
x_axis_pitches_min[int(np.mean([onsets[j], offsets[j]]) / sr * 1000)] = min_pitch[j]
# Plot the mean, min and max pitches
fig, ax = plt.subplots()
#ax.imshow(10 * np.log10(np.square(abs(spect))), origin="lower", aspect="auto", interpolation="none", extent=[0, max(t) * np.size(samples), min(f), max(f)], cmap='inferno')
extent = [T_coef[0], T_coef[-1], F_coef[0], 8000]
ax.imshow(Y, cmap=args.color, aspect='auto', origin='lower', extent=extent, norm=colors.PowerNorm(gamma=0.2))
ax.plot(x_axis_pitches, color='black', linewidth=0, markersize=4, marker='X', label='mean')
ax.plot(x_axis_pitches_max, color='red', linewidth=0, markersize=4, marker='*', label='max')
ax.plot(x_axis_pitches_min, color='red', linewidth=0, markersize=4, marker='*', label='min')
ax.legend()
ax.set_xlim([0, T_coef[-1]])
plt.ylabel('Frequency(Hz)')
plt.xlabel('Time(ms)')
plt.title('Pitch')
plt.savefig(args.data_dir + '/' + args.output_dir + '/' + 'Pitch.' + args.format)
# Cumulative plot
fig, (ax1, ax2) = plt.subplots(nrows=2, ncols=1, figsize=(15,9))
# Plot the spectrogram
#ax3.imshow(10*np.log10(np.square(abs(spect))), origin="lower", aspect="auto", interpolation="none", extent=[0, max(t)*1000, min(f), max(f)], cmap = 'inferno')
ax1.imshow(Y, cmap=args.color, aspect='auto', origin='lower', extent=extent, norm=colors.PowerNorm(gamma=0.2))
ax1.set_ylabel('Frequency(Hz)', fontsize=15)
ax1.set_xticks([])
ax1.title.set_text('Spectrogram')
# Plots song signal amplitude
x_amp = np.arange(len(amp))
ax2.plot(x_amp / sr * 1000, amp, color='grey', label='_Hidden label')
for i in range(0, len(onsets)-2):
ax2.axvline(x=onsets[i] / sr * 1000, color='olivedrab', linestyle='dashed')
ax2.axvline(x=offsets[i] / sr * 1000, color='darkslategrey', linestyle='dashed')
ax2.axvline(x=onsets[len(onsets)-1] / sr * 1000, color='olivedrab', linestyle='dashed', label='Onset')
ax2.axvline(x=offsets[len(onsets)-1] / sr * 1000, color='darkslategrey', linestyle='dashed', label='Offset')
ax2.legend()
ax2.set_ylabel('Amplitude (V)', fontsize=15)
ax2.title.set_text('Selection')
plt.xlabel('Time(ms)', fontsize=15)
plt.tight_layout()
plt.savefig(args.data_dir + '/' + args.output_dir + '/' + 'Summary.' + args.format)
# Cumulative plot 2
fig, (ax1, ax2) = plt.subplots(nrows=2, ncols=1, figsize=(15, 15))
# Plots song signal amplitude
x_amp = np.arange(len(amp))
ax1.plot(x_amp / sr * 1000, amp, color='grey')
for i in range(0, len(onsets)):
ax1.axvline(x=onsets[i] / sr * 1000, color='olivedrab', linestyle='dashed')
ax1.axvline(x=offsets[i] / sr * 1000, color='darkslategrey', linestyle='dashed')
ax1.set_ylabel('Amplitude (V)')
ax1.title.set_text('Syllable selection')
# Plot all the pitches
#(f, t, spect) = sp.signal.spectrogram(samples, sr, args.window, args.nperseg, noverlap, mode='complex')
#ax2.imshow(10 * np.log10(np.square(abs(spect))), origin="lower", aspect="auto", interpolation="none", extent=[0, max(t) * 1000, min(f), max(f)], cmap='inferno')
extent = [T_coef[0], T_coef[-1], F_coef[0], 8000]
ax2.imshow(Y, cmap=args.color, aspect='auto', origin='lower', extent=extent, norm=colors.PowerNorm(gamma=0.2))
for j in range(0, np.size(onsets)):
pitches_all = np.load('pitches_syll_' + str(j) + '.npy')
x = np.linspace(onsets[j] / sr * 1000, offsets[j] / sr * 1000 - 25, np.size(pitches_all))
ax2.plot(x, pitches_all, 'o', c=colors_list[j])
ax2.set_ylabel('Frequency(Hz)')
ax2.title.set_text('Pitch trajectory')
plt.xlabel('Time(ms)')
plt.savefig(args.data_dir + '/' + args.output_dir + '/' + 'Summary_solo.' + args.format)
# Clustering the syllables depending on the features
# Duration VS pitch
plt.subplots()
plt.plot(np.round(dur_syll)/16,mean_pitch, '*')
plt.xlabel('Duration(ms)')
plt.ylabel('Pitch(Hz)')
plt.title('Duration VS pitch')
plt.savefig(args.data_dir + '/' + args.output_dir + '/' + 'durationVSpitch' + args.format)
# Duration VS wiener
plt.subplots()
plt.plot(np.round(dur_syll)/16,wiener, '*')
plt.xlabel('Duration(ms)')
plt.ylabel('Wiener entropy(dB)')
plt.title('Duration VS Wiener entropy')
plt.savefig(args.data_dir + '/' + args.output_dir + '/' + 'durationVSwiener.' + args.format)
# Wiener VS pitch
plt.subplots()
plt.plot(wiener,mean_pitch, '*')
plt.xlabel('Wiener entropy(dB)')
plt.ylabel('Pitch(Hz)')
plt.title('Wiener entropy VS pitch')
plt.savefig(args.data_dir + '/' + args.output_dir + '/' + 'wienerVSpitch.' + args.format)
print('Done')
def repertoire(songfile, classes, args):
"""
:param songfile: list of wav files (one per element of the repertoire)
:param classes: list of the names of each element of the repertoire
:return: a figure with one example per element of the repertoire
"""
samples_repertoire = []
T_coef_all = []
for s in range(0, np.size(songfile)):
y, sr = librosa.load(songfile[s], sr=16000)
# cut the silence
X = librosa.stft(y, n_fft=args.N, hop_length=args.H, win_length=args.N, window='hann', pad_mode='constant', center=True)
Y = np.log(1 + 100 * np.abs(X) ** 2)
T_coef = np.arange(X.shape[1]) * args.H / sr * 1000
K = args.N // 2
F_coef = np.arange(K + 1) * sr / args.N
samples_repertoire.append(Y)
T_coef_all.append(T_coef[-1])
# Plots spectrogram
#plt.style.use('dark_background')
fig, axs = plt.subplots(nrows=4, ncols=4, figsize=(10, 14), sharey=True)
for i in range(0, 4):
for j in range(0,4):
extent = [0, T_coef_all[4*i + j], 0, 8000]
axs[i, j].imshow(samples_repertoire[4*i + j], cmap=args.color, extent = extent, aspect='auto', origin='lower', norm=colors.PowerNorm(gamma=0.2))
axs[i, j].set_title(classes[4*i + j], fontsize=12)
axs[i, j].set_xlim(0, 350)
axs[i, j].spines['top'].set_color('none')
axs[i, j].spines['right'].set_color('none')
axs[0, j].set_xlabel('Time (ms)', fontsize=15)
axs[i, 3].set_ylabel('Frequency (Hz)', fontsize=15)
plt.tight_layout()
plt.savefig(args.data_dir + '/' + 'Repertoire.' + args.format)
print('Done')
def single_syllable_features_from_song(songfile, args):
"""
VARIABLES:
- songfile: list of recordings
OUTPUT:
- .npy file containing the features stored, one single file for the whole directory
"""
# inizialization of variables
dur_syll = [0]
dur_gap = [0]
wiener = [0]
pitch = [0]
for i in range(0,np.size(songfile)):
sr, samples = wav.read(songfile[i])
# determine onset and offset of the syllables for this song
onsets = cut(samples, sr, args.threshold, args.min_syl_dur, args.min_silent_dur, args.f_cut_min, args.f_cut_max)[0]
offsets = cut(samples, sr, args.threshold, args.min_syl_dur, args.min_silent_dur, args.f_cut_min, args.f_cut_max)[1]
dur_syll_aux = np.zeros((np.size(onsets),))
dur_gap_aux = np.zeros((np.size(onsets),))
wiener_aux = np.zeros((np.size(onsets),))
pitch_aux = np.zeros((np.size(onsets),))
for j in range(0,np.size(onsets)):
# syllable duration
dur_syll_aux[j] = offsets[j] - onsets[j]
if j<(np.size(onsets)-1):
dur_gap_aux[j] = onsets[j+1] - offsets[j]
# spectral flatness/wiener entropy
wiener_aux[j] = np.mean(librosa.feature.spectral_flatness(samples[onsets[j]:offsets[j]].astype(np.float)))
# pitch detection
pitches, magnitudes = librosa.core.piptrack(samples[onsets[j]:offsets[j]].astype(np.float), sr=sr, nfft=100, fmin=500, fmax=8000)
pitches_all = 0
for interval in range(0,magnitudes.shape[1]):
index = magnitudes[:,interval].argmax()
pitches_all = np.append(pitches_all,pitches[index,interval])
pitch_aux[j] = np.mean(pitches_all[1::])
dur_syll = np.append(dur_syll, dur_syll_aux) #collect syllable duration for all the i-th recordings
dur_gap = np.append(dur_gap, dur_gap_aux) #collect gap duration for all the i-th recordings
wiener = np.append(wiener, wiener_aux) #collect wiener entropy value for all the i-th recordings
pitch = np.append(pitch, pitch_aux) #collect pitch for all the i-th recordings
# save the data
data = {'File_name': songfile[0::], 'How_many': np.size(songfile), 'Duration_syll': dur_syll[1::], 'Duration_Gap': dur_gap[1::], 'Wiener_entropy': wiener[1::], 'Pitch':pitch[1::]}
np.save(args.data_dir + '/' 'Summary_data_features.npy', data)
def single_syllable_features(songfile, syll_name, template, args):
"""
VARIABLES:
- songfile: list of recordings with syllables
- template: a comparison template (if given) to compute cross-correlation
OUTPUT:
- .npy file containing the features stored
"""
# Count the number of elements in the group
if args.dataset_dim == None:
how_many = np.size(songfile)
elif args.dataset_dim == 0:
if args.dataset_dim > np.size(songfile):
how_many = np.size(songfile)
else:
how_many = args.dataset_dim
else:
songfile = random.sample(songfile, args.dataset_dim)
how_many = np.size(songfile)
# Feature variables initialization
dur_syll = np.zeros((how_many,))
data_list = []
pitches_list = []
mean_pitch = np.zeros((how_many,))
max_pitch = np.zeros((how_many,))
min_pitch = np.zeros((how_many,))
direction_pitch = np.zeros((how_many,))
wiener = np.zeros((how_many,))
for j in range(0,how_many):
# Build the dataset: copy selected file in the training dataset directory
#shutil.copy(songfile[j], args.data_dir + '/' + args.train_dir)
# Read the wave
sr, samples = wav.read(songfile[j])
dur_syll[j] = samples.size/16
# Pitch detection
pitches, magnitudes = librosa.core.piptrack(samples.astype(np.float), sr=sr, n_fft=100, fmin=500, fmax=8000)
pitches_all = 0
for interval in range(0, magnitudes.shape[1]):
index = magnitudes[:, interval].argmax()
pitches_all = np.append(pitches_all, pitches[index, interval])
pitches_all = pitches_all[np.nonzero(pitches_all)]
mean_pitch[j] = np.mean(pitches_all)
max_pitch[j] = np.max(pitches_all)
min_pitch[j] = np.min(pitches_all)
if pitches_all[0] < pitches_all[-1]:
direction_pitch[j] = 1
else:
direction_pitch[j] = -1
# Spectral flatness (Wiener entropy)
wiener[j] = np.mean(librosa.feature.spectral_flatness(samples.astype(np.float)))
# Argmax of duration to determine the longer syllable
template_size = int(np.max(dur_syll))
# Template construction (adding silence before and after for alignment)
if len(template) > 0:
template_samples, sr = librosa.load(template[0], sr=16000)
if template_samples.size / 16 < template_size:
aux_size = template_size - template_samples.size / 16
silence = np.zeros((int(round(aux_size / 2) * 16)), )
aux_template = np.append(silence, template_samples)
aux_template = np.append(aux_template, silence)
else:
aux_template = template_samples
silence = np.zeros((template_size,))
new_template = np.append(silence, aux_template)
new_template = np.append(new_template, silence)
X = librosa.stft(new_template, n_fft=args.N, hop_length=args.H, win_length=args.N, window='hann', pad_mode='constant', center=True)
T_coef = np.arange(X.shape[1]) * args.H / sr * 1000 #save to plot
spectrogram_template = np.log(1 + 100 * np.abs(X ** 2))
shape_template = spectrogram_template.shape
spectrograms = []
spectrograms_envelope = []
cross_correlation = np.zeros((how_many,))
for j in range(0, how_many):
data_list.append(songfile[j])
# compute the spectrogram
samples_aux, sr = librosa.load(songfile[j], sr=16000)
if samples_aux.size / 16 < template_size:
aux_size = template_size - samples_aux.size / 16
silence = np.zeros((int(round(aux_size / 2) * 16)),)
samples_aux = np.append(silence, samples_aux)
samples_aux = np.append(samples_aux, silence)
silence = np.zeros((template_size,))
new_template_aux = np.append(silence, samples_aux)
new_template_aux = np.append(new_template_aux, silence)
if new_template.size > new_template_aux.size:
silence = np.zeros((int(round(new_template.size-new_template_aux.size))),)
new_template_aux = np.append(new_template_aux, silence)
X = librosa.stft(new_template_aux, n_fft=args.N, hop_length=args.H, win_length=args.N, window='hann', pad_mode='constant', center=True)
spectrogram_aux = np.log(1 + 100 * np.abs(X ** 2))
if spectrogram_aux.shape[1] == shape_template[1] + 1:
spectrogram_aux = spectrogram_aux[:,0:shape_template[1]]
fig, ax = plt.subplots()
(lag_aux, corr_aux, line, b) = ax.xcorr(spectrogram_template.flatten(), spectrogram_aux.flatten(), normed=True, maxlags=args.n_lags, lw=2)
#plt.savefig(args.data_dir + '/' + args.output_dir + '/' + 'xcorr_' + syll_name + '_' + str(j) + '.' + args.format)
cross_correlation[j] = np.max(corr_aux[1])
index_aux = lag_aux[np.argmax(corr_aux)]
if index_aux < 0:
spectrogram_new = np.append(np.zeros((-index_aux,)), spectrogram_aux.flatten()[-index_aux::])
spectrograms.append(np.reshape(spectrogram_new, shape_template))
else:
spectrogram_new = np.append(spectrogram_aux.flatten()[index_aux::], np.zeros((index_aux,)))
spectrograms.append(np.reshape(spectrogram_new, shape_template))
# Envelope based
rawsong = samples_aux.astype(float)
rawsong = rawsong.flatten()
amp = Song_functions.smooth_data(rawsong, sr, freq_cutoffs=(500, 7999))
# Debug to see amplitude range
#plt.subplots()
#plt.plot(amp)
#plt.savefig(args.data_dir + '/' + args.output_dir + '/' + 'ampD.' + args.format)
#print(songfile[j])
if syll_name == 'N':
new_song = rawsong[0:np.where(amp > 0.00001)[0][-1]]
silence = np.zeros((new_template.size - np.size(new_song),))
new_song = np.append(silence, new_song)
else:
new_song = rawsong[np.where(amp > 0.00001)[0][0]::]
silence = np.zeros((new_template.size - np.size(new_song),))
new_song = np.append(new_song, silence)
X = librosa.stft(new_song, n_fft=args.N, hop_length=args.H, win_length=args.N, window='hann',
pad_mode='constant', center=True)
spectrograms_envelope.append(np.log(1 + 100 * np.abs(X ** 2)))
plt.close('all')
mean_spectrogram = np.mean(spectrograms, axis=0)
fig, ax = plt.subplots(nrows=1, ncols=1, figsize=(10, 14), sharey=True, sharex=True)
#extent = [0, np.max(T_coef), 0, 8000]
ax.imshow(mean_spectrogram, cmap=args.color, aspect='auto', origin='lower', norm=colors.PowerNorm(gamma=0.2))
ax.set_title(syll_name, fontsize=15)
ax.spines['top'].set_color('none')
ax.spines['right'].set_color('none')
ax.set_xlabel('Time (ms)', fontsize=15)
ax.set_ylabel('Frequency (Hz)', fontsize=15)
plt.tight_layout()
#plt.savefig(args.data_dir + '/' + args.output_dir + '/' + 'Mean_spectrogram_' +syll_name + '.' + args.format)
# Save the data
data = {'File_name': syll_name, 'Data_list':data_list, 'List_song': data_list, 'How_many': how_many, 'Duration_syll': dur_syll,
'Mean_pitch': mean_pitch, 'Min_pitch': min_pitch, 'Max_pitch': max_pitch, 'All_pitches': pitches_list,
'Direction': direction_pitch,
'Wiener_entropy': wiener, 'Cross_correlation': cross_correlation, 'Spectrograms': spectrograms, 'T_spectro':T_coef, 'Spectrograms_envelope':spectrograms_envelope}
return data
def syllable_silence_features(songfile, syll_name, template, args):
"""
VARIABLES:
- songfile: list of recordings with syllables followed by silence up to 1s
produced previously using the trained WaveGAN
- template: a comparison template (if given) to compute cross-correlation
OUTPUT:
- .npy file containing the features stored
"""
# Count the number of elements in the group
if args.dataset_dim == None:
how_many = np.size(songfile)
elif args.dataset_dim == 0:
if args.dataset_dim > np.size(songfile):
how_many = np.size(songfile)
else:
how_many = args.dataset_dim
else:
songfile = random.sample(songfile, args.dataset_dim)
how_many = np.size(songfile)
# Feature variables initialization
dur_syll = np.zeros((how_many,))
data_list = []
pitches_list = []
mean_pitch = np.zeros((how_many,))
max_pitch = np.zeros((how_many,))
min_pitch = np.zeros((how_many,))
direction_pitch = np.zeros((how_many,))
wiener = np.zeros((how_many,))
for j in range(0,how_many):
# Read the wave
sr, samples = wav.read(songfile[j])
trim = librosa.effects.trim(samples.astype(np.float), top_db=20)
samples = trim[0]
dur_syll[j] = samples.size/16
# Pitch detection
pitches, magnitudes = librosa.core.piptrack(samples, sr=sr, n_fft=100, fmin=500, fmax=8000)
pitches_all = 0
for interval in range(0, magnitudes.shape[1]):
index = magnitudes[:, interval].argmax()
pitches_all = np.append(pitches_all, pitches[index, interval])
pitches_all = pitches_all[np.nonzero(pitches_all)]
mean_pitch[j] = np.mean(pitches_all)
max_pitch[j] = np.max(pitches_all)
min_pitch[j] = np.min(pitches_all)
if pitches_all[0] < pitches_all[-1]:
direction_pitch[j] = 1
else:
direction_pitch[j] = -1
# Spectral flatness (Wiener entropy)
wiener[j] = np.mean(librosa.feature.spectral_flatness(samples.astype(np.float)))
# Argmax of duration to determine the longer syllable
if how_many > 0:
template_size = int(np.max(dur_syll))
# Template construction (adding silence before and after for alignment)
if len(template) > 0:
template_samples, sr = librosa.load(template[0], sr=16000)
trim = librosa.effects.trim(template_samples.astype(np.float), top_db=20)
template_samples = trim[0]
if template_samples.size / 16 < template_size:
aux_size = template_size - template_samples.size / 16
silence = np.zeros((int(round(aux_size / 2) * 16)), )
aux_template = np.append(silence, template_samples)
aux_template = np.append(aux_template, silence)
else:
aux_template = template_samples
silence = np.zeros((template_size,))
new_template = np.append(silence, aux_template)
new_template = np.append(new_template, silence)
X = librosa.stft(new_template, n_fft=args.N, hop_length=args.H, win_length=args.N, window='hann', pad_mode='constant', center=True)
T_coef = np.arange(X.shape[1]) * args.H / sr * 1000 #save to plot
spectrogram_template = np.log(1 + 100 * np.abs(X ** 2))
shape_template = spectrogram_template.shape
spectrograms = []
spectrograms_envelope = []
cross_correlation = np.zeros((how_many,))
for j in range(0, how_many):
data_list.append(songfile[j])
# compute the spectrogram
samples_aux, sr = librosa.load(songfile[j], sr=16000)
trim = librosa.effects.trim(samples_aux.astype(np.float), top_db=20)
samples_aux = trim[0]
if samples_aux.size / 16 < template_size:
aux_size = template_size - samples_aux.size / 16
silence = np.zeros((int(round(aux_size / 2) * 16)),)
samples_aux = np.append(silence, samples_aux)
samples_aux = np.append(samples_aux, silence)
silence = np.zeros((template_size,))
new_template_aux = np.append(silence, samples_aux)
new_template_aux = np.append(new_template_aux, silence)
if new_template.size > new_template_aux.size:
silence = np.zeros((int(round(new_template.size-new_template_aux.size))),)
new_template_aux = np.append(new_template_aux, silence)
X = librosa.stft(new_template_aux, n_fft=args.N, hop_length=args.H, win_length=args.N, window='hann', pad_mode='constant', center=True)
spectrogram_aux = np.log(1 + 100 * np.abs(X ** 2))
if spectrogram_aux.shape[1] == shape_template[1] + 1:
spectrogram_aux = spectrogram_aux[:,0:shape_template[1]]
fig, ax = plt.subplots()
(lag_aux, corr_aux, line, b) = ax.xcorr(spectrogram_template.flatten(), spectrogram_aux.flatten(), normed=True, maxlags=args.n_lags, lw=2)
#plt.savefig(args.data_dir + '/' + args.output_dir + '/' + 'xcorr_' + syll_name + '_' + str(j) + '.' + args.format)
cross_correlation[j] = np.max(corr_aux[1])
index_aux = lag_aux[np.argmax(corr_aux)]
if index_aux < 0:
spectrogram_new = np.append(np.zeros((-index_aux,)), spectrogram_aux.flatten()[-index_aux::])
spectrograms.append(np.reshape(spectrogram_new, shape_template))
else:
spectrogram_new = np.append(spectrogram_aux.flatten()[index_aux::], np.zeros((index_aux,)))
spectrograms.append(np.reshape(spectrogram_new, shape_template))
# Envelope based
rawsong = samples_aux.astype(float)
rawsong = rawsong.flatten()
amp = Song_functions.smooth_data(rawsong, sr, freq_cutoffs=(500, 7999))
# Debug to see amplitude range
#plt.subplots()
#plt.plot(amp)
#plt.savefig(args.data_dir + '/' + args.output_dir + '/' + 'ampD.' + args.format)
#print(songfile[j])
if syll_name == 'N':
# new_song = rawsong[0:np.where(amp > 0.00001)[0][-1]] # new training
new_song = rawsong[np.where(amp > 0.00001)[0][0]::] #PRE dataset
silence = np.zeros((new_template.size - np.size(new_song),))
new_song = np.append(silence, new_song)
else:
new_song = rawsong[np.where(amp > 0.00001)[0][0]::]
silence = np.zeros((new_template.size - np.size(new_song),))
new_song = np.append(new_song, silence)
X = librosa.stft(new_song, n_fft=args.N, hop_length=args.H, win_length=args.N, window='hann',
pad_mode='constant', center=True)
spectrograms_envelope.append(np.log(1 + 100 * np.abs(X ** 2)))
plt.close('all')
else:
cross_correlation = np.zeros((1,))
T_coef = 0
spectrograms = np.zeros((8000,1))
spectrograms_envelope = np.zeros((8000,1))
# Save the data
data = {'File_name': syll_name, 'Data_list':data_list, 'List_song': data_list, 'How_many': how_many, 'Duration_syll': dur_syll,
'Mean_pitch': mean_pitch, 'Min_pitch': min_pitch, 'Max_pitch': max_pitch, 'All_pitches': pitches_list,
'Direction': direction_pitch,
'Wiener_entropy': wiener, 'Cross_correlation': cross_correlation, 'Spectrograms': spectrograms, 'T_spectro':T_coef, 'Spectrograms_envelope':spectrograms_envelope}
return data
def lag_corr_training_dataset(songfile, classes, args):
import statistics as stat
data_syll_list = []
for c in range(0, np.size(classes)):
syll_list_aux = []
for i in range(0, np.size(songfile)):
if (songfile[i].find('NEW_' + classes[c]) != -1):
syll_list_aux.append(songfile[i])
data_syll_list.append(syll_list_aux)
cross_corr = []
cross_corr_2 = []
for c in range(0, np.size(classes)):
pairs = stat.pairs(range(0, np.size(data_syll_list[c])), range(0, np.size(data_syll_list[c])))
syll_pairs = random.sample(pairs, args.n_template)
cross_corr_aux = np.zeros((args.n_template,))
cross_corr_aux_2 = np.zeros((args.n_template,))
cross_corr_aux_3 = np.zeros((args.n_template,))
for j in range(0,args.n_template):
cross_corr_aux[j] = stat.lag_cross_corr(args.n_lags, data_syll_list[c][syll_pairs[j][0]], data_syll_list[c][syll_pairs[j][1]], args.nperseg, args.overlap)
plt.close('all')
sr, samples_1 = wav.read(data_syll_list[c][syll_pairs[j][0]])
sr, samples_2 = wav.read(data_syll_list[c][syll_pairs[j][1]])
freq, times, spectrogram_1 = sp.signal.spectrogram(samples_1, sr, window='hann', nperseg=args.nperseg,
noverlap=args.nperseg - args.overlap)
freq, times, spectrogram_2 = sp.signal.spectrogram(samples_2, sr, window='hann', nperseg=args.nperseg,
noverlap=args.nperseg - args.overlap)
fig, ax = plt.subplots()
cross_aux = ax.xcorr(spectrogram_1.flatten(), spectrogram_2.flatten(), maxlags=args.n_lags, lw=2)
cross_correlation_aux_2[j] = np.max(cross_aux[1])
y, sr = librosa.load(data_syll_list[c][syll_pairs[j][0]], sr=16000)
y_2, sr = librosa.load(data_syll_list[c][syll_pairs[j][1]], sr=16000)
X = librosa.stft(y, n_fft=args.N, hop_length=args.H, win_length=args.N, window='hann',
pad_mode='constant', center=True)
spectrogram_aux = np.log(1 + 100 * np.abs(X ** 2))
X_2 = librosa.stft(y_2, n_fft=args.N, hop_length=args.H, win_length=args.N, window='hann',
pad_mode='constant', center=True)
spectrogram_aux_2 = np.log(1 + 100 * np.abs(X_2 ** 2))
freq_downsample_1 = sp.signal.resample(spectrogram_aux, 60, t=None, axis=0)
time_downsample_1 = sp.signal.resample(freq_downsample_1, 120, t=None, axis=1)
freq_downsample_2 = sp.signal.resample(spectrogram_aux_2, 60, t=None, axis=0)
time_downsample_2 = sp.signal.resample(freq_downsample_2, 120, t=None, axis=1)
fig, ax = plt.subplots()
(lag_aux, corr_aux, line, b) = ax.xcorr(time_downsample_1.flatten(), time_downsample_2.flatten(), maxlags=args.n_lags, lw=2)
#(lag_aux, corr_aux, line, b) = ax.xcorr(spectrogram_aux.flatten(), spectrogram_aux_2.flatten(), maxlags=args.n_lags, lw=2)
cross_corr_aux_3[j] = np.max(corr_aux[1])
plt.close('all')
print(cross_corr_aux)
print(cross_corr_aux_2)
print(cross_corr_aux_3)
input()
cross_corr.append(cross_corr_aux)
cross_corr_2.append(cross_corr_aux_2)
np.save(args.data_dir + '/' + args.output_dir + '/' + 'Dataset_cross_corr_distribution.npy', cross_corr)
np.save(args.data_dir + '/' + args.output_dir + '/' + 'Dataset_cross_corr_distribution_2.npy', cross_corr_2)
# Plot
for c in range(0, np.size(classes)):
plt.subplots()
n, x, _ = plt.hist(cross_corr[c,:], 20, color='b', alpha=0)
bin_centers = 0.5 * (x[1:] + x[:-1])
plt.plot(bin_centers, n, 'k', alpha=0.5)
plt.ylabel('Cross-correlation')
plt.title(classes[c], fontsize=15)
plt.savefig(args.data_dir + '/' + args.output_dir + '/' + 'cross_correlation_class_' + classes[c] + '.' + args.format)
plt.subplots()
n, x, _ = plt.hist(cross_corr_2[c,:], 20, color='b', alpha=0)
bin_centers = 0.5 * (x[1:] + x[:-1])
plt.plot(bin_centers, n, 'k', alpha=0.5)
plt.ylabel('Cross-correlation')
plt.title(classes[c], fontsize=15)
plt.savefig(args.data_dir + '/' + args.output_dir + '/' + 'cross_correlation_2_class_' + classes[c] + '.' + args.format)
plt.close('all')
print('Done')
def data_features_analysis_plots(plot_data, args):
#import umap
#import umap.plot
# FEATURES
# Initialization of the features
how_many = [0]
name = ['label']
duration_syll = [0]
duration_syll_aux = list()
mean_pitch = [0]
mean_pitch_aux = list()
max_pitch =[0]
max_pitch_aux = list()
min_pitch = [0]
min_pitch_aux = list()
wiener = [0]
wiener_aux = list()
all_spectrograms = []
all_labels = []
mean_spectrogram = []
mean_spectrogram_env = []
mean_cross_dataset = []
T_coef = []
for i in range(0, np.size(plot_data)):
load_data = np.load(plot_data[i], allow_pickle = True) #added allow_pickle because of a new error I never found before opening datasets I created and already opened months ago
load_data = load_data.item()
how_many = np.append(how_many, load_data['How_many'])
name = np.append(name, load_data['File_name'])
duration_syll_aux.append(np.round(load_data['Duration_syll']))
duration_syll = np.append(duration_syll, duration_syll_aux[i])
mean_pitch_aux.append(load_data['Mean_pitch'])
mean_pitch = np.append(mean_pitch, mean_pitch_aux[i])
min_pitch_aux.append(load_data['Min_pitch'])
min_pitch = np.append(min_pitch, min_pitch_aux[i])
max_pitch_aux.append(load_data['Max_pitch'])
max_pitch = np.append(max_pitch, max_pitch_aux[i])
wiener_aux.append(load_data['Wiener_entropy'])
wiener = np.append(wiener, wiener_aux[i])
spectrograms = load_data['Spectrograms']
spectrograms_envelope = load_data['Spectrograms_envelope']
for s in range(0, len(spectrograms)):
all_spectrograms.append(spectrograms[s].flatten())
all_labels.append(name[i+1])
cross_corr_dataset = load_data['Cross_correlation']
T_coef.append(np.max(load_data['T_spectro']))
mean_spectrogram.append(np.mean(spectrograms,axis=0))
mean_spectrogram_env.append(np.mean(spectrograms_envelope,axis=0))
mean_cross_dataset.append(np.mean(cross_corr_dataset))
if np.int(np.round(np.size(duration_syll_aux[i])/10))>0:
# Duration per type of syllables
h, bins = np.histogram(duration_syll_aux[i], bins = np.int(np.round(np.size(duration_syll_aux[i])/10)))
fig, ax = plt.subplots()
plt.bar(bins[:-1], h, width=0.8, color='b', alpha=0.6, label='Syllable Duration')
ax.spines['top'].set_color('none')
ax.spines['right'].set_color('none')
plt.legend(loc='upper right', fontsize=15, ncol=1, shadow=True, fancybox=True)
ax.set_xlim([0,np.max(duration_syll_aux[i])])
plt.xlabel('Duration(ms)')
plt.ylabel('Number of occurences')
plt.title(name[i+1])
plt.tight_layout() # to avoid the cut of labels
plt.savefig(args.data_dir + '/' + 'Duration_syllable_' + name[i+1] + '.' + args.format)
# Pitch per type of syllable
# Mean pitch
h, bins = np.histogram(mean_pitch_aux[i], bins = np.int(np.round(np.size(mean_pitch_aux[i])/10)))
fig, ax = plt.subplots()
plt.bar(bins[:-1], h, width=0.8, color='b', alpha=0.6, label='Mean pitch')
ax.spines['top'].set_color('none')
ax.spines['right'].set_color('none')
plt.legend(loc='upper right', fontsize=15, ncol=1, shadow=True, fancybox=True)
ax.set_xlim([0,np.max(mean_pitch_aux[i])])
plt.xlabel('Mean pitch (Hz)')
plt.ylabel('Number of occurences')
plt.title(name[i+1])
plt.tight_layout() # to avoid the cut of labels
plt.savefig(args.data_dir + '/' + 'Mean_pitch_syllable_' + name[i+1] + '.' + args.format)
# Min pitch
h, bins = np.histogram(min_pitch_aux[i], bins = np.int(np.round(np.size(min_pitch_aux[i])/10)))
fig, ax = plt.subplots()
plt.bar(bins[:-1], h, width=0.8, color='b', alpha=0.6, label='Min pitch')
ax.spines['top'].set_color('none')
ax.spines['right'].set_color('none')
plt.legend(loc='upper right', fontsize=15, ncol=1, shadow=True, fancybox=True)
ax.set_xlim([0,np.max(min_pitch_aux[i])])
plt.xlabel('Mean pitch (Hz)')
plt.ylabel('Number of occurences')
plt.title(name[i+1])
plt.tight_layout() # to avoid the cut of labels
plt.savefig(args.data_dir + '/' + 'Min_pitch_syllable_' + name[i+1] + '.' + args.format)
# Max pitch
h, bins = np.histogram(max_pitch_aux[i], bins = np.int(np.round(np.size(max_pitch_aux[i])/10)))
fig, ax = plt.subplots()
plt.bar(bins[:-1], h, width=0.8, color='b', alpha=0.6, label='Max pitch')
ax.spines['top'].set_color('none')
ax.spines['right'].set_color('none')
plt.legend(loc='upper right', fontsize=15, ncol=1, shadow=True, fancybox=True)
ax.set_xlim([0,np.max(max_pitch_aux[i])])
plt.xlabel('Mean pitch (Hz)')
plt.ylabel('Number of occurences')
plt.title(name[i+1])
plt.tight_layout() # to avoid the cut of labels
plt.savefig(args.data_dir + '/' + 'Max_pitch_syllable_' + name[i+1] + '.' + args.format)
# Wiener entropy
h, bins = np.histogram(wiener_aux[i], bins = np.int(np.round(np.size(wiener_aux[i])/10)))
fig, ax = plt.subplots()
plt.bar(bins[:-1], h, width=0.001, color='b', alpha=0.6, label='Wiener entropy')
ax.spines['top'].set_color('none')
ax.spines['right'].set_color('none')
plt.legend(loc='upper right', fontsize=15, ncol=1, shadow=True, fancybox=True)
ax.set_xlim([0,np.max(wiener_aux[i])])
plt.xlabel('Wiener entropy(dB)')
plt.ylabel('Number of occurences')
plt.title(name[i+1])
plt.tight_layout() # to avoid the cut of labels
plt.savefig(args.data_dir + '/' + 'Wiener_entropy_syllable_' + name[i+1] + '.' + args.format)
# Cross-correlation
plt.subplots()
n, x, _ = plt.hist(cross_corr_dataset, 20, color='b', alpha=0)
bin_centers = 0.5 * (x[1:] + x[:-1])
plt.plot(bin_centers, n, 'k', alpha=0.5)
plt.ylabel('Cross-correlation')
plt.title(name[i+1], fontsize=15)
plt.savefig(args.data_dir + '/' + 'cross_correlation_class_' + name[i+1] + '.' + args.format)
plt.close('all')
how_many = how_many[1::]
name = name[1::]
duration_syll = duration_syll[1::]
mean_pitch = mean_pitch[1::]
min_pitch = min_pitch[1::]
max_pitch = max_pitch[1::]
wiener = wiener[1::]
# How many syllables per type
fig, ax = plt.subplots()
ax.bar(name, how_many)
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
plt.ylabel('Number of samples', fontsize=15)
plt.xlabel('Classes', fontsize=15)
plt.xticks(fontsize=15)
plt.yticks(fontsize=15)
plt.tight_layout()
#plt.savefig(args.data_dir + '/' + 'How_many_syllables.' + args.format)
# Cumulative duration
h, bins = np.histogram(duration_syll, bins=np.int(np.round(np.size(duration_syll)/10)))
fig, ax = plt.subplots()
plt.bar(bins[:-1], h/np.max(h), width = 0.8, color = 'g', alpha = 0.6)
ax.spines['top'].set_color('none')
ax.spines['right'].set_color('none')
#plt.legend(loc='upper right', fontsize=15, ncol=1, shadow=True, fancybox=True)
#ax.set_xlim([0,np.max(duration_syll)])
plt.xlabel('Duration(ms)', fontsize=15)
plt.ylabel('Probability', fontsize=15)
#plt.title('Syllable duration')
plt.xticks(fontsize=15)
plt.yticks(fontsize=15)
plt.tight_layout() #to avoid the cut of labels
plt.savefig(args.data_dir + '/' + 'Duration_syll_prob.' + args.format)
h, bins = np.histogram(duration_syll, bins=np.int(np.round(np.size(duration_syll)/10)))
fig, ax = plt.subplots()
plt.bar(bins[:-1], h, width = 0.8, color = 'b', alpha = 1)
ax.spines['top'].set_color('none')
ax.spines['right'].set_color('none')
#plt.legend(loc='upper right', fontsize=15, ncol=1, shadow=True, fancybox=True)
#ax.set_xlim([0,np.max(duration_syll)])
plt.xlabel('Duration(ms)', fontsize=15)
plt.ylabel('Number of occurences',fontsize=15)
plt.xticks(fontsize=15)
plt.yticks(fontsize=15)
#plt.title('Syllable duration')
plt.tight_layout() #to avoid the cut of labels
plt.savefig(args.data_dir + '/' +'Duration_syll.' + args.format)
# Cumulative pitch
# Mean pitch
h, bins = np.histogram(mean_pitch, bins=np.int(np.round(np.size(mean_pitch)/10)))
fig, ax = plt.subplots()
plt.bar(bins[:-1], h, width = 0.8, color = 'g', alpha = 0.6, label = 'Pitch')
ax.spines['top'].set_color('none')
ax.spines['right'].set_color('none')
ax.set_xlim([0,np.max(mean_pitch)])
plt.legend(loc='upper right', fontsize=15, ncol=1, shadow=True, fancybox=True)
plt.xlabel('Mean pitch(Hz)')
plt.ylabel('Number of occurences')
plt.title('Mean pitch distribution')
plt.tight_layout() #to avoid the cut of labels
plt.savefig(args.data_dir + '/' + 'Mean_pitch_distribution.' + args.format)
# Mean pitch
h, bins = np.histogram(min_pitch, bins=np.int(np.round(np.size(min_pitch)/10)))
fig, ax = plt.subplots()
plt.bar(bins[:-1], h, width = 0.8, color = 'g', alpha = 0.6, label = 'Pitch')
ax.spines['top'].set_color('none')
ax.spines['right'].set_color('none')
ax.set_xlim([0,np.max(min_pitch)])
plt.legend(loc='upper right', fontsize=15, ncol=1, shadow=True, fancybox=True)
plt.xlabel('Min pitch(Hz)')
plt.ylabel('Number of occurences')
plt.title('Mean pitch distribution')
plt.tight_layout() #to avoid the cut of labels
plt.savefig(args.data_dir + '/' + 'Min_pitch_distribution.' + args.format)
# Mean pitch
h, bins = np.histogram(max_pitch, bins=np.int(np.round( | np.size(max_pitch) | numpy.size |
import math
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import ticker
orders = [2, 3]
fig, axes = plt.subplots(1, len(orders), figsize=(11, 5))
n_cells = 7 # grid will be size (n_cells, n_cells)
# desired interpolation coordinate (xi, yi)
xi, yi = 3.3, 3.7
def get_start(cc, order):
if order % 1 == 0:
start = math.floor(cc) - order // 2
else:
start = math.floor(cc + 0.5) - order // 2
return start
for ax, order in zip(axes, orders):
# draw open circles at the locations of pixel centers
for n in range(n_cells):
ax.plot(np.arange(n_cells), -np.full(n_cells, n), 'ko',
fillstyle='none')
# draw pixel borders
for n in range(n_cells + 1):
ax.plot([n - 0.5, n - 0.5], [0.5, -n_cells + .5], 'k-')
ax.plot([-0.5, n_cells - .5], [-n + 0.5, -n + 0.5], 'k-')
# plot an example coordinate location to interpolate
ax.plot([xi], [-yi], 'rx')
# plot filled circles for the points that will be involved in the
# interpolation
startx = get_start(xi, order)
starty = get_start(yi, order)
xc = np.tile( | np.arange(startx, startx + order + 1) | numpy.arange |
import cv2
import os
import sys
import pcl
from math import copysign, log10
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from scipy.spatial import ConvexHull
import random
import math
import itertools
from sklearn.mixture import GaussianMixture
from sklearn.neighbors import KDTree
SYMMETRY_MEASURE_CLOUD_NORMALS_TRADEOFF= 0.2 # scaling factor for difference in normals wrt. difference in position for points,
# when computing difference between two point clouds.
# 0 => Only look at difference between point and its closest point
# Higher value => matching normals are more important than point distances
SMOOTHNESS_MEASURE_NUMBINS = 8 # Number of bins in histogram. We found 8 to work best quite consistently.
NNRADIUS = 0.004 # Used in Local Convexity and Smoothness measure for local neighborhood finding
dir_name=os.path.dirname(__file__)
image_path = os.path.join(dir_name, "object")
def get_image(filename):
path=os.path.join(image_path,filename)
if "depthcrop" in filename or 'maskcrop' in filename:
im = cv2.imread(path,0)
else:
im = cv2.imread(path)
return im
def apply_mask(mask,image):
i=image.copy()
i[mask == 0]=0
return i
def depth_to_meter(depth):
depth=depth.astype(float)
try:
return 1/((depth * 4 * -0.0030711016) + 3.3309495161)
except:
return 0.0
# just return mean of distances from points in cloud1 to their nearest neighbors in cloud2
def cloudAlignmentScoreDense(cloud1, cloud2):
tree = KDTree(cloud2)
N=cloud1.shape[0]
accum=0.0
result = tree.query(cloud1, k=1)
for i,(dist, ind) in enumerate(zip(*result)):
accum += dist[0]
return accum/N
def cloudAlignmentScoreDenseWithNormalsNormalized(cloud1, normals1, cloud2, normals2, relweight, dnormalize):
tree = KDTree(cloud2)
N=cloud1.shape[0]
accum=0.0
result = tree.query(cloud1, k=1)
for i,(dist, ind) in enumerate(zip(*result)):
accum += dist[0] / dnormalize
dot = np.dot(normals1[i],normals2[ind[0]])
accum += relweight*(1.0 - dot)
return accum/N
def calculate_compactness_3d(points):
max_length = np.max(points,axis=0)[0]
min_length = np.min(points,axis=0)[0]
return points.shape[0] / (max(max_length-min_length, 0.0000001)**2)
def calculate_symmetry_3d(points_np, normals, relweight=SYMMETRY_MEASURE_CLOUD_NORMALS_TRADEOFF):
mins=points_np.min(axis=0)
maxes=points_np.max(axis=0)
ranges = maxes - mins
ranges /= ranges.sum()
score=0.0
for i,vector in enumerate(np.array([[-1,1,1],[1,-1,1],[1,1,-1]])):
dest=points_np*vector
normdest=normals*vector
overlap = cloudAlignmentScoreDenseWithNormalsNormalized(points_np, normals, dest, normdest, relweight, ranges[i])\
+cloudAlignmentScoreDenseWithNormalsNormalized(dest, normdest, points_np, normals, relweight, ranges[i])
score += ranges[i]*overlap
return -score
def calculate_global_convexity_3d(points):
hull=ConvexHull(points)
overlap= cloudAlignmentScoreDense(points, hull.points[hull.vertices])
return -overlap
def calculate_local_convexity_and_smoothness_3d(points, normals, NNradius=NNRADIUS, NUMBINS=SMOOTHNESS_MEASURE_NUMBINS):
tree = KDTree(points)
N=points.shape[0]
score=0.0
Hs=0.0
bins=np.ones(NUMBINS)
neighbors = tree.query_radius(points, NNradius)
for i,(p1,n1,neighbors_current) in enumerate(zip(points,normals,neighbors)):
binsum = NUMBINS
n2=(np.random.rand(3)+1)/2
n2=n2-np.dot(n1,n2)*n1
d = np.linalg.norm(n2)
n2 /= d
n3 = np.cross(n1,n2)
dot=0.0
nc=0
for j in neighbors_current:
if j==i:
continue
v = p1-points[j]
d = np.linalg.norm(v)
v/=d
dot = np.dot(n1,v)
if dot > 0.0:
nc += 1
dot1 = np.dot(n2,v)/d
dot2 = np.dot(n3,v)/d
theta = ((np.arctan2(dot1, dot2)+np.pi)/2)/np.pi # angle in range 0->1
binid = int((theta-0.001)*NUMBINS)
bins[binid] += 1
binsum+=1
score += (1.0*nc)/len(neighbors_current)
bins/=binsum
H=-(bins*np.log(bins)).sum()
if not np.isnan(H):
Hs += H
return score/N,Hs/N
def calculate_local_convexity_3d(points, normals, NNradius=NNRADIUS):
tree = KDTree(points)
N=points.shape[0]
score=0.0
neighbors = tree.query_radius(points, NNradius)
for i,(p,normal,neighbors_current) in enumerate(zip(points,normals,neighbors)):
dot=0.0
nc=0
for j in neighbors_current:
if j==i:
continue
v = p-points[j]
d = np.linalg.norm(v)
v/=d
dot = np.dot(normal,v)
if dot > 0.0:
nc += 1
score += (1.0*nc)/len(neighbors_current)
return score/N
def calculate_smoothness_3d(points, normals, NNradius=NNRADIUS, NUMBINS=SMOOTHNESS_MEASURE_NUMBINS):
Hs=0.0
tree = KDTree(points)
N=points.shape[0]
bins=np.ones(NUMBINS)
neighbors = tree.query_radius(points, NNradius)
for i, (p1,n1,neighbors_current) in enumerate(zip(points,normals,neighbors)):
#print("{:.2f}%".format(i*100/len(points)))
binsum = NUMBINS
n2=(np.random.rand(3)+1)/2
dot=np.dot(n1,n2)
n2=n2-dot*n1
d = np.linalg.norm(n2)
n2 /= d
n3 = np.cross(n1,n2)
for j in neighbors_current:
if j==i:
continue
p2=points[j]
v = p1-p2
d = np.linalg.norm(v)
v/=d
dot1 = np.dot(n2,v)/d
dot2 = np.dot(n3,v)/d
theta = ((np.arctan2(dot1, dot2)+np.pi)/2)/np.pi # angle in range 0->1
binid = int((theta-0.001)*NUMBINS)
bins[binid] += 1
binsum+=1
bins/=binsum
H=-(bins*np.log(bins)).sum()
if not np.isnan(H):
Hs += H
return Hs/N # high entropy = good.
def pad_image(depth,result_shape=(480,640)):
top=int((result_shape[0]-depth.shape[0])/2)
bottom=result_shape[0]-top-depth.shape[0]
left=int((result_shape[1]-depth.shape[1])/2)
right=result_shape[1]-left-depth.shape[1]
return np.pad(depth, ((top, bottom), (left, right)), 'constant')
def cvtDepthColor2Cloud(depth):
cameraMatrix = np.array(
[[525., 0., 320.0],
[0., 525., 240.0],
[0., 0., 1.]])
inv_fx = 1.0 / cameraMatrix[0, 0]
inv_fy = 1.0 / cameraMatrix[1, 1]
ox = cameraMatrix[0, 2]
oy = cameraMatrix[1, 2]
rows, cols = depth.shape
cloud = np.zeros((depth.size, 3), dtype=np.float32)
for y in range(rows):
for x in range(cols):
x1 = float(x)
y1 = float(y)
dist = depth[y][x]
cloud[y * cols + x][0] = np.float32((x1 - ox) * dist * inv_fx)
cloud[y * cols + x][1] = np.float32((y1 - oy) * dist * inv_fy)
cloud[y * cols + x][2] = np.float32(dist)
return pcl.PointCloud().from_array(cloud)
def depth_to_cloud(depth_original):
depth=depth_to_meter(depth_original)
depth=pad_image(depth)
depth_original=pad_image(depth_original)
cameraMatrix = np.array(
[[525., 0., 320.0],
[0., 525., 240.0],
[0., 0., 1.]])
inv_fx = 1.0 / cameraMatrix[0, 0]
inv_fy = 1.0 / cameraMatrix[1, 1]
ox = cameraMatrix[0, 2]
oy = cameraMatrix[1, 2]
xyz_offset=[0,0,depth.min()]
array = []
xy=np.argwhere((depth_original<255) & (depth_original>0))
xy=xy.astype(float)
z=depth[np.where((depth_original<255) & (depth_original>0))]
z=z.astype(float)
a=((xy[:,0]-ox)*z*inv_fx)
b=((xy[:,1]-oy)*z*inv_fy)
xy[:,0]=b
xy[:,1]=a
xyz=np.insert(xy, 2, values=z, axis=1)
xyz = np.float32(xyz)
cloud = pcl.PointCloud()
cloud.from_array(xyz)
return cloud,xyz
def get_cloud_and_normals(depth):
point_cloud,cloud = depth_to_cloud(depth)
# get points and normals
ne = point_cloud.make_NormalEstimation()
tree = point_cloud.make_kdtree()
ne.set_SearchMethod(tree)
ne.set_RadiusSearch(0.05)
normals = ne.compute()
normals_point = normals.to_array()[:,0:3]
return cloud,normals_point
def calculate_descriptor(depth):
mask=depth.copy()
mask[mask>0]=255
descriptors_2d=calculate_descriptors_2d(mask)
descriptors_3d=calculate_descriptors_3d(mask,depth)
return descriptors_2d+descriptors_3d
def calculate_descriptors_3d(mask,depth):
cloud,normals=get_cloud_and_normals(depth)
compactness_3d=calculate_compactness_3d(cloud)
print(compactness_3d)
symmetry_3d=calculate_symmetry_3d(cloud, normals)
print(symmetry_3d)
global_convexity_3d=calculate_global_convexity_3d(cloud)
print(global_convexity_3d)
local_convexity_3d,smoothness_3d=calculate_local_convexity_and_smoothness_3d(cloud, normals)
return [compactness_3d,symmetry_3d,global_convexity_3d,local_convexity_3d,smoothness_3d]
def get_roi(image):
min_x,min_y,w,h = cv2.boundingRect(image)
max_x=min_x+w
max_y=min_y+h
return image[min_y:max_y,min_x:max_x]
def calculate_descriptors_2d(mask):
mask_roi=get_roi(mask)
compactess_2d=calculate_compactess_2d(mask_roi)
symmetry_2d=calculate_symmetry_2d(mask_roi)
global_convexity_2d=calculate_global_convexity_2d(mask)
histogram, uniqueness_2d=calculate_uniqueness_2d(mask)
smoothness_2d=calculate_smoothness_2d(mask,histogram)
return [compactess_2d,symmetry_2d,global_convexity_2d,uniqueness_2d,smoothness_2d]
def calculate_compactess_2d(mask):
pixels_on = cv2.countNonZero(mask)
pixels = mask.shape[0] * mask.shape[1]
return pixels_on/pixels
def calculate_symmetry_2d(mask):
symmetries=[]
for i in range(2):
if i:
mask=mask.T
half=int(mask.shape[1]/2)
first_half = mask[:, 0:half]
second_half = mask[:, half+(mask.shape[1] % 2):]
second_half = np.flip(second_half, axis=1)
symmetry = np.sum(first_half == second_half)
symmetries.append(symmetry/first_half.size)
return max(symmetries)
def euclidean_distance(a,b):
return np.linalg.norm(a-b)
def calculate_global_convexity_2d(mask):
contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE)
hull = cv2.convexHull(contours[0])
m=mask.copy()
cv2.drawContours(m, [hull], -1, 150, 1)
contours_pos=np.argwhere(m==150)
points=np.argwhere(m==255)
result=np.average(np.min(np.linalg.norm(contours_pos - points[:,None], axis=-1),axis=1))
return result
def get_angle(v1,v2):
angles=np.array([[135,120,90,60,45],
[150,135,90,45,30],
[180,180,0,0,0],
[210,225,270,315,330],
[225,240,270,300,315]])
return (angles[v1[0],v1[1]]-angles[v2[0],v2[1]])%180
def entropy(hist):
return -sum([i*math.log(i) for i in hist])
def calculate_uniqueness_2d(mask,show_hist=False):
hist={}
contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE)
m=cv2.cvtColor(mask, cv2.COLOR_GRAY2BGR)
cv2.drawContours(m, contours, -1, (0,255,255), 1)
t=3
contours=contours[0]
l=len(contours)
vectors=[contours[(i+2)%l]-contours[(i-2)%l] for i in range(0,l,t)]
l=len(vectors)
for i in range(l):
angle=get_angle(vectors[i][0],vectors[(i+1)%l][0])
if angle in hist.keys():
hist[angle]+=1
else:
hist[angle]=1
if show_hist:
from collections import Counter
num = Counter(hist)
x = []
y = []
for k in sorted(hist.keys()):
x.append(hist[k])
y.append(k)
x_coordinates = np.arange(len(num.keys()))
plt.bar(x_coordinates,x)
plt.xticks(x_coordinates,y)
plt.show()
h=[i/l for i in hist.values()]
h2=[(k,v) for k,v in hist.items()]
return h2,entropy(h)
def calculate_smoothness_2d(mask,histogram):
X = | np.array(histogram) | numpy.array |
""" Training architectures on 2012 ImageNet """
from __future__ import print_function, division
import sys
import timeit
import argparse
import numpy as np
import torch
import tensormonk
def parse_args():
parser = argparse.ArgumentParser(description="ImageNet using TensorMONK!")
parser.add_argument("-A", "--Architecture", type=str, default="residual50",
choices=["residual18", "residual34",
"residual50", "residual101", "residual152",
"resnext50", "resnext101", "resnext152",
"seresidual50", "seresidual101",
"seresidual152",
"inceptionv4", "mobilev1", "mobilev2",
"shuffle1", "shuffle2", "shuffle3",
"shuffle4", "shuffle8"])
parser.add_argument("-B", "--BSZ", type=int, default=32)
parser.add_argument("-E", "--Epochs", type=int, default=6)
parser.add_argument("--optimizer", type=str, default="sgd",
choices=["adam", "sgd"])
parser.add_argument("--learningRate", type=float, default=0.06)
parser.add_argument("--loss_type", type=str, default="entr",
choices=["entr", "smax", "tentr", "tsmax", "lmcl"])
parser.add_argument("--loss_distance", type=str, default="dot",
choices=["cosine", "dot"])
parser.add_argument("--default_gpu", type=int, default=0)
parser.add_argument("--gpus", type=int, default=1)
parser.add_argument("--cpus", type=int, default=6)
parser.add_argument("--trainDataPath", type=str,
default="./data/ImageNet/train")
parser.add_argument("--testDataPath", type=str,
default="./data/ImageNet/validation")
parser.add_argument("-I", "--ignore_trained", action="store_true")
return parser.parse_args()
def train():
args = parse_args()
tensor_size = (1, 3, 224, 224)
file_name = "./models/" + args.Architecture.lower()
embedding_net, embedding_net_kwargs = \
tensormonk.architectures.Models(args.Architecture.lower())
train_loader, n_labels = \
tensormonk.data.FolderITTR(args.trainDataPath, args.BSZ, tensor_size,
args.cpus, functions=[], random_flip=True)
test_loader, n_labels = \
tensormonk.data.FolderITTR(args.testDataPath, args.BSZ, tensor_size,
args.cpus, functions=[], random_flip=False)
from tensormonk.essentials import MakeModel, SaveModel
Model = MakeModel(file_name, tensor_size, n_labels,
embedding_net=embedding_net,
embedding_net_kwargs=embedding_net_kwargs,
loss_net=tensormonk.loss.CategoricalLoss,
loss_net_kwargs={"type": args.loss_type,
"distance": args.loss_distance},
default_gpu=args.default_gpu,
gpus=args.gpus,
ignore_trained=args.ignore_trained)
params = list(Model.netEmbedding.parameters()) + \
list(Model.netLoss.parameters())
if args.optimizer.lower() == "adam":
optimizer = torch.optim.Adam(params)
elif args.optimizer.lower() == "sgd":
optimizer = torch.optim.SGD(params, lr=args.learningRate)
else:
raise NotImplementedError
# Usual training
for _ in range(args.Epochs):
timer = timeit.default_timer()
Model.netEmbedding.train()
Model.netLoss.train()
for i, (tensor, targets) in enumerate(train_loader):
Model.meterIterations += 1
# forward pass and parameter update
Model.netEmbedding.zero_grad()
Model.netLoss.zero_grad()
features = Model.netEmbedding(tensor)
loss, (top1, top5) = Model.netLoss((features, targets))
loss.backward()
optimizer.step()
# updating all meters
Model.meterTop1.append(float(top1.cpu().data.numpy()))
Model.meterTop5.append(float(top5.cpu().data.numpy()))
Model.meterLoss.append(float(loss.cpu().data.numpy()))
Model.meterSpeed.append(int(float(args.BSZ) /
(timeit.default_timer()-timer)))
timer = timeit.default_timer()
print("... {:6d} :: ".format(Model.meterIterations) +
"Cost {:2.3f} :: ".format(Model.meterLoss[-1]) +
"Top1/Top5 - {:3.2f}/{:3.2f}".format(Model.meterTop1[-1],
Model.meterTop5[-1],) +
" :: {:4d} I/S ".format(Model.meterSpeed[-1]), end="\r")
sys.stdout.flush()
# save every epoch and print the average of epoch
mean_loss = np.mean(Model.meterLoss[-i:])
mean_top1 = np.mean(Model.meterTop1[-i:])
mean_top5 = np.mean(Model.meterTop5[-i:])
mean_speed = int(np.mean(Model.meterSpeed[-i:]))
print("... {:6d} :: ".format(Model.meterIterations) +
"Cost {:2.3f} :: ".format(mean_loss) +
"Top1/Top5 - {:3.2f}/{:3.2f}".format(mean_top1, mean_top5) +
" :: {:4d} I/S ".format(mean_speed))
# save model
SaveModel(Model)
test_top1, test_top5 = [], []
Model.netEmbedding.eval()
Model.netLoss.eval()
for i, (tensor, targets) in enumerate(test_loader):
Model.netEmbedding.zero_grad()
Model.netLoss.zero_grad()
features = Model.netEmbedding(tensor)
loss, (top1, top5) = Model.netLoss((features, targets))
test_top1.append(float(top1.cpu().data.numpy()))
test_top5.append(float(top5.cpu().data.numpy()))
print("... Test accuracy - {:3.2f}/{:3.2f} ".format(
np.mean(test_top1), | np.mean(test_top5) | numpy.mean |
"""
Book "Understanding Digital Signal Processing. Ch 5. 181 page
"""
import numpy as np
import matplotlib.pyplot as plt
import math
from numpy.core.fromnumeric import argmax
from scipy.fft import fft, ifft
import scipy.io.wavfile as wav
import scipy.signal
from scipy.signal import get_window
from scipy.signal.windows.windows import hann
"""
여기서 부터 진행중!!!!
흐름: 필터를 만들자! > 딜레이를 줘서 주파수 반응을 봐보니 끝에 갈무리가 남아! > LPF를 만들고 싶어...
> 주파수에서 짤라서 시간도메인으로 역변환해서 시간 도메인에서 필터를 구해보자!
> 필터가 정확하게 짤리지 않아 ㅠ.ㅠ... > 윈도우를 사용한다! > 윈도우와 transfer function을 주파수 도메인에서 비교해본다!
> 시간도메인에서 평행이동은 주기함수라는 가정하에 주파수 도메인에 변화를 주지 않는다, 위상만 변화할 뿐!
---
그럼 어떤 윈도우와 transfer function 이 있을까?
모든 필터는 디지털에서는 아날로그 필터를 시간도메인 혹은 주파수 영역에서 사용한다.
연산 시간에 따라 주파수 영역에서 필터처리를 할 수 있고 혹은 시간 영역에서 필터처리를 할 수 있다.
---
adaptive filter가 measurement에 따라 필터 coefficient를 변화시켜주는 필터를 의미한다.
---
frequency domain treatment
1. convolution: frequency domain filter ->ifft, idft -> time filter -> apply
2. fft: signal, filter convert to frequeuncy domain using fft -> multiplication
-> fft is usually used above 64 size frame
if making convolute == fft
-> when you get the fft, zero padding should be because convolute get 2 times length
"""
from plotter import *
samplingFreq = 16
bandwidth = 8
coeff = bandwidth * 2 + 1
K = 7
N = samplingFreq
j = complex(0, 1)
x = np.arange(10)
# DFT
def is_pow2(n):
return False if n == 0 else (n == 1 or is_pow2(n >> 1))
def iexp(n):
return np.complex128(complex(math.cos(n), math.sin(n)))
def dft(h):
"""naive dft"""
n = len(h)
return [
sum((h[k] * iexp(-2 * math.pi * i * k / n) for k in range(n))) for i in range(n)
]
def dftinv(h):
"""
naive idft(0 ~ N)
"""
n = len(h)
return [
sum((h[k] * iexp(2 * math.pi * i * k / n) for k in range(n))) / n
for i in range(n)
]
def blackmanWindow_naive(size: int):
return np.array(
[
0.42
- 0.5 * np.cos(2 * np.pi * k / (size - 1))
+ 0.08 * np.cos(4 * np.pi * k / (size - 1))
for k in range(size)
]
)
def blackmanWindow(size: int, sym: bool = False):
return scipy.signal.windows.blackman(size, sym=sym)
def chebyshevWindow(size: int, sym: bool = False):
return scipy.signal.windows.chebwin(size, at=45, sym=sym)
def kaiserWindow(size: int, beta: float = 4, sym: bool = False):
return scipy.signal.windows.kaiser(size, beta, sym=sym)
class TransResponse(object):
def __init__(self, name, transferFunc, size, logscale, symmetric, shift):
self.name = name
self.xaxis = None
self.amplitudes = None
self.phases = None
self.transfunc = transferFunc
self.size = size
self.logscale = logscale
self.symmetric = False
self.shift = shift
self.calculateTransferResponse()
def calculateTransferResponse(self):
self.xaxis, self.amplitudes, self.phases = transfer_response(
self.transfunc,
self.size,
logscale=self.logscale,
half=self.symmetric,
shift=self.shift,
)
class FreqResponse(object):
def __init__(self, name, transferFunc, size, logScale, symmetric, shift):
self.name = name
self.xaxis = None
self.amplitudes = None
self.phases = None
self.transfunc = transferFunc
self.size = size
self.logScale = logScale
self.symmetric = symmetric
self.shift = shift
self.calculateTransferResponse()
def calculateFreqResponse(self):
self.xaxis, self.amplitudes, self.phases = transfer_response(
self.transfunc,
self.size,
logscale=self.logScale,
half=self.symmetric,
shift=self.shift,
)
if __name__ == "__main__":
"""
For Frequency Response about filtered wave file
"""
window_dict = {}
rectangle = np.ones(N) / N
# samplingFreq = N
window_dict["Rectangle"] = rectangle
window_dict["Blackman Window"] = rectangle * blackmanWindow(N, sym=False)
window_dict["Blackman Window_naive"] = rectangle * blackmanWindow_naive(N)
window_dict["Chebyshev Window"] = rectangle * chebyshevWindow(N, sym=False)
window_dict["Kaiser Window"] = rectangle * kaiserWindow(N, sym=False)
def plot_all(datas: list):
for data in datas:
print(data)
plt.plot(data, ".")
plt.grid()
plt.show()
# Check the alignment
# sw(list(window_dict.values()))
def zero_padding(h, n: int):
assert len(h) % 2 == 0
if len(h) >= n:
return h
else:
transfer = h.copy()
n_dft = n - len(h)
zero_padding = np.zeros((n_dft) // 2)
# bias = transfer[0]
# transfer = transfer[1:]
transfer = np.append(zero_padding, transfer)
transfer = np.append(transfer, zero_padding)
# transfer = np.append(bias, transfer)
return transfer
# for label, data in zip(window_dict.keys(), window_dict.values()):
# buf = zero_padding(data, n=512)
# buf = np.roll(buf, len(buf)//2)
# window_dict[label] = dft(buf)
# plot_all(list(window_dict.values()))
sr, white_noise = wav.read("./ExampleMusic/White Noise.wav")
bit_depth = 0
if white_noise.dtype == "int16":
bit_depth = 15
elif white_noise.dtype == "int32":
bit_depth = 31
elif white_noise.dtype == "float32":
bit_depth = 0
elif white_noise.dtype == "float64":
bit_depth = 0
white_noise = white_noise / (2 ** bit_depth)
# white_noise = abs(white_noise)
# test = np.sin(2 * np.pi * 1000 * np.arange(0, 10 * 44100) / 44100, dtype=np.float32) + np.sin(2 * np.pi * 5000 * np.arange(0, 10 * 44100) / 44100, dtype=np.float32)
# white_noise = test
frame_size = 1024
num_chunk = len(white_noise) // frame_size
fft_white_noise = np.zeros((num_chunk, frame_size), dtype=np.complex128)
# hanning = np.array([(0.5 - (0.5 * math.cos((2 * math.pi * i) / (frame_size - 1)))) for i in range(frame_size)],dtype='float64')
for idx in range(num_chunk):
buf = fft(white_noise[idx * frame_size : (idx + 1) * frame_size], n=frame_size)
fft_white_noise[idx] = buf
freq = np.arange(2, frame_size // 2 + 2) * sr // frame_size
y = fft_white_noise[:, : fft_white_noise.shape[-1] // 2 + 1]
# Full fft
# freq = np.arange(1, frame_size+1)*sr//frame_size
# y = fft_white_noise
y = | np.abs(y) | numpy.abs |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Wed Jul 12 11:41:32 2017
@author: <NAME>
"""
import matplotlib
import matplotlib.pyplot as plt
import skimage.io as io
import numpy as np
import time
from mayavi import mlab
import h5py
import scipy.ndimage as ndim
import os
matplotlib.use('AGG')
from mayavi.sources.api import ArraySource
from scipy.spatial import ConvexHull as fc
import skimage.morphology as morph1
import scipy.ndimage.morphology as morph2
from skimage.morphology import skeletonize_3d as sk3d
import scipy.ndimage.filters as filt
from sklearn.cluster import DBSCAN
import matplotlib
import networkx as nx
from PIL import Image
import itertools as it
def visPredict(v):
indices=np.where(v>0)
x1,x2,x3=indices[0],indices[1],indices[2]
d=mlab.pipeline.scalar_scatter(x1,x2,x3)
g=mlab.pipeline.glyph(d)
def visBatch(v):
src = mlab.pipeline.scalar_field(v)
mlab.pipeline.iso_surface(src, contours=[1, 0])
def visVolume(v):
src = mlab.pipeline.scalar_field(v)
mlab.pipeline.volume(src)
def getDist(v):
l1=[v[n,:,:] for n in range(np.shape(v)[0])] #Z-XY
l2=[v[:,n,:] for n in range(np.shape(v)[1])] #X-ZY
l3=[v[:,:,n] for n in range(np.shape(v)[2])] #Y-ZX
d1=np.array([morph2.distance_transform_edt(l1[i]) for i in range(len(l1))])
d1=d1.transpose((0,1,2))
d2=np.array([morph2.distance_transform_edt(l2[i]) for i in range(len(l2))])
d2=d2.transpose((1,0,2))
d3=np.array([morph2.distance_transform_edt(l3[i]) for i in range(len(l3))])
d3=d3.transpose((1,2,0))
d_=np.maximum(d1,d2);d=np.maximum(d_,d3)
return d
def getDist(v):
l1=[v[n,:,:] for n in range(np.shape(v)[0])] #Z-XY
l2=[v[:,n,:] for n in range(np.shape(v)[1])] #X-ZY
l3=[v[:,:,n] for n in range(np.shape(v)[2])] #Y-ZX
d1=np.array([morph2.distance_transform_edt(l1[i]) for i in range(len(l1))])
d1=d1.transpose((0,1,2))
d2=np.array([morph2.distance_transform_edt(l2[i]) for i in range(len(l2))])
d2=d2.transpose((1,0,2))
d3=np.array([morph2.distance_transform_edt(l3[i]) for i in range(len(l3))])
d3=d3.transpose((1,2,0))
d_=np.maximum(d1,d2);d=np.maximum(d_,d3)
return d
def getDataset(path, scale):
X=[]
Y=[]
f=h5py.File(path,'r')
num_P=np.array(f['numberOfPositive'])
num_N=np.array(f['numberOfNegative'])
if scale:
ind=np.array(range(num_P[scale-1])).astype('int')
np.random.shuffle(ind)
s=scale
for i in ind:
d_name=['pos_scale'+str(s)+'_'+str(i)]
d_pos=np.array(f[d_name[0]])
X.append(d_pos)
Y.append(0)
ind=np.array(range(num_N[scale-1])).astype('int')
np.random.shuffle(ind)
s=scale
for i in ind:
d_name=['neg_scale'+str(s)+'_'+str(i)]
d_neg=np.array(f[d_name[0]])
X.append(d_neg)
Y.append(1)
else:
for s in tqdm(range(len(num_d))):
ind=np.array(range(num_d[s])).astype('int')
np.random.shuffle(ind)
for i in ind:
d_name=['pos_scale'+str(s+1)+'_'+str(i),
'neg_scale'+str(s+1)+'_'+str(i)]
d_pos=np.array(f[d_name[0]])
d_neg=np.array(f[d_name[1]])
z=np.array(np.shape(d_pos)).astype('float')
z=np.divide(np.array([16,32,32]),z)
# check if sample has the targeted size
if True in [t != 1 for t in z]:
d_pos=ndim.zoom(d_pos,z)
d_neg=ndim.zoom(d_neg,z)
X.append(d_pos);X.append(d_neg)
Y.append(0);Y.append(1)
f.close()
X=np.array(X[:])
Y=np.array(Y[:])
return X, Y
#Define a model
def getModel(args):
model = Sequential()
model.add(Convolution3D(32, kernel_dim1=3, kernel_dim2=3, kernel_dim3=3,
batch_input_shape=((1,32,32,32,1)), border_mode='same',
activation='relu'))
model.add(Convolution3D(32, kernel_dim1=3, kernel_dim2=3,
kernel_dim3=3, border_mode='same', activation='relu'))
model.add(MaxPooling3D(pool_size=(3, 3, 3), border_mode='same'))
model.add(Dropout(0.25))
model.add(Convolution3D(64, kernel_dim1=3, kernel_dim2=3,
kernel_dim3=3, border_mode='same', activation='relu'))
model.add(Convolution3D(64, kernel_dim1=3, kernel_dim2=3,
kernel_dim3=3, border_mode='same', activation='relu'))
model.add(MaxPooling3D(pool_size=(3, 3, 3), border_mode='same'))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(512, init='normal', activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(args.nb_classes, init='normal'))
model.add(Activation('softmax'))
return model
# creat plots or results
def plotHistory(history, result_dir):
plt.plot(history.history['acc'], marker='.')
plt.plot(history.history['val_acc'], marker='.')
plt.title('model accuracy')
plt.xlabel('epoch')
plt.ylabel('accuracy')
plt.grid()
plt.legend(['acc', 'val_acc'], loc='lower right')
plt.savefig(os.path.join(result_dir, 'model_accuracy.png'))
plt.close()
plt.plot(history.history['loss'], marker='.')
plt.plot(history.history['val_loss'], marker='.')
plt.title('model loss')
plt.xlabel('epoch')
plt.ylabel('loss')
plt.grid()
plt.legend(['loss', 'val_loss'], loc='upper right')
plt.savefig(os.path.join(result_dir, 'model_loss.png'))
plt.close()
# save results
def saveHistory(history, result_dir):
loss = history.history['loss']
acc = history.history['acc']
val_loss = history.history['val_loss']
val_acc = history.history['val_acc']
nb_epoch = len(acc)
with open(os.path.join(result_dir, 'result.txt'), 'w') as fp:
fp.write('epoch\tloss\tacc\tval_loss\tval_acc\n')
for i in range(nb_epoch):
fp.write('{}\t{}\t{}\t{}\t{}\n'.format(
i, loss[i], acc[i], val_loss[i], val_acc[i]))
def cameraPosition(scene):
scene.scene.camera.position = [-567.41776413974469, 1633.7556647598549, 1363.3615455804083]
scene.scene.camera.focal_point = [561.47961291021682, 626.13187551647002, -12.72703501800356]
scene.scene.camera.view_angle = 30.0
scene.scene.camera.view_up = [0.47290363159850934, -0.47961203996493962, 0.73914440154925776]
scene.scene.camera.clipping_range = [929.45157879168619, 3476.2045332275461]
scene.scene.camera.compute_view_plane_normal()
scene.scene.render()
def addText(module,text,position):
text3d=module
text3d.text = text
text3d.scale=[20,20,20]
text3d.position=np.add(position,[0,0,0])
def visStack(v, opacity=.5, color=(1,0,0), mode=''):
if mode!='same':
mlab.figure(bgcolor=(1,1,1))
s=mlab.get_engine() # Returns the running mayavi engine.
scene=s.current_scene # Returns the current scene.
scene.scene.disable_render = True # for speed
origion=[0,0,0]
label= 'Segmentation'
A=ArraySource(scalar_data=v)
A.origin=np.array(origion)
D=s.add_source(A)# add the data to the Mayavi engine
#Apply gaussain 3d filter to smooth visualization
F=mlab.pipeline.user_defined(D, filter='ImageGaussianSmooth')
F.filter.set_standard_deviation(0,0,0)
contour = Contour()
s.add_filter(contour)
smooth = mlab.pipeline.user_defined(contour, filter='SmoothPolyDataFilter')
smooth.filter.number_of_iterations = 1
smooth.filter.relaxation_factor = 0
surface=Surface()
s.add_module(surface)
surface.module_manager.scalar_lut_manager.lut_mode = u'coolwarm'
surface.module_manager.scalar_lut_manager.reverse_lut = True
surface.actor.property.opacity = opacity
surface.actor.mapper.scalar_visibility=False
surface.actor.property.color = color #color
return surface
def readStack(name, l=None, rgb=None):
data=np.array(io.MultiImage(name))
if l:
if len(np.shape(data))>3:
data=(data[0,0:l,:,:,0])
else:
data=(data[0:l,:,:])
else:
if rgb:
data=(data[0,:,:,:,:])
else:
if len(np.shape(data))==5:
data=(data[0,:,:,:,0])
else:
if len(np.shape(data))==4:
data=(data[0,:,:,:])
else:
data=(data[:])
return data
class getSegData:
pad=[64,64,64]
posBatches=list()#to store positive samples
negBatches=list()#to store negative samples
nBatches=0.0
thr=[.3, .7]
indP=list()
indN=list()
pSize=[[8,8,16,8,16,8,16],[16,32,32,64,64,128,128],[16,32,32,64,64,128,128]]
# pSize=[[16],[32],[32]]
def __init__(self,segData):
self.Data=segData
def process1(self, E_param, AE_param=.01, padding=True):
self.E_param=E_param
self.AE_param=AE_param
if padding:
self.Data= np.pad(self.Data, ((self.pad[0],self.pad[0]),(self.pad[1],self.pad[1]),(self.pad[2],self.pad[2])),
mode='constant', constant_values = 0)
self.segData=self.Data
self.d1,self.d2,self.d3=np.shape(self.segData)
self.procSeg()
def process2(self):
self.getSkl()
self.getDist()
self.getKeys()
# indicies
indices=np.where(self.sklData>0)
self.indSkl=np.array([indices[0],indices[1],indices[2]]).T
indices=np.where(self.keysData>0)
indices=np.array([indices[0],indices[1],indices[2]]).T
self.indKeys=getCluster(indices, eps=1, min_samples=1).astype('int')
# self.indKeys=indices
### First Method ###
def checkV(self, ind):
"""
This function returns a batch if it does satisfy the criterion.
It operates by masking the batch at the selected index with a sphere at different sizes, once
a batch at certain size pass the criterion, the function return it and stop
"""
i= int(self.distDataF[ind[0],ind[1],ind[2]]*1.5)
# batch=self.segData[ind[0]-i:ind[0]+i+1 , ind[1]-i:ind[1]+i+1, ind[2]-i:ind[2]+i+1]
# sphere=morph1.ball(i).astype('bool')
# v=np.bitwise_and(sphere, batch)
batch=self.distDataF[ind[0]-i:ind[0]+i+1 , ind[1]-i:ind[1]+i+1, ind[2]-i:ind[2]+i+1]
sphere=morph1.ball(i)
v=sphere*batch
return v
def appendBatch(self, B):
"""
This function save the extracted batch.
"""
self.Batches.append(B)
def getBatches1(self, outS=[32.0,32.0,32.0]):
"""
This function extract positive and negative patches from obtained segmenations
"""
self.Batches=[]
count=0
for i in tqdm(range(np.shape(self.indKeys)[0])):
idx=self.indKeys[i]
B=self.checkV(idx)
if B is not None:
#fix the size.
inS=np.shape(B)
B=ndim.zoom(B, (outS[0]/inS[0], outS[1]/inS[1], outS[2]/inS[2]), order=0)
# B=morph1.remove_small_objects(B, min_size=512)
self.appendBatch(B)
count+=1
self.nBatches=count
def procSeg(self):
"""
This funtion perform two stages of morphological processing on the segmente stack.
First operation is performed globally and the second one is adaptive.
"""
#first
v=morph1.remove_small_holes(self.segData, min_size=8**3)
v=morph1.remove_small_objects(v, min_size=self.E_param*(32**3))
v=morph1.binary_closing(v,morph1.ball(3))
v=morph1.binary_opening(v,morph1.ball(1))
#second (adaptive)
#v=self.adaptive_erosion(v, alpha=self.AE_param)
v=morph1.remove_small_holes(v, min_size=8**3)
v=morph1.remove_small_objects(v, min_size=self.E_param*(32**3))
self.segData=v
def adaptive_erosion(self, v, alpha):
"""
This function perform adaptive erosion based on max. distance transform
"""
dist_v=getDist(v) # based on 2D sectioning to cal. max dist
s=int(np.max(dist_v))
max_v=filt.maximum_filter(dist_v,size=(s,s,s))
max_v=np.square(max_v)
out_v=np.divide(dist_v,(max_v+1))
out_v=out_v>alpha
out_v=morph1.remove_small_holes(out_v, min_size=512)
out_v=morph1.remove_small_objects(out_v, min_size=self.E_param*512)
v=morph1.binary_closing(v,morph1.ball(3))
out_v=morph1.binary_opening(out_v,morph1.ball(1))
return out_v
def getSkl(self):
self.sklData=sk3d(self.segData.astype('int')).astype('bool')
def getDist(self):
self.distDataF=getDist(self.segData.astype('int'))
self.distData=self.distDataF*self.sklData
def getKeys(self):
sk_=(filt.uniform_filter(self.sklData.astype('float'), size=3)*27).astype('int')
self.keysData=sk_>3
def getSmooth(self, sigma=1, mode='same'):
d=self.distDataF
d=filt.gaussian_filter(d,sigma)
s=d*self.sklData
m=np.zeros_like(s)
indices=np.where(s>0)
indices=np.array([indices[0],indices[1],indices[2]]).T # from rows in tuple to columns in np array
for i in tqdm(range(np.shape(indices)[0])):
idx=indices[i]
x0=idx[1]
y0=idx[2]
z0=idx[0]
# radius of the sphere and numbr of point grids
l=s[z0,x0,y0]
n_p=int(2*l+1)
# get the grid for x, y, z
x=np.floor(np.linspace(x0-l,x0+l,n_p))
y=np.floor(np.linspace(y0-l,y0+l,n_p))
z=np.floor(np.linspace(z0-l,z0+l,n_p))
# get the meshgrid and build the sphere
p1,p2,p3=np.meshgrid(x,y,z);
sphere=((p1-x0)**2+(p2-y0)**2+(p3-z0)**2)<=l**2
p11=p1*sphere; p11=np.ndarray.flatten(p11)
p22=p2*sphere; p22=np.ndarray.flatten(p22)
p33=p3*sphere; p33=np.ndarray.flatten(p33)
# set the grid points of the origional data stack that
# intersect with the sphere to value 1
p=np.array([p33,p11,p22]).astype('int')
p=tuple(p)
m[p]=1
if mode =='same':
self.segData=m
else:
self.smoothedSegData=m
### Second Method ###
def cvh(self, v):
points=np.array(np.where(v>0)).T
return np.sum(v)/fc(points).volume
def getBatches2(self, ind, thresh=[0,1], c=.75):
#initialize
batches=[]
selec_ind=np.zeros(np.shape(ind)[0]*len(self.pSize[0]))
for l,m,n in zip(self.pSize[0],self.pSize[1],self.pSize[2]):
print('\n'+'*'*75+'\n'+'Extracting batches at scale: '+'['+str(l)+', '+str(m)+', '+str(n)+']')
s_z=int(l/2)# step in z
s_x=int(m/2)# step in x
s_y=int(n/2)# step in y
for i in tqdm(range(np.shape(ind)[0])):
z,x,y=ind[i]
# check if the patch does not exceed the bounds
if ((self.d1-s_z > z >= s_z+1) and
(self.d2-s_x > x >= s_x+1) and
(self.d3-s_y > y >= s_y+1)):
batch=self.segData[z-s_z:z+s_z , x-s_x:x+s_x, y-s_y:y+s_y]
# check if the patch is representative
if thresh[0]*m*n*l <= np.sum(batch>0) <=thresh[1]*m*n*l:
#check if a batch at this index is not added
if selec_ind[i]==0:
#fix the size if ness.
self.wanted_size=s=[16.0,32.0,32.0]
if not np.array_equal(s,[l,m,n]):
batch=ndim.zoom(batch, (s[0]/l, s[1]/m, s[2]/n), order=0)
batches.append(batch)# add the patch to the dataset
selec_ind[i]=1
return selec_ind, np.array(batches[:])
class arg():
def __init__(self, batch=1, nb_classes=2, w_path=None):
self.batch=batch
self.nb_classes=nb_classes
# perform DBSCAN clustering fot the output of prediction
def getCluster(X, eps=0.05, min_samples=20):
#find labels
db = DBSCAN(eps=eps, min_samples=min_samples).fit(X)
core_samples_mask = np.zeros_like(db.labels_, dtype=bool)
core_samples_mask[db.core_sample_indices_] = True
labels = db.labels_
# Number of clusters in pred labels, ignoring noise if present.
n_clusters = len(set(labels)) - (1 if -1 in labels else 0)
def computeCentroid(points):
x1 = map(lambda p: p[0], points)
x2 = map(lambda p: p[1], points)
x3 = map(lambda p: p[2], points)
centroid = [np.mean(x1), np.mean(x2), np.mean(x3)]
return centroid
#exclude noise from pred (outliers)
ind=np.where(labels >-1)
X_=np.array(X[ind])
labels_=np.array(labels[ind])
#calculate centroids
points=dict()
centroids=dict()
for i in range(n_clusters):
ind=np.where(labels_ ==i)
points[i]=X_[ind]
centroids[i]=computeCentroid(points[i])
X=np.vstack((X,np.array(centroids[i])))
labels=np.append(labels,n_clusters+10)
nodes=[]
for key, value in centroids.iteritems():
temp = [key,value]
nodes.append(temp[1])
nodes=np.array(nodes)
return nodes
#plot scatter points
def plot(v):
indices=np.where(v>0)
x1,x2,x3=indices[0],indices[1],indices[2]
d=mlab.pipeline.scalar_scatter(x1,x2,x3)
g=mlab.pipeline.glyph(d)
# e=mlab.get_engine()
# g=e.scenes[0].children[0].children[0].children[0]
# g.glyph.glyph.range = np.array([ 0., 1])
# g.glyph.glyph.scale_factor = 0.1
def makeMovie(path):
for i in range(360):
# Rotate the camera by 10 degrees.
e=mlab.get_engine()
c=e.current_scene
c.scene.camera.azimuth(1)
# Resets the camera clipping plane so everything fits and then
# renders.
# c.scene.reset_zoom()
# Save the scene.
c.scene.save_png(path+'anim%d.png'%i)
#"ffmpeg -f image2 -r 25 -i anim%d.png -vcodec mpeg4 -vb 20M -y movie.mp4"
def getGraphfromCGAL(filenameVertices, filenameEdges, FullyCC=True):
P1, P2, P11, P22=readCGAL(filenameEdges, filenameVertices)
p, intersections, c=getGraph(P1, P2, P11, P22)
G=nx.Graph()
G.add_nodes_from(range(np.shape(p)[0]))
G.add_edges_from(np.ndarray.tolist(c))
for i in range(np.shape(p)[0]):
G.node[i]['pos']=p[i,:]
G.to_undirected()
if FullyCC==True:
# connected components
graphs=list(nx.connected_component_subgraphs(G))
s=0
ind=0
for idx, i in enumerate(graphs):
if len(i)>s:
s=len(i); ind=idx
G=graphs[ind]
G=fixG(G)
return G
def getGraph(P1, P2, P11, P22):
u1=np.unique(P1,axis=0)
u2=np.unique(P2,axis=0)
P_unique=np.unique(np.vstack([u1,u2]),axis=0)
labels=dict()
for i in range(len(P_unique)):
labels[str(P_unique[i,:])]=i
counter=dict()
intersect_ind=list()
counter1=dict()
for i in P1:
if str(i) in counter1.keys():
counter1[str(i)]=counter1[str(i)]+1
else:
counter1[str(i)]=1
#
counter2=dict()
for i in P2:
if str(i) in counter2.keys():
counter2[str(i)]=counter2[str(i)]+1
else:
counter2[str(i)]=1
for i in labels.keys():
if i in counter1.keys():
if counter1[i]>2:
intersect_ind.append(labels[i])
else:
if counter1[i]==2 and i in counter2.keys():
intersect_ind.append(labels[i])
if i in counter2.keys():
if counter2[i]>2:
intersect_ind.append(labels[i])
else:
if counter2[i]==2 and i in counter1.keys():
intersect_ind.append(labels[i])
intersect=P_unique[intersect_ind]
connections=[]
for i in range(len(P1)):
start=labels[str(P1[i])]
end=labels[str(P2[i])]
connections.append((start,end))
return P_unique, intersect, np.array(connections)
def readCGAL(filenameEdges, filenameVertices):
f_edges = open(filenameEdges, 'r')
c_edges=f_edges.readlines()
f_verts = open(filenameVertices, 'r')
c_verts=f_verts.readlines()
def process(c):
c=c.rstrip('\n')
c=c.split()
for i in range(len(c)):
c[i]=float(c[i])
return c
c_edges=[process(c_edges[i]) for i in range(len(c_edges))]
p_edges=np.array(c_edges)
P1=p_edges[:,0:3]
P2=p_edges[:,3:6]
c_verts=[process(c_verts[i]) for i in range(len(c_verts))]
p_verts=np.array(c_verts)
P11=p_verts[:,0:3]
P22=p_verts[:,3:6]
return P1, P2, P11, P22
def readOFF(filename):
"""
Reads vertices and faces from an off file.
:param file: path to file to read
:type file: str
:return: vertices and faces as lists of tuples
:rtype: [(float)], [(int)]
"""
assert os.path.exists(filename)
with open(filename, 'r') as fp:
lines = fp.readlines()
lines = [line.strip() for line in lines]
assert lines[0] == 'OFF'
parts = lines[1].split(' ')
assert len(parts) == 3
num_vertices = int(parts[0])
assert num_vertices > 0
num_faces = int(parts[1])
assert num_faces > 0
if lines[2]=='':
K=3
else:
K=2
vertices = []
for i in range(num_vertices):
try:
vertex = lines[K + i].split(' ')
vertex = [float(point) for point in vertex]
assert len(vertex) == 3
vertices.append(vertex)
except:
ValueError
faces = []
for i in range(num_faces):
try:
face = lines[K + num_vertices + i].split()
face = [int(index) for index in face if index !='']
except:
ValueError
assert face[0] == len(face) - 1
for index in face:
assert index >= 0 and index < num_vertices
assert len(face) > 1
faces.append(face[1:4])
return [vertices, faces]
def visGraph(p, e, d, radius=.15, color=(0.8,0.8,0), gylph_r=0.5, gylph_c=(1,1,1)):
if d:
pts=mlab.points3d(p[:,0],p[:,1],p[:,2], d)
else:
pts=mlab.points3d(p[:,0],p[:,1],p[:,2], scale_factor=gylph_r, color=gylph_c)
pts.mlab_source.dataset.lines = e
tube = mlab.pipeline.tube(pts, tube_radius=radius)
tube.filter.set_input_data(pts.mlab_source.dataset)
surface=mlab.pipeline.surface(tube, color=color)
if d:
tube.filter.vary_radius = 'vary_radius_by_absolute_scalar'
surface.actor.mapper.scalar_range = [ 0.0, np.max(d)]
surface.actor.mapper.progress = 1.0
surface.actor.mapper.scalar_visibility = True
def visG(G,
radius=.15,
color=(0.8,0.8,0),
gylph_r=0.5,
gylph_c=(1,1,1),
diam=False,
jnodes_r=None,
jnodes_c=(0,0,1)):
nodes=[G.node[i]['pos'] for i in G.nodes()]
edges=[[i[0],i[1]] for i in G.edges()]
#obtain radius in each node
d=None
if diam:
try:
d=[G.node[i]['d'] for i in G.nodes()]
except:
pass
nodes=np.array(nodes).astype('float') # importnat to be float type
edges=np.array(edges)
visGraph(p=nodes, e=edges, d=d,
radius=radius,
color=color,
gylph_r=gylph_r,
gylph_c=gylph_c)
if jnodes_r:
_, jnodes=findNodes(G, j_only=False)
x=[i[0] for i in jnodes]
y=[i[1] for i in jnodes]
z=[i[2] for i in jnodes]
mlab.points3d(x,y,z,scale_factor=jnodes_r, color=jnodes_c)
def getBranches_no(intersections):
branches=[]
points=[]
Input=intersections
px=np.array([np.inf,np.inf,np.inf])
for i in range(np.shape(intersections)[0]):
while px not in points:
Input=intersections
p1=intersections[i,:] # select a point
points.append(p1)
# delet it from Input
ind_p1=np.where(np.all(Input==p1, axis=1))
Input=np.delete(Input,ind_p1,axis=0)
p1.shape=(1,3)
# compute ecludien distance of Input from p1
p1_stack=np.repeat(p1, np.shape(Input)[0], axis=0)
dist=np.sqrt(np.sum(np.square(Input-p1_stack), axis=1))
# find the ind of point (px) in Input that has the min dist with p1
ind=np.where(dist==np.min(dist))
ind=np.array(ind).ravel()
ind=ind[0]
px=Input[ind]
points.append(px)
branches.append([p1.ravel(),px])
return branches
def fixG(G):
Oldnodes=G.nodes()
new=range(len(Oldnodes))
mapping={Oldnodes[i]:new[i] for i in new}
G=nx.relabel_nodes(G, mapping)
return G
def removeEndsG(G):
NodesToRemove=[0]
while len(NodesToRemove)!=0:
NodesToRemove=[]
for i in G.nodes_iter():
k=nx.neighbors(G, i)
if len(k)==1:
NodesToRemove.append(i)
G.remove_nodes_from(NodesToRemove)
return G
def getGraphfromMat(filename):
F=h5py.File(filename, 'r')
In=F['im2']
items=In.keys()
data=dict()
for i in items:
data[i]=np.array(In[i])
nX=data['nX']
nY=data['nY']
nZ=data['nZ']
scale=data['Hvox']
xx=int(nX*scale[0])
yy=int(nY*scale[1])
zz=int(nZ*scale[2])
# read nodes
Pos=data['nodePos_um'].T
# read edges
Edg=(data['nodeEdges'].T).astype('int')
connections=[]
for i in range(len(Edg)):
connections.append((Edg[i,0]-1,Edg[i,1]-1))
# graphing funtion
x,y,z=Pos[:,0].astype('float'), Pos[:,1].astype('float'), Pos[:,2].astype('float')
G=nx.Graph()
G.add_nodes_from(range(np.shape(Pos)[0]))
G.add_edges_from(connections)
x=256
y=256
minx=np.min(Pos[:,0])
miny=np.min(Pos[:,1])
minz=np.min(Pos[:,2])
maxx=np.max(Pos[:,0])
maxy=np.max(Pos[:,1])
maxz=np.max(Pos[:,2])
for i in range(np.shape(Pos)[0]):
px=512*((Pos[i,0]-minx)/maxx)
py=512*((Pos[i,1]-miny)/maxy)
pz=512*((Pos[i,2]-minz)/maxz)
G.node[i]['pos']=np.array([py,y-(px-y),pz])
return G
def createCam(position,
focal_point,
view_angle,
view_up,
clipping_range):
cam=dict()
cam['position']=position
cam['focal_point']=focal_point
cam['view_angle']=view_angle
cam['view_up']= view_up
cam['clipping_range']=clipping_range
return cam
def setCam(cam=None):
if cam:
e=mlab.get_engine()
c=e.current_scene
c.scene.camera.position = cam['position']
c.scene.camera.focal_point = cam['focal_point']
c.scene.camera.view_angle = cam['view_angle']
c.scene.camera.view_up = cam['view_up']
c.scene.camera.clipping_range = cam['clipping_range']
c.scene.camera.compute_view_plane_normal()
c.scene.render()
def getSlicesfromGraph(G, name='graphSlices', mode='slices', image=False):
fig=mlab.figure(bgcolor=(0,0,0),size=(512,561))
def setCamera():
e=mlab.get_engine()
c=e.current_scene
c.scene.camera.azimuth(1)
c.scene.camera.position = [255.5, 255.5, -1125]
c.scene.camera.focal_point = [255.5, 255.5, 255.0]
c.scene.camera.view_angle = 30
c.scene.camera.view_up = [1, 0, 0]
c.scene.camera.clipping_range = [0, 3000]
c.scene.camera.compute_view_plane_normal()
c.scene.render()
depth=c.scene.camera.position
return c, depth[2]
visG(G, radius=2, color=(0,1,0))
if image:
scr=mlab.pipeline.scalar_field(stk)
imageCut=mlab.pipeline.scalar_cut_plane(scr)
imageCut.actor.property.opacity=.2
imageCut.implicit_plane.widget.normal_to_z_axis=True
e=mlab.get_engine()
gylph= e.scenes[0].children[0].children[0].children[0]
gylph.actor.actor.visibility=False
surface = e.scenes[0].children[0].children[1].children[0].children[0]
surface.actor.actor.visibility=False
cut_plane = mlab.pipeline.scalar_cut_plane(surface,
plane_orientation='z_axes')
cut_plane.implicit_plane.origin = (256, 256, 0)
cut_plane.actor.property.color = (1, 1, 1)
cut_plane.implicit_plane.widget.enabled = False
c,depth=setCamera()
slices=[]
for i in range(512):
cut_plane.implicit_plane.origin = (256, 256, i)
c.scene.camera.position = [255.5, 255.5, depth+i]
if image:
imageCut.implicit_plane.origin = (256, 256, i)
s = mlab.screenshot(figure=fig, mode='rgba', antialiased=True)
s=ndim.filters.maximum_filter(s[:,:,0]>0,size=(3,3))
#plt.imshow(s)
im=Image.fromarray(np.array(s*255, dtype=np.uint8))
if mode=='slices':
im.save(name+str(i)+'.png')
else:
slices.append(np.array(s*255, dtype=np.uint8))
if len(slices)>0:
slices=np.array(slices)
slices=slices[:,:,:]
io.imsave(name,slices)
def displayAdj(G):
admG=nx.adjacency_matrix(G).toarray()
scatterG=np.where(admG==1)
x=scatterG[0]
y=scatterG[1]
plt.figure()
plt.scatter(x,y)
def reduceG(G, j_only=False):
cont=1
idNodes,_=findNodes(G, j_only=j_only)
while cont!=0:
# NodesToRemove=[]
# NodesToConnect=[]
cont=0
for i in list(G.nodes_iter()):
k=nx.neighbors(G, i)
if len(k)==2:
if i not in idNodes:
G.remove_node(i)
G.add_edge(k[0],k[1])
cont=1
#to account for loopy structure
#G=fixG(G)
return G
def visPoints(points, scale_factor=1, color=(1,1,1)):
x=[i[0] for i in points]
y=[i[1] for i in points]
z=[i[2] for i in points]
mlab.points3d(x, y, z,
scale_factor=scale_factor,
color=color)
e=mlab.get_engine()
def findNodes(G, j_only=False):
nodes=[]
ind=[]
if j_only:
for i in G.nodes():
if len(G.neighbors(i))==3:
nodes.append(G.node[i]['pos'])
ind.append(i)
else:
for i in G.nodes():
if len(G.neighbors(i))!=2:
nodes.append(G.node[i]['pos'])
ind.append(i)
try:
nodes=[i.tolist() for i in nodes]
except:
pass
return ind, nodes
def findPoints(G):
p=[]
for i in range(G.number_of_nodes()):
p.append(G.node[i]['pos'].tolist())
return p
def findEnds(G):
p=[]
for i in range(G.number_of_nodes()):
if len(G.neighbors(i))==1:
p.append(i)
return p
def prunG(G):
"""
This function remove branches of length =1.
Input:
"G": NetworkX undirected graph
Output:
"G": pruned version of the intput "G"
"""
j_nodes,_=findNodes(G)
nbrs=[]
for i in j_nodes:
nbrs.append(nx.neighbors(G,i))
for n, nb in zip(j_nodes, nbrs):
if len(nb)==1:
if nb[0] in j_nodes:
G.remove_node(n)
G=fixG(G)
return G
# This does not work !!!!!!!
#def prunG(G):
# endP=findEnds(G)
# crossP,_=findNodes(G)
# nodes_to_remove=[]
# for i in crossP:
# n=G.neighbors(i)
# if len(n)>2:
# for j in n:
# if j in endP:
# nodes_to_remove.append(j)
# G.remove_nodes_from(nodes_to_remove)
# return fixG(G)
def rescaleG(G, cube=512):
p=findPoints(G)
pmin=np.min(p,axis=0)
pmax=np.max(p,axis=0)
for i in range(G.number_of_nodes()):
p_=G.node[i]['pos']
G.node[i]['pos']=512*(p_-pmin)/pmax
return G
def saveSceneToPNG(name):
#save as PNG
s = mlab.screenshot( mode='rgba', antialiased=True)
im=Image.fromarray(np.array(s*255, dtype=np.uint8))
im.save(name)
def decideThresh(v, portion):
vals,bins=np.histogram(v,bins=1000)
vals=vals.astype(float)/sum(vals)
s=0
thresh=0
for idx, i in enumerate(vals):
s+=i
if s>portion:
thresh=bins[idx]
break
return thresh
def getCoreGraph(G, indices):
#obtain reduced graphs (with only burifications)
Gr=reduceG(G.copy()) # note that Gr is not fixed by fixG
nodesGr=Gr.nodes()
nbrs=[]
#find connections between nodes
#connections=[]
for i in Gr.nodes():
nbrs_=Gr.neighbors(i)
nbrs.append(nbrs_)
#connections_=[[i,j] for j in nbrs_]
#connections.append(connections_)
#find the complete branches(pathes) between nodes
pathes=[]
for i, j in zip(nodesGr, nbrs):
pathes_=[]
for nbr in j:
pth=nx.shortest_path(G, i, nbr)
pth.pop() # to avoid removing the node on the other side of the branch
pathes_.append(pth)
pathes.append(pathes_)
pathes_to_remove=[]
for id_i, i in enumerate(nodesGr):
if i in indices:
pathes_to_remove.append(pathes[id_i])
#find nodes and points on the corresponding branches to be removed
nodes_to_remove=list(set([i[j][k] for i in pathes_to_remove
for j in range(len(i))
for k in range(len(i[j]))]))
for i in nodes_to_remove:
G.remove_node(i)
for i in G.nodes():
if len(G.neighbors(i))<1:
G.remove_node(i)
return G
def getBranches(G):
idNodes,_=findNodes(G)
Gr=reduceG(G.copy())
nbrs=[]
#find connections between nodes
for i in idNodes:
nbrs_=Gr.neighbors(i)
nbrs.append(nbrs_)
#find the complete branches(pathes) between nodes
pathes=[]
for i, j in zip(idNodes, nbrs):
for nbr in j:
pth=set(nx.shortest_path(G, i, nbr))
if not pth in pathes:
pathes.append(pth)
pathes=[list(i) for i in pathes]
return pathes
# get graph in the middle
def getMiddleGraph(G, thr):
max_p1=0
max_p2=0
max_p3=0
for i in G.nodes():
if max_p1<G.node[i]['pos'][0]:
max_p1=G.node[i]['pos'][0]
if max_p2<G.node[i]['pos'][1]:
max_p2=G.node[i]['pos'][1]
if max_p3<G.node[i]['pos'][2]:
max_p3=G.node[i]['pos'][2]
for i in G.nodes():
p1,p2,p3=G.node[i]['pos']
if p1>thr and p1<max_p1-thr and p2>thr and p2<max_p2-thr and p3>thr and p3<max_p3-thr:
pass
else:
G.remove_node(i)
return fixG(G)
def getFullyConnected(G):
# connected components
graphs=list(nx.connected_component_subgraphs(G))
s=0
ind=0
for idx, i in enumerate(graphs):
if len(i)>s:
s=len(i); ind=idx
G=graphs[ind]
G=fixG(G)
return G
import SimpleITK as sitk
def makeMIP(array=None, image_path=None, output_dir=None, output=True):
if array is not None:
image=sitk.GetImageFromArray(array)
if image_path is not None:
image = sitk.ReadImage(image_path)
basename = os.path.basename(image_path)
if not os.path.isdir(output_dir):
os.makedirs(output_dir)
image_size = image.GetSize()
for dim in range(3):
projection = sitk.MaximumProjection(image, dim)
if image_size[dim] % 2: # odd number
voxel = [0, 0, 0]
voxel[dim] = (image_size[dim] - 1) / 2
origin = image.TransformIndexToPhysicalPoint(voxel)
else: # even
voxel1 = np.array([0, 0, 0], int)
voxel2 = np.array([0, 0, 0], int)
voxel1[dim] = image_size[dim] / 2 - 1
voxel2[dim] = image_size[dim] / 2
point1 = np.array(image.TransformIndexToPhysicalPoint(voxel1.tolist()))
point2 = np.array(image.TransformIndexToPhysicalPoint(voxel2.tolist()))
origin = np.mean(np.vstack((point1, point2)), 0)
projection.SetOrigin(origin)
projection.SetDirection(image.GetDirection())
if output_dir:
proj_basename = basename.replace('.nii.gz', '_mip_{}.nii.gz'.format(dim))
sitk.WriteImage(projection, os.path.join(output_dir, proj_basename))
if output:
return sitk.GetArrayFromImage(projection)
def visProG(G, radius=.15,
color=(0.8,0.8,0),
gylph_r=1,
gylph_c=(1,1,1),
bound=1,
bgcolor=(1,1,1),
init=False):
# figure = mlab.gcf()
# mlab.clf()
figure=mlab.figure(bgcolor=bgcolor)
figure.scene.disable_render = True
def showG(P_unique, connections, radius=.15, color=(0.8,0.8,0), gylph_r=0.5, gylph_c=(1,1,1)):
pts=mlab.points3d(P_unique[:,0],P_unique[:,1],P_unique[:,2],scale_factor=gylph_r, color=gylph_c)
pts.mlab_source.dataset.lines = np.array(connections)
tube = mlab.pipeline.tube(pts, tube_radius=radius)
tube.filter.radius_factor = 1.
tube.filter.vary_radius = 'vary_radius_by_scalar'
tube.filter.set_input_data(pts.mlab_source.dataset)
mlab.pipeline.surface(tube, color=color)
return pts
def inG(G, radius=.15, color=(0.8,0.8,0), gylph_r=0.5, gylph_c=(1,1,1)):
nodes=[]
for i in range(G.number_of_nodes()):
nodes.append(G.node[i]['pos'])
edges=[]
for i in G.edges_iter():
e=[i[0],i[1]]
edges.append(e)
nodes=np.array(nodes)
edges=np.array(edges)
pts=showG(nodes, edges,
radius=radius,
color=color,
gylph_r=gylph_r,
gylph_c=gylph_c)
return pts
g_points=np.array(findPoints(G))
if init:
p1,p2,p3=[init[0], init[1], init[2]]
else:
p1,p2,p3=g_points[1]
pts=inG(G,
radius=radius,
color=color,
gylph_r=gylph_r,
gylph_c=gylph_c)
# outline = mlab.outline(line_width=5)
# outline.outline_mode = 'full'
# outline.bounds = (p1-bound, p1+bound,
# p2-bound, p2+bound,
# p3-bound, p3+bound)
sphere = mlab.points3d(p1, p2, p3, scale_mode='none',
scale_factor=bound,
color=(1, 1, 1),
opacity=.7)
figure.scene.disable_render = False
glyph_points = pts.glyph.glyph_source.glyph_source.output.points.to_array()
def picker_callback(picker):
""" Picker callback: this get called when on pick events.
"""
if picker.actor in pts.actor.actors:
point_id = picker.point_id/glyph_points.shape[0]
# If the no points have been selected, we have '-1'
if point_id != -1:
x, y, z = g_points[point_id]
# # Move the outline to the data point.
# outline.bounds = (x-bound, x+bound,
# y-bound, y+bound,
# z-bound, z+bound)
sphere.mlab_source.set(x=x,y=y,z=z)
print(point_id)
print(x,y,z)
picker = figure.on_mouse_pick(picker_callback)
picker.tolerance = 0.001
def getPropagate2(G, idx, cutoff=10):
path=nx.single_source_shortest_path(G, idx, cutoff=cutoff)
end_points=[i for i in path.keys()]
path_p=[path[i] for i in path.keys()]
path_points=[]
for i in path_p:
try:
len(i)
for j in i:
path_points.append(j)
except:
path_points.append(i)
points= set(path_points).union(set(end_points))
points=list(points)
for i in G.nodes():
if i in points:
pass
else:
G.remove_node(i)
return fixG(G)
def getPropagate(G, idp, cutoff=5):
Gc=reduceG(G.copy())
#get other juction nodes through the pathes
J=nx.single_source_shortest_path(Gc, idp, cutoff=cutoff)
eJ=[i for i in J.keys()]
pJ=[J[i] for i in J.keys()]
pairJ=[]
for i in pJ:
l=len(i)
if len(i)>1:
for idx, j in enumerate(i):
if idx<(l-1):
pairJ.append([j,i[idx+1]])
#all nodes in the pathes between j nodes
pnts=[]
for i in pairJ:
pnts.append(nx.shortest_path(G,i[0],i[1]))
pnts=[i for j in pnts for i in j]
pnts=list(set(pnts))
for i in G.nodes():
if i in pnts:
pass
else:
G.remove_node(i)
return fixG(G)
def readPAJEK(filename):
"""
Reads a Pajek file storing a Graph
following the format used in this mudule.
Input:
"filename": The full directory to Graph file.
"""
G_seg=nx.read_pajek(filename)
G=nx.Graph()
# build geometry
for i in range(G_seg.number_of_nodes()):
node=G_seg.node[str(i)]
# add node
n=int(node['id'].encode())
G.add_node(n-1)
#add position
pos=node['pos'].encode()
pos=pos.split(' ')
xyz=[]
for j in range(len(pos)):
try:
value=float(pos[j])
xyz.append(value)
except:
try:
value=pos[j].split('[')
xyz.append(float(value[1]))
except:
try:
value=pos[j].split(']')
xyz.append(float(value[0]))
except : pass
G.node[i]['pos']=np.array(xyz)
# add label
try:
yORn=node['node'].encode()
if yORn=='False':
G.node[i]['node']=False
else:
G.node[i]['node']=True
except:
pass
#build Topology
connections_=G_seg.edges()
connections=[[int((connections_[i][0]).encode()), int((connections_[i][1]).encode())] for i in range(len(connections_))]
G.add_edges_from(connections)
return G
def fixConnections(G):
# find wrong nodes and their positions
w_nodes=[] # wrong nodes
w_p=[] # position of wrong nodes
w_nbrs=[] # wrong neighbors
w_pos=[] # position of wrong neigbors
for i in G.nodes():
w_nbrs_=G.neighbors(i)
if len(w_nbrs_)==4:
w_nodes.append(i)
w_p.append(G.node[i]['pos'])
w_nbrs.append(w_nbrs_)
w_pos_=[G.node[j]['pos'] for j in w_nbrs_]
w_pos.append(np.array(w_pos_))
# decide which nodes to be connected avoiding the juction
ind_nodes=[] # indcies of nodes to avoid junction
a=[]
ind=[]
kk=list(it.combinations([0,1,2,3],2))
for i, j in zip(w_p, w_pos):
a_=[]
for k in kk:
p=[i, j[k[0]], j[k[1]]]
a_.append(cycleArea(p))
idx=np.argsort(a_)
ind.append(kk[idx[0]])
a.append(a_)
for i, j in zip(w_nbrs, ind):
ind_nodes.append([ i[j[0]], i[j[1]] ])
# modify_graph
for i, j in zip(w_nodes, ind_nodes):
G.remove_edge(i,j[0])
G.remove_edge(i,j[1])
G.add_edge(j[0],j[1])
return G
def TrianArea(p1, p2, p3):
def cal_abc(p1,p2,p3):
a=np.linalg.norm(p1-p2)
b=np.linalg.norm(p1-p3)
c=np.linalg.norm(p2-p3)
return a, b, c
try:
cal_abc(p1,p2,p3)
except:
p1=np.cross
cal_abc(p1,p2,p3)
# calculate the sides
s = (a + b + c) / 2
# calculate the area
area = (s*(s-a)*(s-b)*(s-c)) ** 0.5
return area
def cycleArea(corners):
n = len(corners) # of corners
cross= [0.0,0.0,0.0]
for i in range(n):
j = (i + 1) % n
crss=np.cross(corners[i],corners[j])
cross=cross+crss
#nrm+=np.linalg.norm(crss)
area = np.linalg.norm(cross) / 2.0
return area
def eigV(p):
centered_matrix = p - p.mean(axis=1)[:, np.newaxis]
cov = np.dot(centered_matrix, centered_matrix.T)
eigvals, _ = np.linalg.eig(cov)
delta=np.exp(1/(eigvals[0]+eigvals[1]))-1
return delta
def angle(a, p1, p2):
ap1 = p1 - a
ap2 = p2 - a
x1,x2,y1,y2,z1,z2=ap1[0],ap2[0],ap1[1],ap2[1],ap1[2],ap2[2]
dot=x1*x2+y1*y2+z1*z2
norm1=(x1**2+y1**2+z1**2)**.5
norm2=(x2**2+y2**2+z2**2)**.5
if norm1>0 and norm2>0:
cosine_angle = dot/(norm1*norm2)
else:
cosine_angle = 1
add=0
cosine_angle=round(cosine_angle,5)
if cosine_angle <0:
add=np.pi/2
cosine_angle+=1
angle = np.arccos(cosine_angle)
return np.degrees(angle+add)
def isSklNode(node, p, thr):
thr1, thr2=thr,180-thr
idx=range(np.shape(p)[0])
idx.pop(0)
skl_node=True
for i in idx:
ang=angle(node, p[0], p[i])
if ang>thr1 and ang<thr2:
skl_node=False
return skl_node
def getPropagate_branches(G, idp, cutoff=5):
Gc=reduceG(G.copy(), j_only=True)
#get other juction nodes through the pathes
J=nx.single_source_shortest_path(Gc, idp, cutoff=cutoff)
J=[J[i] for i in J.keys()]
# get branches at different levels
levels=dict()
for j in range(cutoff):
branches_=[]
for i in J:
if len(i)>1:
try:
branches_.append([i[j],i[j+1]])
except:
pass
branches_=[tuple(i) for i in branches_]
branches_=list(set(branches_))
branches_=[list(i) for i in branches_]
levels[j]=(branches_)
#all nodes in the pathes between pair of j nodes
b=dict()
for i in levels.keys():
pairJ=levels[i]
pnts=[]
for j in pairJ:
pnts.append(nx.shortest_path(G,j[0],j[1]))
b[i]=pnts
Graphs=dict()# represent each level as a graph
for k in b.keys():
pnts=b[k]
pnts=[i for j in pnts for i in j]
G_=G.copy()
for i in G_.nodes():
if i in pnts:
pass
else:
G_.remove_node(i)
G_=fixG(G_)
Graphs[k]=G_
return Graphs
def visGs(Graphs, radius=.5, bound=5, gylph_r=2):
colors=[(0.0, 0.0, 0.0),
(0.0, 0.0, 1.0),
(0.6470588235294118, 0.16470588235294117, 0.16470588235294117),
(0.8705882352941177, 0.7215686274509804, 0.5294117647058824),
(0.37254901960784315, 0.6196078431372549, 0.6274509803921569),
(1.0, 0.3803921568627451, 0.011764705882352941),
(0.23921568627450981, 0.34901960784313724, 0.6705882352941176),
(0.5019607843137255, 0.5411764705882353, 0.5294117647058824),
(1.0, 0.5490196078431373, 0.0),
(0.0, 0.7490196078431373, 1.0)]
for i in Graphs.keys():
if i <1:
visProG(Graphs[i], radius=radius, color=colors[i], bound=7, gylph_r=gylph_r)
else:
visG(Graphs[i], radius=radius, color=colors[i], gylph_r=gylph_r)
def visMesh(m, color=(1,0,0), opacity=.5,
figure=True,
axes=False,
adjust=False,
wire=True):
#build pipeline
if figure:
mlab.figure(bgcolor=(1,1,1))
x,y,z=[i[0] for i in m[0]], [i[1] for i in m[0]], [i[2] for i in m[0]]
if adjust:
# the next line is to fix the coordinates in the meshes datasets
y=max(y)-np.array(y)
y=y.tolist()
t=[i for i in m[1]]
if adjust:
mesh=mlab.pipeline.triangular_mesh_source(x,y,z,t) # coordinates are flipped to error in my meshes
else:
mesh=mlab.pipeline.triangular_mesh_source(x,y,z,t) # coordinates are flipped to error in my meshes
mesh.mlab_source.scalars=[1]*len(t)
s=mlab.pipeline.surface(mesh)
#modify surface
#s=mlab.get_engine().scenes[0].children[0].children[0].children[0]
s.module_manager.scalar_lut_manager.lut_mode=u'autumn' # colormap
if opacity:
s.actor.property.opacity = opacity
if color:
s.actor.mapper.scalar_visibility=False
s.actor.property.color = color #color
if axes:
ax=mlab.axes(color=(0,0,1), line_width=2, ranges=[0,512,0,512,0,660])
if wire:
s.actor.property.representation = 'wireframe'
def adjustMesh(m, flip=[0,0,0], switch=[0, 0, 0], reverse=[0,0,0]):
'''
modify mesh coordinates
Input:
m: the input mesh
flip: parameters used to flip or not the coordinates: [x, y, z].
switch: parameters used to switch or not coordinates: [xy, xz, yz]
'''
v=m[0]
t=m[1]
x, y, z = [i[0] for i in v], [i[1] for i in v], [i[2] for i in v]
if flip[0]==1:
x=max(x)-np.array(x)
x=x.tolist()
if flip[1]==1:
y=max(y)-np.array(y)
y=y.tolist()
if flip[2]==1:
z=max(z)-np.array(z)
z=z.tolist()
if reverse[0]==1:
x=x[::-1]
if reverse[1]==1:
y=y[::-1]
if reverse[2]==1:
z=z[::-1]
if switch[0]==1:
h=x
x=y
y=h
if switch[1]==1:
h=x
x=z
z=h
if switch[2]==1:
h=y
y=z
z=h
# rebuild v
v=[[i, j, k] for i, j, k in zip(x, y, z)]
return [v,t]
def sliceG(G, slc=[0,100], flat=True):
g=G.copy()
p=findPoints(g)
p=np.array(p)
x, y ,z = p[:,0], p[:,1], p[:,2]
index=np.ravel(np.where(
np.logical_or((z<slc[0]),(z>slc[1]))
))
g.remove_nodes_from(index)
g=fixG(g)
if flat:
for i in g.nodes():
p_=g.node[i]['pos']
g.node[i]['pos']=p_*[1,1,0]
return g
def adjustGraph(g, flip=[0,0,0], switch=[0,0,0]):
'''
modify graph coordinates
Input:
m: the input mesh
flip: parameters used to flip or not the coordinates: [x, y, z].
switch: parameters used to switch or not coordinates: [xy, xz, yz]
'''
v=[g.node[i]['pos'] for i in g.nodes()]
x, y, z = [i[0] for i in v], [i[1] for i in v], [i[2] for i in v]
if flip[0]==1:
x=max(x)- | np.array(x) | numpy.array |
### import used modules first
import scipy.optimize as opt
import math
from sys import platform
import ctypes
import struct
import numpy as np
from pathlib import Path
import matplotlib.pyplot as plt
import matplotlib.pylab as pylab
import cv2
import os
from glob import glob
from PIL import Image, ImageEnhance
import pandas as pd
import io
import random
import string
### 2-D Gaussian function with rotation angle
def twoD_Gaussian(xy, amplitude, sigma_x, sigma_y, xo, yo, theta_deg, offset):
xo = float(xo)
yo = float(yo)
theta = theta_deg / 360 * (2 * math.pi) # in rad
x = xy[0]
y = xy[1]
a = (np.cos(theta) ** 2) / (2 * sigma_x ** 2) + (np.sin(theta) ** 2) / (2 * sigma_y ** 2)
b = -(np.sin(2 * theta)) / (4 * sigma_x ** 2) + (np.sin(2 * theta)) / (4 * sigma_y ** 2)
c = (np.sin(theta) ** 2) / (2 * sigma_x ** 2) + (np.cos(theta) ** 2) / (2 * sigma_y ** 2)
g = offset + amplitude * np.exp(- (a * ((x - xo) ** 2) + 2 * b * (x - xo) * (y - yo)
+ c * ((y - yo) ** 2)))
return g.ravel()
### define a class for all glimpse data
class BinaryImage:
def __init__(self, path_folder, read_mode=1, frame_setread_num=20, frame_start=0,
criteria_dist=20, aoi_size=20, frame_read_forcenter=0,
N_loc=40, contrast=10, low=40, high=120,
blacklevel=30, whitelevel=200):
self.random_string = self.__gen_random_code(3)
self.path_folder = os.path.abspath(path_folder)
self.path_header = os.path.abspath(os.path.join(path_folder, 'header.glimpse'))
self.path_header_utf8 = self.path_header.encode('utf8')
self.path_header_txt = os.path.abspath(os.path.join(path_folder, 'header.txt'))
self.path_data = self.__get_path_data()
[self.frames_acquired, self.height, self.width, self.pixeldepth, self.med_fps] = self.getheader()
self.data_type, self.size_a_image, self.frame_per_file = self.__getdatainfo()
self.read_mode = read_mode
self.frame_setread_num = frame_setread_num
self.criteria_dist = criteria_dist
self.aoi_size = aoi_size
self.frame_read_forcenter = frame_read_forcenter
self.frame_start = frame_start
self.N_loc = N_loc
self.contrast = contrast
self.low = low
self.high = high
self.blacklevel = blacklevel
self.whitelevel = whitelevel
self.offset, self.fileNumber = self.__getoffset()
self.cut_image_width = 30
self.readN = self.__readGlimpseN(frame_read_forcenter, N_loc) # N image from i
self.image = self.__stackimageN(self.readN) # image used to be localized
self.x_fit = np.array([[i for i in range(aoi_size)] for j in range(aoi_size)]).astype(float)
self.y_fit = np.array([[j for i in range(aoi_size)] for j in range(aoi_size)]).astype(float)
self.background = np.mean(self.image)
self.initial_guess = [50., 2., 2., aoi_size/2, aoi_size/2, 0., self.background]
self.image_cut = []
###########################################################################
## main for localization
def Localize(self, put_text=True):
print('start centering')
image = self.image
image = self.__enhance_contrast(image, self.contrast)
contours = self.getContour(image, self.low, self.high)
cX, cY = self.getXY(contours)
## need to sort according to X first and select
for i in range(2):
cX, cY = self.__sortXY(cX, cY)
cX, cY = self.select_XY(cX, cY, self.criteria_dist)
cX, cY, amplitude = self.get_accurate_xy(image, cX, cY)
cX, cY, amplitude = self.removeblack(cX, cY, amplitude, self.blacklevel)
self.bead_number = len(cX)
image = self.__drawAOI(image, cX, cY, self.aoi_size, put_text=put_text)
self.__show_grayimage(image, save=True)
self.cX = cX
self.cY = cY
self.image = image
print('finish centering')
bead_radius = self.radius_save.reshape((-1,1))
random_string = self.random_string
return bead_radius, random_string
## main for tracking all frames and all beads(cX, cY)
def Track_All_Frames(self, selected_aoi=None, IC=False):
frames_acquired = self.frames_acquired
frame_start = self.frame_start
aoi_size = self.aoi_size
read_mode = self.read_mode
frame_setread_num = self.frame_setread_num
frame_read_forcenter = self.frame_read_forcenter
initial_guess, initial_guess_beads, N = self.__preparefit_info(read_mode, frame_setread_num, frames_acquired)
if selected_aoi == None:
cX = self.cX
cY = self.cY
else:
cX = np.array(self.cX[selected_aoi], ndmin=1)
cY = np.array(self.cY[selected_aoi], ndmin=1)
initial_guess_beads = np.array(initial_guess_beads[selected_aoi], ndmin=2)
p0_1 = initial_guess_beads # initialize fitting parameters for each bead
tracking_results_list = []
for i in range(N):
image = self.__readGlimpse1(frame_start+i)
data, p0_2 = self.trackbead(image, cX, cY, aoi_size, frame=i, initial_guess_beads=p0_1,IC=IC)
# p0_1 = self.__update_p0(p0_1, p0_2, i) # update fitting initial guess
tracking_results_list += data
print(f'frame {i}')
self.N = N
self.initial_guess_beads = p0_1
tracking_results = np.array(tracking_results_list)
self.tracking_results = tracking_results
self.aoi = [cX, cY]
return tracking_results
## main for getting fit-video of an aoi
def Get_fitting_video_offline(self, selected_aoi, frame_i, N):
tracking_results = self.tracking_results
cX, cY = self.aoi
x = self.x_fit
y = self.y_fit
n_fit = len(x)
aoi_size = self.aoi_size
path_folder = self.path_folder
tracking_results_select = self.get_aoi_from_tracking_results(tracking_results, selected_aoi)
imageN = self.__readGlimpseN(frame_i, N=N)
fourcc = cv2.VideoWriter_fourcc(*'H264')
output_movie = cv2.VideoWriter(os.path.abspath(path_folder) + f'/{self.random_string}-fitting2.mp4', fourcc, 5.0, (1200, 800))
i=0
for image, tracking_result_select in zip(imageN, tracking_results_select):
image_aoi, intensity = self.__getAOI(image, cY[selected_aoi], cX[selected_aoi], aoi_size)
para_fit = tracking_result_select[2:9]
data_fitted = twoD_Gaussian((x, y), *para_fit)
fig, ax = plt.subplots(1, 1)
# ax.imshow(image_aoi, cmap=plt.cm.gray, origin='lower',
# extent=(x.min(), x.max(), y.min(), y.max()))
ax.imshow(image_aoi)
ax.contour(x, y, data_fitted.reshape(n_fit, n_fit), 5, colors='r')
plot_img_np = self.get_img_from_fig(fig)
plot_img_np = cv2.resize(plot_img_np, (1200, 800))
output_movie.write(plot_img_np)
plt.close()
print(f'storing frame {i}')
i+= 1
self.image_aoi = image_aoi
self.ax = ax
output_movie.release()
###############################################################################
## get accurate position using Gaussian fit
def get_accurate_xy(self, image, cX, cY):
aoi_size = self.aoi_size
initial_guess_beads = np.array([self.initial_guess] * len(cX))
data, popt_beads = self.trackbead(image, cX, cY, aoi_size, frame=0, initial_guess_beads=initial_guess_beads)
amplitude = popt_beads[:, 0]
x, y = popt_beads[:, 3], popt_beads[:, 4]
self.dx_localization, self.dy_localization = x-aoi_size/2, y-aoi_size/2
self.initial_guess_beads = initial_guess_beads
self.amplitude = amplitude
cX = cX + self.dx_localization
cY = cY + self.dy_localization
return cX, cY, amplitude
## tracking position of all beads in a image, get all parameters and frame number
def trackbead(self, image, cX, cY, aoi_size, frame, initial_guess_beads, IC=False):
bead_number = len(cX)
bounds = self.__get_bounds(aoi_size)
x, y = self.x_fit, self.y_fit
data = []
for j in range(bead_number):
image_tofit, intensity = self.__getAOI(image, cY[j], cX[j], aoi_size)
initial_guess = self.__get_guess(image_tofit)
if IC==True:
contrast = 8
image_tofit = ImageEnhance.Contrast(Image.fromarray(image_tofit.astype('uint8'))).enhance(contrast)
image_tofit = np.array(image_tofit)
try:
# popt, pcov = opt.curve_fit(twoD_Gaussian, [x, y], image_tofit.ravel(), initial_guess_beads[j, :],
# bounds=bounds)
popt, pcov = opt.curve_fit(twoD_Gaussian, [x, y], image_tofit.ravel(), initial_guess,
bounds=bounds, method='trf')
ss_res = self.__get_residuals(twoD_Gaussian, x, y, image_tofit, popt)
## popt: optimized parameters, pcov: covariance of popt, diagonal terms are variance of parameters
# data_fitted = twoD_Gaussian((x, y), *popt)
intensity_integral = 2 * math.pi * popt[0] * popt[1] * popt[2]
data += [
[frame] + [j] + list(popt) +
[intensity] + [intensity_integral] + [ss_res]
]
# initial_guess_beads[j] = list(popt)
initial_guess_beads[j, :] = popt
except RuntimeError:
# popt, pcov = opt.curve_fit(twoD_Gaussian, [x, y],image_tofit.ravel(), initial_guess)
data += [[frame] + [j] + [0.] * 10]
initial_guess_beads[j, :] = np.array(initial_guess) # initial guess for all beads
except:
data += [[frame] + [j] + [0.] * 10]
initial_guess_beads[j, :] = np.array(initial_guess)
popt_beads = np.array(initial_guess_beads)
return data, popt_beads
### methods for localization
## get egde using frame in file,f
def getContour(self, image, low=30, high=90):
cut = self.cut_image_width
## get edges using openCV
image_cut = np.uint8(image[0 + cut:self.height - cut, 0 + cut:self.width - cut])
edges = cv2.Canny(image_cut, low, high) # cv2.Canny(image, a, b), reject value < a and detect value > b
# ret, thresh = cv2.threshold(self.edges, 0, 50, cv2.THRESH_BINARY) # THRESH_BINARY: transform into black/white depending on low/high value
contours, hierarchy = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
self.edges = edges
self.contours = contours
return contours
## get center point using moment of edge
def getXY(self, contours):
cut = self.cut_image_width
radius, radius_save = [], []
n_contours = len(contours)
cX, cY = [], []
saved_contours, perimeters, areas = [], [], []
for i in range(n_contours):
c = contours[i]
perimeters += [cv2.arcLength(c, True)]
areas += [cv2.contourArea(c)]
# if (perimeters[-1] <= 0) | (areas[-1] <= 0) | (len(c) < 2):
if (perimeters[-1] == 0):
continue ## ingore code below
radius += [2 * areas[-1] / perimeters[-1]] ## r^2/2r = r/2
M = cv2.moments(c)
# if (M['m00'] != 0) & (radius[-1] > 1):
if (M['m00'] != 0):
radius_save += [radius[-1]]
saved_contours += [c]
cX += [(M['m10'] / M['m00']) + cut]
cY += [(M['m01'] / M['m00']) + cut]
self.perimeters = perimeters
self.areas = areas
self.saved_contours = np.array(saved_contours)
cX = np.array(cX)
cY = np.array(cY)
radius_save = np.array(radius_save)
self.radius_save = radius_save
return cX, cY
## core for selecting points which are not too close
def select_XY(self, cX, cY, criteria):
cX1, cY1 = np.array(cX), np.array(cY)
n = len(cX1)
cX_selected, cY_selected = np.empty(0), np.empty(0)
r_selected = np.empty(0)
index = []
for i in range(n):
x2, y2 = cX1[i], cY1[i]
r = np.sqrt(x2**2 + y2**2)
c1 = abs(x2-cX_selected) >= criteria
c2 = abs(y2-cY_selected) >= criteria
c3 = abs(r-r_selected) >= criteria
c = np.array([c1 or c2 or c3 for c1,c2,c3 in zip(c1,c2,c3)]) ## get boolean array for outside of criteria distance
if all(c) or (i==0): ## collecting centers, every point should qualify
cX_selected = np.append(cX_selected, x2)
cY_selected = np.append(cY_selected, y2)
r = np.sqrt(x2**2 + y2**2)
r_selected = np.append(r_selected, r)
index += [i]
self.radius_save = self.radius_save[index]
self.saved_contours = self.saved_contours[index]
return cX_selected, cY_selected
## remove beads are too close, choose two image, refer to smaller bead#
def removeXY(self, cX, cY, criteria):
cX1, cY1 = np.array(cX), np.array(cY) # len of cXr1 is smaller, as ref
i_dele = np.empty(0).astype(int)
for i in range(len(cX1)):
dx = cX1 - cX1[i]
dy = cY1 - cY1[i]
dr = np.sqrt(dx ** 2 + dy ** 2)
if any(dr[dr != 0] <= criteria):
i_dele = np.append(i_dele, int(i))
cX = np.delete(cX1, i_dele)
cY = np.delete(cY1, i_dele)
self.radius_save = np.delete(self.radius_save, i_dele)
self.saved_contours = np.delete(self.saved_contours, i_dele)
return cX, cY
## get avg intensity of all AOI(20 * 20 pixel)
def getintensity(self, image, cX, cY, aoi_size=20): # i: bead number: 1,2,3,...,N
half_size = int(aoi_size/2)
intensity = []
for i in range(len(cX)):
horizontal = int(cY[i]) # width
vertical = int(cX[i]) # height
intensity += [np.mean(image[horizontal - half_size:(horizontal + half_size),
vertical - half_size:(vertical + half_size)])] # [x,y] = [width, height]
intensity = | np.array(intensity) | numpy.array |
#Copyright (C) 2021 <NAME>, <NAME>, University of California, Berkeley
#Licensed under the Apache License, Version 2.0 (the "License");
#you may not use this file except in compliance with the License.
#You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
#Unless required by applicable law or agreed to in writing, software
#distributed under the License is distributed on an "AS IS" BASIS,
#WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#See the License for the specific language governing permissions and
#limitations under the License.
import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), '../external'))
sys.path.append(os.path.join(os.path.dirname(__file__), '../src'))
import vtk
from vtk.util.numpy_support import vtk_to_numpy, numpy_to_vtk
import numpy as np
#np.random.seed(42)
from vtk_utils.vtk_utils import *
from pre_process import *
import argparse
from datetime import datetime
import scipy.sparse as sp
import pickle
from scipy.sparse.linalg.eigen.arpack import eigsh
def build_transform_matrix(image):
matrix = np.eye(4)
matrix[:-1,:-1] = np.matmul(np.reshape(image.GetDirection(), (3,3)), np.diag(image.GetSpacing()))
matrix[:-1,-1] = np.array(image.GetOrigin())
return matrix
def map_polydata_coords(poly, displacement, transform, size):
coords = vtk_to_numpy(poly.GetPoints().GetData())
coords += displacement
coords = np.concatenate((coords,np.ones((coords.shape[0],1))), axis=-1)
coords = np.matmul(np.linalg.inv(transform), coords.transpose()).transpose()[:,:3]
coords /= np.array(size)
return coords
def transform_polydata(poly, displacement, transform, size):
coords = map_polydata_coords(poly, displacement, transform, size)
poly.GetPoints().SetData(numpy_to_vtk(coords))
return poly
def get_image_patch(image_py, coords):
"""
return a patch of the image defined under coords, the coords should be in [0,1]R^3
"""
dim_x, dim_y, dim_z = image_py.shape
indices = coords * np.array([[dim_x, dim_y, dim_z]])
x1 = np.floor(indices[:,0]).astype(int)
y1 = np.floor(indices[:,1]).astype(int)
z1 = np.floor(indices[:,2]).astype(int)
x2 = np.ceil(indices[:,0]).astype(int)
y2 = np.ceil(indices[:,1]).astype(int)
z2 = np.ceil(indices[:,2]).astype(int)
q11 = image_py[x1, y1, z1]
q21 = image_py[x2, y1, z1]
q12 = image_py[x1, y2, z1]
q22 = image_py[x2, y2, z1]
wx = indices[:, 0] - x1
wx2 = x2 - indices[:, 0]
lerp_x1 = q21 * wx + q11 * wx2
lerp_x2 = q12 * wx + q22 * wx2
wy = indices[:, 1] - y1
wy2 = y2 - indices[:, 1]
lerp_y1 = lerp_x2 * wy + lerp_x1 * wy2
q112 = image_py[x1, y1, z2]
q212 = image_py[x2, y1, z2]
q122 = image_py[x1, y2, z2]
q222 = image_py[x2, y2, z2]
lerp_x12 = q212 * wx + q112 * wx2
lerp_x22 = q122 * wx + q222 * wx2
lerp_y12 = lerp_x22 * wy + lerp_x12 * wy2
wz = indices[:, 2] - z1
wz2 = z2 - indices[:,2]
lerp_z = lerp_y12 * wz + lerp_y1 * wz2
return lerp_z
def make_grid_vtk(ctrl_points, diagonal=True):
# assume equal number of control points along each dim
num_pts = int(round(len(ctrl_points)**(1/3)))
# points
grid = vtk.vtkPolyData()
vtk_points = vtk.vtkPoints()
vtk_points.SetData(numpy_to_vtk(ctrl_points))
grid.SetPoints(vtk_points)
# edges
lines = vtk.vtkCellArray()
for i in range(num_pts):
for j in range(num_pts):
for k in range(num_pts-1):
id1 = i*num_pts*num_pts+j*num_pts +k
ids = []
ids.append(i*num_pts*num_pts+j*num_pts +k+1)
if diagonal:
if j<num_pts-1:
ids.append(i*num_pts*num_pts+(j+1)*num_pts +k+1)
if i < num_pts-1:
ids.append((i+1)*num_pts*num_pts+(j+1)*num_pts +k+1)
if i >0:
ids.append((i-1)*num_pts*num_pts+(j+1)*num_pts +k+1)
if j>0:
ids.append(i*num_pts*num_pts+(j-1)*num_pts +k+1)
if i < num_pts-1:
ids.append((i+1)*num_pts*num_pts+(j-1)*num_pts +k+1)
if i >0:
ids.append((i-1)*num_pts*num_pts+(j-1)*num_pts +k+1)
#if i<num_pts-1:
# ids.append((i+1)*num_pts*num_pts+(j+1)*num_pts +k)
for id_p in ids:
line = vtk.vtkLine()
line.GetPointIds().SetId(0, id1)
line.GetPointIds().SetId(1, id_p)
lines.InsertNextCell(line)
for i in range(num_pts):
for j in range(num_pts-1):
for k in range(num_pts):
id1 = i*num_pts*num_pts+j*num_pts +k
ids = []
ids.append(i*num_pts*num_pts+(j+1)*num_pts +k)
if diagonal:
if i<num_pts-1:
ids.append((i+1)*num_pts*num_pts+(j+1)*num_pts +k)
if i>0:
ids.append((i-1)*num_pts*num_pts+(j+1)*num_pts +k)
for id_p in ids:
line = vtk.vtkLine()
line.GetPointIds().SetId(0, id1)
line.GetPointIds().SetId(1, id_p)
lines.InsertNextCell(line)
for i in range(num_pts-1):
for j in range(num_pts):
for k in range(num_pts):
id1 = i*num_pts*num_pts+j*num_pts +k
ids = []
ids.append((i+1)*num_pts*num_pts+j*num_pts +k)
if diagonal:
if k<num_pts-1:
ids.append((i+1)*num_pts*num_pts+j*num_pts +k+1)
if k>0:
ids.append((i+1)*num_pts*num_pts+j*num_pts +k-1)
for id_p in ids:
line = vtk.vtkLine()
line.GetPointIds().SetId(0, id1)
line.GetPointIds().SetId(1, id_p)
lines.InsertNextCell(line)
grid.SetLines(lines)
return grid
def make_grid(num_pts, bounds, diagonal=True):
# compute bounding box of the template
min_bound, max_bound = bounds
# create control points
x = np.linspace(min_bound[0], max_bound[0], num_pts, endpoint=True)
y = np.linspace(min_bound[1], max_bound[1], num_pts, endpoint=True)
z = np.linspace(min_bound[2], max_bound[2], num_pts, endpoint=True)
# create vtk polydata
u, v, w = np.meshgrid(x, y, z, indexing='ij')
coords = np.column_stack((u.flatten(), v.flatten(), w.flatten()))
grid = make_grid_vtk(coords, diagonal)
#write_vtk_polydata(grid, os.path.join(os.path.dirname(__file__), 'grid_pts{}.vtk'.format(num_pts)))
return grid
def load_geometry_from_file(fn, target_node_num):
template = load_vtk_mesh(fn)
try:
region_ids = np.unique(vtk_to_numpy(template.GetCellData().GetArray('Scalars_'))).astype(int)
except:
region_ids = np.unique(vtk_to_numpy(template.GetCellData().GetArray('RegionId'))).astype(int)
print("Unique ids of template mesh: ", region_ids)
struct_list = []
node_list = [0]
total_node = 0
face_list = []
region_id = []
for i in region_ids:
poly_i = thresholdPolyData(template, 'Scalars_', (i, i),'cell')
if poly_i.GetNumberOfPoints() == 0:
poly_i = thresholdPolyData(template, 'RegionId', (i, i),'cell')
num_pts = poly_i.GetNumberOfPoints()
rate = max(0., 1. - float(target_node_num)/num_pts)
print("Target reduction rate of structure: ", i, target_node_num, num_pts, rate)
poly_i = decimation(poly_i, rate)
total_node += poly_i.GetNumberOfPoints()
node_list.append(total_node)
struct_list.append(poly_i)
cells = vtk_to_numpy(poly_i.GetPolys().GetData())
cells = cells.reshape(poly_i.GetNumberOfCells(), 4)
cells = cells[:,1:]
region_id += list(np.ones(poly_i.GetNumberOfCells())*i)
face_list.append(cells)
template_deci = appendPolyData(struct_list)
region_id_vtk = numpy_to_vtk(region_id)
region_id_vtk.SetName('Scalars_')
template_deci.GetCellData().AddArray(region_id_vtk)
return template_deci, node_list, face_list
def process_template(template_fn, target_node_num=None, template_im_fn=None, ref_template_fn=None):
if target_node_num is None:
template = load_vtk_mesh(template_fn)
node_list = [template.GetNumberOfPoints()]
face_list = vtk_to_numpy(template.GetPolys().GetData()).reshape(template.GetNumberOfCells(), 4)[:, 1:]
else:
template, node_list, face_list = load_geometry_from_file(template_fn, target_node_num)
if template_im_fn is None:
coords = vtk_to_numpy(template.GetPoints().GetData())
if ref_template_fn is not None:
ref = load_vtk_mesh(ref_template_fn)
ref_coords = vtk_to_numpy(ref.GetPoints().GetData())
ref_mean = np.mean(ref_coords, axis=0)
coords -= ref_mean
ref_coords -= ref_mean
ref_nrm = np.max(np.linalg.norm(ref_coords, axis=1))
coords /= ref_nrm * 1.8
ref_coords /= ref_nrm * 1.8
ref_coords += np.array([0.5, 0.5, 0.5])
else:
mean = np.mean(coords, axis=0)
coords -= mean
coords /= np.max(np.linalg.norm(coords, axis=1)) * 1.8
coords += np.array([0.5, 0.5, 0.5])
template.GetPoints().SetData(numpy_to_vtk(coords))
else:
SIZE = (128, 128, 128)
imgVol_o = sitk.ReadImage(template_im_fn)
img_center = np.array(imgVol_o.TransformContinuousIndexToPhysicalPoint(np.array(imgVol_o.GetSize())/2.0))
imgVol = resample_spacing(imgVol_o, template_size=SIZE, order=1)[0] # numpy array
img_center2 = np.array(imgVol.TransformContinuousIndexToPhysicalPoint(np.array(imgVol.GetSize())/2.0))
transform = build_transform_matrix(imgVol)
template = transform_polydata(template, img_center2-img_center, transform, SIZE)
coords = vtk_to_numpy(template.GetPoints().GetData())
#write_vtk_polydata(template, os.path.join(os.path.dirname(__file__), datetime.now().strftime("%m_%d_%Y_%H_%M_%S")+'_template_'+os.path.basename(template_fn)))
write_vtk_polydata(template, os.path.join(os.path.dirname(__file__), '../examples/template_with_veins_normalized.vtp'))
if ref_template_fn is not None:
bounds = (np.min(ref_coords, axis=0), np.max(ref_coords, axis=0))
else:
bounds = (np.min(coords, axis=0), np.max(coords, axis=0))
return template, node_list, face_list, bounds
from math import factorial
def comb(n, k):
return factorial(n) / factorial(k) / factorial(n - k)
def ffd(ctrl_pts, tmplt_coords, bounds):
'''
Ctrl points or d_cntrl points should be in world coordinates
Tmple_coords is in world coordinates and will be normalized to grid coordinates
'''
min_bound, max_bound = bounds
tmplt_coords = tmplt_coords - np.expand_dims(min_bound, axis=0)
tmplt_coords /= np.expand_dims(max_bound - min_bound, axis=0)
num_pts = int(round(len(ctrl_pts)**(1/3)))
# Bernstein tensor
B = []
for i in range(num_pts):
for j in range(num_pts):
for k in range(num_pts):
coeff = comb(num_pts-1, k) * comb(num_pts-1, j) * comb(num_pts-1, i)
b_list = coeff * ((1 - tmplt_coords[:,0]) ** (num_pts-1 - i)) * (tmplt_coords[:,0] ** i) \
* ((1 - tmplt_coords[:,1]) ** (num_pts-1 - j)) * (tmplt_coords[:,1] ** j)\
* ((1 - tmplt_coords[:,2]) ** (num_pts-1 - k)) * (tmplt_coords[:,2] ** k)
B.append(b_list)
B = np.stack(B, axis=1)
B[B<1e-5] = 0.
s_B = sp.csr_matrix(B, copy=True)
print("Number of elements in grid matrix: ", len(sparse_to_tuple(s_B)[1]))
output = s_B.dot(ctrl_pts)
#output = np.matmul(B, ctrl_pts)
return output, sparse_to_tuple(s_B)
def construct_bspline_volume(ctrl_pts, tmplt_coords, bounds, order=3):
min_bound, max_bound = bounds
num_pts = int(round(len(ctrl_pts)**(1/3)))
# create knot vectors
u, v, w = [], [], []
for i in range(num_pts+order+1):
coeff = min(max(0, i-order), num_pts-order)
u.append(min_bound[0] + coeff*(max_bound[0]-min_bound[0])/(num_pts-order))
v.append(min_bound[1] + coeff*(max_bound[1]-min_bound[1])/(num_pts-order))
w.append(min_bound[2] + coeff*(max_bound[2]-min_bound[2])/(num_pts-order))
#print("knots: ", u)
#print("knots: ", v)
#print("knots: ", w)
return construct_bspline_matrix(ctrl_pts, tmplt_coords, u, v, w, order)
def construct_bspline_matrix(ctrl_pts, tmplt_coords, u, v, w, order=3):
def _compute_basis(x, t, i, p):
if p == 0:
b = np.where((x >= t[i]-1e-5) & (x <= t[i+1]+1e-5), 1., 0.)
#b = np.where((x >= t[i]) & (x <= t[i+1]), 1., 0.)
return b
seg_i = t[i+p] - t[i]
seg_ip1 = (t[i+p+1] - t[i+1])
if np.isclose(seg_i, 0.):
left = np.zeros(x.shape)
else:
left = (x - t[i])/seg_i * _compute_basis(x, t, i, p-1)
if np.isclose(seg_ip1, 0.):
right = np.zeros(x.shape)
else:
right = (t[i+p+1] - x)/(t[i+p+1] - t[i+1]) * _compute_basis(x, t, i+1, p-1)
b = left + right
return b
num_pts = int(round(len(ctrl_pts)**(1/3)))
B = []
B = []
for i in range(num_pts):
for j in range(num_pts):
for k in range(num_pts):
basis_u = _compute_basis(tmplt_coords[:,0], u, i, order)
basis_v = _compute_basis(tmplt_coords[:,1], v, j, order)
basis_w = _compute_basis(tmplt_coords[:,2], w, k, order)
b_list = basis_u * basis_v * basis_w
B.append(b_list)
B = np.stack(B, axis=1)
if np.any(np.sum(B, axis=-1)==0):
raise RuntimeError("NaN in the B spline matrix!.")
#np.set_printoptions(threshold=np.inf)
#print(B)
B /= np.sum(B, axis=-1, keepdims=True)
B[B<1e-5] = 0.
B[np.isnan(B)] = 0.
#print("Check NaN: ", np.any(np.isnan(B)))
#print("Check Inf: ", np.any(np.isinf(B)))
#print(B)
s_B = sp.csr_matrix(B, copy=True)
print("Number of elements in grid matrix: ", len(sparse_to_tuple(s_B)[1]))
return s_B
def bspline(Basis_matrix, curr_grid, order=3):
if type(Basis_matrix)==tuple:
Basis_matrix = sp.csr_matrix((Basis_matrix[1], (Basis_matrix[0][:,0], Basis_matrix[0][:,1])), shape=Basis_matrix[-1])
output = Basis_matrix.dot(curr_grid)
return output
def sparse_to_tuple(sparse_mx):
"""Convert sparse matrix to tuple representation."""
def to_tuple(mx):
if not sp.isspmatrix_coo(mx):
mx = mx.tocoo()
coords = np.vstack((mx.row, mx.col)).transpose()
values = mx.data
shape = mx.shape
return coords, values, shape
if isinstance(sparse_mx, list):
for i in range(len(sparse_mx)):
sparse_mx[i] = to_tuple(sparse_mx[i])
else:
sparse_mx = to_tuple(sparse_mx)
return sparse_mx
def normalize_adj(adj):
"""Symmetrically normalize adjacency matrix."""
adj = sp.coo_matrix(adj)
rowsum = np.array(adj.sum(1))
d_inv_sqrt = np.power(rowsum, -0.5).flatten()
d_inv_sqrt[np.isinf(d_inv_sqrt)] = 0.
d_mat_inv_sqrt = sp.diags(d_inv_sqrt)
return adj.dot(d_mat_inv_sqrt).transpose().dot(d_mat_inv_sqrt).tocoo()
def preprocess_adj(adj):
"""Preprocessing of adjacency matrix for simple GCN model and conversion to tuple representation."""
adj_normalized = normalize_adj(adj + sp.eye(adj.shape[0]))
return sparse_to_tuple(adj_normalized)
def chebyshev_polynomials(adj, k):
"""Calculate Chebyshev polynomials up to order k. Return a list of sparse matrices (tuple representation)."""
print("Calculating Chebyshev polynomials up to order {}...".format(k))
adj_normalized = normalize_adj(adj)
laplacian = sp.eye(adj.shape[0]) - adj_normalized
largest_eigval, _ = eigsh(laplacian, 1, which='LM')
scaled_laplacian = (2. / largest_eigval[0]) * laplacian - sp.eye(adj.shape[0])
t_k = list()
t_k.append(sp.eye(adj.shape[0]))
t_k.append(scaled_laplacian)
def chebyshev_recurrence(t_k_minus_one, t_k_minus_two, scaled_lap):
s_lap = sp.csr_matrix(scaled_lap, copy=True)
return 2 * s_lap.dot(t_k_minus_one) - t_k_minus_two
for i in range(2, k+1):
t_k.append(chebyshev_recurrence(t_k[-1], t_k[-2], scaled_laplacian))
return sparse_to_tuple(t_k)
def transition_matrix_for_multi_level_grid(grid1, grid2, inverse=False):
"""
build a matrix B such that grid2 = B grid1
we assume grid2 is denser than grid1
if inverse, we can compute the left inverse (B^TB)^-1B^T
"""
grid1_min, grid1_max = np.min(grid1, axis=0, keepdims=True), np.max(grid1, axis=0, keepdims=True)
grid2_min, grid2_max = np.min(grid2, axis=0, keepdims=True), np.max(grid2, axis=0, keepdims=True)
grid2_nrmed = (grid2 - grid2_min)/grid2_max
grid1_nrmed = (grid1 - grid1_min)/grid1_max
# find steps
x_step = np.unique(grid1_nrmed[:, 0])
y_step = np.unique(grid1_nrmed[:, 1])
z_step = np.unique(grid1_nrmed[:, 2])
num_x, num_y, num_z = len(x_step), len(y_step), len(z_step)
steps = [x_step[1]-x_step[0], y_step[1]-y_step[0], z_step[1]-z_step[0]]
indices = np.round(grid2_nrmed/np.array(steps), decimals=5)
B = np.zeros((grid2_nrmed.shape[0], grid1_nrmed.shape[0]))
ind_f = np.floor(indices)
ind_c = np.ceil(indices)
ind_f = np.where(ind_f==ind_c, ind_f-1., ind_f)
mask = ind_f<0
ind_f[mask] = 0.
ind_c[mask] =1.
ind_corners = [ind_f, ind_c]
w_f = ind_c - indices
w_c = indices - ind_f
weight_corners = [w_f, w_c]
for i in range(len(ind_corners)):
x_comp = ind_corners[i][:,0]*num_y*num_z
for j in range(len(ind_corners)):
y_comp = ind_corners[j][:,1]*num_z
for k in range(len(ind_corners)):
z_comp = ind_corners[k][:,2]
ind = x_comp + y_comp + z_comp
weight = weight_corners[i][:,0]*weight_corners[j][:,1]*weight_corners[k][:,2]
B[range(grid2_nrmed.shape[0]), ind.astype(int)] = weight
# debug:
test = np.sum(np.matmul(B, grid1) - grid2)
print("Test error: ", test)
if inverse:
inv = np.linalg.inv(np.matmul(B.transpose(), B))
B = np.matmul(inv, B.transpose())
test = np.sum(np.matmul(B, grid2) - grid1)
print("Inverse test error: ", test)
return B
else:
s_B = sp.csr_matrix(B, copy=True)
print("Number of elements in upsample matrix: ", len(sparse_to_tuple(s_B)[1]))
return sparse_to_tuple(s_B)
def transition_matrix_for_multi_level_grid_gaussion(grid1, grid2):
"""
build a matrix B such that grid2 = B grid1
we assume grid2 is denser than grid1
if inverse, we can compute the left inverse (B^TB)^-1B^T
"""
grid1_min, grid1_max = np.min(grid1, axis=0, keepdims=True), np.max(grid1, axis=0, keepdims=True)
grid2_min, grid2_max = np.min(grid2, axis=0, keepdims=True), np.max(grid2, axis=0, keepdims=True)
grid2_nrmed = (grid2 - grid2_min)/grid2_max
grid1_nrmed = (grid1 - grid1_min)/grid1_max
# find steps
x_step = np.unique(grid2_nrmed[:, 0])
y_step = np.unique(grid2_nrmed[:, 1])
z_step = np.unique(grid2_nrmed[:, 2])
num_x, num_y, num_z = len(x_step), len(y_step), len(z_step)
B = np.zeros((grid2.shape[0], grid1.shape[0]))
#assum the grid distribution is uniform
x_space = np.mean(x_step[1:] - x_step[:-1])/3.
y_space = np.mean(y_step[1:] - y_step[:-1])/3.
z_space = np.mean(z_step[1:] - z_step[:-1])/3.
co_var = np.diag([x_space, y_space, z_space])
inv_co_var = np.linalg.inv(co_var)
for i in range(grid2.shape[0]):
curr_pt = np.expand_dims(grid2[i, :], axis=0)
prob = np.sum(np.matmul(grid1-curr_pt, inv_co_var)*(grid1-curr_pt), axis=-1)
B[i,:] = np.squeeze(prob)
B = np.exp(-0.5*B)/np.sqrt((2*np.pi)**3*np.linalg.det(co_var))
B = B/np.max(B, axis=-1, keepdims=True)
rej = B * np.random.rand(*B.shape)
sort_rej = np.argsort(rej, axis=-1)
thres = np.expand_dims(rej[range(B.shape[0]), sort_rej[:, -32]], axis=-1)
B[np.less(rej, thres)] = 0.
B = B/np.sum(B, axis=-1, keepdims=True)
print("CHECK min, max: ", np.min(B[B>0.]), | np.mean(B[B>0.]) | numpy.mean |
import json
import os, time
from multiprocessing import Process
from malib.agents.agent_factory import *
from malib.environments import DifferentialGame
from malib.environments.fortattack import make_fortattack_env
from malib.logger.utils import set_logger
from malib.samplers.sampler import SingleSampler, MASampler
from malib.trainers import SATrainer, MATrainer
from malib.utils.random import set_seed
import numpy as np, pickle
def svd_sol(A, b):
U, sigma, Vt = np.linalg.svd(A)
sigma[sigma<1e-10] = 0
sigma_reci = [(1/s if s!=0 else 0) for s in sigma]
sigma_reci = | np.diag(sigma_reci) | numpy.diag |
import numpy as np
import unittest
import discretize
from discretize.utils import volume_average
from numpy.testing import assert_array_equal, assert_allclose
class TestVolumeAverage(unittest.TestCase):
def test_tensor_to_tensor(self):
h1 = np.random.rand(16)
h1 /= h1.sum()
h2 = np.random.rand(16)
h2 /= h2.sum()
h1s = []
h2s = []
for i in range(3):
print(f"Tensor to Tensor {i+1}D: ", end="")
h1s.append(h1)
h2s.append(h2)
mesh1 = discretize.TensorMesh(h1s)
mesh2 = discretize.TensorMesh(h2s)
in_put = np.random.rand(mesh1.nC)
out_put = np.empty(mesh2.nC)
# test the three ways of calling...
out1 = volume_average(mesh1, mesh2, in_put, out_put)
assert_array_equal(out1, out_put)
out2 = volume_average(mesh1, mesh2, in_put)
assert_allclose(out1, out2)
Av = volume_average(mesh1, mesh2)
out3 = Av @ in_put
assert_allclose(out1, out3)
vol1 = np.sum(mesh1.vol * in_put)
vol2 = np.sum(mesh2.vol * out3)
print(vol1, vol2)
self.assertAlmostEqual(vol1, vol2)
def test_tree_to_tree(self):
h1 = np.random.rand(16)
h1 /= h1.sum()
h2 = np.random.rand(16)
h2 /= h2.sum()
h1s = [h1]
h2s = [h2]
insert_1 = [0.25]
insert_2 = [0.75]
for i in range(1, 3):
print(f"Tree to Tree {i+1}D: ", end="")
h1s.append(h1)
h2s.append(h2)
insert_1.append(0.25)
insert_2.append(0.75)
mesh1 = discretize.TreeMesh(h1s)
mesh1.insert_cells([insert_1], [4])
mesh2 = discretize.TreeMesh(h2s)
mesh2.insert_cells([insert_2], [4])
in_put = np.random.rand(mesh1.nC)
out_put = np.empty(mesh2.nC)
# test the three ways of calling...
out1 = volume_average(mesh1, mesh2, in_put, out_put)
assert_array_equal(out1, out_put)
out2 = volume_average(mesh1, mesh2, in_put)
assert_allclose(out1, out2)
Av = volume_average(mesh1, mesh2)
out3 = Av @ in_put
assert_allclose(out1, out3)
vol1 = np.sum(mesh1.vol * in_put)
vol2 = np.sum(mesh2.vol * out3)
print(vol1, vol2)
self.assertAlmostEqual(vol1, vol2)
def test_tree_to_tensor(self):
h1 = np.random.rand(16)
h1 /= h1.sum()
h2 = np.random.rand(16)
h2 /= h2.sum()
h1s = [h1]
h2s = [h2]
insert_1 = [0.25]
for i in range(1, 3):
print(f"Tree to Tensor {i+1}D: ", end="")
h1s.append(h1)
h2s.append(h2)
insert_1.append(0.25)
mesh1 = discretize.TreeMesh(h1s)
mesh1.insert_cells([insert_1], [4])
mesh2 = discretize.TensorMesh(h2s)
in_put = np.random.rand(mesh1.nC)
out_put = np.empty(mesh2.nC)
# test the three ways of calling...
out1 = volume_average(mesh1, mesh2, in_put, out_put)
assert_array_equal(out1, out_put)
out2 = volume_average(mesh1, mesh2, in_put)
assert_allclose(out1, out2)
Av = volume_average(mesh1, mesh2)
out3 = Av @ in_put
assert_allclose(out1, out3)
vol1 = np.sum(mesh1.vol * in_put)
vol2 = np.sum(mesh2.vol * out3)
print(vol1, vol2)
self.assertAlmostEqual(vol1, vol2)
def test_tensor_to_tree(self):
h1 = np.random.rand(16)
h1 /= h1.sum()
h2 = np.random.rand(16)
h2 /= h2.sum()
h1s = [h1]
h2s = [h2]
insert_2 = [0.75]
for i in range(1, 3):
print(f"Tensor to Tree {i+1}D: ", end="")
h1s.append(h1)
h2s.append(h2)
insert_2.append(0.75)
mesh1 = discretize.TensorMesh(h1s)
mesh2 = discretize.TreeMesh(h2s)
mesh2.insert_cells([insert_2], [4])
in_put = np.random.rand(mesh1.nC)
out_put = np.empty(mesh2.nC)
# test the three ways of calling...
out1 = volume_average(mesh1, mesh2, in_put, out_put)
assert_array_equal(out1, out_put)
out2 = volume_average(mesh1, mesh2, in_put)
assert_allclose(out1, out2)
Av = volume_average(mesh1, mesh2)
out3 = Av @ in_put
assert_allclose(out1, out3)
vol1 = np.sum(mesh1.vol * in_put)
vol2 = np.sum(mesh2.vol * out3)
print(vol1, vol2)
self.assertAlmostEqual(vol1, vol2)
def test_errors(self):
h1 = np.random.rand(16)
h1 /= h1.sum()
h2 = np.random.rand(16)
h2 /= h2.sum()
mesh1D = discretize.TensorMesh([h1])
mesh2D = discretize.TensorMesh([h1, h1])
mesh3D = discretize.TensorMesh([h1, h1, h1])
hr = np.r_[1, 1, 0.5]
hz = np.r_[2, 1]
meshCyl = discretize.CylMesh([hr, 1, hz], np.r_[0.0, 0.0, 0.0])
mesh2 = discretize.TreeMesh([h2, h2])
mesh2.insert_cells([0.75, 0.75], [4])
with self.assertRaises(TypeError):
# Gives a wrong typed object to the function
volume_average(mesh1D, h1)
with self.assertRaises(NotImplementedError):
# Gives a wrong typed mesh
volume_average(meshCyl, mesh2)
with self.assertRaises(ValueError):
# Gives mismatching mesh dimensions
volume_average(mesh2D, mesh3D)
model1 = np.random.randn(mesh2D.nC)
bad_model1 = np.random.randn(3)
bad_model2 = np.random.rand(1)
# gives input values with incorrect lengths
with self.assertRaises(ValueError):
volume_average(mesh2D, mesh2, bad_model1)
with self.assertRaises(ValueError):
volume_average(mesh2D, mesh2, model1, bad_model2)
def test_tree_to_tree_same_base(self):
h1 = np.random.rand(16)
h1 /= h1.sum()
h1s = [h1]
insert_1 = [0.25]
insert_2 = [0.75]
for i in range(1, 3):
print(f"Tree to Tree {i+1}D: same base", end="")
h1s.append(h1)
insert_1.append(0.25)
insert_2.append(0.75)
mesh1 = discretize.TreeMesh(h1s)
mesh1.insert_cells([insert_1], [4])
mesh2 = discretize.TreeMesh(h1s)
mesh2.insert_cells([insert_2], [4])
in_put = np.random.rand(mesh1.nC)
out_put = np.empty(mesh2.nC)
# test the three ways of calling...
out1 = volume_average(mesh1, mesh2, in_put, out_put)
assert_array_equal(out1, out_put)
out2 = volume_average(mesh1, mesh2, in_put)
assert_allclose(out1, out2)
Av = volume_average(mesh1, mesh2)
out3 = Av @ in_put
assert_allclose(out1, out3)
vol1 = np.sum(mesh1.vol * in_put)
vol2 = np.sum(mesh2.vol * out3)
print(vol1, vol2)
self.assertAlmostEqual(vol1, vol2)
def test_tree_to_tensor_same_base(self):
h1 = np.random.rand(16)
h1 /= h1.sum()
h1s = [h1]
insert_1 = [0.25]
for i in range(1, 3):
print(f"Tree to Tensor {i+1}D same base: ", end="")
h1s.append(h1)
insert_1.append(0.25)
mesh1 = discretize.TreeMesh(h1s)
mesh1.insert_cells([insert_1], [4])
mesh2 = discretize.TensorMesh(h1s)
in_put = np.random.rand(mesh1.nC)
out_put = np.empty(mesh2.nC)
# test the three ways of calling...
out1 = volume_average(mesh1, mesh2, in_put, out_put)
assert_array_equal(out1, out_put)
out2 = volume_average(mesh1, mesh2, in_put)
assert_allclose(out1, out2)
Av = volume_average(mesh1, mesh2)
out3 = Av @ in_put
assert_allclose(out1, out3)
vol1 = np.sum(mesh1.vol * in_put)
vol2 = np.sum(mesh2.vol * out3)
print(vol1, vol2)
self.assertAlmostEqual(vol1, vol2)
def test_tensor_to_tree_same_base(self):
h1 = np.random.rand(16)
h1 /= h1.sum()
h1s = [h1]
insert_2 = [0.75]
for i in range(1, 3):
print(f"Tensor to Tree {i+1}D same base: ", end="")
h1s.append(h1)
insert_2.append(0.75)
mesh1 = discretize.TensorMesh(h1s)
mesh2 = discretize.TreeMesh(h1s)
mesh2.insert_cells([insert_2], [4])
in_put = np.random.rand(mesh1.nC)
out_put = np.empty(mesh2.nC)
# test the three ways of calling...
out1 = volume_average(mesh1, mesh2, in_put, out_put)
assert_array_equal(out1, out_put)
out2 = volume_average(mesh1, mesh2, in_put)
assert_allclose(out1, out2)
Av = volume_average(mesh1, mesh2)
out3 = Av @ in_put
assert_allclose(out1, out3)
vol1 = np.sum(mesh1.vol * in_put)
vol2 = np.sum(mesh2.vol * out3)
print(vol1, vol2)
self.assertAlmostEqual(vol1, vol2)
def test_tensor_to_tensor_sub(self):
h1 = np.ones(32)
h2 = np.ones(16)
h1s = []
h2s = []
for i in range(3):
print(f"Tensor to smaller Tensor {i+1}D: ", end="")
h1s.append(h1)
h2s.append(h2)
mesh1 = discretize.TensorMesh(h1s)
mesh2 = discretize.TensorMesh(h2s)
in_put = np.random.rand(mesh1.nC)
out_put = np.empty(mesh2.nC)
# test the three ways of calling...
out1 = volume_average(mesh1, mesh2, in_put, out_put)
assert_array_equal(out1, out_put)
out2 = volume_average(mesh1, mesh2, in_put)
assert_allclose(out1, out2)
Av = volume_average(mesh1, mesh2)
out3 = Av @ in_put
assert_allclose(out1, out3)
# get cells in extent of smaller mesh
cells = mesh1.gridCC < [16] * (i + 1)
if i > 0:
cells = np.all(cells, axis=1)
vol1 = np.sum(mesh1.vol[cells] * in_put[cells])
vol2 = np.sum(mesh2.vol * out3)
print(vol1, vol2)
self.assertAlmostEqual(vol1, vol2)
def test_tree_to_tree_sub(self):
h1 = np.ones(32)
h2 = np.ones(16)
h1s = [h1]
h2s = [h2]
insert_1 = [12]
insert_2 = [4]
for i in range(1, 3):
print(f"Tree to smaller Tree {i+1}D: ", end="")
h1s.append(h1)
h2s.append(h2)
insert_1.append(12)
insert_2.append(4)
mesh1 = discretize.TreeMesh(h1s)
mesh1.insert_cells([insert_1], [4])
mesh2 = discretize.TreeMesh(h2s)
mesh2.insert_cells([insert_2], [4])
in_put = np.random.rand(mesh1.nC)
out_put = np.empty(mesh2.nC)
# test the three ways of calling...
out1 = volume_average(mesh1, mesh2, in_put, out_put)
assert_array_equal(out1, out_put)
out2 = volume_average(mesh1, mesh2, in_put)
assert_allclose(out1, out2)
Av = volume_average(mesh1, mesh2)
out3 = Av @ in_put
assert_allclose(out1, out3)
# get cells in extent of smaller mesh
cells = mesh1.gridCC < [16] * (i + 1)
if i > 0:
cells = np.all(cells, axis=1)
vol1 = np.sum(mesh1.vol[cells] * in_put[cells])
vol2 = np.sum(mesh2.vol * out3)
print(vol1, vol2)
self.assertAlmostEqual(vol1, vol2)
def test_tree_to_tensor_sub(self):
h1 = np.ones(32)
h2 = np.ones(16)
h1s = [h1]
insert_1 = [12]
h2s = [h2]
for i in range(1, 3):
print(f"Tree to smaller Tensor {i+1}D: ", end="")
h1s.append(h1)
h2s.append(h2)
insert_1.append(12)
mesh1 = discretize.TreeMesh(h1s)
mesh1.insert_cells([insert_1], [4])
mesh2 = discretize.TensorMesh(h2s)
in_put = np.random.rand(mesh1.nC)
out_put = np.empty(mesh2.nC)
# test the three ways of calling...
out1 = volume_average(mesh1, mesh2, in_put, out_put)
assert_array_equal(out1, out_put)
out2 = volume_average(mesh1, mesh2, in_put)
assert_allclose(out1, out2)
Av = volume_average(mesh1, mesh2)
out3 = Av @ in_put
assert_allclose(out1, out3)
# get cells in extent of smaller mesh
cells = mesh1.gridCC < [16] * (i + 1)
if i > 0:
cells = np.all(cells, axis=1)
vol1 = np.sum(mesh1.vol[cells] * in_put[cells])
vol2 = np.sum(mesh2.vol * out3)
print(vol1, vol2)
self.assertAlmostEqual(vol1, vol2)
def test_tensor_to_tree_sub(self):
h1 = np.ones(32)
h2 = np.ones(16)
h1s = [h1]
h2s = [h2]
insert_2 = [4]
for i in range(1, 3):
print(f"Tensor to smaller Tree {i+1}D: ", end="")
h1s.append(h1)
h2s.append(h2)
insert_2.append(4)
mesh1 = discretize.TensorMesh(h1s)
mesh2 = discretize.TreeMesh(h2s)
mesh2.insert_cells([insert_2], [4])
in_put = np.random.rand(mesh1.nC)
out_put = np.empty(mesh2.nC)
# test the three ways of calling...
out1 = volume_average(mesh1, mesh2, in_put, out_put)
assert_array_equal(out1, out_put)
out2 = volume_average(mesh1, mesh2, in_put)
assert_allclose(out1, out2)
Av = volume_average(mesh1, mesh2)
out3 = Av @ in_put
| assert_allclose(out1, out3) | numpy.testing.assert_allclose |
import os
os.chdir('C:/Users/Martim_Pc/Desktop/DACO_fin')
from Unet import Unet
import numpy as np
import cv2.cv2 as cv2
from skimage.measure import label, regionprops
from skimage.transform import downscale_local_mean,hough_ellipse
from skimage.filters.rank import entropy, mean
from skimage.filters import gabor, gabor_kernel
from skimage.morphology import disk, skeletonize, thin
from skimage.feature import local_binary_pattern, greycomatrix, greycoprops
from skimage.draw import ellipse_perimeter
from skimage import data, color, img_as_ubyte
from matplotlib import pyplot as plt
import pickle
import math
import time
from sklearn.naive_bayes import GaussianNB
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC
from scipy.ndimage.filters import maximum_filter
from scipy.ndimage.morphology import distance_transform_edt
def myShowImage(img,name = "from_show_function"):
cv2.imshow(name, img)
cv2.waitKey(0) # waits until a key is pressed
cv2.destroyAllWindows() # destroys the window showing image
return
def removeBackground(img):
maskRed = img[...,0]>30
maskGreen = img[...,1]>30
maskBlue = img[...,2]>30
mask1 = np.logical_or(maskRed,maskGreen)
maskFinal = np.logical_or(mask1,maskBlue)
zeros = np.zeros(img.shape)
zeros[maskFinal] = img[maskFinal]
zeros = zeros.astype(np.uint8)
img = np.copy(zeros)
return img
testImages = ['20051020_44982_0100_PP.tif',
'20051019_38557_0100_PP.tif',
'20051213_62383_0100_PP.tif',
'IDRiD_14.jpg',
'OD0375EY.JPG']
def getVesselsUtils(imgPath):
img = cv2.imread(imgPath)#,cv2.CV_8UC1)
img = removeBackground(img)
scale_percent = 25 # percent of original size
width = int(img.shape[1] * scale_percent / 100)
height = int(img.shape[0] * scale_percent / 100)
dim = (width, height)
# resize image
resized = cv2.resize(img, dim, interpolation = cv2.INTER_AREA) # BGR - blue: 0; green: 1; red: 2
resized = resized.astype(np.uint8)
clahe = cv2.createCLAHE(clipLimit=1, tileGridSize=(8, 8))
img_out1 = clahe.apply(resized[...,1])
kernel_ones = np.ones([25,25],np.uint8)
bh_1_cv = cv2.morphologyEx(img_out1, cv2.MORPH_BLACKHAT,kernel_ones)
int_vs = clahe.apply(bh_1_cv)
_,thresh2 = cv2.threshold(int_vs,60,255,cv2.THRESH_BINARY) # thresh2 is vessels segmentation used in OD segmentation
labels, _ = label(thresh2, neighbors=8, background = 0, return_num = True)
regions = regionprops(labels)
for region in regions:
value = labels[region['coords'][0][0],region['coords'][0][1]]
#circularity = (4*math.pi*region['area']) / (region['perimeter']**2)
bboxAreRel = region['area']/region['bbox_area']
if region['area'] < 10 or (bboxAreRel > 0.35): #circularity > 0.3 and
removeIndexs = np.where(labels==value)
labels[removeIndexs[0],removeIndexs[1]] = 0
labels[labels > 0] = 1
labelsImg = np.multiply(np.array(labels, np.uint8),255) # labelsImg = segmented relevant vessels
myShowImage(labelsImg)
# get skeleton of image
doublT_small = downscale_local_mean(labels,(2,2))
myShowImage(doublT_small)
skeleton = skeletonize(doublT_small)
skel = skeleton * 1
skel = skel.astype(np.uint8)
skel = np.multiply(skel,255)
myShowImage(skel)
threshAcc = 40
for k in range(1,6):
try:
#fig, ax = plt.subplots(ncols=1, nrows=1, figsize=(10, 4))
#doublT_small = color.gray2rgb(img_as_ubyte(doublT_small))
tic = time.time()
result = hough_ellipse(skeleton, accuracy=20, threshold=threshAcc, min_size=50, max_size=None) # thresh = 30
result.sort(order='accumulator')
aSizeResult_Arr = np.array(result['a'])
bSizeResult_Arr = np.array(result['b'])
aIndex = np.where(aSizeResult_Arr > 0)
bIndex = np.where(bSizeResult_Arr > 0)
relevantIndexs = np.intersect1d(aIndex,bIndex)
axisRelation = np.divide(aSizeResult_Arr[relevantIndexs],bSizeResult_Arr[relevantIndexs])
goodRelationIndexs = np.where(axisRelation<1.5)
ellipsLargest = np.max(relevantIndexs[goodRelationIndexs])
toc = time.time()
ellapsedTime = toc-tic
print(ellapsedTime)
best = list(result[ellipsLargest])
yc, xc, a, b = [int(round(x)) for x in best[1:5]]
orientation = best[5]
#print(best[0])
# Draw the ellipse on the original image
cy, cx = ellipse_perimeter(yc, xc, a, b, orientation)
# Draw the edge (white) and the resulting ellipse (red)
outsideX = np.where(cx>doublT_small.shape[1])
preX = np.where(cx<0)
outsideY = np.where(cy>doublT_small.shape[0])
preY = np.where(cy<0)
cx[outsideX] = doublT_small.shape[1]
cy[outsideY] = doublT_small.shape[0]
cx[preX] = 0
cy[preY] = 0
break
except:
threshAcc = threshAcc - 10
if k == 5:
threshAcc = threshAcc + 5
ellipseMask = np.zeros(doublT_small.shape)
ellipseMask[abs(cy-1),abs(cx-1)] = 1
elipsResized = cv2.resize(ellipseMask, dsize=dim, interpolation=cv2.INTER_CUBIC)
#elipsResized = np.average(elipsResized,axis = 2) # 3 channels -> 1 channel
elipsResized[elipsResized>0.5] = 1
elipsResized[elipsResized<1] = 0
elipsResized = thin(elipsResized)
elipsResized = elipsResized*1
elipsImage = (elipsResized*255).astype(np.uint8)
myShowImage(elipsImage)
entr_img = entropy(labelsImg, disk(5))
myShowImage(entr_img)
vessels = np.copy(thresh2)
ellipse = np.copy(elipsResized)
entropyVessels = np.copy(entr_img)
return vessels, entropyVessels, ellipse
def getDistanceArray(height,width):
indices_Arr = np.indices((height,width)).transpose((1,2,0))
centreCoords = np.array([height/2,width/2])
distance_Arr = np.sqrt(np.add(np.power(indices_Arr[...,0]-centreCoords[0],2),np.power(indices_Arr[...,1]-centreCoords[1],2)))
normDistance_Arr = distance_Arr / np.max(distance_Arr)
normDistanceColumn_Arr = np.squeeze(normDistance_Arr.reshape([1,normDistance_Arr.shape[0]*normDistance_Arr.shape[1]])).T
return normDistanceColumn_Arr
def reshapeFeature(img,featureSize,normalize=True):
feature = np.squeeze(img.reshape([1,featureSize])).T
if normalize:
feature = (feature-np.average(feature)) / np.std(feature)
return feature
def newBBcoords(img_pred_Log,test_image):
# returns coordinates of the bounding box for the region with the largest area
kernel_ones = np.ones([3,3],np.uint8)
closing_Log = cv2.morphologyEx(img_pred_Log, cv2.MORPH_CLOSE, kernel_ones)
labelsLog, numLog = label(closing_Log, neighbors=8, background = 0, return_num = True)
regionsLog = regionprops(labelsLog)
areasLog = [region['area'] for region in regionsLog]
areasLogArr = np.array(areasLog)
maxIndex = np.argmax(areasLogArr)
value = labelsLog[regionsLog[maxIndex]['coords'][0][0],regionsLog[maxIndex]['coords'][0][1]]
labelsLog[labelsLog != value] = 0
labelsLog[labelsLog == value] = 1
labelsImg = np.multiply(np.array(labelsLog, np.uint8),255)
#myShowImage(labelsImg)
sizeBoxX = regionsLog[maxIndex]['bbox'][3]-regionsLog[maxIndex]['bbox'][1]
sizeBoxY = regionsLog[maxIndex]['bbox'][2]-regionsLog[maxIndex]['bbox'][0]
coordsBbox = list(regionsLog[maxIndex]['bbox'])
if sizeBoxX <= 0.4 * img_pred_Log.shape[1]:
newSizeBoxX = 0.3 / (sizeBoxX / img_pred_Log.shape[1])
coordsBbox[1] = coordsBbox[1] - sizeBoxX*(0.5*(newSizeBoxX-1))
coordsBbox[3] = coordsBbox[3] + sizeBoxX*(0.5*(newSizeBoxX-1))
if sizeBoxY <= 0.4 * img_pred_Log.shape[0]:
newSizeBoxY = 0.5 / (sizeBoxY / img_pred_Log.shape[0])
coordsBbox[0] = coordsBbox[0] - sizeBoxY*(0.5*(newSizeBoxY-1))
coordsBbox[2] = coordsBbox[2] + sizeBoxY*(0.5*(newSizeBoxY-1))
if coordsBbox[0] < 0:
coordsBbox[0] = 0
if coordsBbox[1] < 0:
coordsBbox[1] = 0
if coordsBbox[2] > test_image.shape[0]:
coordsBbox[2] = test_image.shape[0] - 1
if coordsBbox[3] > test_image.shape[1]:
coordsBbox[3] = test_image.shape[1] - 1
coordsBboxInt = [round(x) for x in coordsBbox]
return coordsBboxInt
def getLargestAreaEcentroid(img_pred_Log):
# returns mask with the regions with the largest area, coords of centroid and radius
kernel_ones = np.ones([3,3],np.uint8)
closing_Log = cv2.morphologyEx(img_pred_Log, cv2.MORPH_CLOSE, kernel_ones)
labelsLog, numLog = label(closing_Log, neighbors=8, background = 0, return_num = True)
regionsLog = regionprops(labelsLog)
areasLog = [region['area'] for region in regionsLog]
areasLogArr = np.array(areasLog)
maxIndex = np.argmax(areasLogArr)
value = labelsLog[regionsLog[maxIndex]['coords'][0][0],regionsLog[maxIndex]['coords'][0][1]]
labelsLog[labelsLog != value] = 0
labelsLog[labelsLog == value] = 1
centreCoords = np.round(regionsLog[maxIndex]['centroid'])
centreCoords = centreCoords.astype(np.uint)
radius = (regionsLog[maxIndex]['major_axis_length'] + regionsLog[maxIndex]['minor_axis_length']) / 4
colsCoord = [regionsLog[maxIndex]['bbox'][1],regionsLog[maxIndex]['bbox'][3]]
labelsArr = np.array(labelsLog)
return labelsArr, centreCoords, radius, colsCoord
def gaborFilter(img_in):
filtered_ims = []
for theta in range(4):
theta = theta / 4. * np.pi
for sigma in (6, 7):
for frequency in (0.06, 0.07):
filt_real, _ = gabor(img_in, frequency, theta=theta,sigma_x=sigma, sigma_y=sigma) # _ = imaginary part
filtered_ims.append(filt_real)
filtered_ims_arr = np.array(filtered_ims)
return filtered_ims_arr
def getFeature2(greenChannel):
filtered_ims_arr = gaborFilter(greenChannel)
mean = filtered_ims_arr[0]
for k in range(1,16):
mean = np.add(mean,filtered_ims_arr[k])
mean = np.divide(mean,16)
mean = mean.astype(np.uint8)
clahe = cv2.createCLAHE(clipLimit=4, tileGridSize=(8, 8))
imgContrasted = clahe.apply(mean)
maxVal = np.max(imgContrasted)
feature2 = np.multiply(np.divide(imgContrasted,maxVal),255)
feature2 = feature2.astype(np.uint8)
return feature2
def getFeature3(elipsResized,Od_res,resized):
Od_uint8 = np.copy(Od_res.astype(np.uint8))
Od_uint8 = np.divide(Od_uint8,np.max(Od_uint8)).astype(np.uint8)
testDistance = distance_transform_edt(1 - Od_uint8)
testDistance = np.multiply(testDistance,255/np.max(testDistance))
testDistance = testDistance.astype(np.uint8)
distanceToOd = 255-testDistance
distanceToOd[distanceToOd >220] = 255
distanceToOd[distanceToOd <=220] = 0
vesselsRelevantLine = np.logical_and(distanceToOd,elipsResized)
vesselsRelevantLine = vesselsRelevantLine*1
distanceToVesselLine = distance_transform_edt(1 - vesselsRelevantLine)
distanceToVesselLine = np.multiply(distanceToVesselLine,255/np.max(distanceToVesselLine))
distanceToVesselLine = distanceToVesselLine.astype(np.uint8)
distanceToVesselLine = 255-distanceToVesselLine
distanceToVesselLine[distanceToVesselLine >220] = 255
distanceToVesselLine[distanceToVesselLine <=220] = 0
distanceToVesselLine = np.logical_or(distanceToVesselLine,Od_uint8)
greenChannel = np.copy(resized[...,1])
vesselLine_indxs=np.where(distanceToVesselLine!=0)
#greenChannel[vesselLine_indxs] = 0
clahe = cv2.createCLAHE(clipLimit=4, tileGridSize=(8, 8))
greenContrasted = clahe.apply(greenChannel)
greenContrasted = np.multiply(greenContrasted,255/ | np.max(greenContrasted) | numpy.max |
import numpy as np
import numpy.linalg as la
import scipy.interpolate as inter
import scipy.optimize as opt
from numpy.polynomial.legendre import leggauss
import numpy.random as ra
from neml.nlsolvers import MaximumIterations, MaximumSubdivisions, newton, scalar_newton
class Driver(object):
"""
Superclass of all drivers, basically just sets up history and reports
results.
"""
def __init__(self, model, verbose = False, rtol = 1.0e-6, atol = 1.0e-10,
miter = 25, T_init = 0.0, no_thermal_strain = False):
"""
Parameters:
model: material model to play with
verbose: verbose output
rtol: relative tolerance, where needed
atol: absolute tolerance, where needed
miter: maximum iterations, where needed
"""
self.model = model
self.verbose = verbose
self.rtol = rtol
self.atol = atol
self.miter = miter
self.nts = no_thermal_strain
self.stress_int = [np.zeros((6,))]
self.stored_int = [self.model.init_store()]
self.T_int = [T_init]
self.t_int = [0.0]
self.u_int = [0.0]
self.p_int = [0.0]
@property
def stress(self):
return np.array(self.stress_int)
@property
def stored(self):
return np.array(self.stored_int)
@property
def history(self):
return self.stored[:,:self.model.nhist]
@property
def T(self):
return np.array(self.T_int)
@property
def t(self):
return np.array(self.t_int)
@property
def u(self):
return np.array(self.u_int)
@property
def p(self):
return np.array(self.p_int)
class Driver_sd(Driver):
"""
Superclass of generic small strain drivers, contains generic step methods.
"""
def __init__(self, *args, **kwargs):
"""
Parameters:
model: material model to play with
verbose: verbose output
rtol: relative tolerance, where needed
atol: absolute tolerance, where needed
miter: maximum iterations, where needed
"""
super(Driver_sd, self).__init__(*args, **kwargs)
self.strain_int = [np.zeros((6,))]
self.thermal_strain_int = [np.zeros((6,))]
self.mechanical_strain_int = [np.zeros((6,))]
def solve_try(self, RJ, x0, extra = []):
"""
Try several different nonlinear solvers in the hope that at least
one will converge
Parameters:
RJ: function that returns the residual equations and associated
Jacobian
x0: initial guess
extra: list of extra solver functions of the type below
"""
def s1(x0i):
try:
x = newton(RJ, x0i, verbose = self.verbose,
rtol = self.rtol, atol = self.atol, miter = self.miter)
return x, True
except Exception:
return np.zeros((12,)), False
def s2(x0i):
try:
res = opt.root(RJ, x0i, jac = True, method = 'lm')
return res.x, res.success
except Exception:
return np.zeros((12,)), False
def s3(x0i):
try:
x = newton(RJ, x0i, verbose = self.verbose,
rtol = self.rtol, atol = self.atol, miter = self.miter,
linesearch = 'backtracking')
return x, True
except Exception:
return np.zeros((12,)), False
solvers = [s1,s3]
guesses = [x0] + extra
success = False
for xi in guesses:
for solv in solvers:
x, success = solv(xi)
if success:
break
if success:
break
if not success:
raise MaximumIterations()
return x
@property
def strain(self):
return np.array(self.strain_int)
@property
def thermal_strain(self):
return np.array(self.thermal_strain_int)
@property
def mechanical_strain(self):
return np.array(self.mechanical_strain_int)
def update_thermal_strain(self, T_np1):
"""
Move the thermal strains to the next step
Parameters:
T_np1: next temperature
"""
if self.nts:
return np.zeros((6,))
else:
dT = T_np1 - self.T_int[-1]
a_np1 = self.model.alpha(T_np1)
a_n = self.model.alpha(self.T_int[-1])
return self.thermal_strain_int[-1] + dT * (a_np1 + a_n) / 2 * np.array([1.0,1,1,0,0,0])
def strain_step(self, e_np1, t_np1, T_np1):
"""
Take a strain-controlled step
Parameters:
e_np1: next strain
t_np1: next time
T_np1: next temperature
"""
enext = self.update_thermal_strain(T_np1)
s_np1, h_np1, A_np1, u_np1, p_np1 = self.model.update_sd(e_np1 - enext,
self.mechanical_strain_int[-1],
T_np1, self.T_int[-1], t_np1, self.t_int[-1], self.stress_int[-1],
self.stored_int[-1], self.u_int[-1], self.p_int[-1])
self.strain_int.append(np.copy(e_np1))
self.mechanical_strain_int.append(e_np1 - enext)
self.thermal_strain_int.append(enext)
self.stress_int.append(np.copy(s_np1))
self.stored_int.append(np.copy(h_np1))
self.T_int.append(T_np1)
self.t_int.append(t_np1)
self.u_int.append(u_np1)
self.p_int.append(p_np1)
def stress_step(self, s_np1, t_np1, T_np1):
"""
Take a stress-controlled step
Parameters:
s_np1: next stress
t_np1: next time
T_np1: next temperature
"""
enext = self.update_thermal_strain(T_np1)
def RJ(e):
s, h, A, u, p = self.model.update_sd(e - enext, self.mechanical_strain_int[-1],
T_np1, self.T_int[-1], t_np1, self.t_int[-1],
self.stress_int[-1],
self.stored_int[-1], self.u_int[-1], self.p_int[-1])
R = s - s_np1
return R, A
if len(self.strain_int) > 1:
inc = self.strain_int[-1] - self.strain_int[-2]
extra = [self.strain_int[-1] + inc]
else:
extra = []
e_np1 = self.solve_try(RJ, self.strain_int[-1], extra = extra)
self.strain_step(e_np1, t_np1, T_np1)
def erate_step(self, sdir, erate, t_np1, T_np1,
einc_guess = None, ainc_guess = None):
"""
Drive in a given stress direction at a prescribed strain rate, like
an actual "stress controlled" experiment.
Parameters:
sdir: stress direction
erate: strain rate (in the direction)
t_np1: next time
T_np1: next temperature
einc_guess: a guess at the strain increment
ainc_guess: a guess at the stress increment
"""
sdir = sdir / la.norm(sdir)
dt = t_np1 - self.t_int[-1]
enext = self.update_thermal_strain(T_np1)
def RJ(x):
a = x[0]
e_inc = x[1:]
s, h, A, u, p = self.model.update_sd(self.strain_int[-1] + e_inc - enext,
self.mechanical_strain_int[-1],
T_np1, self.T_int[-1], t_np1, self.t_int[-1], self.stress_int[-1],
self.stored_int[-1],
self.u_int[-1], self.p_int[-1])
R = np.zeros((7,))
J = np.zeros((7,7))
R[:6] = s - (sdir * a + self.stress_int[-1])
R[6] = np.dot(e_inc, sdir) / dt - erate
J[:6,0] = -sdir
J[:6,1:] = A
J[6,0] = 0.0
J[6,1:] = sdir / dt
return R, J
x0 = np.zeros((7,))
if einc_guess is not None:
x0[1:] = einc_guess
else:
x0[1:] = sdir / 10000.0
if ainc_guess is not None:
x0[0] = ainc_guess
else:
x0[0] = 1.0
x = self.solve_try(RJ, x0)
e_np1 = self.strain_int[-1] + x[1:]
self.strain_step(e_np1, t_np1, T_np1)
return x[1:], x[0]
def erate_einc_step(self, sdir, erate, einc, T_np1, **kwargs):
"""
Similar to erate_step but specify the strain increment instead of the
time increment.
Parameters:
sdir: stress direction
erate: strain rate, in stress direction
einc: strain increment, in stress direction
T_np1: temperature at next time step
"""
dt = einc / erate
return self.erate_step(sdir, erate, self.t_int[-1] + dt, T_np1, **kwargs)
def srate_sinc_step(self, sdir, srate, sinc, T_np1):
"""
Similar to rate_step but specify the stress increment instead of the
time increment.
Parameters:
sdir: stress direction
srate: stress rate
sinc: stress increment
T_np1: temperature at next time step
"""
if np.allclose(sdir, 0.0):
s_np1 = self.stress_int[-1]
else:
s_np1 = self.stress_int[-1] + sdir / la.norm(sdir) * sinc
if np.isclose(srate, 0.0):
dt = 0.0
else:
dt = np.abs(np.dot(s_np1 - self.stress_int[-1], sdir) / srate)
self.stress_step(s_np1, self.t_int[-1] + dt, T_np1)
def strain_hold_step(self, i, t_np1, T_np1, q = 1.0, E = -1.0):
"""
A special, mixed step which holds the strain in index i constant
while holding the stress in the other directions to their previous
values
Parameters:
i: index to hold
t_np1: next time
T_np1: next temperature
q: follow up factor
E: Young's modulus to use -- must redo interface at some point
"""
if not np.isclose(q, 1.0) and np.isclose(E, -1.0):
raise ValueError("You must supply the Youngs modulus")
enext = self.update_thermal_strain(T_np1)
oset = sorted(list(set(range(6)) - set([i])))
def RJ(e_np1):
s, h, A, u, p = self.model.update_sd(e_np1 - enext,
self.mechanical_strain_int[-1],
T_np1, self.T_int[-1], t_np1, self.t_int[-1], self.stress_int[-1],
self.stored_int[-1], self.u_int[-1], self.p_int[-1])
R = np.zeros((6,))
R[0] = (e_np1[i] - self.strain_int[-1][i]
) + (s[i] - self.stress_int[-1][i]) / E * (q - 1)
R[1:] = s[oset] - self.stress_int[-1][oset]
J = np.zeros((6,6))
J[0,0] = 1.0
J[0,:] += A[i,:] / E * (q - 1)
J[1:,:] = A[oset,:][:]
return R, J
x0 = np.copy(self.strain_int[-1])
e_np1 = self.solve_try(RJ, x0)
self.strain_step(e_np1, t_np1, T_np1)
def uniaxial_test(model, erate, T = 300.0, emax = 0.05, nsteps = 250,
sdir = np.array([1,0,0,0,0,0]), verbose = False,
offset = 0.2/100.0, history = None, tdir = np.array([0,1,0,0,0,0]),
rtol = 1e-6, atol = 1e-10, miter = 25):
"""
Make a uniaxial stress/strain curve
Parameters:
model: material model
erate: strain rate
Keyword Args:
T: temperature, default 300.0
emax: maximum strain, default 5%
nsteps: number of steps to use, default 250
sdir: stress direction, default tension in x
verbose: whether to be verbose
offset: used to calculate yield stress
history: initial model history
tdir: transverse direction for Poisson's ratio
Returns:
dict: results dictionary containing...
**Results in dictionary:**
================= ============================================
Name Description
================= ============================================
strain strain in direction
stress stress in direction
energy_density strain energy density
plastic_work plastic dissipation
youngs young's modulus of initial curve
yield yield stress implied by curve
poissons poisson's ratio implied by non-axial strains
================= ============================================
"""
e_inc = emax / nsteps
driver = Driver_sd(model, verbose = verbose, T_init = T, rtol = rtol,
atol = atol, miter = miter)
if history is not None:
driver.stored_int[0] = history
strain = [0.0]
stress = [0.0]
for i in range(nsteps):
if i == 0:
einc, ainc = driver.erate_einc_step(sdir, erate, e_inc, T)
else:
einc, ainc = driver.erate_einc_step(sdir, erate, e_inc, T,
einc_guess = einc, ainc_guess = ainc)
strain.append(np.dot(driver.strain_int[-1], sdir))
stress.append(np.dot(driver.stress_int[-1], sdir))
strain = np.array(strain)
stress = np.array(stress)
# Calculate the yield stress and Young's modulus
E = np.abs(stress[1]) / np.abs(strain[1])
nu = -np.dot(driver.strain_int[1], tdir) / np.dot(
driver.strain_int[1], sdir)
sfn = inter.interp1d(np.abs(strain), np.abs(stress))
tfn = lambda e: E * (e - offset)
try:
sYe = opt.brentq(lambda e: sfn(e) - tfn(e), 0.0, np.max(strain))
sY = tfn(sYe)
except Exception:
sY = np.inf
return {'strain': strain, 'stress': stress,
'energy_density': np.copy(driver.u),
'plastic_work': np.copy(driver.p),
'youngs': E, 'yield': sY, 'poissons': nu,
'history': driver.stored_int[-1]}
def strain_cyclic(model, emax, R, erate, ncycles, T = 300.0, nsteps = 50,
sdir = np.array([1,0,0,0,0,0]), hold_time = None, n_hold = 25,
verbose = False, check_dmg = False, dtol = 0.75):
"""
Strain controlled cyclic test.
Parameters:
emax: maximum strain
R: R = emin / emax
erate: strain rate to go at
ncycles: number of cycles
T: temperature, default 300
Keyword Args:
nsteps: number of steps per half cycle
sdir: stress direction, defaults to x and tension first
hold_time: if None don't hold, if scalar then hold symmetrically top/bot
if an array specify different hold times for first direction
(default tension) and second direction
n_hold: number of steps to hold over
verbose: whether to be verbose
check_dmg: check to see if material damage exceeds dtol, stop the
simulation when that happens
dtol: damage to stop at
Returns:
dict: results dictionary containing...
**Results in dictionary:**
============= ========================
Name Description
============= ========================
strain: strain in direction
stress: stress in direction
cycles: list of cycle numbers
max: maximum stress per cycle
min: minimum stress per cycle
mean: mean stress per cycle
============= ========================
"""
# Setup
driver = Driver_sd(model, verbose = verbose, T_init = T)
emin = emax * R
if hold_time:
if np.isscalar(hold_time):
hold_time = [hold_time, hold_time]
else:
hold_time = [0,0]
# Setup results
strain = [0.0]
stress = [0.0]
time = [0.0]
cycles = []
smax = []
smin = []
smean = []
ecycle = []
pcycle = []
# First half cycle
if verbose:
print("Initial half cycle")
e_inc = emax / nsteps
try:
for i in range(nsteps):
if i == 0:
einc, ainc = driver.erate_einc_step(sdir, erate, e_inc, T)
else:
einc, ainc = driver.erate_einc_step(sdir, erate, e_inc, T, einc_guess = einc,
ainc_guess = ainc)
if check_dmg:
if driver.stored_int[-1][0] > dtol:
raise Exception("Damage check exceeded")
strain.append(np.dot(driver.strain_int[-1], sdir))
stress.append(np.dot(driver.stress_int[-1], sdir))
time.append(time[-1] + e_inc / erate)
except Exception as e:
print("Failed to make first half cycle")
raise e
# Begin cycling
for s in range(ncycles):
if verbose:
print("Cycle %i" % s)
try:
# Tension hold
if hold_time[0] > 0.0:
dt = hold_time[0] / n_hold
for i in range(n_hold):
einc, ainc = driver.erate_step(sdir, 0.0, time[-1] + dt, T,
einc_guess = np.zeros((6,)), ainc_guess = -1)
if check_dmg:
if driver.stored_int[-1][0] > dtol:
raise Exception("Damage check exceeded")
strain.append(np.dot(driver.strain_int[-1], sdir))
stress.append(np.dot(driver.stress_int[-1], sdir))
time.append(time[-1] + dt)
si = len(driver.strain_int)
e_inc = np.abs(emin - emax) / nsteps
for i in range(nsteps):
if i == 0:
einc, ainc = driver.erate_einc_step(-sdir, erate, e_inc, T,
einc_guess = -einc, ainc_guess = -ainc)
else:
einc, ainc = driver.erate_einc_step(-sdir, erate, e_inc, T,
einc_guess = einc, ainc_guess = ainc)
if check_dmg:
if driver.stored_int[-1][0] > dtol:
raise Exception("Damage check exceeded")
strain.append(np.dot(driver.strain_int[-1], sdir))
stress.append(np.dot(driver.stress_int[-1], sdir))
time.append(time[-1] + e_inc / erate)
# Compression hold
if hold_time[1] > 0.0:
dt = hold_time[1] / n_hold
for i in range(n_hold):
einc, ainc = driver.erate_step(sdir, 0.0, time[-1] + dt, T,
einc_guess = np.zeros((6,)), ainc_guess = -1)
if check_dmg:
if driver.stored_int[-1][0] > dtol:
raise Exception("Damage check exceeded")
strain.append(np.dot(driver.strain_int[-1], sdir))
stress.append(np.dot(driver.stress_int[-1], sdir))
time.append(time[-1] + dt)
e_inc = np.abs(emax - emin) / nsteps
for i in range(nsteps):
if i == 0:
einc, ainc = driver.erate_einc_step(sdir, erate, e_inc, T,
einc_guess = -einc, ainc_guess = -ainc)
else:
einc, ainc = driver.erate_einc_step(sdir, erate, e_inc, T,
einc_guess = einc, ainc_guess = ainc)
if check_dmg:
if driver.stored_int[-1][0] > dtol:
raise Exception("Damage check exceeded")
strain.append(np.dot(driver.strain_int[-1], sdir))
stress.append(np.dot(driver.stress_int[-1], sdir))
time.append(time[-1] + e_inc / erate)
# Calculate
if np.isnan(max(stress[si:])) or np.isnan(min(stress[si:])):
break
cycles.append(s)
smax.append(max(stress[si:]))
smin.append(min(stress[si:]))
smean.append((smax[-1]+smin[-1])/2)
ecycle.append(driver.u_int[-1])
pcycle.append(driver.p_int[-1])
except Exception as e:
break
# Setup and return
return {"strain": np.array(strain), "stress": np.array(stress),
"cycles": np.array(cycles, dtype = int), "max": np.array(smax),
"min": np.array(smin), "mean": np.array(smean),
"energy_density": np.array(ecycle), "plastic_work": np.array(pcycle),
"history": driver.stored_int[-1], "time": np.array(time)}
def strain_cyclic_extrapolated(model, emax, R, erate, ncycles, T = 300.0, nsteps = 50,
sdir = np.array([1,0,0,0,0,0]), hold_time = None, n_hold = 25,
verbose = False, check_dmg = False, dtol = 0.75, min_cycle=3, unit_extrapolate = 10,
jump_delta_N=10, allowable_jump_stress=5.0):
"""
Strain controlled cyclic test extrapolation.
Extra Keyword Args:
min_cycle minimum cycles to start the extrapolation process
unit_extrapolate number of cycles to perform single cycle extrapolation
jump_delta_N number of cycles to jump
allowable_jump_stress extrapolate when stress jump is within this limit
Returns:
dict: results dictionary containing...
**Results in dictionary:**
============= ========================
Name Description
============= ========================
cycles: list of cycle numbers
max: maximum stress per cycle
min: minimum stress per cycle
============= ========================
"""
# Setup
driver = Driver_sd(model, verbose = verbose, T_init = T)
emin = emax * R
if hold_time:
if np.isscalar(hold_time):
hold_time = [hold_time, hold_time]
else:
hold_time = [0,0]
# Setup results
strain = [0.0]
stress = [0.0]
time = [0.0]
cycles = []
smax = []
smin = []
smean = []
ecycle = []
pcycle = []
# First half cycle
if verbose:
print("Initial half cycle")
e_inc = emax / nsteps
try:
for i in range(nsteps):
if i == 0:
einc, ainc = driver.erate_einc_step(sdir, erate, e_inc, T)
else:
einc, ainc = driver.erate_einc_step(sdir, erate, e_inc, T, einc_guess = einc,
ainc_guess = ainc)
if check_dmg:
if driver.stored_int[-1][0] > dtol:
raise Exception("Damage check exceeded")
strain.append(np.dot(driver.strain_int[-1], sdir))
stress.append(np.dot(driver.stress_int[-1], sdir))
time.append(time[-1] + e_inc / erate)
except Exception as e:
print("Failed to make first half cycle")
raise e
s = 0
# steps in one cycle
if (hold_time[0] > 0) and (hold_time[1] == 0):
steps = 2*nsteps + n_hold
elif (hold_time[1] > 0) and (hold_time[0] == 0):
steps = 2*nsteps + n_hold
elif (hold_time[0] > 0) and (hold_time[1] > 0):
steps = 2*nsteps + 2*n_hold
else:
steps = 2*nsteps
extrapolate = False
while s < ncycles:
if verbose:
print("Cycle %i" % s)
if check_dmg:
if driver.stored_int[-1][0] > dtol:
print("Damage check exceeded")
break
if (s >= min_cycle) and (extrapolate == True): # No extrapolation before min_cycle
if (s <= unit_extrapolate): # single cycle jump for first unit_extrapolate cycles
delta_N = 1
else:
delta_N = jump_delta_N # specified cycles to jump
n = len(driver.stored_int)
# extrapolating history
pos_hist_last_last = driver.stored_int[n - 1 - steps]
pos_hist_last = driver.stored_int[n-1]
dN_1 = cycles[-1] - cycles[-2]
pos_extrapolated_history = pos_hist_last + (pos_hist_last - pos_hist_last_last)*delta_N/dN_1
# extrapolating smax
smax_last_last = smax[-2]
smax_last = smax[-1]
extrapolated_smax = smax_last + (smax_last - smax_last_last)*delta_N/dN_1
# extrapolating smax
smin_last_last = smin[-2]
smin_last = smin[-1]
extrapolated_smin = smin_last + (smin_last - smin_last_last)*delta_N/dN_1
# criteria for extrapolation
pos_stress_last_last = driver.stress_int[n - 1 - 2*steps]
pos_stress_last = driver.stress_int[n-1]
pos_extrapolated_stress = pos_stress_last + (pos_stress_last - pos_stress_last_last)*delta_N/dN_1
stress_jump = pos_extrapolated_stress[0] - pos_stress_last[0]
if np.fabs(stress_jump) <= allowable_jump_stress:
s = s + delta_N
if s > ncycles:
break
driver.stored_int.append(pos_extrapolated_history)
driver.stress_int.append(pos_extrapolated_stress)
smax.append(extrapolated_smax)
smin.append(extrapolated_smin)
cycles.append(s)
extrapolate = False
else:
extrapolate = False
else:
try:
if hold_time[0] > 0.0:
dt = hold_time[0] / n_hold
for i in range(n_hold):
einc, ainc = driver.erate_step(sdir, 0.0, time[-1] + dt, T,
einc_guess = np.zeros((6,)), ainc_guess = -1)
if check_dmg:
if driver.stored_int[-1][0] > dtol:
raise Exception("Damage check exceeded")
strain.append(np.dot(driver.strain_int[-1], sdir))
stress.append(np.dot(driver.stress_int[-1], sdir))
time.append(time[-1] + dt)
si = len(driver.strain_int)
e_inc = np.abs(emin - emax) / nsteps
for i in range(nsteps):
if i == 0:
einc, ainc = driver.erate_einc_step(-sdir, erate, e_inc, T,
einc_guess = -einc, ainc_guess = -ainc)
else:
einc, ainc = driver.erate_einc_step(-sdir, erate, e_inc, T,
einc_guess = einc, ainc_guess = ainc)
if check_dmg:
if driver.stored_int[-1][0] > dtol:
raise Exception("Damage check exceeded")
strain.append(np.dot(driver.strain_int[-1], sdir))
stress.append(np.dot(driver.stress_int[-1], sdir))
time.append(time[-1] + e_inc / erate)
# Compression hold
if hold_time[1] > 0.0:
dt = hold_time[1] / n_hold
for i in range(n_hold):
einc, ainc = driver.erate_step(sdir, 0.0, time[-1] + dt, T,
einc_guess = np.zeros((6,)), ainc_guess = -1)
if check_dmg:
if driver.stored_int[-1][0] > dtol:
raise Exception("Damage check exceeded")
strain.append(np.dot(driver.strain_int[-1], sdir))
stress.append(np.dot(driver.stress_int[-1], sdir))
time.append(time[-1] + dt)
e_inc = np.abs(emax - emin) / nsteps
for i in range(nsteps):
if i == 0:
einc, ainc = driver.erate_einc_step(sdir, erate, e_inc, T,
einc_guess = -einc, ainc_guess = -ainc)
else:
einc, ainc = driver.erate_einc_step(sdir, erate, e_inc, T,
einc_guess = einc, ainc_guess = ainc)
if check_dmg:
if driver.stored_int[-1][0] > dtol:
raise Exception("Damage check exceeded")
strain.append(np.dot(driver.strain_int[-1], sdir))
stress.append(np.dot(driver.stress_int[-1], sdir))
time.append(time[-1] + e_inc / erate)
# Calculate
if np.isnan(max(stress[si:])) or np.isnan(min(stress[si:])):
break
s += 1
cycles.append(s)
smax.append(max(stress[si:]))
smin.append(min(stress[si:]))
smean.append((smax[-1]+smin[-1])/2)
ecycle.append(driver.u_int[-1])
pcycle.append(driver.p_int[-1])
extrapolate = True
except Exception as e:
break
# Setup and return
return {"cycles": np.array(cycles, dtype = int), "max": np.array(smax),
"min": np.array(smin),"time": np.array(time)}
def strain_cyclic_followup(model, emax, R, erate, ncycles,
q = 1.0, T = 300.0, nsteps = 50,
sind = 0, hold_time = None, n_hold = 25,
verbose = False, check_dmg = False, dtol = 0.75,
logspace = False):
"""
Strain controlled cyclic test with follow up.
This is a "fallback" to the old version that does things by index
so that I can use the index-based hold routine with follow up
Parameters:
emax: maximum strain
R: R = emin / emax
erate: strain rate to go at
ncycles: number of cycles
Keyword Args:
q: follow up factor
T: temperature, default 300
nsteps: number of steps per half cycle
sind: index to pull on
hold_time: if None don't hold, if scalar then hold symmetrically top/bot
if an array specify different hold times for first direction
(default tension) and second direction
n_hold: number of steps to hold over
verbose: whether to be verbose
check_dmg: check to see if damage exceeds a threshold
dtol: damage threshold
logspace: logspace the hold time steps (instead of linspace)
Returns:
dict: dictionary of results...
**Results in dictionary**
========= ========================
Name Description
========= ========================
strain strain in direction
stress stress in direction
cycles list of cycle numbers
max maximum stress per cycle
min minimum stress per cycle
mean mean stress per cycle
========= ========================
"""
# Setup
sdir = np.zeros((6,))
sdir[sind] = 1.0
res = uniaxial_test(model, erate, T = T, emax = 1.0e-4, nsteps = 2)
E = res['youngs']
driver = Driver_sd(model, verbose = verbose, T_init = T)
emin = emax * R
if hold_time:
if np.isscalar(hold_time):
hold_time = [hold_time, hold_time]
else:
hold_time = [0,0]
# Setup results
strain = [0.0]
stress = [0.0]
time = [0.0]
cycles = []
smax = []
smin = []
smean = []
ecycle = []
pcycle = []
# First half cycle
if verbose:
print("Initial half cycle")
e_inc = emax / nsteps
try:
for i in range(nsteps):
if i == 0:
einc, ainc = driver.erate_einc_step(sdir, erate, e_inc, T)
else:
einc, ainc = driver.erate_einc_step(sdir, erate, e_inc, T, einc_guess = einc,
ainc_guess = ainc)
if check_dmg:
if driver.stored_int[-1][0] > dtol:
raise Exception("Damage check exceeded")
strain.append(np.dot(driver.strain_int[-1], sdir))
stress.append(np.dot(driver.stress_int[-1], sdir))
time.append(time[-1] + e_inc / erate)
except Exception as e:
print("Failed to make first half cycle")
raise e
# Begin cycling
for s in range(ncycles):
if verbose:
print("Cycle %i" % s)
try:
# Tension hold
if hold_time[0] > 0.0:
if logspace:
dts = np.diff(np.logspace(0, np.log10(hold_time[0]), n_hold+1))
else:
dts = np.diff(np.linspace(0,hold_time[0],n_hold+1))
#dt = hold_time[0] / n_hold
for i, dt in enumerate(dts):
driver.strain_hold_step(sind, time[-1] + dt, T,
q = q, E = E)
if check_dmg:
if driver.stored_int[-1][0] > dtol:
raise Exception("Damage check exceeded")
strain.append(np.dot(driver.strain_int[-1], sdir))
stress.append(np.dot(driver.stress_int[-1], sdir))
time.append(time[-1] + dt)
si = len(driver.strain_int)
e_inc = np.abs(emin - emax) / nsteps
for i in range(nsteps):
if i == 0:
einc, ainc = driver.erate_einc_step(-sdir, erate, e_inc, T,
einc_guess = np.zeros((6,)), ainc_guess = -1)
else:
einc, ainc = driver.erate_einc_step(-sdir, erate, e_inc, T,
einc_guess = einc, ainc_guess = ainc)
if check_dmg:
if driver.stored_int[-1][0] > dtol:
raise Exception("Damage check exceeded")
strain.append(np.dot(driver.strain_int[-1], sdir))
stress.append(np.dot(driver.stress_int[-1], sdir))
time.append(time[-1] + e_inc / erate)
# Compression hold
if hold_time[1] > 0.0:
if logspace:
dts = np.diff(np.logspace(0, np.log10(hold_time[1]), n_hold+1))
else:
dts = np.diff(np.linspace(0,hold_time[1],n_hold+1))
for i, dt in enumerate(dts):
driver.strain_hold_step(sind, time[-1] + dt, T,
q = q, E = E)
if check_dmg:
if driver.stored_int[-1][0] > dtol:
raise Exception("Damage check exceeded")
strain.append(np.dot(driver.strain_int[-1], sdir))
stress.append(np.dot(driver.stress_int[-1], sdir))
time.append(time[-1] + dt)
e_inc = np.abs(emax - emin) / nsteps
for i in range(nsteps):
if i == 0:
einc, ainc = driver.erate_einc_step(sdir, erate, e_inc, T,
einc_guess = np.zeros((6,)), ainc_guess = 1.0)
else:
einc, ainc = driver.erate_einc_step(sdir, erate, e_inc, T,
einc_guess = einc, ainc_guess = ainc)
if check_dmg:
if driver.stored_int[-1][0] > dtol:
raise Exception("Damage check exceeded")
strain.append(np.dot(driver.strain_int[-1], sdir))
stress.append(np.dot(driver.stress_int[-1], sdir))
time.append(time[-1] + e_inc / erate)
# Calculate
if np.isnan(max(stress[si:])) or np.isnan(min(stress[si:])):
break
cycles.append(s)
smax.append(max(stress[si:]))
smin.append(min(stress[si:]))
smean.append((smax[-1]+smin[-1])/2)
ecycle.append(driver.u_int[-1])
pcycle.append(driver.p_int[-1])
except Exception as e:
break
# Setup and return
return {"strain": np.array(strain), "stress": np.array(stress),
"cycles": np.array(cycles, dtype = int), "max": np.array(smax),
"min": np.array(smin), "mean": np.array(smean),
"energy_density": np.array(ecycle), "plastic_work": np.array(pcycle),
"history": driver.stored_int[-1], "time": np.array(time)}
def stress_cyclic(model, smax, R, srate, ncycles, T = 300.0, nsteps = 50,
sdir = np.array([1,0,0,0,0,0]), hold_time = None, n_hold = 10,
verbose = False, etol = 0.1):
"""
Stress controlled cyclic test.
Parameters:
emax: maximum stress
R: R = smin / smax
erate: strain rate to go at
ncycles: number of cycles
Keyword Args:
T: temperature, default 300
nsteps: number of steps per half cycle
sdir: stress direction, defaults to x and tension first
hold_time: if None don't hold, if scalar then hold symmetrically top/bot
if an array specify different hold times for first direction
(default tension) and second direction
n_hold: number of steps to hold over
verbose: whether to be verbose
etol: stop if the strain increment exceeds this threshold
Returns:
dict: dictionary of results
**Results in dictionary:**
============= ========================
Name Description
============= ========================
strain strain in direction
stress stress in direction
cycles list of cycle numbers
max maximum strain per cycle
min minimum strain per cycle
mean mean strain per cycle
============= ========================
"""
# Setup
driver = Driver_sd(model, verbose = verbose, T_init = T)
smin = smax * R
if hold_time:
if np.isscalar(hold_time):
hold_time = [hold_time, hold_time]
# Setup results
strain = [0.0]
stress = [0.0]
cycles = []
emax = []
emin = []
emean = []
ecycle = []
pcycle = []
# First half cycle
s_inc = smax / nsteps
if verbose:
print("First half cycle")
for i in range(nsteps):
driver.srate_sinc_step(sdir, srate, s_inc, T)
strain.append(np.dot(driver.strain_int[-1], sdir))
stress.append(np.dot(driver.stress_int[-1], sdir))
# Begin cycling
for s in range(ncycles):
quit = False
if verbose:
print("Cycle %i" % s)
si = len(driver.strain_int)
# Hold, if requested
if hold_time and (hold_time[0] > 0.0):
ht = hold_time[0]
dt = ht / n_hold
for i in range(n_hold):
try:
driver.stress_step(driver.stress_int[-1], driver.t_int[-1] + dt, T)
except:
quit = True
break
if la.norm(driver.strain_int[-1] - driver.strain_int[-2]) > etol:
quit = True
break
strain.append(np.dot(driver.strain_int[-1], sdir))
stress.append(np.dot(driver.stress_int[-1], sdir))
if quit:
break
s_inc = (smin - smax) / nsteps
for i in range(nsteps):
try:
driver.srate_sinc_step(sdir, srate, s_inc, T)
except:
quit = True
break
if la.norm(driver.strain_int[-1] - driver.strain_int[-2]) > etol:
quit = True
break
strain.append(np.dot(driver.strain_int[-1], sdir))
stress.append(np.dot(driver.stress_int[-1], sdir))
if quit:
break
# Hold, if requested
if hold_time and (hold_time[1] > 0.0):
ht = hold_time[1]
dt = ht / n_hold
for i in range(n_hold):
try:
driver.stress_step(driver.stress_int[-1], driver.t_int[-1] + dt, T)
except:
quit = True
break
if la.norm(driver.strain_int[-1] - driver.strain_int[-2]) > etol:
quit = True
break
strain.append(np.dot(driver.strain_int[-1], sdir))
stress.append(np.dot(driver.stress_int[-1], sdir))
if quit:
break
s_inc = (smax - smin) / nsteps
for i in range(nsteps):
try:
driver.srate_sinc_step(sdir, srate, s_inc, T)
except:
quit = True
break
if la.norm(driver.strain_int[-1] - driver.strain_int[-2]) > etol:
quit = True
break
strain.append(np.dot(driver.strain_int[-1], sdir))
stress.append(np.dot(driver.stress_int[-1], sdir))
if quit:
break
# Calculate
cycles.append(s)
emax.append(max(strain[si:]))
emin.append(min(strain[si:]))
emean.append((emax[-1]+emin[-1])/2)
ecycle.append(driver.u_int[-1])
pcycle.append(driver.p_int[-1])
# Setup and return
return {"strain": np.array(strain), "stress": np.array(stress),
"cycles": np.array(cycles, dtype = int), "max": np.array(emax),
"min": np.array(emin), "mean": np.array(emean),
"energy_density": np.array(ecycle), "plastic_work": np.array(pcycle),
"time": np.array(driver.t_int)}
def stress_relaxation(model, emax, erate, hold, T = 300.0, nsteps = 250,
nsteps_up = 50, index = 0, tc = 1.0,
verbose = False, logspace = False, q = 1.0):
"""
Simulate a stress relaxation test.
Parameters:
model: material model
emax : maximum strain to attain
erate: strain rate to take getting there
hold: hold time
Keyword Args:
T: temperature
nsteps: number of steps to relax over
nsteps_up: number of steps to take getting up to stress
index: direction to pull in, default x tension
tc: 1.0 for tension -1.0 for compression
verbose: whether to be verbose
logspace: log space the relaxation timesteps
q: follow up factor
Results:
dict: dictionary of results
**Results in dictionary:**
============== ======================
Name Description
============== ======================
time time
strain strain
stress stress
rtime relaxation time
rrate stress relaxation rate
============== ======================
"""
# Setup
driver = Driver_sd(model, verbose = verbose, T_init = T)
time = [0]
strain = [0]
stress = [0]
res = uniaxial_test(model, erate, T = T, emax = 1.0e-4, nsteps = 2)
E = res['youngs']
# Ramp up
if verbose:
print("Ramp up")
sdir = np.zeros((6,))
sdir[index] = tc
einc = emax / nsteps_up
for i in range(nsteps_up):
if i == 0:
eincg, ainc = driver.erate_einc_step(sdir, erate, einc, T)
else:
eincg, ainc = driver.erate_einc_step(sdir, erate, einc, T,
einc_guess = eincg, ainc_guess = ainc)
time.append(driver.t[-1])
strain.append(np.dot(driver.strain_int[-1],sdir))
stress.append(np.dot(driver.stress_int[-1],sdir))
ri = len(driver.strain_int)
if verbose:
print("Hold")
if logspace:
ts = np.logspace(0, np.log10(hold), num = nsteps+1)
dts = np.diff(ts)
else:
dt = hold / nsteps
dts = [dt] * nsteps
for i, dt in enumerate(dts):
driver.strain_hold_step(index, driver.t_int[-1] + dt, T,
q = q, E = E)
time.append(driver.t_int[-1])
strain.append(np.dot(driver.strain_int[-1],sdir))
stress.append(np.dot(driver.stress_int[-1],sdir))
time = np.array(time)
strain = np.array(strain)
stress = np.array(stress)
rrate = -np.diff(stress[ri:]) / np.diff(time[ri:])
return {'time': np.copy(time), 'strain': np.copy(strain),
'stress': np.copy(stress), 'rtime': np.copy(time[ri:-1] - time[ri]),
'rrate': np.copy(rrate), 'rstress': np.copy(stress[ri:-1]),
'rstrain': np.copy(strain[ri:-1])}
def creep(model, smax, srate, hold, T = 300.0, nsteps = 250,
nsteps_up = 150, sdir = np.array([1,0,0,0,0,0]), verbose = False,
logspace = False, history = None, elimit = 1.0, check_dmg = False,
dtol = 0.75):
"""
Simulate a creep test
Parameters:
model: material model
smax: stress to attain
srate: stress rate to take getting there
hold: total hold time
Keyword Args:
T: temperature
nsteps: number of steps over relaxation period
nsteps_up: number of steps to get to stress value
sdir: stress direction, defaults to x-tension
verbose: whether to be verbose
logspace: if true logspace the time steps
history: use damaged material
check_dmg: check damage as a break condition
dtol: damage to define failure at
Returns:
dict: results dictionary
"""
# Setup
driver = Driver_sd(model, verbose = verbose, T_init = T)
if history is not None:
driver.stored_int[0] = history
time = [0]
strain = [0]
stress = [0]
# Ramp up
sinc = float(smax) / nsteps_up
for i in range(nsteps_up):
driver.srate_sinc_step(sdir, srate, sinc, T)
time.append(driver.t[-1])
strain.append(np.dot(driver.strain_int[-1],sdir))
stress.append(np.dot(driver.stress_int[-1],sdir))
ri = len(driver.strain_int)
t0 = time[-1]
if logspace:
ts = np.logspace(0, np.log10(hold), num = nsteps) + t0
else:
ts = np.linspace(0,hold, num = nsteps) + t0
failed = False
for t in ts:
# You can exceed the creep life of the sample doing this...
# Need to allow a non-convergent result to break
try:
driver.stress_step(driver.stress_int[-1], t, T)
except:
failed = True
break
if np.any(np.isnan(driver.strain_int[-1])):
failed = True
break
if np.any(np.abs(driver.strain_int[-1]) > elimit):
failed = True
break
ed = np.dot(driver.strain_int[-1],sdir)
if ed < strain[-1]:
failed = True
break
if check_dmg:
if driver.stored_int[-1][0] > dtol:
failed = True
break
time.append(t)
strain.append(ed)
stress.append(np.dot(driver.stress_int[-1],sdir))
time = np.array(time)
strain = | np.array(strain) | numpy.array |
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont
import scipy
import scipy.stats
import cv2
import os
import emnist_helpers
def save_metadata(metadata, contour_path, batch_id):
# Converts metadata (list of lists) into an nparray, and then saves
metadata_path = os.path.join(contour_path, 'metadata')
if not os.path.exists(metadata_path):
os.makedirs(metadata_path)
metadata_fn = str(batch_id) + '.npy'
np.save(os.path.join(metadata_path,metadata_fn), metadata)
# Accumulate metadata
def accumulate_meta(array, im_subpath, seg_sub_path, im_filename, nimg,
image_category, letter_img_indices):
# NEW VERSION
array += [[im_subpath, seg_sub_path, im_filename, nimg, image_category] + letter_img_indices]
return array
# Accumulate metadata
def accumulate_meta_segment(array, im_subpath, seg_sub_path, im_filename, nimg,
letter_img_indices):
# NEW VERSION
array += [[im_subpath, seg_sub_path, im_filename, nimg] + letter_img_indices]
return array
def crop_center(img,cropx,cropy):
y,x = img.shape
startx = x//2-(cropx//2)
starty = y//2-(cropy//2)
return img[starty:starty+cropy,startx:startx+cropx]
def translate_coord(coord, orientation, dist, allow_float=False):
y_displacement = float(dist)*np.sin(orientation)
x_displacement = float(dist)*np.cos(orientation)
if allow_float is True:
new_coord = [coord[0]+y_displacement, coord[1]+x_displacement]
else:
new_coord = [int(np.ceil(coord[0] + y_displacement)), int(np.ceil(coord[1] + x_displacement))]
return new_coord
def get_availability_notouch(im, com_on_im, radius, canvas_size,
existing_canvas=None, existing_deg=None,
min_separation_deg=45, min_separation_px=15):
if (min_separation_deg>180):
return ValueError('min_separation_deg should be leq than 180')
# Filter available positions to prevent overlap
if existing_canvas is not None:
print('placing second letter')
im_inverted = im[::-1,::-1]
com_on_im_inverted = [im.shape[0]-com_on_im[0]-1, im.shape[1]-com_on_im[1]-1]
h_offset = com_on_im[0]-com_on_im_inverted[0]
w_offset = com_on_im[1]-com_on_im_inverted[1]
pad_thickness = ((np.maximum(h_offset, 0) + min_separation_px, np.maximum(-h_offset, 0) + min_separation_px),
(np.maximum(w_offset, 0) + min_separation_px, np.maximum(-w_offset, 0) + min_separation_px))
im_inverted_padded = \
np.pad(im_inverted, pad_thickness, 'constant', constant_values=((0,0), (0,0))).astype(np.bool)
im_inverted_dilated = scipy.ndimage.morphology.binary_dilation(im_inverted_padded, iterations=min_separation_px)
occupation_mask = cv2.dilate(existing_canvas.astype(np.uint8), im_inverted_dilated.astype(np.uint8)).astype(np.bool)
# print('positive = ' + str(np.sum(occupation_mask.astype(np.int)[:])))
# print('negative = ' + str(np.sum(1 - occupation_mask.astype(np.int)[:])))
else:
print('placing first letter')
occupation_mask = np.zeros((canvas_size[0], canvas_size[1])).astype(np.bool)
# Filter available positions to ensure angular dist between COMs
availability_mask = np.zeros((canvas_size[0], canvas_size[1]))
canvase_center = [canvas_size[0]/2, canvas_size[1]/2]
if existing_deg is not None:
degs = [x for x in range(360) if np.abs(existing_deg-x)]
else:
degs = [x for x in range(360)]
for deg in degs:
coord = translate_coord(canvase_center, deg*np.pi/180, radius, allow_float=False)
availability_mask[coord[0], coord[1]] = not occupation_mask[coord[0], coord[1]]
# Filter available positions to prevent overflow of obj window
availability_mask[:com_on_im[0]+1, :] = False
availability_mask[-(im.shape[0] - com_on_im[0])-1:, :] = False
availability_mask[:, :com_on_im[1]+1] = False
availability_mask[:, -(im.shape[1] - com_on_im[1])-1:] = False
# if existing_canvas is not None:
# plt.subplot(141);plt.imshow(im)
# plt.subplot(142);plt.imshow(existing_canvas.astype(np.uint8))
# plt.subplot(143);plt.imshow(occupation_mask)
# plt.subplot(144);plt.imshow(availability_mask.astype(np.uint8))
# plt.show()
return availability_mask
def place_on_canvas(im, com_in_im, canvas_size, com_in_canvas):
canvas = np.zeros((canvas_size[0], canvas_size[1]))
hrange = [com_in_canvas[0] - com_in_im[0], com_in_canvas[0] + (im.shape[0] - com_in_im[0])]
wrange = [com_in_canvas[1] - com_in_im[1], com_in_canvas[1] + (im.shape[1] - com_in_im[1])]
# if canvas[hrange[0]:hrange[1], wrange[0]:wrange[1]].shape != im.shape:
# import ipdb
# ipdb.set_trace()
canvas[hrange[0]:hrange[1], wrange[0]:wrange[1]] = im
return canvas
def gauss_mask(shape=(10,10),sigma=4):
m,n = [(ss-1.)/2. for ss in shape]
y,x = np.ogrid[-m:m+1,-n:n+1]
h = np.exp( -(x*x + y*y) / (2.*sigma*sigma) )
h[ h < np.finfo(h.dtype).eps*h.max() ] = 0
sumh = h.sum()
if sumh != 0:
h /= sumh
return h
def obj_exclusive_mask(master_canvas, dilate_others=0, obj_idx=0, dynamic_range=255.):
temp_master_canvas = master_canvas.copy()*dynamic_range/ | np.max(master_canvas) | numpy.max |
#%%
import pickle
import matplotlib.pyplot as plt
from matplotlib import rcParams
rcParams.update({'figure.autolayout': True})
import numpy as np
from itertools import product
import seaborn as sns
### MAIN HYPERPARAMS ###
slots = 1
shifts = 6
alg_name = ['L2N','L2F']
########################
#%%
def unpickle(file):
with open(file, 'rb') as fo:
dict = pickle.load(fo, encoding='bytes')
return dict
def get_fte_bte(err, single_err):
bte = [[] for i in range(10)]
te = [[] for i in range(10)]
fte = []
for i in range(10):
for j in range(i,10):
#print(err[j][i],j,i)
bte[i].append(err[i][i]/err[j][i])
te[i].append(single_err[i]/err[j][i])
for i in range(10):
fte.append(single_err[i]/err[i][i])
return fte,bte,te
def calc_mean_bte_(btes,task_num=10,reps=6):
mean_bte = [[] for i in range(task_num)]
for j in range(task_num):
tmp = 0
for i in range(reps):
tmp += | np.array(btes[i][j]) | numpy.array |
from ...utils import gradient_diffusion
import numpy as np
import skimage.morphology as mp
from skimage import measure as ms
def gvf_tracking(I, Mask, K=1000, Diffusions=10, Mu=5, Lambda=5, Iterations=10,
dT=0.05):
"""
Performs gradient-field tracking to segment smoothed images of cell nuclei.
Takes as input a smoothed intensity or Laplacian-of-Gaussian filtered image
and a foreground mask, and groups pixels by tracking them to mutual
gradient sinks. Typically requires merging of sinks (seeds) as a post
processing steps.
Parameters
----------
I : array_like
Smoothed intensity or log-filtered response where nuclei regions have
larger intensity values than background.
Mask : array_like
Binary mask where foreground objects have value 1, and background
objects have value 0. Used to restrict influence of background vectors
on diffusion process and to reduce tracking computations.
K : float
Number of steps to check for tracking cycle. Default value = 1000.
Mu : float
Weight parmeter from Navier-Stokes diffusion - weights divergence and
Laplacian terms. Default value = 5.
Lambda : float
Weight parameter from Navier-Stokes diffusion - used to weight
divergence. Default value = 5.
Iterations : float
Number of time-steps to use in Navier-Stokes diffusion. Default value =
10.
dT : float
Timestep to be used in Navier-Stokes diffusion. Default value = 0.05.
Returns
-------
Segmentation : array_like
Label image where positive values correspond to foreground pixels that
share mutual sinks.
Sinks : array_like
N x 2 array containing the (x,y) locations of the tracking sinks. Each
row is an (x,y) pair - in that order.
See Also
--------
histomicstk.utils.gradient_diffusion,
histomicstk.segmentation.label.shuffle
References
----------
.. [#] G. Li et al "3D cell nuclei segmentation based on gradient flow
tracking" in BMC Cell Biology,vol.40,no.8, 2007.
"""
# get image shape
M = I.shape[0]
N = I.shape[1]
# calculate gradient
dy, dx = np.gradient(I)
# diffusion iterations
if Diffusions > 0:
dx, dy = gradient_diffusion(dx, dy, Mask, Mu, Lambda, Diffusions,
dT)
# normalize to unit magnitude
Mag = ((dx**2 + dy**2)**0.5 + np.finfo(float).eps)
dy = dy / Mag
dx = dx / Mag
# define mask to track pixels that are mapped to a sink
Mapped = np.zeros(I.shape)
# define label image
Segmentation = np.zeros(I.shape)
# initialize lists of sinks
Sinks = []
# define coordinates for foreground pixels (Mask == 1)
i, j = np.nonzero(Mask)
# track pixels
for index, (x, y) in enumerate(zip(j, i)):
# initialize angle, trajectory length, novel flag, and allocation count
phi = 0
points = 1
novel = 1
alloc = 1
# initialize trajectory
Trajectory = np.zeros((K, 2))
Trajectory[0, 0] = x
Trajectory[0, 1] = y
# track while angle defined by successive steps is < np.pi / 2
while(phi < np.pi / 2):
# calculate step
xStep = round_float(dx[Trajectory[points-1, 1],
Trajectory[points-1, 0]])
yStep = round_float(dy[Trajectory[points-1, 1],
Trajectory[points-1, 0]])
# check image edge
if ((Trajectory[points-1, 0] + xStep < 0) or
(Trajectory[points-1, 0] + xStep > N-1) or
(Trajectory[points-1, 1] + yStep < 0) or
(Trajectory[points-1, 1] + yStep > M-1)):
break
# add new point to trajectory list
if points < K: # buffer is not overrun
Trajectory[points, 0] = Trajectory[points-1, 0] + xStep
Trajectory[points, 1] = Trajectory[points-1, 1] + yStep
else: # buffer overrun
# check for cycle
cycle = detect_cycle(Trajectory, points)
if cycle == points: # no cycle, simple overflow. grow buffer.
# copy and reallocate
temp = Trajectory
Trajectory = np.zeros((K*alloc, 2))
Trajectory[K*(alloc-1):K*alloc, ] = temp
alloc += 1
# add new point
Trajectory[points, 0] = Trajectory[points-1, 0] + xStep
Trajectory[points, 1] = Trajectory[points-1, 1] + yStep
else: # overflow due to cycle, terminate tracking
points = cycle
# check mapping
if Mapped[Trajectory[points, 1], Trajectory[points, 0]] == 1:
novel = 0
phi = np.pi
elif Mask[Trajectory[points, 1], Trajectory[points, 0]] == 0:
phi = np.pi
else:
phi = np.arccos(dy[Trajectory[points-1, 1],
Trajectory[points-1, 0]] *
dy[Trajectory[points, 1],
Trajectory[points, 0]] +
dx[Trajectory[points-1, 1],
Trajectory[points-1, 0]] *
dx[Trajectory[points, 1],
Trajectory[points, 0]])
# increment trajectory length counter
points += 1
# determine if sink is novel
if novel == 1:
# record sinks
Sinks.append(Trajectory[points-1, ])
# add trajectory to label image with new sink value, add mapping
for j in range(points):
Segmentation[Trajectory[j, 1], Trajectory[j, 0]] = len(Sinks)
Mapped[Trajectory[j, 1], Trajectory[j, 0]] = 1
else:
# add trajectory to label image with sink value of final point
for j in range(points):
Segmentation[Trajectory[j, 1], Trajectory[j, 0]] = \
Segmentation[Trajectory[points-1, 1],
Trajectory[points-1, 0]]
# convert Sinks to numpy array
Sinks = np.asarray(Sinks)
return Segmentation, Sinks
def merge_sinks(Label, Sinks, Radius=5):
"""
Merges attraction basins obtained from gradient flow tracking using
sink locations.
Parameters
----------
Segmentation : array_like
Label image where positive values correspond to foreground pixels that
share mutual sinks.
Sinks : array_like
N x 2 array containing the (x,y) locations of the tracking sinks. Each
row is an (x,y) pair - in that order.
Radius : float
Radius used to merge sinks. Sinks closer than this radius to one
another will have their regions of attraction merged.
Default value = 5.
Returns
-------
Merged : array_like
Label image where attraction regions are merged.
"""
# build seed image
SeedImage = np.zeros(Label.shape)
for i in range(Sinks.shape[0]):
SeedImage[Sinks[i, 1], Sinks[i, 0]] = i+1
# dilate sink image
Dilated = mp.binary_dilation(SeedImage, mp.disk(Radius))
# generate new labels for merged seeds, define memberships
Labels = ms.label(Dilated)
New = Labels[Sinks[:, 1].astype(np.int), Sinks[:, 0].astype(np.int)]
# get unique list of seed clusters
Unique = np.arange(1, New.max()+1)
# generate new seed list
Merged = np.zeros(Label.shape)
# get pixel list for each sink object
Props = ms.regionprops(Label.astype(np.int))
# fill in new values
for i in Unique:
Indices = np.nonzero(New == i)[0]
for j in Indices:
Coords = Props[j].coords
Merged[Coords[:, 0], Coords[:, 1]] = i
return Merged
def detect_cycle(Trajectory, points):
# initialize trajectory length
length = 0
# identify trajectory bounding box
xMin = np.min(Trajectory[0:points, 0])
xMax = np.max(Trajectory[0:points, 0])
xRange = xMax - xMin + 1
yMin = np.min(Trajectory[0:points, 1])
yMax = np.max(Trajectory[0:points, 1])
yRange = yMax - yMin + 1
# fill in trajectory map
Map = | np.zeros((yRange, xRange)) | numpy.zeros |
#!/usr/bin/env python
import numpy as np
import matplotlib.pyplot as plt
import datetime as dt
from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter
import csv
import os.path
from download import download
import tensorflow as tf
import tensorflow_probability as tfp
from tensorflow_probability import distributions as tfd
def define_model(info: dict, level: str = "stock"):
"""
Define and return graphical model.
Parameters
----------
info: dict
Data information.
level: str
Level of the model; possible candidates are "stock", "industry", "sector" and "market".
"""
tt = info['tt']
order_scale = info['order_scale']
order = len(order_scale) - 1
num_sectors = info['num_sectors']
sec2ind_id = info['sector_industries_id']
ind_id = info['industries_id']
available_levels = ["market", "sector", "industry", "stock"]
if level not in available_levels:
raise Exception("Selected level is unknown. Please provide one of the following levels: {}.".format(available_levels))
m = [tfd.Normal(loc=tf.zeros([1, order + 1]), scale=4 * order_scale), # phi_m
tfd.Normal(loc=0, scale=4)] # psi_m
if level != "market":
m += [lambda psi_m, phi_m: tfd.Normal(loc=tf.repeat(phi_m, num_sectors, axis=0), scale=2 * order_scale), # phi_s
lambda phi_s, psi_m: tfd.Normal(loc=psi_m, scale=2 * tf.ones([num_sectors, 1]))] # psi_s
if level != "sector":
sec2ind_id = info['sector_industries_id']
m += [lambda psi_s, phi_s: tfd.Normal(loc=tf.gather(phi_s, sec2ind_id, axis=0), scale=order_scale), # phi_i
lambda phi_i, psi_s: tfd.Normal(loc=tf.gather(psi_s, sec2ind_id, axis=0), scale=1)] # psi_ii
if level != "industry":
ind_id = info['industries_id']
m += [lambda psi_i, phi_i: tfd.Normal(loc=tf.gather(phi_i, ind_id, axis=0), scale=0.5 * order_scale), # phi
lambda phi, psi_i: tfd.Normal(loc=tf.gather(psi_i, ind_id, axis=0), scale=0.5)] # psi
if level == "market":
m += [lambda psi_m, phi_m: tfd.Normal(loc=tf.tensordot(phi_m, tt, axes=1), scale=tf.math.softplus(psi_m))] # y
if level == "sector":
m += [lambda psi_s, phi_s: tfd.Normal(loc=tf.tensordot(phi_s, tt, axes=1), scale=tf.math.softplus(psi_s))] # y
if level == "industry":
m += [lambda psi_i, phi_i: tfd.Normal(loc=tf.tensordot(phi_i, tt, axes=1), scale=tf.math.softplus(psi_i))] # y
if level == "stock":
m += [lambda psi, phi: tfd.Normal(loc=tf.tensordot(phi, tt, axes=1), scale=tf.math.softplus(psi))] # y
return tfd.JointDistributionSequentialAutoBatched(m)
def training(logp: np.array, info: dict, learning_rate: float = 0.01, num_steps: int = 20000, plot_losses: bool = False):
"""
It performs sequential optimization over the model parameters via Adam optimizer, training at different levels to
provide sensible initial solutions at finer levels.
Parameters
----------
logp: np.array
Log-price at stock-level.
info: dict
Data information.
learning_rate: float
Adam's fixed learning rate.
num_steps: int
Adam's fixed number of iterations.
plot_losses: bool
If True, a losses decay plot is saved in the current directory.
Returns
-------
It returns trained parameters.
"""
optimizer = tf.optimizers.Adam(learning_rate=learning_rate)
num_steps_l = int(np.ceil(num_steps // 4))
# market
model = define_model(info, "market")
phi_m, psi_m = (tf.Variable(tf.zeros_like(model.sample()[:2][i])) for i in range(2))
loss_m = tfp.math.minimize(lambda: -model.log_prob([phi_m, psi_m, logp.mean(0, keepdims=1)]),
optimizer=optimizer, num_steps=num_steps_l)
# sector
model = define_model(info, "sector")
phi_m, psi_m = tf.constant(phi_m), tf.constant(psi_m)
phi_s, psi_s = (tf.Variable(tf.zeros_like(model.sample()[2:4][i])) for i in range(2))
logp_s = np.array([logp[np.where(np.array(info['sectors_id']) == k)[0]].mean(0) for k in range(info['num_sectors'])])
loss_s = tfp.math.minimize(lambda: -model.log_prob([phi_m, psi_m, phi_s, psi_s, logp_s]),
optimizer=optimizer, num_steps=num_steps_l)
# industry
model = define_model(info, "industry")
phi_s, psi_s = tf.constant(phi_s), tf.constant(psi_s)
phi_i, psi_i = (tf.Variable(tf.zeros_like(model.sample()[4:6][i])) for i in range(2))
logp_i = np.array([logp[np.where(np.array(info['industries_id']) == k)[0]].mean(0) for k in range(info['num_industries'])])
loss_i = tfp.math.minimize(lambda: -model.log_prob([phi_m, psi_m, phi_s, psi_s, phi_i, psi_i, logp_i]),
optimizer=optimizer, num_steps=num_steps_l)
# stock
model = define_model(info, "stock")
phi_i, psi_i = tf.constant(phi_i), tf.constant(psi_i)
phi, psi = (tf.Variable(tf.zeros_like(model.sample()[6:8][i])) for i in range(2))
loss = tfp.math.minimize(lambda: -model.log_prob([phi_m, psi_m, phi_s, psi_s, phi_i, psi_i, phi, psi, logp]),
optimizer=optimizer, num_steps=num_steps_l)
if plot_losses:
fig_name = 'losses_decay.png'
fig = plt.figure(figsize=(20, 3))
plt.subplot(141)
plt.title("market-level", fontsize=12)
plt.plot(loss_m)
plt.subplot(142)
plt.title("sector-level", fontsize=12)
plt.plot(loss_s)
plt.subplot(143)
plt.title("industry-level", fontsize=12)
plt.plot(loss_i)
plt.subplot(144)
plt.title("stock-level", fontsize=12)
plt.plot(loss)
plt.legend(["loss decay"], fontsize=12, loc="upper right")
plt.xlabel("iteration", fontsize=12)
fig.savefig(fig_name, dpi=fig.dpi)
print('Losses decay plot has been saved in this directory as {}.'.format(fig_name))
return phi_m, psi_m, phi_s, psi_s, phi_i, psi_i, phi, psi
def softplus(x: np.array):
"""
It is a function from real to positive numbers
Parameters
----------
x: np.array
Real value.
"""
return np.log(1 + np.exp(x))
def order_selection(logp: np.array, info: dict, orders: np.array = np.arange(1, 14), horizon: int = 5):
"""
It is a function from real to positive numbers
Parameters
----------
logp: np.array
Log-prices at stock-level.
info: dict
Data information.
orders: np.array
Array of candidate orders.
horizon: int
Number of days to evaluate prediction.
"""
print("\nModel selection in progress. This can take a few minutes...")
t = logp[:, :-horizon].shape[1]
min_loss = np.inf
count = 0
for i, order in enumerate(orders):
info['tt'] = (np.linspace(1 / t, 1, t) ** np.arange(order + 1).reshape(-1, 1)).astype('float32')
info['order_scale'] = np.linspace(1 / (order + 1), 1, order + 1)[::-1].astype('float32')[None, :]
# training the model
phi_m, psi_m, phi_s, psi_s, phi_i, psi_i, phi, psi = training(logp[:, :-horizon], info)
# construct loss
tt_pred = ((1 + (np.arange(1, 1 + horizon) / t)) ** np.arange(order + 1).reshape(-1, 1)).astype('float32')
logp_pred = np.dot(phi.numpy(), tt_pred)
std_logp_pred = softplus(psi.numpy())
scores = (logp_pred - logp[:, -horizon:]) / std_logp_pred
loss = np.abs(np.mean(scores ** 2) - 1)
print("Loss value for backtested polynomial model of order {}: {}.".format(order, loss))
if i > 0 and loss > min_loss:
count += 1
else:
min_loss = loss
min_order = order
count = 0
if count == 3:
break
print("Model selection completed. Volatile will use a polynomial model of degree {}.".format(min_order))
return min_order
if __name__ == '__main__':
cli = ArgumentParser('Volatile: your day-to-day trading companion.',
formatter_class=ArgumentDefaultsHelpFormatter)
cli.add_argument('-s', '--symbols', type=str, nargs='+', help='List of symbols.')
cli.add_argument('--save-table', action='store_true',
help='Save prediction table in csv format.')
cli.add_argument('--no-plots', action='store_true',
help='Plot estimates with their uncertainty over time.')
cli.add_argument('--plot-losses', action='store_true',
help='Plot loss function decay over training iterations.')
args = cli.parse_args()
today = dt.date.today().strftime("%Y-%m-%d")
print('\nDownloading all available closing prices in the last year...')
if args.symbols is None:
with open("symbols_list.txt", "r") as my_file:
args.symbols = my_file.readlines()[0].split(" ")
data = download(args.symbols)
tickers = data["tickers"]
num_stocks, t = data['logp'].shape
# find unique names of sectors
usectors = np.unique(data['sectors'])
num_sectors = len(usectors)
# provide sector IDs at stock-level
sectors_id = [np.where(usectors == sector)[0][0] for sector in data['sectors']]
# find unique names of industries and store indices
uindustries, industries_idx = np.unique(data['industries'], return_index=True)
num_industries = len(uindustries)
# provide industry IDs at stock-level
industries_id = [np.where(uindustries == industry)[0][0] for industry in data['industries']]
# provide sector IDs at industry-level
sector_industries_id = np.array(sectors_id)[industries_idx].tolist()
# place relevant information in dictionary
info = dict(num_sectors=num_sectors, num_industries=num_industries, sector_industries_id=sector_industries_id,
industries_id=industries_id, sectors_id=sectors_id)
# how many days to look ahead when comparing the current price against a prediction
horizon = 5
# order of the polynomial
order = order_selection(data['logp'], info)
print("\nTraining the model...")
# times corresponding to trading dates in the data
info['tt'] = (np.linspace(1 / t, 1, t) ** np.arange(order + 1).reshape(-1, 1)).astype('float32')
# reweighing factors for parameters corresponding to different orders of the polynomial
info['order_scale'] = np.linspace(1 / (order + 1), 1, order + 1)[::-1].astype('float32')[None, :]
# training the model
phi_m, psi_m, phi_s, psi_s, phi_i, psi_i, phi, psi = training(data['logp'], info, plot_losses=args.plot_losses)
# calculate stock-level estimators of log-prices
logp_est = np.dot(phi.numpy(), info['tt'])
std_logp_est = softplus(psi.numpy())
# calculate stock-level estimators of prices
p_est = np.exp(logp_est + std_logp_est ** 2 / 2)
std_p_est = np.sqrt(np.exp(2 * logp_est + std_logp_est ** 2) * (np.exp(std_logp_est ** 2) - 1))
# calculate stock-level predictions of log-prices
tt_pred = ((1 + (np.arange(1 + horizon) / t)) ** np.arange(order + 1).reshape(-1, 1)).astype('float32')
logp_pred = np.dot(phi.numpy(), tt_pred)
std_logp_pred = softplus(psi.numpy())
# calculate stock-level prediction of prices
p_pred = np.exp(logp_pred + std_logp_pred ** 2 / 2)
std_p_pred = np.sqrt(np.exp(2 * logp_pred + std_logp_pred ** 2) * (np.exp(std_logp_pred ** 2) - 1))
# calculate industry-level estimators of log-prices
logp_ind_est = np.dot(phi_i.numpy(), info['tt'])
std_logp_ind_est = softplus(psi_i.numpy())
# calculate industry-level estimators of prices
p_ind_est = np.exp(logp_ind_est + std_logp_ind_est ** 2 / 2)
std_p_ind_est = np.sqrt(np.exp(2 * logp_ind_est + std_logp_ind_est ** 2) * (np.exp(std_logp_ind_est ** 2) - 1))
# calculate sector-level estimators of log-prices
logp_sec_est = np.dot(phi_s.numpy(), info['tt'])
std_logp_sec_est = softplus(psi_s.numpy())
# calculate sector-level estimators of prices
p_sec_est = np.exp(logp_sec_est + std_logp_sec_est ** 2 / 2)
std_p_sec_est = np.sqrt(np.exp(2 * logp_sec_est + std_logp_sec_est ** 2) * (np.exp(std_logp_sec_est ** 2) - 1))
# calculate market-level estimators of log-prices
logp_mkt_est = np.dot(phi_m.numpy(), info['tt'])
std_logp_mkt_est = softplus(psi_m.numpy())
# calculate market-level estimators of prices
p_mkt_est = np.exp(logp_mkt_est + std_logp_mkt_est ** 2 / 2)
std_p_mkt_est = np.sqrt(np.exp(2 * logp_mkt_est + std_logp_mkt_est ** 2) * (np.exp(std_logp_mkt_est ** 2) - 1))
print("Training completed.")
# calculate score
scores = ((logp_pred[:, horizon] - data["logp"][:, -1]) / std_logp_pred.squeeze())
# rank according to score
rank = np.argsort(scores)[::-1]
ranked_tickers = np.array(tickers)[rank]
ranked_scores = scores[rank]
ranked_p = np.exp(data["logp"])[rank]
ranked_p_est = p_est[rank]
ranked_std_p_est = std_p_est[rank]
ranked_p_pred = p_pred[rank]
ranked_std_p_pred = std_p_pred[rank]
# stock thresholds
st = {"HIGHLY BELOW TREND": 3, "BELOW TREND": 2, "ALONG TREND": 0, "ABOVE TREND": -2, "HIGHLY ABOVE TREND": -3}
# stock information
si = {"HIGHLY BELOW TREND": np.where(ranked_scores > st["HIGHLY BELOW TREND"])[0],
"BELOW TREND": np.where((ranked_scores <= st["HIGHLY BELOW TREND"]) & (ranked_scores > st["BELOW TREND"]))[0],
"ALONG TREND": np.where((ranked_scores <= st["BELOW TREND"]) & (ranked_scores > st["ABOVE TREND"]))[0],
"ABOVE TREND": np.where((ranked_scores <= st["ABOVE TREND"]) & (ranked_scores > st["HIGHLY ABOVE TREND"]))[0],
"HIGHLY ABOVE TREND": np.where(ranked_scores <= st["HIGHLY ABOVE TREND"])[0]}
si = {k: v[0] for k, v in si.items() if len(v) > 0}
# rate all stocks
ranked_rating = np.array(list(si.keys())).repeat(list(np.diff(list(si.values()))) + [num_stocks - list(si.values())[-1]]).tolist()
if not args.no_plots:
## information for plotting
# find unique names of sectors
usectors = np.unique(data['sectors'])
num_sectors = len(usectors)
# determine which sectors were not available to avoid plotting
NA_sectors = np.where(np.array([sec[:2] for sec in usectors]) == "NA")[0]
num_NA_sectors = len(NA_sectors)
# provide sector IDs at stock-level
sectors_id = [np.where(usectors == sector)[0][0] for sector in data['sectors']]
# find unique names of industries and store indices
uindustries = np.unique(data['industries'])
num_industries = len(uindustries)
# determine which industries were not available to avoid plotting
NA_industries = np.where(np.array([ind[:2] for ind in uindustries]) == "NA")[0]
num_NA_industries = len(NA_industries)
# provide industry IDs at stock-level
industries_id = [np.where(uindustries == industry)[0][0] for industry in data['industries']]
# ranked volume at stock level
ranked_volume = data["volume"][rank]
print('\nPlotting market estimation...')
fig = plt.figure(figsize=(10,3))
left_mkt_est = np.maximum(0, p_mkt_est - 2 * std_p_mkt_est)
right_mkt_est = p_mkt_est + 2 * std_p_mkt_est
plt.title("Market", fontsize=15)
l1 = plt.plot(data["dates"], np.exp(data['logp'].mean(0)), label="avg. price", color="C0")
l2 = plt.plot(data["dates"], p_mkt_est[0], label="trend", color="C1")
l3 = plt.fill_between(data["dates"], left_mkt_est[0], right_mkt_est[0], alpha=0.2, label="+/- 2 st. dev.", color="C0")
plt.ylabel("avg. price", fontsize=12)
plt.twinx()
l4 = plt.bar(data["dates"], ranked_volume.mean(0), width=1, color='g', alpha=0.2, label='avg. volume')
plt.ylabel("avg. volume", fontsize=12)
ll = l1 + l2 + [l3] + [l4]
labels = [l.get_label() for l in ll]
plt.legend(ll, labels, loc="upper left")
fig_name = 'market_estimation.png'
fig.savefig(fig_name, dpi=fig.dpi)
print('Market estimation plot has been saved to {}/{}.'.format(os.getcwd(), fig_name))
num_columns = 3
print('\nPlotting sector estimation...')
left_sec_est = np.maximum(0, p_sec_est - 2 * std_p_sec_est)
right_sec_est = p_sec_est + 2 * std_p_sec_est
fig = plt.figure(figsize=(20, max(num_sectors - num_NA_sectors, 5)))
j = 0
for i in range(num_sectors):
if i not in NA_sectors:
j += 1
plt.subplot(int(np.ceil((num_sectors - num_NA_sectors) / num_columns)), num_columns, j)
plt.title(usectors[i], fontsize=15)
idx_sectors = np.where(np.array(sectors_id) == i)[0]
l1 = plt.plot(data["dates"], np.exp(data['logp'][idx_sectors].reshape(-1, t).mean(0)), label="avg. price", color="C0")
l2 = plt.plot(data["dates"], p_sec_est[i], label="trend", color="C1")
l3 = plt.fill_between(data["dates"], left_sec_est[i], right_sec_est[i], alpha=0.2, label="+/- 2 st. dev.", color="C0")
plt.ylabel("avg. price", fontsize=12)
plt.xticks(rotation=45)
plt.twinx()
l4 = plt.bar(data["dates"], data['volume'][np.where(np.array(sectors_id) == i)[0]].reshape(-1, t).mean(0),
width=1, color='g', alpha=0.2, label='avg. volume')
plt.ylabel("avg. volume", fontsize=12)
ll = l1 + l2 + [l3] + [l4]
labels = [l.get_label() for l in ll]
plt.legend(ll, labels, loc="upper left")
plt.tight_layout()
fig_name = 'sector_estimation.png'
fig.savefig(fig_name, dpi=fig.dpi)
print('Sector estimation plot has been saved to {}/{}.'.format(os.getcwd(), fig_name))
print('\nPlotting industry estimation...')
left_ind_est = np.maximum(0, p_ind_est - 2 * std_p_ind_est)
right_ind_est = p_ind_est + 2 * std_p_ind_est
fig = plt.figure(figsize=(20, max(num_industries - num_NA_industries, 5)))
j = 0
for i in range(num_industries):
if i not in NA_industries:
j += 1
plt.subplot(int(np.ceil((num_industries - num_NA_industries) / num_columns)), num_columns, j)
plt.title(uindustries[i], fontsize=15)
idx_industries = np.where( | np.array(industries_id) | numpy.array |
# Copyright (c) 2022 ETH Zurich, <NAME>
# MIT License
# Load modules
import os
import numpy as np
from shapely.geometry import shape, box
import fiona
from scipy.spatial import cKDTree
import pygeos
import time
from skimage.measure import find_contours
# Load required functions
import functions_cy
###############################################################################
def get_GSHHS_coastlines(dom, path_GSHHG, path_temp):
"""Get relevant GSHHS coastline data.
Get relevant GSHHS coastline data for rectangular latitude/longitude
domain.
Parameters
----------
dom : dict
Specifications of rectangular latitude/longitude domain
('lat_min', 'lat_max', 'lon_min', 'lon_max')
path_GSHHG: str
Path to folder of GSHHS data with shapefile 'GSHHS_f_L1.shp'
path_temp: str
Path to temporary directory in which bounding boxes for coastline
polygons are cached
Returns
-------
poly_coastlines : list
Relevant coastline polygons as Shapely polygons
Notes
-----
Source of GSHHS data: https://www.soest.hawaii.edu/pwessel/gshhg/"""
# Check arguments
keys_req = ("lon_min", "lon_max", "lat_min", "lat_max")
if not set(keys_req).issubset(set(dom.keys())):
raise ValueError("one or multiple key(s) are missing in 'dom'")
if (dom["lon_min"] >= dom["lon_max"])\
or (dom["lat_min"] >= dom["lat_max"]):
raise ValueError("invalid domain extent")
if not os.path.isfile(path_GSHHG + "GSHHS_f_L1.shp"):
raise ValueError("file 'GSHHS_f_L1.shp' not found in provided "
+ "path for GSHHG data")
if not os.path.isdir(path_temp):
raise ValueError("temporary directory does not exist")
t_beg_func = time.time()
# Compute and save bounding boxes of coastlines polygons
file_bbc = path_temp + "Bounding_boxes_coastlines.npy"
if not os.path.isfile(file_bbc):
t_beg = time.time()
ds = fiona.open(path_GSHHG + "GSHHS_f_L1.shp")
bounds = np.empty((len(ds), 4), dtype=np.float32)
for idx, var in enumerate(ds):
bounds[idx, :] = shape(var["geometry"]).bounds
# (lon_min, lat_min, lon_max, lat_max)
ds.close()
np.save(file_bbc, bounds)
print("Bounding boxes for coastline polygons computed "
+ "(%.2f" % (time.time() - t_beg) + " s)")
# Find relevant polygons for domain
bounds = np.load(file_bbc)
geoms = pygeos.box(bounds[:, 0], bounds[:, 1], bounds[:, 2], bounds[:, 3])
tree = pygeos.STRtree(geoms)
quer_rang = [dom["lon_min"], dom["lat_min"],
dom["lon_max"], dom["lat_max"]]
ind = tree.query(pygeos.box(*quer_rang))
# Load relevant polygons
ds = fiona.open(path_GSHHG + "GSHHS_f_L1.shp")
poly_all = [shape(ds[int(i)]["geometry"]) for i in ind]
ds.close()
print("Number of polygons: " + str(len(poly_all)))
# Crop polygons (if necessary)
quer_rang_s = box(*quer_rang)
poly_coastlines = []
for i in poly_all:
if quer_rang_s.contains(i):
poly_coastlines.append(i)
elif quer_rang_s.intersects(i):
poly_coastlines.append(quer_rang_s.intersection(i))
print("Run time: %.2f" % (time.time() - t_beg_func) + " s")
return poly_coastlines
###############################################################################
def coastline_contours(lon, lat, mask_bin):
"""Compute coastline contours.
Compute coastline contours from binary land-sea mask.
Parameters
----------
lon : ndarray of double
Array (1-dimensional) with geographic longitude [degree]
lat: ndarray of double
Array (1-dimensional) with geographic latitude [degree]
mask_bin: str
Array (2-dimensional) with binary land-sea mask (0: water, 1: land)
Returns
-------
contours_latlon : list
List with contour lines in latitude/longitude coordinates [degree]"""
# Check arguments
if (lat.ndim != 1) or (lon.ndim != 1):
raise ValueError("Input coordinates arrays must be 1-dimensional")
if (mask_bin.shape[0] != len(lat)) or (mask_bin.shape[1] != len(lon)):
raise ValueError("Input data has inconsistent dimension length(s)")
if (mask_bin.dtype != "uint8") or (len(np.unique(mask_bin)) != 2) \
or (not np.all(np.unique(mask_bin) == [0, 1])):
raise ValueError("'mask_bin' must be of type 'uint8' and may "
+ "only contain 0 and 1")
t_beg_func = time.time()
# Compute contour lines
contours = find_contours(mask_bin, 0.5, fully_connected="high")
# Get latitude/longitude coordinates of contours
lon_ind = np.linspace(lon[0], lon[-1], len(lon) * 2 - 1)
lat_ind = np.linspace(lat[0], lat[-1], len(lat) * 2 - 1)
contours_latlon = []
for i in contours:
pts_latlon = np.empty(i.shape, dtype=np.float64)
pts_latlon[:, 0] = lon_ind[(i[:, 1] * 2).astype(np.int32)]
pts_latlon[:, 1] = lat_ind[(i[:, 0] * 2).astype(np.int32)]
contours_latlon.append(pts_latlon)
print("Run time: %.2f" % (time.time() - t_beg_func) + " s")
return contours_latlon
###############################################################################
def coastline_distance(x_ecef, y_ecef, z_ecef, mask_land, pts_ecef):
"""Compute minimal chord distance.
Compute minimal chord distance between all water grid cells (centre)
and the coastline.
Parameters
----------
x_ecef : ndarray of double
Array (two-dimensional) with ECEF x-coordinates [metre]
y_ecef : ndarray of double
Array (two-dimensional) with ECEF y-coordinates [metre]
z_ecef : ndarray of double
Array (two-dimensional) with ECEF z-coordinates [metre]
mask_land: ndarray of bool
Array (two-dimensional) with land mask
pts_ecef: ndarray of double
Array (two-dimensional) with ECEF coordinates of coastline vertices
(number of vertices, x/y/z) [metre]
Returns
-------
dist_chord : ndarray of double
Array (2-dimensional) minimal chord distance between grid cells and
coastline [metre]"""
# Check arguments
if x_ecef.shape != mask_land.shape:
raise ValueError("Input data has inconsistent dimension length(s)")
if mask_land.dtype != "bool":
raise ValueError("'mask_land' must be a boolean mask")
t_beg_func = time.time()
# Build k-d tree
tree = cKDTree(pts_ecef)
# Query k-d tree
pts_quer = np.vstack((x_ecef[~mask_land], y_ecef[~mask_land],
z_ecef[~mask_land])).transpose()
dist_quer, idx = tree.query(pts_quer, k=1, workers=-1)
# Save distances in two-dimensional array
dist_chord = np.empty(x_ecef.shape, dtype=np.float64)
dist_chord.fill(np.nan)
dist_chord[~mask_land] = dist_quer # [m]
print("Run time: %.2f" % (time.time() - t_beg_func) + " s")
return dist_chord
###############################################################################
def coastline_buffer(x_ecef, y_ecef, z_ecef, mask_land, pts_ecef, lat,
dist_thr, dem_res, ellps, block_size=(5 * 2 + 1)):
"""Compute mask according to coastline buffer.
Compute mask according to coastline buffer. Grid cells, whose minimal
chord distance from the coastline is longer than 'dist_thr', are masked.
Parameters
----------
x_ecef : ndarray of double
Array (two-dimensional) with ECEF x-coordinates [metre]
y_ecef : ndarray of double
Array (two-dimensional) with ECEF y-coordinates [metre]
z_ecef : ndarray of double
Array (two-dimensional) with ECEF z-coordinates [metre]
mask_land: ndarray of bool
Array (two-dimensional) with land mask
pts_ecef: ndarray of double
Array (two-dimensional) with ECEF coordinates of coastline vertices
(number of vertices, x/y/z) [metre]
lat: ndarray of double
Array (1-dimensional) with geographic latitude [degree]
dist_thr: double
Threshold for minimal distance from coastline [metre]
dem_res: double
Spatial resolution of digital elevation model [degree]
ellps : str
Earth's surface approximation (sphere, GRS80 or WGS84)
block_size: int
Block size of grid cells that are processed together.
Returns
-------
mask_buffer : ndarray of bool
Array (2-dimensional) with grid cells that are located outside
of the coastline buffer [metre]"""
# Check arguments
if (x_ecef.shape != mask_land.shape) or (x_ecef.shape[0] != len(lat)):
raise ValueError("Input data has inconsistent dimension length(s)")
if mask_land.dtype != "bool":
raise ValueError("'mask_land' must be a boolean mask")
if ellps not in ("sphere", "WGS84", "GRS80"):
raise ValueError("invalid value for 'ellps'")
if block_size % 2 != 1:
raise ValueError("Integer value for 'block_size' must be uneven")
t_beg_func = time.time()
# Compute maximal chord length for block (-> diagonal at equator)
# lat_ini = 0.0 # equator
lat_ini = np.maximum(np.abs(lat).min() - 1.0, 0.0)
lon_max = np.array([[0.0,
0.0 + dem_res * int((block_size - 1) / 2)]],
dtype=np.float64).reshape(1, 2)
lat_max = np.array([[lat_ini,
lat_ini + dem_res * int((block_size - 1) / 2)]],
dtype=np.float64).reshape(1, 2)
h_max = np.zeros(lon_max.shape, dtype=np.float32)
coord_ecef = functions_cy.lonlat2ecef(lon_max, lat_max, h_max, ellps=ellps)
chord_max = np.sqrt(np.diff(coord_ecef[0])[0][0] ** 2
+ np.diff(coord_ecef[1])[0][0] ** 2
+ | np.diff(coord_ecef[2]) | numpy.diff |
import numpy as np
from numpy.testing import TestCase, run_module_suite, assert_raises, \
assert_almost_equal, assert_array_almost_equal, assert_equal, \
assert_
from scipy.special import sinc
from scipy.signal import kaiser_beta, kaiser_atten, kaiserord, \
firwin, firwin2, freqz, remez
def test_kaiser_beta():
b = kaiser_beta(58.7)
assert_almost_equal(b, 0.1102 * 50.0)
b = kaiser_beta(22.0)
assert_almost_equal(b, 0.5842 + 0.07886)
b = kaiser_beta(21.0)
assert_equal(b, 0.0)
b = kaiser_beta(10.0)
assert_equal(b, 0.0)
def test_kaiser_atten():
a = kaiser_atten(1, 1.0)
assert_equal(a, 7.95)
a = kaiser_atten(2, 1/np.pi)
| assert_equal(a, 2.285 + 7.95) | numpy.testing.assert_equal |
import numpy as np
import scipy as sp
from scipy import sparse
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
from scipy import signal
from random import gauss
#import hdf5storage
import h5py
import timeit
import time
#from sympy.solvers.solveset import nonlinsolve
#from sympy.core.symbol import symbols
#from sympy import exp
from scipy import stats
import os
from .analysis import *
opj = os.path.join
#written for python 3.6
####################################################################################################
####################################################################################################
####GRAPH SIMULATIONS
####################################################################################################
####################################################################################################
####################################################################################################
#testing any time-evolution propagator defined by a kernel on the graph
####################################################################################################
def graph_propagator_test(u_0, Time, Delta_t, kernel_param, Graph_Kernel, a=1, b=1, c=1, sigma_noise=0,
one_dim=False, syn=0, gridsize=1000, h=0.01, GF_domain=False, eigvals=None, eigvecs=None,
Visual=False, SaveActivity=False, Filepath=' ', NSim=0):
if one_dim==True:
s,U = one_dim_Laplacian_eigenvalues(gridsize, h, syn, vecs=True)
else:
s=eigvals
U=eigvecs
#note that s is a vector of eigenvalues, not the diagonal matrix of eigenvalues
#s_matrix=sp.sparse.diags(s).toarray()
if Graph_Kernel!='Damped Wave':
kernel_gf = GraphKernel(s,kernel_param, type=Graph_Kernel)
if GF_domain == False:
kernel_matrix=sp.sparse.diags(kernel_gf).toarray()
Laplacian_based_propagator = np.dot(U, np.dot(kernel_matrix, U.T))
else:
kernel_gf, kernel_gf_prime=GraphKernel(s,kernel_param, type=Graph_Kernel, a=a, b=b, c=c, prime=True)
if GF_domain == False:
Laplacian_based_propagator = np.dot(U, np.dot(sp.sparse.diags(kernel_gf).toarray(), U.T))
Laplacian_based_propagator_prime = np.dot(U, np.dot(sp.sparse.diags(kernel_gf_prime).toarray(), U.T))
Timesteps = int(round(Time/Delta_t))
u_Delta_t = np.zeros_like(u_0)
u_prime = np.zeros_like(u_0)
if SaveActivity==True or GF_domain == True:
u_total = np.zeros((len(u_0),Timesteps))
if Visual==True and GF_domain == False:
plt.ion()
fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_xlim(0, len(u_0))
#ax.set_ylim(0, 11)
#line2, = ax.plot(np.arange(len(I_0)), I_0, 'b-')
#line1, = ax.plot(np.arange(len(E_0)), E_0, 'r-')
ax.plot(u_0, 'b-')
fig.canvas.draw()
for i in range(Timesteps):
if sigma_noise!=0:
Noise = sigma_noise * np.array([gauss(0.0, 1.0) for k in range(len(u_0))])
else:
Noise = 0
if SaveActivity==True or GF_domain == True:
u_total[:,i]=np.copy(u_0)
if i%10 == 0:
print(i)
#impulse response
# if i==500:
# E_Delta_t[600:650]=0.9*np.ones(50)
# I_Delta_t[580:620]=0.9*np.ones(40)
if Graph_Kernel!='Damped Wave':
if GF_domain == False:
u_Delta_t = np.dot(Laplacian_based_propagator,u_0)+np.sqrt(Delta_t)*Noise
else:
u_Delta_t = kernel_gf * u_0 + np.sqrt(Delta_t)*Noise
else:
if GF_domain == False:
u_Delta_t = np.dot(Laplacian_based_propagator,u_0)+np.dot(Laplacian_based_propagator_prime,u_prime)+np.sqrt(Delta_t)*Noise
u_prime=(u_Delta_t-u_0)/kernel_param
else:
u_Delta_t = kernel_gf * u_0 + kernel_gf_prime * u_prime + np.sqrt(Delta_t)*Noise
u_prime=(u_Delta_t-u_0)/kernel_param
if Visual==True and i%5 == 0 and GF_domain == False:
time.sleep(0.03)
ax.clear()
ax.set_xlim(0, len(u_0))
#ax.set_ylim(-0.05,0.1)
#line2.set_ydata(I_Delta_t)
#line1.set_ydata(E_Delta_t)
ax.plot(u_Delta_t, 'b-')
fig.canvas.draw()
fig.canvas.flush_events()
u_0 = np.copy(u_Delta_t)
if SaveActivity==True:
if Filepath==' ':
if one_dim==True:
filepath = 'G:/Macbook Stuff/Simulation Results/1D '+Graph_Kernel+' Kernel Test t=%.f/'%(kernel_param)
else:
filepath = 'G:/Macbook Stuff/Simulation Results/'+Graph_Kernel+' Kernel Test t=%.f/'%(kernel_param)
else:
filepath=Filepath
if not os.path.exists(filepath):
os.makedirs(filepath)
with h5py.File(filepath+"%d# Sim Activity.h5"%(NSim)) as hf:
if "Activity" not in list(hf.keys()):
hf.create_dataset("Activity", data=u_total)
else:
print("Warning: overwriting results of a previous simulation.")
del hf["Activity"]
hf.create_dataset("Activity", data=u_total)
if GF_domain == False:
return u_Delta_t
else:
return u_total
####################################################################################################
####################################################################################################
##################################################################
##GRAPH STOCHASTIC <NAME>
##################################################################
#compute the four diffusion operators beforehand
def graph_WCM_propagators(alpha_EE=1, alpha_IE=1, alpha_EI=1, alpha_II=1,
sigma_EE=10, sigma_IE=10, sigma_EI=10, sigma_II=10, D=1,
Graph_Kernel='Gaussian', one_dim=False, syn=0, gridsize=1000, h=0.01,
eigvals=None, eigvecs=None):
t_EE = (0.5*sigma_EE**2)/D
t_IE = (0.5*sigma_IE**2)/D
t_EI = (0.5*sigma_EI**2)/D
t_II = (0.5*sigma_II**2)/D
ForceParallel=True
if one_dim==True:
s,U = one_dim_Laplacian_eigenvalues(gridsize, h, syn, vecs=True)
V=U.T
else:
s=eigvals
U=eigvecs
V=eigvecs.T
if ForceParallel==True:
diag_prop_EE = alpha_EE * GraphKernel(s, t_EE, Graph_Kernel)
diag_prop_IE = alpha_IE * GraphKernel(s, t_IE, Graph_Kernel)
diag_prop_EI = alpha_EI * GraphKernel(s, t_EI, Graph_Kernel)
diag_prop_II = alpha_II * GraphKernel(s, t_II, Graph_Kernel)
mask_EE = np.flatnonzero(diag_prop_EE)
mask_IE = np.flatnonzero(diag_prop_IE)
mask_EI = np.flatnonzero(diag_prop_EI)
mask_II = np.flatnonzero(diag_prop_II)
EE_skip = diag_prop_EE[mask_EE]
IE_skip = diag_prop_IE[mask_IE]
EI_skip = diag_prop_EI[mask_EI]
II_skip = diag_prop_II[mask_II]
prop_EEV = EE_skip[:,None] * V[mask_EE,:]
prop_IEV = IE_skip[:,None] * V[mask_IE,:]
prop_EIV = EI_skip[:,None] * V[mask_EI,:]
prop_IIV = II_skip[:,None] * V[mask_II,:]
propagator_EE = transpose_parallel_dot(V[mask_EE,:], prop_EEV) #np.dot(U, np.dot(s_exp_matrix_EE,V))
propagator_IE = transpose_parallel_dot(V[mask_IE,:], prop_IEV)
propagator_EI = transpose_parallel_dot(V[mask_EI,:], prop_EIV)
propagator_II = transpose_parallel_dot(V[mask_II,:], prop_IIV)
else:
diag_prop_EE = sp.sparse.diags(alpha_EE * GraphKernel(s, t_EE, Graph_Kernel)).toarray()
diag_prop_IE = sp.sparse.diags(alpha_IE * GraphKernel(s, t_IE, Graph_Kernel)).toarray()
diag_prop_EI = sp.sparse.diags(alpha_EI * GraphKernel(s, t_EI, Graph_Kernel)).toarray()
diag_prop_II = sp.sparse.diags(alpha_II * GraphKernel(s, t_II, Graph_Kernel)).toarray()
propagator_EE = np.dot(U, np.dot(diag_prop_EE,V))
propagator_IE = np.dot(U, np.dot(diag_prop_IE,V))
propagator_EI = np.dot(U, np.dot(diag_prop_EI,V))
propagator_II = np.dot(U, np.dot(diag_prop_II,V))
return propagator_EE.astype('float64'), propagator_IE.astype('float64'), propagator_EI.astype('float64'), propagator_II.astype('float64')
#@jit(nopython=True, parallel=True)
def transpose_parallel_dot(A, B):
return np.dot(A.T, B)
#@jit(nopython=True, parallel=True)
def GWCM_Loop(E_0, I_0, Delta_t,
propagator_EE, propagator_IE, propagator_EI, propagator_II,
d_e, d_i, P, Q, tau_e, tau_i, Noise_E, Noise_I):
time_E = Delta_t/tau_e
time_I = Delta_t/tau_i
#print(I_0.dtype)
E_Delta_t = E_0 + time_E*(-d_e*E_0 + 1/(1+np.exp(-np.dot(propagator_EE,np.float64(E_0)) + np.dot(propagator_IE,np.float64(I_0)) - P)))+ Noise_E*np.sqrt(Delta_t)/tau_e
I_Delta_t = I_0 + time_I*(-d_i*I_0 + 1/(1+np.exp(-np.dot(propagator_EI,np.float64(E_0)) + np.dot(propagator_II,np.float64(I_0)) - Q)))+ Noise_I*np.sqrt(Delta_t)/tau_i
#print(E_Delta_t.shape)
return E_Delta_t, I_Delta_t
#Wilson Cowan model
def Graph_Wilson_Cowan_Model(Ess, Iss, Time, Delta_t,
alpha_EE=1, alpha_IE=1, alpha_EI=1, alpha_II=1,
sigma_EE=10, sigma_IE=10, sigma_EI=10, sigma_II=10, D=1,
d_e=1, d_i=1, P=0, Q=0, tau_e=1, tau_i=1, sigma_noise_e=1, sigma_noise_i=1,
Graph_Kernel='Gaussian', one_dim=False, syn=0, gridsize=1000, h=0.01, eigvals=None, eigvecs=None,
Visual=False, SaveActivity=False, Filepath=' ', NSim=0):
propagator_EE, propagator_IE, propagator_EI, propagator_II = graph_WCM_propagators(
alpha_EE, alpha_IE, alpha_EI, alpha_II,
sigma_EE, sigma_IE, sigma_EI, sigma_II, D,
Graph_Kernel, one_dim, syn, gridsize, h, eigvals,eigvecs)
if one_dim==True:
E_0=Ess*np.ones(gridsize, dtype='float64')
I_0=Iss*np.ones(gridsize, dtype='float64')
else:
E_0=Ess*np.ones(len(eigvals), dtype='float64')
I_0=Iss*np.ones(len(eigvals), dtype='float64')
E_Delta_t = np.zeros_like(E_0)
I_Delta_t = np.zeros_like(I_0)
Timesteps = int(round(Time/Delta_t))
E_total = np.zeros((len(E_0),Timesteps-1000), dtype='float32')
if Visual==True:
plt.ion()
fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_xlim(0, len(E_0))
ax.set_ylim(0, 1)
#line2, = ax.plot(np.arange(len(I_0)), I_0, 'b-')
#line1, = ax.plot(np.arange(len(E_0)), E_0, 'r-')
ax.plot(I_0, 'b-')
ax.plot(E_0, 'r-')
fig.canvas.draw()
numerical_SS = True
if numerical_SS == True:
Ess_numerical=[]
Iss_numerical=[]
for i in range(Timesteps):
if sigma_noise_e!=0 or sigma_noise_i!=0:
Noise_E = (sigma_noise_e * np.array([gauss(0.0, 1.0) for k in range(len(E_0))])).astype('float64')
Noise_I = (sigma_noise_i * np.array([gauss(0.0, 1.0) for k in range(len(I_0))])).astype('float64')
else:
Noise_E = 0
Noise_I = 0
#it turns out that the alphas ARE important, ie. at least manually, i cant get oscillations if i set them to one
#simply manipulating the sigmas doesnt appear to be enough for oscillations. analysis or systematic numerics would solve this
#impulse response
# if i==500:
# E_Delta_t[600:650]=0.9*np.ones(50)
# I_Delta_t[580:620]=0.9*np.ones(40)
E_Delta_t, I_Delta_t = GWCM_Loop(E_0, I_0, Delta_t,
propagator_EE, propagator_IE, propagator_EI, propagator_II,
d_e, d_i, P, Q, tau_e, tau_i, Noise_E, Noise_I)
if i>=1000:
E_total[:,i-1000]=np.copy(E_Delta_t).astype('float32')
if numerical_SS == True:
Ess_numerical.append(np.mean(E_Delta_t))
Iss_numerical.append(np.mean(I_Delta_t))
if i%10 == 0:
print(i)
if Visual==True:
ax.clear()
ax.set_ylim(Ess-sigma_noise_e, Ess+sigma_noise_e)
#line2.set_ydata(I_Delta_t)
#line1.set_ydata(E_Delta_t)
ax.plot(I_Delta_t, 'b-')
ax.plot(E_Delta_t, 'r-')
fig.canvas.draw()
fig.canvas.flush_events()
E_0 = np.copy(E_Delta_t)
I_0 = np.copy(I_Delta_t)
#print(E_0.shape)
#print(str(E_0[10])+" "+str(I_0[20]))
if SaveActivity==True:
if Filepath==' ':
filepath = 'G:/Macbook Stuff/Results/'+Graph_Kernel+' Kernel/aEE=%.3f aIE=%.3f aEI=%.3f aII=%.3f dE=%.3f dI=%.3f ' %(alpha_EE,alpha_IE,alpha_EI,alpha_II,d_e,d_i)
filepath += 'P=%.3f Q=%.3f sEE=%.3f sIE=%.3f sEI=%.3f sII=%.3f D=%.3f tE=%.3f tI=%.3f/'%(P,Q,sigma_EE,sigma_IE,sigma_EI,sigma_II,D,tau_e,tau_i)
else:
filepath=Filepath
if not os.path.exists(filepath):
os.makedirs(filepath)
#make DAT files with sim-only parameters (delta t, time, etc)
with h5py.File(filepath+"Activity E0=%.5f Sim #%d.h5"%(Ess, NSim)) as hf:
if "Activity" not in list(hf.keys()):
hf.create_dataset("Activity", data=E_total)
else:
print("Warning: overwriting results of a previous simulation.")
del hf["Activity"]
hf.create_dataset("Activity", data=E_total)
if numerical_SS==True:
print(np.mean(np.array(Ess_numerical)))
print(np.mean(np.array(Iss_numerical)))
return E_total
#################################################################################
#
# LINEARIZED MODEL
#
##################################################################################
def Linearized_GLDomain_Wilson_Cowan_Model(Ess, Iss, Time, Delta_t,
alpha_EE=1, alpha_IE=1, alpha_EI=1, alpha_II=1,
sigma_EE=10, sigma_IE=10, sigma_EI=10, sigma_II=10, D=1,
d_e=1, d_i=1, P=0, Q=0, tau_e=1, tau_i=1, sigma_noise_e=1, sigma_noise_i=1,
Graph_Kernel='Gaussian', one_dim=False, syn=0, gridsize=1000, h=0.01, eigvals=None, eigvecs=None,
Visual=False, SaveActivity=False, Filepath=' ', NSim=0):
t_EE = (0.5*sigma_EE**2)/D
t_IE = (0.5*sigma_IE**2)/D
t_EI = (0.5*sigma_EI**2)/D
t_II = (0.5*sigma_II**2)/D
a = d_e*Ess*(1-d_e*Ess)
b = d_i*Iss*(1-d_i*Iss)
#eigenvectors are used for plotting purposes only.
if one_dim==True:
s, U = one_dim_Laplacian_eigenvalues(gridsize, h, syn, vecs=True)
else:
s=eigvals
U=eigvecs
#fluctuations about the steady state
beta_E_0 = np.zeros(len(s), dtype='float64')
beta_I_0 = np.zeros(len(s), dtype='float64')
prop_EE = (alpha_EE * GraphKernel(s, t_EE, Graph_Kernel)).astype('float64')
prop_IE = (alpha_IE * GraphKernel(s, t_IE, Graph_Kernel)).astype('float64')
prop_EI = (alpha_EI * GraphKernel(s, t_EI, Graph_Kernel)).astype('float64')
prop_II = (alpha_II * GraphKernel(s, t_II, Graph_Kernel)).astype('float64')
beta_E_Delta_t = np.zeros_like(beta_E_0)
beta_I_Delta_t = np.zeros_like(beta_I_0)
Timesteps = int(round(Time/Delta_t))
time_E = Delta_t/tau_e
time_I = Delta_t/tau_i
beta_E_total = np.zeros((len(beta_E_0),Timesteps-1000), dtype='float32')
if Visual==True:
plt.ion()
fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_xlim(0, len(beta_E_0))
#ax.set_ylim(0, 1)
#line2, = ax.plot(np.arange(len(I_0)), I_0, 'b-')
#line1, = ax.plot(np.arange(len(E_0)), E_0, 'r-')
ax.plot(np.dot(U,beta_I_0), 'b-')
ax.plot(np.dot(U,beta_E_0), 'r-')
fig.canvas.draw()
for i in range(Timesteps):
if sigma_noise_e!=0 or sigma_noise_i!=0:
Noise_E = (sigma_noise_e * np.array([gauss(0.0, 1.0) for k in range(len(beta_E_0))])).astype('float64')
Noise_I = (sigma_noise_i * np.array([gauss(0.0, 1.0) for k in range(len(beta_I_0))])).astype('float64')
else:
Noise_E = 0
Noise_I = 0
beta_E_Delta_t = beta_E_0 + time_E*((-d_e+a*prop_EE)*beta_E_0 - a*prop_IE*beta_I_0) + Noise_E* | np.sqrt(Delta_t) | numpy.sqrt |
from __future__ import division, print_function
import numpy as np
from cudf.dataframe import columnops
from librmm_cffi import librmm as rmm
import cudf.bindings.copying as cpp_copying
def test_gather_single_col():
col = columnops.as_column(np.arange(100), dtype=np.int32)
gather_map = np.array([0, 1, 2, 3, 5, 8, 13, 21], dtype=np.int32)
device_gather_map = rmm.to_device(gather_map)
out = cpp_copying.apply_gather_column(col, device_gather_map)
np.testing.assert_array_equal(out.to_array(), gather_map)
def test_gather_cols():
cols = [columnops.as_column(np.arange(10), dtype=np.int32),
columnops.as_column(np.arange(0.0, 2.0, 0.2), dtype=np.float32)]
gather_map = np.array([0, 1, 2, 3, 5, 8], dtype=np.int32)
expected = np.array(gather_map * 0.2, dtype=np.float32)
device_gather_map = rmm.to_device(gather_map)
out = cpp_copying.apply_gather(cols, device_gather_map)
np.testing.assert_array_equal(out[0].to_array(), gather_map)
np.testing.assert_array_almost_equal(out[1].to_array(), expected)
def test_scatter_single_col():
col = columnops.as_column(np.arange(2.0, 0.0, -0.2), dtype=np.float32)
col_out = columnops.as_column(np.arange(0.0, 100.0, 1.0), dtype=np.float32)
scatter_map = | np.arange(10, 0, -1) | numpy.arange |
from __future__ import absolute_import
from __future__ import division
from builtins import str
from builtins import range
from past.utils import old_div
import proteus
import numpy as np
from math import fabs
import os
from proteus import cfemIntegrals, Quadrature, Norms, Comm
from proteus.NonlinearSolvers import NonlinearEquation
from proteus.FemTools import (DOFBoundaryConditions,
FluxBoundaryConditions,
C0_AffineLinearOnSimplexWithNodalBasis)
from proteus.Comm import globalMax
from proteus.Profiling import memory
from proteus.Profiling import logEvent as log
from proteus.Transport import OneLevelTransport
from proteus.TransportCoefficients import TC_base
from proteus.SubgridError import SGE_base
from proteus.ShockCapturing import ShockCapturing_base
from . import cNCLS3P
from . import cArgumentsDict
class SubgridError(proteus.SubgridError.SGE_base):
def __init__(self, coefficients, nd):
proteus.SubgridError.SGE_base.__init__(self, coefficients, nd, False)
def initializeElementQuadrature(self, mesh, t, cq):
for ci in range(self.nc):
cq[('dH_sge', ci, ci)] = cq[('dH', ci, ci)]
def calculateSubgridError(self, q):
pass
def updateSubgridErrorHistory(self, initializationPhase=False):
pass
class ShockCapturing(proteus.ShockCapturing.ShockCapturing_base):
def __init__(
self,
coefficients,
nd,
shockCapturingFactor=0.25,
lag=True,
nStepsToDelay=None):
proteus.ShockCapturing.ShockCapturing_base.__init__(
self, coefficients, nd, shockCapturingFactor, lag)
self.nStepsToDelay = nStepsToDelay
self.nSteps = 0
if self.lag:
log("NCLS3P.ShockCapturing: lagging requested but must lag the first step; switching lagging off and delaying")
self.nStepsToDelay = 1
self.lag = False
def initializeElementQuadrature(self, mesh, t, cq):
self.mesh = mesh
self.numDiff = []
self.numDiff_last = []
for ci in range(self.nc):
self.numDiff.append(cq[('numDiff', ci, ci)])
self.numDiff_last.append(cq[('numDiff', ci, ci)])
def updateShockCapturingHistory(self):
self.nSteps += 1
if self.lag:
for ci in range(self.nc):
self.numDiff_last[ci][:] = self.numDiff[ci]
if self.lag == False and self.nStepsToDelay is not None and self.nSteps > self.nStepsToDelay:
log("NCLS3P.ShockCapturing: switched to lagged shock capturing")
self.lag = True
self.numDiff_last = []
for ci in range(self.nc):
self.numDiff_last.append(self.numDiff[ci].copy())
log("NCLS3P: max numDiff %e" %
(globalMax(self.numDiff_last[0].max()),))
class NumericalFlux(
proteus.NumericalFlux.HamiltonJacobi_DiagonalLesaintRaviart):
def __init__(self, vt, getPointwiseBoundaryConditions,
getAdvectiveFluxBoundaryConditions,
getDiffusiveFluxBoundaryConditions):
proteus.NumericalFlux.HamiltonJacobi_DiagonalLesaintRaviart.__init__(
self,
vt,
getPointwiseBoundaryConditions,
getAdvectiveFluxBoundaryConditions,
getDiffusiveFluxBoundaryConditions)
class Coefficients(proteus.TransportCoefficients.TC_base):
from proteus.ctransportCoefficients import ncLevelSetCoefficientsEvaluate
def __init__(self,
V_model=0,
RD_model=None,
ME_model=1,
checkMass=True, epsFact=1.5,
useMetrics=0.0, sc_uref=1.0, sc_beta=1.0,
waterline_interval=-1,
movingDomain=False,
PURE_BDF=False,
EXPLICIT_METHOD=False,
outputQuantDOFs=False):
self.EXPLICIT_METHOD=EXPLICIT_METHOD
self.outputQuantDOFs=outputQuantDOFs
self.PURE_BDF=PURE_BDF
self.movingDomain = movingDomain
self.useMetrics = useMetrics
self.epsFact = epsFact
self.variableNames = ['phi']
nc = 1
mass = {0: {0: 'linear'}}
hamiltonian = {0: {0: 'linear'}}
advection = {}
diffusion = {}
potential = {}
reaction = {}
TC_base.__init__(self,
nc,
mass,
advection,
diffusion,
potential,
reaction,
hamiltonian,
['phi'],
movingDomain=movingDomain)
self.flowModelIndex = V_model
self.modelIndex = ME_model
self.RD_modelIndex = RD_model
self.checkMass = checkMass
self.sc_uref = sc_uref
self.sc_beta = sc_beta
self.waterline_interval = waterline_interval
def attachModels(self, modelList):
# the level set model
self.model = modelList[self.modelIndex]
# the velocity
if self.flowModelIndex >= 0:
self.flowModel = modelList[self.flowModelIndex]
self.q_v = modelList[self.flowModelIndex].q[('velocity', 0)]
self.ebqe_v = modelList[self.flowModelIndex].ebqe[('velocity', 0)]
if ('velocity', 0) in modelList[self.flowModelIndex].ebq:
self.ebq_v = modelList[
self.flowModelIndex].ebq[
('velocity', 0)]
else:
self.ebq_v = None
if ('u', 0) not in self.model.ebq and ('u', 0) in self.flowModel.ebq:
self.model.ebq[('u', 0)] = np.zeros(
self.flowModel.ebq[('u', 0)].shape, 'd')
self.model.ebq[('grad(u)', 0)] = np.zeros(
self.flowModel.ebq[('grad(u)', 0)].shape, 'd')
if ('v', 1) in self.flowModel.ebq:
self.model.u[0].getValuesTrace(
self.flowModel.ebq[
('v', 1)], self.model.ebq[
('u', 0)])
self.model.u[0].getGradientValuesTrace(
self.flowModel.ebq[
('grad(v)', 1)], self.model.ebq[
('grad(u)', 0)])
if self.RD_modelIndex is not None:
self.rdModel = modelList[self.RD_modelIndex]
self.rdModel_ebqe = self.rdModel.ebqe[('u',0)]
else:
self.rdModel = None
self.rdModel_ebqe = np.copy(self.model.ebqe[('u',0)])
def initializeElementQuadrature(self, t, cq):
if self.flowModelIndex is None:
self.q_v = np.zeros(cq[('grad(u)', 0)].shape, 'd')
def initializeElementBoundaryQuadrature(self, t, cebq, cebq_global):
if self.flowModelIndex is None:
self.ebq_v = np.zeros(cebq[('grad(u)', 0)].shape, 'd')
def initializeGlobalExteriorElementBoundaryQuadrature(self, t, cebqe):
if self.flowModelIndex is None:
self.ebqe_v = np.zeros(cebqe[('grad(u)', 0)].shape, 'd')
def preStep(self, t, firstStep=False):
# BOUNDARY CONDITION FROM re-distancing model
if self.rdModel is None:
self.rdModel_ebqe[:] = self.model.ebqe[('u',0)]
# Restart flags for stages of taylor galerkin
self.model.stage = 1
self.model.auxTaylorGalerkinFlag = 1
# SAVE OLD SOLUTION #
self.model.u_dof_old[:] = self.model.u[0].dof
# COMPUTE NEW VELOCITY (if given by user) #
if self.model.hasVelocityFieldAsFunction:
self.model.updateVelocityFieldAsFunction()
# if self.checkMass:
# self.m_pre = Norms.scalarSmoothedHeavisideDomainIntegral(self.epsFact,
# self.model.mesh.elementDiametersArray,
# self.model.q['dV'],
# self.model.q[('m',0)],
# self.model.mesh.nElements_owned)
# log("Phase 0 mass before NCLS3P step = %12.5e" % (self.m_pre,),level=2)
# self.m_last = Norms.scalarSmoothedHeavisideDomainIntegral(self.epsFact,
# self.model.mesh.elementDiametersArray,
# self.model.q['dV'],
# self.model.timeIntegration.m_last[0],
# self.model.mesh.nElements_owned)
# log("Phase 0 mass before NCLS3P step (m_last) = %12.5e" % (self.m_last,),level=2)
# #cek todo why is this here
# if self.flowModelIndex >= 0 and self.flowModel.ebq.has_key(('v',1)):
# self.model.u[0].getValuesTrace(self.flowModel.ebq[('v',1)],self.model.ebq[('u',0)])
# self.model.u[0].getGradientValuesTrace(self.flowModel.ebq[('grad(v)',1)],self.model.ebq[('grad(u)',0)])
copyInstructions = {}
return copyInstructions
def postStep(self, t, firstStep=False):
self.model.q['dV_last'][:] = self.model.q['dV']
# if self.checkMass:
# self.m_post = Norms.scalarSmoothedHeavisideDomainIntegral(self.epsFact,
# self.model.mesh.elementDiametersArray,
# self.model.q['dV'],
# self.model.q[('u',0)],
# self.model.mesh.nElements_owned)
# log("Phase 0 mass after NCLS3P step = %12.5e" % (self.m_post,),level=2)
# #need a flux here not a velocity
# self.fluxIntegral = Norms.fluxDomainBoundaryIntegralFromVector(self.flowModel.ebqe['dS'],
# self.flowModel.ebqe[('velocity',0)],
# self.flowModel.ebqe['n'],
# self.model.mesh)
# log("Flux integral = %12.5e" % (self.fluxIntegral,),level=2)
# log("Phase 0 mass conservation after NCLS3P step = %12.5e" % (self.m_post - self.m_last + self.model.timeIntegration.dt*self.fluxIntegral,),level=2)
# self.lsGlobalMass = self.m_post
# self.fluxGlobal = self.fluxIntegral*self.model.timeIntegration.dt
# self.totalFluxGlobal += self.fluxGlobal
# self.lsGlobalMassArray.append(self.lsGlobalMass)
# self.lsGlobalMassErrorArray.append(self.lsGlobalMass - self.lsGlobalMassArray[0] + self.totalFluxGlobal)
# self.fluxArray.append(self.fluxIntegral)
# self.timeArray.append(self.model.timeIntegration.t)
# if self.flowModelIndex >= 0 and self.flowModel.ebq.has_key(('v',1)):
# self.model.u[0].getValuesTrace(self.flowModel.ebq[('v',1)],self.model.ebq[('u',0)])
# self.model.u[0].getGradientValuesTrace(self.flowModel.ebq[('grad(v)',1)],self.model.ebq[('grad(u)',0)])
copyInstructions = {}
return copyInstructions
def updateToMovingDomain(self, t, c):
# in a moving domain simulation the velocity coming in is already for
# the moving domain
pass
def evaluate(self, t, c):
v = None
if c[('dH', 0, 0)].shape == self.q_v.shape:
v = self.q_v
elif c[('dH', 0, 0)].shape == self.ebqe_v.shape:
v = self.ebqe_v
elif self.ebq_v is not None and c[('dH', 0, 0)].shape == self.ebq_v.shape:
v = self.ebq_v
else:
raise RuntimeError("don't have v for NC Level set of shape = " + \
repr(c[('dH', 0, 0)].shape))
if v is not None:
self.ncLevelSetCoefficientsEvaluate(v,
c[('u', 0)],
c[('grad(u)', 0)],
c[('m', 0)],
c[('dm', 0, 0)],
c[('H', 0)],
c[('dH', 0, 0)])
class LevelModel(OneLevelTransport):
nCalls = 0
def __init__(self,
uDict,
phiDict,
testSpaceDict,
matType,
dofBoundaryConditionsDict,
dofBoundaryConditionsSetterDict,
coefficients,
elementQuadrature,
elementBoundaryQuadrature,
fluxBoundaryConditionsDict=None,
advectiveFluxBoundaryConditionsSetterDict=None,
diffusiveFluxBoundaryConditionsSetterDictDict=None,
stressTraceBoundaryConditionsSetterDict=None,
stabilization=None,
shockCapturing=None,
conservativeFluxDict=None,
numericalFluxType=None,
TimeIntegrationClass=None,
massLumping=False,
reactionLumping=False,
options=None,
name='defaultName',
reuse_trial_and_test_quadrature=True,
sd=True,
movingDomain=False,
bdyNullSpace=False):
self.bdyNullSpace = bdyNullSpace
#
# set the objects describing the method and boundary conditions
#
self.movingDomain = movingDomain
self.tLast_mesh = None
#
self.name = name
self.sd = sd
self.Hess = False
self.lowmem = True
self.timeTerm = True # allow turning off the time derivative
# self.lowmem=False
self.testIsTrial = True
self.phiTrialIsTrial = True
self.u = uDict
self.ua = {} # analytical solutions
self.phi = phiDict
self.dphi = {}
self.matType = matType
# mwf try to reuse test and trial information across components if
# spaces are the same
self.reuse_test_trial_quadrature = reuse_trial_and_test_quadrature # True#False
if self.reuse_test_trial_quadrature:
for ci in range(1, coefficients.nc):
assert self.u[ci].femSpace.__class__.__name__ == self.u[
0].femSpace.__class__.__name__, "to reuse_test_trial_quad all femSpaces must be the same!"
self.u_dof_old = None
# Simplicial Mesh
# assume the same mesh for all components for now
self.mesh = self.u[0].femSpace.mesh
self.testSpace = testSpaceDict
self.dirichletConditions = dofBoundaryConditionsDict
# explicit Dirichlet conditions for now, no Dirichlet BC constraints
self.dirichletNodeSetList = None
self.coefficients = coefficients
self.coefficients.initializeMesh(self.mesh)
self.nc = self.coefficients.nc
self.stabilization = stabilization
self.shockCapturing = shockCapturing
# no velocity post-processing for now
self.conservativeFlux = conservativeFluxDict
self.fluxBoundaryConditions = fluxBoundaryConditionsDict
self.advectiveFluxBoundaryConditionsSetterDict = advectiveFluxBoundaryConditionsSetterDict
self.diffusiveFluxBoundaryConditionsSetterDictDict = diffusiveFluxBoundaryConditionsSetterDictDict
# determine whether the stabilization term is nonlinear
self.stabilizationIsNonlinear = False
# cek come back
if self.stabilization is not None:
for ci in range(self.nc):
if ci in coefficients.mass:
for flag in list(coefficients.mass[ci].values()):
if flag == 'nonlinear':
self.stabilizationIsNonlinear = True
if ci in coefficients.advection:
for flag in list(coefficients.advection[ci].values()):
if flag == 'nonlinear':
self.stabilizationIsNonlinear = True
if ci in coefficients.diffusion:
for diffusionDict in list(coefficients.diffusion[ci].values()):
for flag in list(diffusionDict.values()):
if flag != 'constant':
self.stabilizationIsNonlinear = True
if ci in coefficients.potential:
for flag in list(coefficients.potential[ci].values()):
if flag == 'nonlinear':
self.stabilizationIsNonlinear = True
if ci in coefficients.reaction:
for flag in list(coefficients.reaction[ci].values()):
if flag == 'nonlinear':
self.stabilizationIsNonlinear = True
if ci in coefficients.hamiltonian:
for flag in list(coefficients.hamiltonian[ci].values()):
if flag == 'nonlinear':
self.stabilizationIsNonlinear = True
# determine if we need element boundary storage
self.elementBoundaryIntegrals = {}
for ci in range(self.nc):
self.elementBoundaryIntegrals[ci] = (
(self.conservativeFlux is not None) or (
numericalFluxType is not None) or (
self.fluxBoundaryConditions[ci] == 'outFlow') or (
self.fluxBoundaryConditions[ci] == 'mixedFlow') or (
self.fluxBoundaryConditions[ci] == 'setFlow'))
#
# calculate some dimensions
#
# assume same space dim for all variables
self.nSpace_global = self.u[0].femSpace.nSpace_global
self.nDOF_trial_element = [
u_j.femSpace.max_nDOF_element for u_j in list(self.u.values())]
self.nDOF_phi_trial_element = [
phi_k.femSpace.max_nDOF_element for phi_k in list(self.phi.values())]
self.n_phi_ip_element = [
phi_k.femSpace.referenceFiniteElement.interpolationConditions.nQuadraturePoints for phi_k in list(self.phi.values())]
self.nDOF_test_element = [
femSpace.max_nDOF_element for femSpace in list(self.testSpace.values())]
self.nFreeDOF_global = [
dc.nFreeDOF_global for dc in list(self.dirichletConditions.values())]
self.nVDOF_element = sum(self.nDOF_trial_element)
self.nFreeVDOF_global = sum(self.nFreeDOF_global)
#
NonlinearEquation.__init__(self, self.nFreeVDOF_global)
#
# build the quadrature point dictionaries from the input (this
# is just for convenience so that the input doesn't have to be
# complete)
#
elementQuadratureDict = {}
elemQuadIsDict = isinstance(elementQuadrature, dict)
if elemQuadIsDict: # set terms manually
for I in self.coefficients.elementIntegralKeys:
if I in elementQuadrature:
elementQuadratureDict[I] = elementQuadrature[I]
else:
elementQuadratureDict[I] = elementQuadrature['default']
else:
for I in self.coefficients.elementIntegralKeys:
elementQuadratureDict[I] = elementQuadrature
if self.stabilization is not None:
for I in self.coefficients.elementIntegralKeys:
if elemQuadIsDict:
if I in elementQuadrature:
elementQuadratureDict[
('stab',) + I[1:]] = elementQuadrature[I]
else:
elementQuadratureDict[
('stab',) + I[1:]] = elementQuadrature['default']
else:
elementQuadratureDict[
('stab',) + I[1:]] = elementQuadrature
if self.shockCapturing is not None:
for ci in self.shockCapturing.components:
if elemQuadIsDict:
if ('numDiff', ci, ci) in elementQuadrature:
elementQuadratureDict[('numDiff', ci, ci)] = elementQuadrature[
('numDiff', ci, ci)]
else:
elementQuadratureDict[('numDiff', ci, ci)] = elementQuadrature[
'default']
else:
elementQuadratureDict[
('numDiff', ci, ci)] = elementQuadrature
if massLumping:
for ci in list(self.coefficients.mass.keys()):
elementQuadratureDict[('m', ci)] = Quadrature.SimplexLobattoQuadrature(
self.nSpace_global, 1)
for I in self.coefficients.elementIntegralKeys:
elementQuadratureDict[
('stab',) + I[1:]] = Quadrature.SimplexLobattoQuadrature(self.nSpace_global, 1)
if reactionLumping:
for ci in list(self.coefficients.mass.keys()):
elementQuadratureDict[('r', ci)] = Quadrature.SimplexLobattoQuadrature(
self.nSpace_global, 1)
for I in self.coefficients.elementIntegralKeys:
elementQuadratureDict[
('stab',) + I[1:]] = Quadrature.SimplexLobattoQuadrature(self.nSpace_global, 1)
elementBoundaryQuadratureDict = {}
if isinstance(elementBoundaryQuadrature, dict): # set terms manually
for I in self.coefficients.elementBoundaryIntegralKeys:
if I in elementBoundaryQuadrature:
elementBoundaryQuadratureDict[
I] = elementBoundaryQuadrature[I]
else:
elementBoundaryQuadratureDict[
I] = elementBoundaryQuadrature['default']
else:
for I in self.coefficients.elementBoundaryIntegralKeys:
elementBoundaryQuadratureDict[I] = elementBoundaryQuadrature
#
# find the union of all element quadrature points and
# build a quadrature rule for each integral that has a
# weight at each point in the union
# mwf include tag telling me which indices are which quadrature rule?
(self.elementQuadraturePoints, self.elementQuadratureWeights,
self.elementQuadratureRuleIndeces) = Quadrature.buildUnion(elementQuadratureDict)
self.nQuadraturePoints_element = self.elementQuadraturePoints.shape[0]
self.nQuadraturePoints_global = self.nQuadraturePoints_element * \
self.mesh.nElements_global
#
# Repeat the same thing for the element boundary quadrature
#
(self.elementBoundaryQuadraturePoints, self.elementBoundaryQuadratureWeights,
self.elementBoundaryQuadratureRuleIndeces) = Quadrature.buildUnion(elementBoundaryQuadratureDict)
self.nElementBoundaryQuadraturePoints_elementBoundary = self.elementBoundaryQuadraturePoints.shape[
0]
self.nElementBoundaryQuadraturePoints_global = (
self.mesh.nElements_global *
self.mesh.nElementBoundaries_element *
self.nElementBoundaryQuadraturePoints_elementBoundary)
# if isinstance(self.u[0].femSpace,C0_AffineLinearOnSimplexWithNodalBasis):
# print self.nQuadraturePoints_element
# if self.nSpace_global == 3:
# assert(self.nQuadraturePoints_element == 5)
# elif self.nSpace_global == 2:
# assert(self.nQuadraturePoints_element == 6)
# elif self.nSpace_global == 1:
# assert(self.nQuadraturePoints_element == 3)
#
# print self.nElementBoundaryQuadraturePoints_elementBoundary
# if self.nSpace_global == 3:
# assert(self.nElementBoundaryQuadraturePoints_elementBoundary == 4)
# elif self.nSpace_global == 2:
# assert(self.nElementBoundaryQuadraturePoints_elementBoundary == 4)
# elif self.nSpace_global == 1:
# assert(self.nElementBoundaryQuadraturePoints_elementBoundary == 1)
#
# simplified allocations for test==trial and also check if space is mixed or not
#
self.q = {}
self.ebq = {}
self.ebq_global = {}
self.ebqe = {}
self.phi_ip = {}
# mesh
self.q['x'] = np.zeros(
(self.mesh.nElements_global, self.nQuadraturePoints_element, 3), 'd')
self.ebqe['x'] = np.zeros(
(self.mesh.nExteriorElementBoundaries_global,
self.nElementBoundaryQuadraturePoints_elementBoundary,
3),
'd')
self.q[('dV_u', 0)] = (old_div(1.0, self.mesh.nElements_global)) * \
np.ones((self.mesh.nElements_global, self.nQuadraturePoints_element), 'd')
self.q[('u', 0)] = np.zeros(
(self.mesh.nElements_global, self.nQuadraturePoints_element), 'd')
self.q[
('grad(u)',
0)] = np.zeros(
(self.mesh.nElements_global,
self.nQuadraturePoints_element,
self.nSpace_global),
'd')
self.q[('m_last', 0)] = np.zeros(
(self.mesh.nElements_global, self.nQuadraturePoints_element), 'd')
self.q[('mt', 0)] = np.zeros(
(self.mesh.nElements_global, self.nQuadraturePoints_element), 'd')
self.q['dV'] = np.zeros(
(self.mesh.nElements_global, self.nQuadraturePoints_element), 'd')
self.q['dV_last'] = -1000 * \
np.ones((self.mesh.nElements_global, self.nQuadraturePoints_element), 'd')
# np.zeros((self.mesh.nElements_global,self.nQuadraturePoints_element),'d')
self.q[('m_tmp', 0)] = self.q[('u', 0)]
# np.zeros((self.mesh.nElements_global,self.nQuadraturePoints_element),'d')
self.q[('m', 0)] = self.q[('u', 0)]
# cek todo for NCLS3P we really don't need dH because it's just q_v
# from the flow model
self.q[('dH', 0, 0)] = np.zeros((self.mesh.nElements_global,
self.nQuadraturePoints_element, self.nSpace_global), 'd')
self.q[
('dH_sge',
0,
0)] = np.zeros(
(self.mesh.nElements_global,
self.nQuadraturePoints_element,
self.nSpace_global),
'd')
self.q[('cfl', 0)] = np.zeros(
(self.mesh.nElements_global, self.nQuadraturePoints_element), 'd')
self.q[('numDiff', 0, 0)] = np.zeros(
(self.mesh.nElements_global, self.nQuadraturePoints_element), 'd')
self.ebqe[
('u',
0)] = np.zeros(
(self.mesh.nExteriorElementBoundaries_global,
self.nElementBoundaryQuadraturePoints_elementBoundary),
'd')
self.ebqe[
('grad(u)',
0)] = np.zeros(
(self.mesh.nExteriorElementBoundaries_global,
self.nElementBoundaryQuadraturePoints_elementBoundary,
self.nSpace_global),
'd')
# mwf for running as standalone
self.ebqe[
('dH',
0,
0)] = np.zeros(
(self.mesh.nExteriorElementBoundaries_global,
self.nElementBoundaryQuadraturePoints_elementBoundary,
self.nSpace_global),
'd')
self.q[('dm', 0, 0)] = np.zeros(
(self.mesh.nElements_global, self.nQuadraturePoints_element), 'd')
self.q[('H', 0)] = np.zeros(
(self.mesh.nElements_global, self.nQuadraturePoints_element), 'd')
self.points_elementBoundaryQuadrature = set()
self.scalars_elementBoundaryQuadrature = set(
[('u', ci) for ci in range(self.nc)])
self.vectors_elementBoundaryQuadrature = set()
self.tensors_elementBoundaryQuadrature = set()
#
# allocate residual and Jacobian storage
#
self.inflowBoundaryBC = {}
self.inflowBoundaryBC_values = {}
self.inflowFlux = {}
for cj in range(self.nc):
self.inflowBoundaryBC[cj] = np.zeros(
(self.mesh.nExteriorElementBoundaries_global,), 'i')
self.inflowBoundaryBC_values[cj] = np.zeros(
(self.mesh.nExteriorElementBoundaries_global, self.nDOF_trial_element[cj]), 'd')
self.inflowFlux[cj] = np.zeros(
(self.mesh.nExteriorElementBoundaries_global,
self.nElementBoundaryQuadraturePoints_elementBoundary),
'd')
self.internalNodes = set(range(self.mesh.nNodes_global))
# identify the internal nodes this is ought to be in mesh
# \todo move this to mesh
for ebNE in range(self.mesh.nExteriorElementBoundaries_global):
ebN = self.mesh.exteriorElementBoundariesArray[ebNE]
eN_global = self.mesh.elementBoundaryElementsArray[ebN, 0]
ebN_element = self.mesh.elementBoundaryLocalElementBoundariesArray[
ebN, 0]
for i in range(self.mesh.nNodes_element):
if i != ebN_element:
I = self.mesh.elementNodesArray[eN_global, i]
self.internalNodes -= set([I])
self.nNodes_internal = len(self.internalNodes)
self.internalNodesArray = np.zeros((self.nNodes_internal,), 'i')
for nI, n in enumerate(self.internalNodes):
self.internalNodesArray[nI] = n
#
del self.internalNodes
self.internalNodes = None
log("Updating local to global mappings", 2)
self.updateLocal2Global()
log("Building time integration object", 2)
log(memory("inflowBC, internalNodes,updateLocal2Global",
"OneLevelTransport"), level=4)
# mwf for interpolating subgrid error for gradients etc
if self.stabilization and self.stabilization.usesGradientStabilization:
self.timeIntegration = TimeIntegrationClass(
self, integrateInterpolationPoints=True)
else:
self.timeIntegration = TimeIntegrationClass(self)
if options is not None:
self.timeIntegration.setFromOptions(options)
log(memory("TimeIntegration", "OneLevelTransport"), level=4)
log("Calculating numerical quadrature formulas", 2)
self.calculateQuadrature()
self.setupFieldStrides()
comm = Comm.get()
self.comm = comm
if comm.size() > 1:
assert numericalFluxType is not None and numericalFluxType.useWeakDirichletConditions, "You must use a numerical flux to apply weak boundary conditions for parallel runs"
log(memory("stride+offset", "OneLevelTransport"), level=4)
if numericalFluxType is not None:
if options is None or options.periodicDirichletConditions is None:
self.numericalFlux = numericalFluxType(
self,
dofBoundaryConditionsSetterDict,
advectiveFluxBoundaryConditionsSetterDict,
diffusiveFluxBoundaryConditionsSetterDictDict)
else:
self.numericalFlux = numericalFluxType(
self,
dofBoundaryConditionsSetterDict,
advectiveFluxBoundaryConditionsSetterDict,
diffusiveFluxBoundaryConditionsSetterDictDict,
options.periodicDirichletConditions)
else:
self.numericalFlux = None
# set penalty terms
# cek todo move into numerical flux initialization
if 'penalty' in self.ebq_global:
for ebN in range(self.mesh.nElementBoundaries_global):
for k in range(
self.nElementBoundaryQuadraturePoints_elementBoundary):
self.ebq_global['penalty'][ebN, k] = old_div(self.numericalFlux.penalty_constant, (
self.mesh.elementBoundaryDiametersArray[ebN]**self.numericalFlux.penalty_power))
# penalty term
# cek move to Numerical flux initialization
if 'penalty' in self.ebqe:
for ebNE in range(self.mesh.nExteriorElementBoundaries_global):
ebN = self.mesh.exteriorElementBoundariesArray[ebNE]
for k in range(
self.nElementBoundaryQuadraturePoints_elementBoundary):
self.ebqe['penalty'][ebNE, k] = old_div(self.numericalFlux.penalty_constant, \
self.mesh.elementBoundaryDiametersArray[ebN]**self.numericalFlux.penalty_power)
log(memory("numericalFlux", "OneLevelTransport"), level=4)
self.elementEffectiveDiametersArray = self.mesh.elementInnerDiametersArray
# use post processing tools to get conservative fluxes, None by default
from proteus import PostProcessingTools
self.velocityPostProcessor = PostProcessingTools.VelocityPostProcessingChooser(
self)
log(memory("velocity postprocessor", "OneLevelTransport"), level=4)
# helper for writing out data storage
from proteus import Archiver
self.elementQuadratureDictionaryWriter = Archiver.XdmfWriter()
self.elementBoundaryQuadratureDictionaryWriter = Archiver.XdmfWriter()
self.exteriorElementBoundaryQuadratureDictionaryWriter = Archiver.XdmfWriter()
# TODO get rid of this
# for ci,fbcObject in self.fluxBoundaryConditionsObjectsDict.iteritems():
# self.ebqe[('advectiveFlux_bc_flag',ci)] = np.zeros(self.ebqe[('advectiveFlux_bc',ci)].shape,'i')
# for t,g in fbcObject.advectiveFluxBoundaryConditionsDict.iteritems():
# if self.coefficients.advection.has_key(ci):
# self.ebqe[('advectiveFlux_bc',ci)][t[0],t[1]] = g(self.ebqe[('x')][t[0],t[1]],self.timeIntegration.t)
# self.ebqe[('advectiveFlux_bc_flag',ci)][t[0],t[1]] = 1
if hasattr(self.numericalFlux, 'setDirichletValues'):
self.numericalFlux.setDirichletValues(self.ebqe)
if not hasattr(self.numericalFlux, 'isDOFBoundary'):
self.numericalFlux.isDOFBoundary = {
0: np.zeros(self.ebqe[('u', 0)].shape, 'i')}
if not hasattr(self.numericalFlux, 'ebqe'):
self.numericalFlux.ebqe = {
('u', 0): np.zeros(self.ebqe[('u', 0)].shape, 'd')}
# TODO how to handle redistancing calls for
# calculateCoefficients,calculateElementResidual etc
self.globalResidualDummy = None
compKernelFlag = 0
self.ncls3p = cNCLS3P.newNCLS3P(
self.nSpace_global,
self.nQuadraturePoints_element,
self.u[0].femSpace.elementMaps.localFunctionSpace.dim,
self.u[0].femSpace.referenceFiniteElement.localFunctionSpace.dim,
self.testSpace[0].referenceFiniteElement.localFunctionSpace.dim,
self.nElementBoundaryQuadraturePoints_elementBoundary,
compKernelFlag)
self.forceStrongConditions = False
if self.forceStrongConditions:
self.dirichletConditionsForceDOF = DOFBoundaryConditions(
self.u[0].femSpace,
dofBoundaryConditionsSetterDict[0],
weakDirichletConditions=False)
if self.movingDomain:
self.MOVING_DOMAIN = 1.0
else:
self.MOVING_DOMAIN = 0.0
if self.mesh.nodeVelocityArray is None:
self.mesh.nodeVelocityArray = np.zeros(
self.mesh.nodeArray.shape, 'd')
self.waterline_calls = 0
self.waterline_prints = 0
# mql. Allow the user to provide functions to define the velocity field
self.hasVelocityFieldAsFunction = False
if ('velocityField') in dir(options):
self.velocityField = options.velocityField
self.hasVelocityFieldAsFunction = True
# interface locator
self.cell_interface_locator = np.zeros(self.mesh.nElements_global,'d')
self.interface_locator = | np.zeros(self.u[0].dof.shape,'d') | numpy.zeros |
### MDP Value Iteration and Policy Iteration
import numpy as np
import gym
import time
from lake_envs import *
np.set_printoptions(precision=3)
"""
For policy_evaluation, policy_improvement, policy_iteration and value_iteration,
the parameters P, nS, nA, gamma are defined as follows:
P: nested dictionary|
From gym.core.Environment
For each pair of states in [1, nS] and actions in [1, nA], P[state][action] is a
tuple of the form (probability, nextstate, reward, terminal) where
- probability: float
the probability of transitioning from "state" to "nextstate" with "action"
- nextstate: int
denotes the state we transition to (in range [0, nS - 1])
- reward: int
either 0 or 1, the reward for transitioning from "state" to
"nextstate" with "action"
- terminal: bool
True when "nextstate" is a terminal state (hole or goal), False otherwise
nS: int
number of states in the environment
nA: int
number of actions in the environment
gamma: float
Discount factor. Number in range [0, 1)
"""
def policy_evaluation(P, nS, nA, policy, gamma=0.9, tol=1e-3):
"""Evaluate the value function from a given policy.
Parameters
----------
P, nS, nA, gamma:
defined at beginning of file
policy: np.array[nS]
The policy to evaluate. Maps states to actions.
tol: float
Terminate policy evaluation when
max |value_function(s) - prev_value_function(s)| < tol
Returns
-------
value_function: np.ndarray[nS]
The value function of the given policy, where value_function[s] is
the value of state s
"""
value_function = np.zeros(nS)
############################
# YOUR IMPLEMENTATION HERE #
n_iter = 0
while True:
prev_value_function = np.copy(value_function)
for s in range(nS):
action = policy[s]
temp_v = 0
### Stochastic 에서 확률적으로 같은 action을 하더라도 다른 state로 넘어가는 경우가 있음####
for state_action_pair in P[s][action]:
prob, next_state, reward, terminal = state_action_pair
# print(prob, next_state, reward, terminal)
stochastic_v = prob * (reward + gamma * prev_value_function[next_state])
temp_v += stochastic_v
value_function[s] = temp_v
n_iter +=1
diff = np.max(np.abs(value_function - prev_value_function))
print(diff)
if diff < tol:
break;
############################
return value_function
def policy_improvement(P, nS, nA, value_from_policy, policy, gamma=0.9):
"""Given the value function from policy improve the policy.
Parameters
----------
P, nS, nA, gamma:
defined at beginning of file
value_from_policy: np.ndarray
The value calculated from the policy
policy: np.array
The previous policy.
Returns
-------
new_policy: np.ndarray[nS]
An array of integers. Each integer is the optimal action to take
in that state according to the environment dynamics and the
given value function.
"""
new_policy = np.zeros(nS, dtype='int')
############################
# YOUR IMPLEMENTATION HERE #
for s in range(nS):
q_max = 0
q_list = np.array([])
for a in range(nA):
temp_q = 0
for state_action_pair in P[s][a]:
prob, next_state, reward, terminal = state_action_pair
stochastic_q = prob * (reward + gamma * value_from_policy[next_state])
temp_q += stochastic_q
q_list = np.append(q_list, temp_q)
q_max = np.argmax(q_list)
new_policy[s] = q_max
# print(new_policy)
############################
return new_policy
def policy_iteration(P, nS, nA, gamma=0.9, tol=10e-3):
"""Runs policy iteration.
You should call the policy_evaluation() and policy_improvement() methods to
implement this method.
Parameters
----------
P, nS, nA, gamma:
defined at beginning of file
tol: float
tol parameter used in policy_evaluation()
Returns:
----------
value_function: np.ndarray[nS]
policy: np.ndarray[nS]
"""
n_iter = 0
value_function = np.zeros(nS)
policy = np.zeros(nS, dtype=int)
###########################YOUR IMPLEMENTATION HERE #
prev_value_function = np.copy(value_function)
while True :
prev_value_function = policy_evaluation(P, nS, nA, policy)
policy = policy_improvement(P, nS, nA, prev_value_function, policy)
value_function = policy_evaluation(P, nS, nA, policy)
if | np.sum(value_function - prev_value_function) | numpy.sum |
import numpy
import sys
def local_energy_generic(h1e, eri, G, ecore=0.0, Ghalf=None):
r"""Calculate local for generic two-body hamiltonian.
This uses the full form for the two-electron integrals.
For testing purposes only.
Parameters
----------
system : :class:`hubbard`
System information for the hubbard model.
G : :class:`numpy.ndarray`
Walker's "green's function"
Returns
-------
(E, T, V): tuple
Local, kinetic and potential energies.
"""
e1 = (numpy.einsum('ij,ij->', h1e[0], G[0]) +
numpy.einsum('ij,ij->', h1e[1], G[1]))
euu = 0.5*(numpy.einsum('prqs,pr,qs->', eri, G[0], G[0]) -
numpy.einsum('prqs,ps,qr->', eri, G[0], G[0]))
edd = 0.5*(numpy.einsum('prqs,pr,qs->', eri, G[1], G[1]) -
numpy.einsum('prqs,ps,qr->', eri, G[1], G[1]))
eud = 0.5*numpy.einsum('prqs,pr,qs->', eri, G[0], G[1])
edu = 0.5*numpy.einsum('prqs,pr,qs->', eri, G[1], G[0])
e2 = euu + edd + eud + edu
return (e1+e2+ecore, e1+ecore, e2)
def local_energy_generic_pno(system, G, Ghalf=None, eri=None, C0=None,\
ecoul0 = None, exxa0 = None, exxb0 = None, UVT=None):
na = system.nup
nb = system.ndown
M = system.nbasis
UVT_aa = UVT[0]
UVT_bb = UVT[1]
UVT_ab = UVT[2]
Ga, Gb = Ghalf[0], Ghalf[1]
# Element wise multiplication.
e1b = numpy.sum(system.H1[0]*G[0]) + numpy.sum(system.H1[1]*G[1])
eJaa = 0.0
eKaa = 0.0
if (len(C0.shape) == 3):
CT = C0[0,:,:].T
else:
CT = C0[:,:].T
GTa = CT[:na,:] # hard-coded to do single slater
GTb = CT[na:,:] # hard-coded to do single slater
for (i,j),(U,VT) in zip(system.ij_list_aa, UVT_aa):
if (i == j):
c = 0.5
else:
c = 1.0
theta_i = Ga[i,:]
theta_j = Ga[j,:]
thetaT_i = GTa[i,:]
thetaT_j = GTa[j,:]
thetaU = numpy.einsum("p,pk->k", theta_i,U)
thetaV = numpy.einsum("p,kp->k", theta_j,VT)
thetaTU = numpy.einsum("p,pk->k", thetaT_i,U)
thetaTV = numpy.einsum("p,kp->k", thetaT_j,VT)
eJaa += c * (numpy.dot(thetaU, thetaV) - numpy.dot(thetaTU, thetaTV))
thetaU = numpy.einsum("p,pk->k", theta_j,U)
thetaV = numpy.einsum("p,kp->k", theta_i,VT)
thetaTU = numpy.einsum("p,pk->k", thetaT_j,U)
thetaTV = numpy.einsum("p,kp->k", thetaT_i,VT)
eKaa -= c * (numpy.dot(thetaU, thetaV) - numpy.dot(thetaTU, thetaTV))
eJbb = 0.0
eKbb = 0.0
for (i,j),(U,VT) in zip(system.ij_list_bb, UVT_bb):
if (i == j):
c = 0.5
else:
c = 1.0
theta_i = Gb[i,:]
theta_j = Gb[j,:]
thetaT_i = GTb[i,:]
thetaT_j = GTb[j,:]
thetaU = numpy.einsum("p,pk->k", theta_i,U)
thetaV = numpy.einsum("p,kp->k", theta_j,VT)
thetaTU = numpy.einsum("p,pk->k", thetaT_i,U)
thetaTV = numpy.einsum("p,kp->k", thetaT_j,VT)
eJbb += c * (numpy.dot(thetaU, thetaV) - numpy.dot(thetaTU, thetaTV))
thetaU = numpy.einsum("p,pk->k", theta_j,U)
thetaV = numpy.einsum("p,kp->k", theta_i,VT)
thetaTU = numpy.einsum("p,pk->k", thetaT_j,U)
thetaTV = numpy.einsum("p,kp->k", thetaT_i,VT)
eKbb -= c * (numpy.dot(thetaU, thetaV) - numpy.dot(thetaTU, thetaTV))
eJab = 0.0
for (i,j),(U,VT) in zip(system.ij_list_ab, UVT_ab):
theta_i = Ga[i,:]
theta_j = Gb[j,:]
thetaT_i = GTa[i,:]
thetaT_j = GTb[j,:]
thetaU = numpy.einsum("p,pk->k", theta_i,U)
thetaV = numpy.einsum("p,kp->k", theta_j,VT)
thetaTU = numpy.einsum("p,pk->k", thetaT_i,U)
thetaTV = numpy.einsum("p,kp->k", thetaT_j,VT)
eJab += (numpy.dot(thetaU, thetaV) - numpy.dot(thetaTU, thetaTV))
e2b = 0.5*(ecoul0 - exxa0 - exxb0) + eJaa + eJbb + eJab + eKaa + eKbb
return (e1b + e2b + system.ecore, e1b + system.ecore, e2b)
def local_energy_generic_opt(system, G, Ghalf=None, eri=None):
na = system.nup
nb = system.ndown
M = system.nbasis
vipjq_aa = eri[0,:na**2*M**2].reshape((na,M,na,M))
vipjq_bb = eri[0,na**2*M**2:na**2*M**2+nb**2*M**2].reshape((nb,M,nb,M))
vipjq_ab = eri[0,na**2*M**2+nb**2*M**2:].reshape((na,M,nb,M))
Ga, Gb = Ghalf[0], Ghalf[1]
# Element wise multiplication.
e1b = numpy.sum(system.H1[0]*G[0]) + numpy.sum(system.H1[1]*G[1])
# Coulomb
eJaa = 0.5 * numpy.einsum("irjs,ir,js", vipjq_aa, Ga, Ga)
eJbb = 0.5 * numpy.einsum("irjs,ir,js", vipjq_bb, Gb, Gb)
eJab = numpy.einsum("irjs,ir,js", vipjq_ab, Ga, Gb)
eKaa = -0.5 * numpy.einsum("irjs,is,jr", vipjq_aa, Ga, Ga)
eKbb = -0.5 * numpy.einsum("irjs,is,jr", vipjq_bb, Gb, Gb)
e2b = eJaa + eJbb + eJab + eKaa + eKbb
return (e1b + e2b + system.ecore, e1b + system.ecore, e2b)
def local_energy_generic_cholesky_opt(system, G, Ghalf, rchol):
r"""Calculate local for generic two-body hamiltonian.
This uses the cholesky decomposed two-electron integrals.
Parameters
----------
system : :class:`hubbard`
System information for the hubbard model.
G : :class:`numpy.ndarray`
Walker's "green's function"
Returns
-------
(E, T, V): tuple
Local, kinetic and potential energies.
"""
#import cProfile
#pr = cProfile.Profile()
#pr.enable()
# Element wise multiplication.
e1b = numpy.sum(system.H1[0]*G[0]) + numpy.sum(system.H1[1]*G[1])
nalpha, nbeta = system.nup, system.ndown
nbasis = system.nbasis
if rchol is not None:
naux = rchol.shape[1]
Ga, Gb = Ghalf[0], Ghalf[1]
Xa = rchol[:nalpha*nbasis].T.dot(Ga.ravel())
Xb = rchol[nalpha*nbasis:].T.dot(Gb.ravel())
ecoul = numpy.dot(Xa,Xa)
ecoul += numpy.dot(Xb,Xb)
ecoul += 2*numpy.dot(Xa,Xb)
rchol_a, rchol_b = rchol[:nalpha*nbasis], rchol[nalpha*nbasis:]
# T_{abn} = \sum_k Theta_{ak} LL_{ak,n}
# LL_{ak,n} = \sum_i L_{ik,n} A^*_{ia}
# rchol_a = rchol_a.reshape((nalpha,nbasis, naux))
# rchol_b = rchol_b.reshape((nbeta,nbasis, naux))
# Ta = numpy.tensordot(Ga, rchol_a, axes=((1),(1)))
# exxa = numpy.tensordot(Ta, Ta, axes=((0,1,2),(1,0,2)))
# Tb = numpy.tensordot(Gb, rchol_b, axes=((1),(1)))
# exxb = numpy.tensordot(Tb, Tb, axes=((0,1,2),(1,0,2)))
rchol_a = rchol_a.T
rchol_b = rchol_b.T
Ta = numpy.zeros((naux, nalpha, nalpha), dtype=rchol_a.dtype)
Tb = numpy.zeros((naux, nbeta, nbeta), dtype=rchol_b.dtype)
GaT = Ga.T
GbT = Gb.T
for x in range(naux):
rmi_a = rchol_a[x].reshape((nalpha,nbasis))
Ta[x] = rmi_a.dot(GaT)
rmi_b = rchol_b[x].reshape((nbeta,nbasis))
Tb[x] = rmi_b.dot(GbT)
exxa = numpy.tensordot(Ta, Ta, axes=((0,1,2),(0,2,1)))
exxb = numpy.tensordot(Tb, Tb, axes=((0,1,2),(0,2,1)))
exx = exxa + exxb
e2b = 0.5 * (ecoul - exx)
#pr.disable()
#pr.print_stats(sort='tottime')
return (e1b + e2b + system.ecore, e1b + system.ecore, e2b)
# def local_energy_generic_cholesky_opt_stochastic(system, G, nsamples, Ghalf=None, rchol=None):
# r"""Calculate local for generic two-body hamiltonian.
# This uses the cholesky decomposed two-electron integrals.
# Parameters
# ----------
# system : :class:`hubbard`
# System information for the hubbard model.
# G : :class:`numpy.ndarray`
# Walker's "green's function"
# Returns
# -------
# (E, T, V): tuple
# Local, kinetic and potential energies.
# """
# # Element wise multiplication.
# e1b = numpy.sum(system.H1[0]*G[0]) + numpy.sum(system.H1[1]*G[1])
# if rchol is None:
# rchol = system.rchol_vecs
# nalpha, nbeta= system.nup, system.ndown
# nbasis = system.nbasis
# Ga, Gb = Ghalf[0], Ghalf[1]
# Xa = rchol[0].T.dot(Ga.ravel())
# Xb = rchol[1].T.dot(Gb.ravel())
# ecoul = numpy.dot(Xa,Xa)
# ecoul += numpy.dot(Xb,Xb)
# ecoul += 2*numpy.dot(Xa,Xb)
# # O(ON s)
# # Xa = numpy.tensordot(ra, Ga, axes=((0,1),(0,1)))
# # Xb = numpy.tensordot(rb, Gb, axes=((0,1),(0,1)))
# # ecoul = numpy.dot(Xa,Xa)
# # ecoul += numpy.dot(Xb,Xb)
# # ecoul += 2*numpy.dot(Xa,Xb)
# naux = rchol[0].shape[-1]
# theta = numpy.zeros((naux,nsamples), dtype=numpy.int64)
# for i in range(nsamples):
# theta[:,i] = (2*numpy.random.randint(0,2,size=(naux))-1)
# if system.sparse:
# rchol_a, rchol_b = [rchol[0].toarray(), rchol[1].toarray()]
# else:
# rchol_a, rchol_b = rchol[0], rchol[1]
# rchol_a = rchol_a.reshape((nalpha,nbasis, naux))
# rchol_b = rchol_b.reshape((nbeta,nbasis, naux))
# # ra = numpy.tensordot(rchol_a, theta, axes=((2),(0))) * numpy.sqrt(1.0/nsamples)
# # rb = numpy.tensordot(rchol_b, theta, axes=((2),(0))) * numpy.sqrt(1.0/nsamples)
# ra = numpy.einsum("ipX,Xs->ips",rchol_a, theta, optimize=True) * numpy.sqrt(1.0/nsamples)
# rb = numpy.einsum("ipX,Xs->ips",rchol_b, theta, optimize=True) * numpy.sqrt(1.0/nsamples)
# Gra = numpy.einsum("kq,lqx->lkx", Ga, ra, optimize=True)
# Grb = numpy.einsum("kq,lqx->lkx", Gb, rb, optimize=True)
# # Gra = numpy.tensordot(Ga, ra, axes=((1),(1))).transpose(1,0,2)
# # Grb = numpy.tensordot(Gb, rb, axes=((1),(1))).transpose(1,0,2)
# exxa = numpy.tensordot(Gra, Gra, axes=((0,1,2),(1,0,2)))
# exxb = numpy.tensordot(Grb, Grb, axes=((0,1,2),(1,0,2)))
# exx = exxa + exxb
# e2b = 0.5 * (ecoul - exx)
# return (e1b + e2b + system.ecore, e1b + system.ecore, e2b)
def local_energy_generic_cholesky_opt_stochastic(system, G, nsamples, Ghalf=None, rchol=None, C0=None,\
ecoul0 = None, exxa0 = None, exxb0 = None):
r"""Calculate local for generic two-body hamiltonian.
This uses the cholesky decomposed two-electron integrals.
Parameters
----------
system : :class:`hubbard`
System information for the hubbard model.
G : :class:`numpy.ndarray`
Walker's "green's function"
Returns
-------
(E, T, V): tuple
Local, kinetic and potential energies.
"""
#import cProfile
#pr = cProfile.Profile()
#pr.enable()
if (type(C0) == numpy.ndarray):
control = True
else:
control = False
# Element wise multiplication.
e1b = numpy.sum(system.H1[0]*G[0]) + numpy.sum(system.H1[1]*G[1])
if rchol is None:
rchol = system.rchol_vecs
nalpha, nbeta= system.nup, system.ndown
nbasis = system.nbasis
Ga, Gb = Ghalf[0], Ghalf[1]
Xa = rchol[0].T.dot(Ga.ravel())
Xb = rchol[1].T.dot(Gb.ravel())
ecoul = numpy.dot(Xa,Xa)
ecoul += numpy.dot(Xb,Xb)
ecoul += 2*numpy.dot(Xa,Xb)
if system.sparse:
rchol_a, rchol_b = [rchol[0].toarray(), rchol[1].toarray()]
else:
rchol_a, rchol_b = rchol[0], rchol[1]
# T_{abn} = \sum_k Theta_{ak} LL_{ak,n}
# LL_{ak,n} = \sum_i L_{ik,n} A^*_{ia}
naux = rchol_a.shape[-1]
theta = numpy.zeros((naux,nsamples), dtype=numpy.int64)
for i in range(nsamples):
theta[:,i] = (2*numpy.random.randint(0,2,size=(naux))-1)
if (control):
ra = rchol_a.dot(theta).T * numpy.sqrt(1.0/nsamples)
rb = rchol_b.dot(theta).T * numpy.sqrt(1.0/nsamples)
Ta0 = numpy.zeros((nsamples, nalpha, nalpha), dtype=rchol_a.dtype)
Tb0 = numpy.zeros((nsamples, nbeta, nbeta), dtype=rchol_b.dtype)
Ta = numpy.zeros((nsamples, nalpha, nalpha), dtype=rchol_a.dtype)
Tb = numpy.zeros((nsamples, nbeta, nbeta), dtype=rchol_b.dtype)
G0aT = C0[:,:system.nup]
G0bT = C0[:,system.nup:]
GaT = Ga.T
GbT = Gb.T
for x in range(nsamples):
rmi_a = ra[x].reshape((nalpha,nbasis))
rmi_b = rb[x].reshape((nbeta,nbasis))
Ta0[x] = rmi_a.dot(G0aT)
Tb0[x] = rmi_b.dot(G0bT)
Ta[x] = rmi_a.dot(GaT)
Tb[x] = rmi_b.dot(GbT)
exxa_hf = numpy.tensordot(Ta0, Ta0, axes=((0,1,2),(0,2,1)))
exxb_hf = | numpy.tensordot(Tb0, Tb0, axes=((0,1,2),(0,2,1))) | numpy.tensordot |
"""
Contents:
flatten: a function to flatten lists of lists.
retrieve_tess_lcdata: given lcfiles (spoc/cdips) get dict of time/flux/err.
_subset_cut: slice/trim LC to transit windows.
get_model_transit: given parameters, evaluate LC model.
_get_fitted_data_dict: get params and model LCs from ModelFitter object.
_get_fitted_data_dict_alltransit: ditto, for "alltransit" model.
_estimate_mode: get mode of unimodal pdf given samples, via gaussian KDE.
get_wasp4_lightcurve: used for module testing.
_given_mag_get_flux
"""
import os, collections
import numpy as np, pandas as pd
from collections import OrderedDict
from astropy.io import fits
from betty.paths import TESTDATADIR
from astrobase.services.identifiers import simbad_to_tic
from astrobase.services.tesslightcurves import get_two_minute_spoc_lightcurves
# sensible default keys to use for light curve retrieval
LCKEYDICT = {
'spoc': {'time': 'TIME',
'flux': 'PDCSAP_FLUX',
'flux_err': 'PDCSAP_FLUX_ERR',
'qual': 'QUALITY'},
'cdips': {'time': 'TMID_BJD',
'flux': 'IRM1',
'flux_err': 'IRE1',
'qual': 'IRQ1'}
}
def flatten(l):
for el in l:
if (
isinstance(el, collections.Iterable) and
not isinstance(el, (str, bytes))
):
yield from flatten(el)
else:
yield el
def retrieve_tess_lcdata(lcfiles, provenance=None, merge_sectors=1,
simple_clean=1):
"""
retrieve_tess_lcdata: Given a list of files pointing to TESS light-curves
(single-sector, or multi-sector), collect them, and return requested data
keys.
Kwargs:
provenance: string. Can be 'spoc' or 'cdips'.
merge_sectors: bool/int. Whether or not to merge multisectors. If false
and multiple lcfiles are passed, raises error.
simple_clean: whether to apply quick-hack cleaning diagnostics (e.g.,
"all non-zero quality flags removed").
Returns:
lcdict: has keys
`d['time'], d['flux'], d['flux_err'], d['qual'], d['texp']`
"""
allowed_provenances = ['spoc', 'cdips']
if provenance not in allowed_provenances:
raise NotImplementedError
if len(lcfiles) > 1 and not merge_sectors:
raise NotImplementedError
# retrieve time, flux, flux_err, and quality flags from fits files
getkeydict = LCKEYDICT[provenance]
getkeys = list(getkeydict.values())
d = {}
for l in lcfiles:
d[l] = {}
hdul = fits.open(l)
for k,v in getkeydict.items():
d[l][k] = hdul[1].data[v]
hdul.close()
# merge across sectors
_d = {}
for k,v in getkeydict.items():
vec = np.hstack([
d[l][k] for l in lcfiles
])
if k == 'flux' or k == 'flux_err':
# stitch absolute flux levels by median-dividing (before cleaning,
# which will remove nans anyway)
vec = np.hstack([
d[l][k]/np.nanmedian(d[l]['flux']) for l in lcfiles
])
_d[k] = vec
if not simple_clean:
raise NotImplementedError(
'you probably want to apply simple_clean '
'else you will have NaNs and bad quality flags.'
)
sel = (
np.isfinite(_d['time'])
&
np.isfinite(_d['flux'])
&
np.isfinite(_d['flux_err'])
&
np.isfinite(_d['qual'])
)
if provenance == 'spoc':
sel &= (_d['qual'] == 0)
elif provenance == 'cdips':
raise NotImplementedError('need to apply cdips quality flags')
#FIXME FIXME divding..
_f = _d['flux'][sel]
outd = {
'time': _d['time'][sel],
'flux': _f/np.nanmedian(_f),
'flux_err': _d['flux_err'][sel]/np.nanmedian(_f),
'qual': _d['qual'][sel],
'texp': np.nanmedian(np.diff(_d['time'][sel]))
}
return outd
def get_model_transit(paramd, time_eval, t_exp=2/(60*24)):
"""
you know the paramters, and just want to evaluate the median lightcurve.
"""
import exoplanet as xo
period = paramd['period']
t0 = paramd['t0']
try:
r = paramd['ror']
except KeyError:
r = np.exp(paramd['log_ror'])
b = paramd['b']
u0 = paramd['u[0]']
u1 = paramd['u[1]']
r_star = paramd['r_star']
logg_star = paramd['logg_star']
try:
mean = paramd['mean']
except KeyError:
mean_key = [k for k in list(paramd.keys()) if 'mean' in k]
assert len(mean_key) == 1
mean_key = mean_key[0]
mean = paramd[mean_key]
# factor * 10**logg / r_star = rho
factor = 5.141596357654149e-05
rho_star = factor*10**logg_star / r_star
orbit = xo.orbits.KeplerianOrbit(
period=period, t0=t0, b=b, rho_star=rho_star
)
u = [u0, u1]
mu_transit = xo.LimbDarkLightCurve(u).get_light_curve(
orbit=orbit, r=r, t=time_eval, texp=t_exp
).T.flatten()
return mu_transit.eval() + mean
def _get_fitted_data_dict(m, summdf):
instrkeys = [k for k in m.priordict.keys() if '_mean' in k]
if len(instrkeys) > 1:
msg = 'Expected 1 instrument for this fit.'
raise NotImplementedError(msg)
instr = instrkeys[0].split('_')[0]
_m = m.data[instr]
d = {
'x_obs': _m[0],
'y_obs': _m[1],
'y_orb': None, # NOTE: "detrended" beforehand
'y_resid': None, # for now.
'y_mod': None, # for now [could be MAP, if MAP were good]
'y_err': _m[2]
}
params = ['period', 't0', 'log_ror', 'b', 'u[0]', 'u[1]', f'{instr}_mean',
'r_star', 'logg_star']
paramd = {k:summdf.loc[k, 'median'] for k in params}
y_mod_median = get_model_transit(
paramd, d['x_obs'], t_exp=np.nanmedian(np.diff(d['x_obs']))
)
d['y_mod'] = y_mod_median
d['y_resid'] = d['y_obs']-y_mod_median
return d, params, paramd
def _get_fitted_data_dict_alltransit(m, summdf):
d = OrderedDict()
for name in m.data.keys():
d[name] = {}
d[name]['x_obs'] = m.data[name][0]
d[name]['y_obs'] = m.data[name][1]
d[name]['y_err'] = m.data[name][2]
params = ['period', 't0', 'log_ror', 'b', 'u[0]', 'u[1]', 'r_star',
'logg_star', f'{name}_mean']
paramd = {k : summdf.loc[k, 'median'] for k in params}
y_mod_median = get_model_transit(
paramd, d[name]['x_obs'],
t_exp=np.nanmedian(np.diff(d[name]['x_obs']))
)
d[name]['y_mod'] = y_mod_median
d[name]['y_resid'] = d[name]['y_obs'] - y_mod_median
d[name]['params'] = params
# merge all the available LC data
d['all'] = {}
_p = ['x_obs', 'y_obs', 'y_err', 'y_mod']
for p in _p:
d['all'][p] = np.hstack([d[f'{k}'][p] for k in d.keys()
if '_' in k or 'tess' in k])
return d
def _get_fitted_data_dict_allindivtransit(m, summdf, bestfitmeans='median'):
"""
args:
bestfitmeans: "map", "median", "mean, "mode"; depending on which you
think will produce the better fitting model.
"""
d = OrderedDict()
for name in m.data.keys():
d[name] = {}
d[name]['x_obs'] = m.data[name][0]
# d[name]['y_obs'] = m.data[name][1]
d[name]['y_err'] = m.data[name][2]
params = ['period', 't0', 'log_ror', 'b', 'u[0]', 'u[1]', 'r_star',
'logg_star', f'{name}_mean', f'{name}_a1', f'{name}_a2']
_tmid = np.nanmedian(m.data[name][0])
t_exp = np.nanmedian( | np.diff(m.data[name][0]) | numpy.diff |
# -*- coding: utf-8 -*-
# Copyright 2020 PyePAL 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.
"""Testing the PAL base class"""
# pylint:disable=protected-access
import numpy as np
import pytest
from pyepal.models.gpr import build_coregionalized_model
from pyepal.pal.pal_base import PALBase
from pyepal.pal.pal_coregionalized import PALCoregionalized
def test_pal_base(make_random_dataset):
"""Testing basic functionality of the PAL base class"""
palinstance = PALBase(make_random_dataset[0], ["model"], 3)
assert palinstance.number_discarded_points == 0
assert palinstance.number_pareto_optimal_points == 0
assert palinstance.number_unclassified_points == 100
assert palinstance.number_sampled_points == 0
assert palinstance.number_design_points == 100
assert palinstance.should_cross_validate()
assert len(palinstance.discarded_points) == 0
assert len(palinstance.pareto_optimal_points) == 0
assert len(palinstance.unclassified_points) == 100
with pytest.raises(ValueError):
palinstance.hyperrectangle_sizes # pylint:disable=pointless-statement
assert (
str(palinstance)
== "pyepal at iteration 1. \
0 Pareto optimal points, \
0 discarded points, \
100 unclassified points."
)
assert palinstance._should_optimize_hyperparameters()
assert not palinstance._has_train_set
with pytest.raises(ValueError):
palinstance.sample()
assert palinstance.y.shape == (100, 3)
assert not palinstance.uses_fixed_epsilon
palinstance = PALBase(make_random_dataset[0], ["model"], 3, ranges=[1, 1, 1])
assert palinstance.uses_fixed_epsilon
def test_reset_classification(make_random_dataset):
"""Make sure the reset of the reclassification status works as expected."""
X, _ = make_random_dataset # pylint: disable=invalid-name
palinstance = PALBase(X, ["model"], 3)
lows = np.zeros((100, 3))
highs = np.zeros((100, 3))
means = np.full((100, 3), 1)
palinstance._means = means
palinstance.std = np.full((100, 3), 0.1)
pareto_optimal = np.array([False] * 98 + [True, True])
sampled = np.array([[False] * 3, [False] * 3, [False] * 3, [False] * 3])
unclassified = np.array([True] * 98 + [False, False])
palinstance.rectangle_lows = lows
palinstance.rectangle_ups = highs
palinstance.sampled = sampled
palinstance.pareto_optimal = pareto_optimal
palinstance.unclassified = unclassified
palinstance._reset_classification()
assert palinstance.number_unclassified_points == len(X)
assert palinstance.number_pareto_optimal_points == 0
assert palinstance.number_discarded_points == 0
def test_update_train_set(make_random_dataset):
"""Check if the update of the training set works"""
X, y = make_random_dataset # pylint:disable=invalid-name
palinstance = PALBase(X, ["model"], 3)
assert not palinstance._has_train_set
assert palinstance.sampled.sum() == 0
palinstance.update_train_set(np.array([0]), y[0, :].reshape(-1, 3))
assert palinstance.sampled_indices == np.array([0])
assert palinstance.number_sampled_points == 1
assert (palinstance.y[0] == y[0, :]).all()
def test_means_property(binh_korn_points):
"""based on #185 and example in
https://deepnote.com/project/
Pyepal-mirrored-results-Yeuc095QRE6ToMXFtwFjnA/
%2Fbinh_korn_goals_issue.ipynb/#00012-ebf692a0-f995-4e25-98b6-8d34a7db7f54"""
x, points = binh_korn_points # pylint:disable=invalid-name
np.random.seed(10)
points[:, 0] = -points[:, 0]
model = build_coregionalized_model(x, points)
palinstance = PALCoregionalized(
x, [model], 2, goals=["min", "max"], epsilon=[0.5, 0.5], restarts=3
)
indices = np.array([0, 1, 5, 10, 20, 30, 40, 50, 60, 70, 80, 90, 99])
palinstance.update_train_set(indices, points[indices])
palinstance.run_one_step()
assert np.all(palinstance.means[:, 0] >= 0)
def test_means_property2(binh_korn_points):
"""based on #185 and example in
https://deepnote.com/project/
Pyepal-mirrored-results-Yeuc095QRE6ToMXFtwFjnA/
%2Fbinh_korn_goals_issue.ipynb/#00012-ebf692a0-f995-4e25-98b6-8d34a7db7f54"""
x, points = binh_korn_points # pylint:disable=invalid-name
points = -points
np.random.seed(10)
model = build_coregionalized_model(x, points)
palinstance = PALCoregionalized(
x, [model], 2, goals=["min", "min"], epsilon=[0.5, 0.5], restarts=3
)
indices = np.array([0, 1, 5, 10, 20, 30, 40, 50, 60, 70, 80, 90, 99])
palinstance.update_train_set(indices, points[indices])
palinstance.run_one_step()
assert np.all(palinstance.means[:, 0] >= 0)
assert np.all(palinstance.means[:, 1] >= 0)
def test_augment_design_space(make_random_dataset):
"""Testing the basic functionality of the augmentation method
Does NOT test the re-classification step, which needs a model"""
X, _ = make_random_dataset # pylint: disable=invalid-name
X_augmented = np.vstack([X, X]) # pylint: disable=invalid-name
palinstance = PALBase(X, ["model"], 3)
# Iteration count to low
with pytest.raises(ValueError):
palinstance.augment_design_space(X_augmented)
palinstance.iteration = 2
# Incorrect shape
with pytest.raises(AssertionError):
palinstance.augment_design_space(X_augmented[:, 2])
with pytest.raises(ValueError):
palinstance.augment_design_space(X_augmented[:, :2])
# Mock that we already ran that
lows = np.zeros((100, 3))
highs = np.zeros((100, 3))
means = np.full((100, 3), 1)
palinstance._means = means
palinstance.std = np.full((100, 3), 0.1)
pareto_optimal = np.array([False] * 98 + [True, True])
sampled = np.array([[False] * 3, [False] * 3, [False] * 3, [False] * 3])
unclassified = np.array([True] * 98 + [False, False])
palinstance.rectangle_lows = lows
palinstance.rectangle_ups = highs
palinstance.sampled = sampled
palinstance.pareto_optimal = pareto_optimal
palinstance.unclassified = unclassified
# As we do not have a model, we cannot test the classification
palinstance.augment_design_space(X_augmented, clean_classify=False)
assert palinstance.number_discarded_points == 0
assert palinstance.number_pareto_optimal_points == 2
assert palinstance.number_unclassified_points == 298
assert palinstance.number_sampled_points == 0
assert palinstance.number_design_points == 300
assert len(palinstance.means) == 300
assert len(palinstance.std) == 300
def test_beta_update(make_random_dataset):
"""testing that the beta update works"""
X, _ = make_random_dataset # pylint:disable=invalid-name
palinstance = PALBase(X, ["model"], 3)
assert palinstance.beta is None
palinstance._update_beta()
assert palinstance.beta is not None
assert palinstance.beta == 1 / 9 * 2 * np.log(
3 * 100 * np.square(np.pi) * np.square(2) / (6 * 0.05)
)
def test_turn_to_maximization(make_random_dataset):
"""Test that flipping the sign for minimization problems works"""
X, y = make_random_dataset # pylint:disable=invalid-name
palinstance = PALBase(X, ["model"], 3)
palinstance.update_train_set(np.array([0]), y[0, :].reshape(-1, 3))
assert (palinstance.y[0] == y[0, :]).all()
assert (palinstance._y[0] == y[0, :]).all()
palinstance = PALBase(X, ["model"], 3, goals=[1, 1, -1])
palinstance.update_train_set(np.array([0]), y[0, :].reshape(-1, 3))
assert (palinstance.y[0] == y[0, :] * np.array([1, 1, -1])).all()
assert (palinstance._y[0] == y[0, :]).all()
def test_sample(make_random_dataset):
"""Test the sampling"""
X, _ = make_random_dataset # pylint:disable=invalid-name
palinstance = PALBase(X, ["model"], 4)
lows = np.array(
[
[0.0, 0.0, 0.0, 0.0],
[-1.0, -1.0, -1.0, -1.0],
[-2.0, -2.0, -2.0, -2.0],
[2.0, 2.0, 2.0, 2.0],
]
)
highs = np.array(
[
[1.0, 1.0, 1.0, 1.0],
[1.0, 1.0, 1.0, 1.0],
[1.0, 1.0, 1.0, 1.0],
[2.0, 2.0, 2.0, 2.0],
]
)
means = np.array([[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]])
palinstance._means = means
pareto_optimal = np.array([False, False, True, True])
sampled = np.array([[False] * 4, [False] * 4, [False] * 4, [False] * 4])
unclassified = np.array([True, True, False, False])
palinstance.rectangle_lows = lows
palinstance.rectangle_ups = highs
palinstance.sampled = sampled
palinstance.pareto_optimal = pareto_optimal
palinstance.unclassified = unclassified
sampled_idx = palinstance.sample()
assert sampled_idx == 2
pareto_optimal = np.array([False, False, True, True])
sampled = np.array([[False] * 4, [False] * 4, [False] * 4, [False] * 4])
unclassified = np.array([True, True, False, False])
palinstance.sampled = sampled
palinstance.pareto_optimal = pareto_optimal
palinstance.unclassified = unclassified
sampled_idx = palinstance.sample()
assert sampled_idx == 2
pareto_optimal = np.array([False, False, True, True])
sampled = np.array([[False] * 4, [False] * 4, [True] * 4, [False] * 4])
unclassified = np.array([True, True, False, False])
palinstance.sampled = sampled
palinstance.pareto_optimal = pareto_optimal
palinstance.unclassified = unclassified
sampled_idx = palinstance.sample()
assert sampled_idx == 1
pareto_optimal = np.array([False, False, False, True])
sampled = np.array([[False] * 4, [False] * 4, [True] * 4, [False] * 4])
unclassified = np.array([True, True, False, False])
palinstance.sampled = sampled
palinstance.pareto_optimal = pareto_optimal
palinstance.unclassified = unclassified
sampled_idx = palinstance.sample()
assert sampled_idx == 1
def test__update_hyperrectangles(make_random_dataset):
"""Testing if the updating of the hyperrectangles works as expected.
As above, the core functionality is tested in for the function with the logic.
Here, we're more interested in seeing how it works with the class object
"""
X, _ = make_random_dataset # pylint:disable=invalid-name
palinstance = PALBase(X, ["model"], 4, beta_scale=1)
palinstance._means = np.array([[0, 0, 1, 0], [0, 0, 0, 1]])
palinstance.std = np.array([[0, 0, 0, 0], [1, 0, 0, 0]])
with pytest.raises(TypeError):
# Beta is not defined
palinstance._update_hyperrectangles()
palinstance._update_beta()
palinstance._update_hyperrectangles()
assert palinstance.rectangle_lows is not None
assert palinstance.rectangle_ups is not None
assert palinstance.rectangle_lows[0][0] == 0
assert palinstance.rectangle_ups[0][0] == 0
assert palinstance.rectangle_lows[0][2] == 1
assert palinstance.rectangle_ups[0][2] == 1
assert palinstance.rectangle_lows[1][0] < -1
assert palinstance.rectangle_ups[1][0] > 1
assert len(palinstance.hyperrectangle_sizes) == len(palinstance._means)
def test_orchestration_run_one_step(make_random_dataset):
"""Test if the orchestration works.
In the base class it should raise an error as without
prediction function we cannot do anything
"""
X, y = make_random_dataset # pylint:disable=invalid-name
palinstance = PALBase(X, ["model"], 3, beta_scale=1)
sample_idx = np.array([1, 2, 3, 4])
palinstance.update_train_set(sample_idx, y[sample_idx])
with pytest.raises(NotImplementedError):
_ = palinstance.run_one_step()
def test__replace_by_measurements(make_random_dataset):
"""Test that replacing the mean/std by the measured ones works"""
X, y = make_random_dataset # pylint:disable=invalid-name
palinstance = PALBase(X, ["model"], 3, beta_scale=1)
assert palinstance.measurement_uncertainty.sum() == 0
sample_idx = np.array([1, 2, 3, 4])
palinstance.update_train_set(sample_idx, y[sample_idx], y[sample_idx])
palinstance._means = palinstance.measurement_uncertainty
palinstance.std = palinstance.measurement_uncertainty
palinstance._replace_by_measurements()
assert (palinstance.y == palinstance.std).all()
def test__update_coef_var_mask(make_random_dataset):
"""Test that the coefficient of variation mask works as expected"""
X, _ = make_random_dataset # pylint:disable=invalid-name
palinstance = PALBase(X[:2], ["model"], 3, beta_scale=1)
palinstance._means = np.array([[1, 1, 1, 1], [1, 1, 1, 1]])
palinstance.std = np.array([[0, 0, 0, 0], [3, 1, 1, 1]])
assert (palinstance.coef_var_mask == | np.array([True, True]) | numpy.array |
from polymuse import rnn, dutils, dataset, dataset2 as d2, enc_deco
from polymuse.losses import rmsecat
import tensorflow as tf
import numpy, random
"""
rnn_player -- capable of playing/generating the music output as octave/time encoded representation
These also includes two most important functions :
* shift:
* add_flatroll:
"""
def rmsecat(depth):
def rmsecat_(y_true, y_pred):
a = []
h_ = None
for i in range(depth * 2):
h__ = categorical_crossentropy(y_true[:, i : i + 16], y_pred[ :, i : i + 16])
if h_ is None: h_ = tf.square(h__)
else: h_ += tf.square(h__)
a = (tf.sqrt(h_) / (2 * depth))
return a
return rmsecat_
def rsingle_note_stateful_play(model_note, ini_ip, y_expected_note = None, bs = 32, ip_memory = None, predict_instances = 250):
"""stateful player
Arguments:
model_note {keras.Sequential} -- [description]
ini_ip {numpy.ndarray} -- input initiater, shape (note_instances, ip_memory, depth, tuple(enc)), enc = (2, 16)
Keyword Arguments:
y_expected_note {numpy.ndarray} -- [description] (default: {None})
ip_memory {int} -- [description] (default: {None})
predict_instances {int} -- [description] (default: {250})
Returns:
[numpy.ndarray] -- [description]
"""
model_note = rnn.load(model_note) if type(model_note) == str else model_note
ip_memory = ip_memory if ip_memory else ini_ip.shape[1]
depth = ini_ip.shape[2]
enc = ini_ip.shape[3:]
r1 = random.randint(0, ini_ip.shape[0])
inp = numpy.zeros((bs, ip_memory, depth) + enc)
print("iin inin : ", inp.shape)
print(r1)
ini = numpy.array(ini_ip)
bs_ = ini.shape[0]
print("iin iniiiiiiiii : ", ini.shape)
inp[bs - (bs_ - r1):] = ini[r1: r1+bs]
print('inp note shape : ', inp.shape)
notes_shape = (1, predict_instances) + inp.shape[2:]
predict_instances = (predict_instances // bs) * bs
mem = inp.shape[1]
notes = numpy.zeros(notes_shape)
print(bs, "--bs")
print("notes : ", notes.shape)
for tm in range(0, predict_instances, bs):
y = rnn.predict(model_note, inp)
for j in range(bs):
for i in range(y.shape[1]):
# ocn, freqn = dutils.sample(y[j, i, 0], temperature= 3), dutils.sample(y[j, i, 1], temperature= 3)
ocn, freqn = numpy.argmax(y[j, i, 0]), dutils.sample(y[j, i, 1], temperature= 3)
y[j, i] = dutils.arg_oct_max(ocn, freqn, size = 16)
# y[j, i] = dutils.arg_octave_max(y[j, i])
notes[0, tm : tm + bs] = y
#Note Value
inp = shift(inp, axis= 1)
add_flatroll(inp, y)
pass
return notes
def rnote_track_stateful_player(mnote, ini= None, expected_note= None, TM = 8, bs = 32, ip_memory = 32, DEPTH = 1, predict_instances = 400):
model_note = rnn.load(model_note) if type(model_note) == str else model_note
ip_memory = ip_memory if ip_memory else ini.shape[1]
depth = ini.shape[2]
enc = ini.shape[3:]
r1 = random.randint(0, ini.shape[0])
inp = numpy.zeros((bs, ip_memory, depth) + enc)
print("iin inin : ", inp.shape)
print(r1)
ini = numpy.array(ini_ip)
bs_ = ini.shape[0]
print("iin iniiiiiiiii : ", ini.shape)
inp[bs - (bs_ - r1):] = ini[r1: r1+bs]
print('inp note shape : ', inp.shape)
notes_shape = (1, predict_instances) + inp.shape[2:]
predict_instances = (predict_instances // bs) * bs
mem = inp.shape[1]
notes = numpy.zeros(notes_shape)
print(bs, "--bs")
print("notes : ", notes.shape)# notes[0, :mem, :] = inp #initiating the start
k = 0
for tm in range(0, predict_instances):
# print("loop", tm)
if k >= inp.shape[0] and inp.shape[0] != 1: k = random.randint(0, inp.shape[0] - 1)
if inp.shape[0] == 0: k = 0
print('inp : ', inp[k].shape, "k : ", k)
inp_ = numpy.reshape(inp[k:k+1], (1, ip_memory, -1))
y = rnn.predict_b(model_note, inp_)
y = numpy.reshape(y, (1, DEPTH, 2, 16))
y_len = numpy.zeros((1, 64))
y_len[ :, TM] = 1
for j in range(bs):
# print('y : ', y, y.shape)
for i in range(y.shape[1]):
# ocn, freqn = dutils.sample(y[j, i, 0], temperature= 3), dutils.sample(y[j, i, 1], temperature= 3)
ocn, freqn = numpy.argmax(y[j, i, 0]), dutils.sample(y[j, i, 1], temperature= 3)
y[j, i] = dutils.arg_oct_max(ocn, freqn, size = 16)
# y[j, i] = dutils.arg_octave_max(y[j, i])
notes[0, tm : tm + bs] = y
# time[0, tm : tm + bs] = y_len
k += 1
pass
return enc_deco.octave_to_sFlat(notes)
def rsingle_note_time_play(model_note, model_time, ini_ip, ini_ip_tm, y_expected_note = None, y_expected_time = None, ip_memory = None, predict_instances = 250):
model_note = rnn.load(model_note) if type(model_note) == str else model_note
model_time = rnn.load(model_time) if type(model_time) == str else model_time
ip_memory = ip_memory if ip_memory else ini_ip.shape[0]
inp = numpy.array([ini_ip])
# inp = numpy.array(ini_ip)
inp_tm = numpy.array([ini_ip_tm])
print("inp time shape : ", inp_tm.shape)
print('inp note shape : ', inp.shape)
notes_shape = (1, predict_instances) + inp.shape[2:]
time_shape = (1, predict_instances) + inp_tm.shape[2:]
# notes_shape.extend(inp.shape[2:])
# time_shape.extend(inp_tm.shape[2:])
bs = inp.shape[0]
predict_instances = (predict_instances // bs) * bs
mem = inp.shape[1]
notes = numpy.zeros(notes_shape)
time = numpy.zeros(time_shape)
print(bs, "--bs")
print("notes, time : ", notes.shape, time.shape)
# notes[0, :mem, :] = inp #initiating the start
for tm in range(0, predict_instances):
# print("loop", tm)
y = rnn.predict_b(model_note, inp)
y_len = rnn.predict_b(model_time, inp_tm)
# print(y.shape, " --------------")
if 95 < tm < 150 :
# print("inp tm : ", inp_tm)
# print("time : ", time[0, :10])
# print("shape : ", y.shape)
# print("Expected y_len NOTE: ", y_expected_note[tm + 1])
# print("y_len : ", dutils.arg_octave_max(y[0, 0]))
# print("+=================================================================+")
# print("Expected y_len : ", y_expected_time[tm + 1])
# print("y_len -- : ", y_len[0])
# print("y_len : ", dutils.arg_max(y_len[0]))
# print("ynum argmax : ", numpy.argmax(y_len[0]))
pass
for j in range(bs):
y_len[j] = dutils.arg_max(y_len[j])
for j in range(bs):
for i in range(y.shape[1]):
y[j, i] = dutils.arg_octave_max(y[j, i])
notes[0, tm : tm + bs] = y
time[0, tm : tm + bs] = y_len
#Note Value
inp = shift(inp, axis= 1)
add_flatroll(inp, y)
#Time Length
inp_tm = shift(inp_tm, axis=1)
add_flatroll(inp_tm, y_len)
pass
return notes, time
def rsingle_note_time_play(model_note, model_time, ini_ip, ini_ip_tm, y_expected_note = None, y_expected_time = None, ip_memory = None, predict_instances = 250):
model_note = rnn.load(model_note) if type(model_note) == str else model_note
model_time = rnn.load(model_time) if type(model_time) == str else model_time
ip_memory = ip_memory if ip_memory else ini_ip.shape[0]
inp = numpy.array([ini_ip])
# inp = numpy.array(ini_ip)
# inp_tm = numpy.array([ini_ip_tm])
print("inp time shape : ", inp_tm.shape)
print('inp note shape : ', inp.shape)
notes_shape = (1, predict_instances) + inp.shape[2:]
time_shape = (1, predict_instances) + inp_tm.shape[2:]
notes_shape.extend(inp.shape[2:])
time_shape.extend(inp_tm.shape[2:])
bs = inp.shape[0]
predict_instances = (predict_instances // bs) * bs
mem = inp.shape[1]
notes = numpy.zeros(notes_shape)
time = numpy.zeros(time_shape)
print(bs, "--bs")
print("notes, time : ", notes.shape, time.shape)
# notes[0, :mem, :] = inp #initiating the start
for tm in range(0, predict_instances):
# print("loop", tm)
y = rnn.predict_b(model_note, inp)
y_len = rnn.predict_b(model_time, inp_tm)
# print(y.shape, " --------------")
for j in range(bs):
y_len[j] = dutils.arg_max(y_len[j])
for j in range(bs):
for i in range(y.shape[1]):
y[j, i] = dutils.arg_octave_max(y[j, i])
notes[0, tm : tm + bs] = y
time[0, tm : tm + bs] = y_len
#Note Value
inp = shift(inp, axis= 1)
add_flatroll(inp, y)
#Time Length
inp_tm = shift(inp_tm, axis=1)
add_flatroll(inp_tm, y_len)
pass
return notes, time
def rsing_note_time_play(model_note, model_time, ini_ip, ini_ip_tm, y_expected_note = None, y_expected_time = None, ip_memory = None, predict_instances = 250):
model_note = rnn.load(model_note) if type(model_note) == str else model_note
model_time = rnn.load(model_time) if type(model_time) == str else model_time
ip_memory = ip_memory if ip_memory else ini_ip.shape[0]
inp = numpy.array([ini_ip])
inp_tm = numpy.array([ini_ip_tm])
print("inp time shape : ", inp_tm.shape)
print('inp note shape : ', inp.shape)
notes_shape = (1, predict_instances) + inp.shape[2:]
time_shape = (1, predict_instances) + inp_tm.shape[2:]
# notes_shape.extend(inp.shape[2:])
# time_shape.extend(inp_tm.shape[2:])
mem = inp.shape[1]
notes = numpy.zeros(notes_shape)
time = numpy.zeros(time_shape)
print("notes, time : ", notes.shape, time.shape)
# notes[0, :mem, :] = inp #initiating the start
for tm in range(predict_instances):
# print("loop", tm)
y = rnn.predict_b(model_note, inp)
y_len = rnn.predict_b(model_time, inp_tm)
# print(y.shape, y_len.shape)
if 95 < tm < 150 :
# print(y.shape, y_len.shape)
pass
y_len[0] = dutils.arg_max(y_len[0])
for i in range(y.shape[1]):
# ocn, freqn = dutils.sample(y[j, i, 0], temperature= 3), dutils.sample(y[j, i, 1], temperature= 3)
ocn, freqn = numpy.argmax(y[j, i, 0]), dutils.sample(y[j, i, 1], temperature= 3)
y[j, i] = dutils.arg_oct_max(ocn, freqn, size = 16)
# y[0, i] = dutils.arg_octave_max(y[0, i])
notes[0, tm] = y[0]
time[0, tm] = y_len[0]
#Note Value
inp = shift(inp, axis= 1)
add_flatroll(inp, y)
#Time Length
inp_tm = shift(inp_tm, axis=1)
add_flatroll(inp_tm, y_len)
pass
return notes, time
def rnn_dense_player(models, ini, ip_memory = None, predict_instances= 400): #works on tick
#models = (model_n_rnn, model_t_rnn, drum_n_rnn, drum_t_rnn, drum_dense_1, drum_dense_2)
#ini = (ini_ip, ini_ip_tm, inp_drm_ip, inp_drm_tm) # pinao note, piano time, drum note, drum time
model_note, model_time, drum_note, drum_time, dense_1, dense_2 = models
tick = 0
delt = 32
ini_ip, ini_t, ini_drm_ip, ini_drm_t = numpy.array([ini[0]]), numpy.array([ini[1]]), numpy.array([ini[2]]), numpy.array([ini[3]])
muse_op_piano_n = numpy.zeros((1, 4 * predict_instances) + ini_ip.shape[2:])
muse_op_piano_t = numpy.zeros((1, 4 * predict_instances) + ini_t.shape[2:])
muse_op_drum_n = numpy.zeros((1, 4 * predict_instances) + ini_drm_ip.shape[2:])
print(ini_ip.shape, ini_t.shape, ini_drm_ip.shape, ini_drm_t.shape, "-- ini_ip, ini_tm, inp_drm_ip, inp_drm_tm")
print(muse_op_piano_n.shape, muse_op_piano_t.shape, "-- muse_op_piano_n, muse_op_piano_t")
TIME = predict_instances * 4
ticker = [0, 0]
tm, dtm = 0, 0
while tick < TIME:
if ticker[0] >= 0:
y = rnn.predict_b(model_note, ini_ip)
y_len = rnn.predict_b(model_time, ini_t)
y_len[0] = dutils.arg_max(y_len[0])
for i in range(y.shape[1]):
y[0, i] = dutils.arg_octave_max(y[0, i])
muse_op_piano_n[0, tm] = y[0]
muse_op_piano_t[0, tm] = y_len[0]
#Note Value
inp = shift(ini_ip, axis= 1)
add_flatroll(ini_ip, y)
#Time Length
inp_tm = shift(ini_t, axis=1)
add_flatroll(ini_t, y_len)
ticker[0] = dutils.tm(y_len[0])
tm += 1
if ticker[1] >=0 :
#write here code
y = rnn.predict_b(drum_note, ini_drm_ip)
for i in range(y.shape[1]):
y[0, i] = dutils.arg_octave_max(y[0, i])
muse_op_drum_n[0, dtm] = y[0]
# print(y.shape, "y . .. ")
y_ = | numpy.zeros((3, 2, 16)) | numpy.zeros |
import numpy as np
from matplotlib import pyplot as plt
# Set up figures look and feel
import style_figs
# %%
# Our data-generating process
def f(t):
return 1.2 * t ** 2 + .1 * t ** 3 - .4 * t ** 5 - .5 * t ** 9
N_SAMPLES = 50
rng = np.random.RandomState(0)
x = 2 * rng.rand(N_SAMPLES) - 1
y = f(x) + .4 * rng.normal(size=N_SAMPLES)
plt.figure()
plt.scatter(x, y, s=20, color='k')
style_figs.no_axis()
plt.subplots_adjust(top=.96)
plt.xlim(-1.1, 1.1)
plt.ylim(-.74, 2.1)
plt.savefig('polynomial_overfit_0.svg', facecolor='none', edgecolor='none')
# %%
# Our model (polynomial regression)
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression
# %%
# Fit model with various complexity in the polynomial degree
plt.figure()
plt.scatter(x, y, s=20, color='k')
t = np.linspace(-1, 1, 100)
for d in (1, 2, 5, 9):
model = make_pipeline(PolynomialFeatures(degree=d), LinearRegression())
model.fit(x.reshape(-1, 1), y)
plt.plot(t, model.predict(t.reshape(-1, 1)), label='Degree %d' % d)
style_figs.no_axis()
plt.legend(loc='upper center', borderaxespad=0, borderpad=0)
plt.subplots_adjust(top=.96)
plt.ylim(-.74, 2.1)
plt.savefig('polynomial_overfit_%d.svg' % d, facecolor='none',
edgecolor='none')
plt.plot(t, f(t), 'k--', label='Truth')
style_figs.no_axis()
plt.legend(loc='upper center', borderaxespad=0, borderpad=0)
plt.ylim(-.74, 2.1)
plt.subplots_adjust(top=.96)
plt.savefig('polynomial_overfit.svg', facecolor='none', edgecolor='none')
# %%
# A figure with the true model and the estimated one
plt.figure(figsize=[.5 * 6.4, .5 * 4.8])
plt.scatter(x, y, s=20, color='k')
plt.plot(t, model.predict(t.reshape(-1, 1)), color='C3',
label='$\hat{f}$')
plt.plot(t, f(t), 'k--', label='$f^{\star}$')
style_figs.no_axis()
plt.legend(loc='upper center', borderaxespad=0, borderpad=0,
labelspacing=.2, fontsize=26)
plt.subplots_adjust(top=.96)
plt.savefig('polynomial_overfit_simple.svg', facecolor='none', edgecolor='none')
# %%
# A figure with the true model and the estimated one
plt.figure(figsize=[.5 * 6.4, .5 * 4.8])
plt.scatter(x, y, s=20, color='k')
plt.plot(t, model.predict(t.reshape(-1, 1)), color='C3',
label='$\hat{f}$')
plt.plot(t, f(t), 'k--', label='$f^{\star}$')
style_figs.no_axis()
plt.legend(loc='upper center', borderaxespad=0, borderpad=0,
labelspacing=.2, fontsize=26)
plt.subplots_adjust(top=.96)
# More detailed legend
plt.savefig('polynomial_overfit_simple_legend.svg', facecolor='none', edgecolor='none')
# %%
# Assymptotic settings
rng = np.random.RandomState(0)
x = 2 * rng.rand(10 * N_SAMPLES) - 1
y = f(x) + .4 * rng.normal(size=10 * N_SAMPLES)
model = make_pipeline(PolynomialFeatures(degree=1), LinearRegression())
model.fit(x.reshape(-1, 1), y)
plt.figure(figsize=[.5 * 6.4, .5 * 4.8])
plt.scatter(x, y, s=20, color='k', alpha=.3)
plt.plot(t, model.predict(t.reshape(-1, 1)), color='C0',
label='$\hat{f} \\approx f^{\star}$')
plt.plot(t, f(t), 'k--', label='$g$')
style_figs.no_axis()
plt.legend(loc='upper center', borderaxespad=0, borderpad=0,
labelspacing=.2, fontsize=26)
plt.subplots_adjust(top=.96)
plt.savefig('polynomial_overfit_assymptotic.svg', facecolor='none', edgecolor='none')
# %%
# Validation curves
from sklearn import model_selection
plt.figure()
param_range = np.arange(1, 20)
train_scores, test_scores = model_selection.validation_curve(
model, x[::2].reshape((-1, 1)), y[::2],
param_name='polynomialfeatures__degree',
param_range=param_range,
cv=model_selection.ShuffleSplit(n_splits=20))
plt.plot(param_range, -np.mean(test_scores, axis=1), 'k',
label='Generalization error')
plt.plot(param_range, -np.mean(train_scores, axis=1), 'k--',
label='Training error')
ax = plt.gca()
for s in ('top', 'right'):
ax.spines[s].set_visible(False)
plt.ylim(ymax=.05)
plt.legend(loc='center')
plt.yticks(())
plt.ylabel('Error')
plt.xlabel('Polynomial degree')
plt.subplots_adjust(left=.07, bottom=.18, top=.99, right=.99)
plt.savefig('polynomial_validation_curve.svg', facecolor='none',
edgecolor='none')
# %%
# Learning curves
rng = np.random.RandomState(0)
x = 2 * rng.rand(100 * N_SAMPLES) - 1
y = f(x) + .4 * rng.normal(size=100 * N_SAMPLES)
X = x.reshape((-1, 1))
np.random.seed(42)
plt.figure()
def savefig(name):
" Ajust layout, and then save"
ax = plt.gca()
for s in ('top', 'right'):
ax.spines[s].set_visible(False)
plt.ylim(-.65, .15)
plt.xlim(train_sizes.min(), train_sizes.max())
plt.xticks((100, 1000), ('100', '1000'), size=13)
plt.yticks(())
plt.ylabel('Error')
plt.xlabel('Number of samples')
plt.subplots_adjust(left=.07, bottom=.16, top=.99, right=.99)
plt.savefig(name, edgecolor='none', facecolor='none')
# Degree 9
model = make_pipeline(PolynomialFeatures(degree=9), LinearRegression())
train_sizes, train_scores, test_scores = model_selection.learning_curve(
model, X, y, cv=model_selection.ShuffleSplit(n_splits=20),
train_sizes=np.logspace(-2.5, -.3, 30))
test_plot = plt.semilogx(train_sizes, -np.mean(test_scores, axis=1),
label='9',
color='C3')
savefig('polynomial_learning_curve_0.svg')
train_plot = plt.semilogx(train_sizes, - | np.mean(train_scores, axis=1) | numpy.mean |
import numpy as np
import torch
import gym
import time
import os
import json
from copy import deepcopy
from functools import partial
from mrl.import_all import *
from mrl.configs.make_continuous_agents import *
from mrl.utils.misc import batch_block_diag
from envs.customfetch.custom_fetch import DisentangledFetchPushEnv,\
DisentangledFetchSlideEnv, DisentangledFetchPickAndPlaceEnv, SlideNEnv, PushNEnv
from gym.wrappers import TimeLimit
from experiments.coda.coda_generic import get_true_abstract_mask_spriteworld, batch_get_heuristic_mask_fetchpush
from experiments.coda.coda_module import CodaBuffer
from experiments.coda.sandy_module import CodaAttentionBasedMask, SimpleStackedAttn
config = best_slide_config()
config.alg = 'ddpg'
import multiprocessing as mp
def make_disentangled_fetch_env(envstr):
if 'push' in envstr.lower():
env = lambda: TimeLimit(DisentangledFetchPushEnv(), 50)
eval_env = env
dummy_env = gym.make('FetchPush-v1')
elif 'pick' in envstr.lower():
env = lambda: TimeLimit(DisentangledFetchPickAndPlaceEnv(), 50)
eval_env = env
dummy_env = gym.make('FetchPickAndPlace-v1')
elif 'slide' in envstr.lower():
env = lambda: TimeLimit(DisentangledFetchSlideEnv(), 50)
eval_env = lambda: TimeLimit(DisentangledFetchSlideEnv(), 50)
dummy_env = DisentangledFetchSlideEnv()
I = np.concatenate((np.zeros(10), np.ones(12))).astype(np.int64)
J = np.arange(22, dtype=np.int64)
state_dims = (I, J)
return env, eval_env, dummy_env, state_dims
def main(args):
if args.num_envs is None:
import multiprocessing as mp
args.num_envs = max(mp.cpu_count() - 1, 1)
# hard code num_eval envs...
args.num_eval_envs = args.num_envs
merge_args_into_config(args, config)
config.min_experience_to_train_coda_attn = args.min_experience_to_train_coda_attn
if config.gamma < 1.: config.clip_target_range = (np.round(-(1 / (1 - config.gamma)), 2), 0.)
if config.gamma == 1: config.clip_target_range = (np.round(-args.env_max_step - 5, 2), 0.)
config.agent_name = make_agent_name(config, [
'envstr', 'alg', 'her', 'relabel_type', 'seed', 'tb', 'max_coda_ratio', 'coda_every', 'coda_source_pairs',
'batch_size', 'optimize_every'
],
prefix=args.prefix)
# 5. Setup / add basic modules to the config
config.update(
dict(trainer=StandardTrain(),
evaluation=EpisodicEval(),
policy=ActorPolicy(),
logger=Logger(),
state_normalizer=Normalizer(MeanStdNormalizer()),
replay=OnlineHERBuffer(),
action_noise=ContinuousActionNoise(GaussianProcess, std=ConstantSchedule(args.action_noise)),
algorithm=DDPG()))
torch.set_num_threads(min(4, args.num_envs))
torch.set_num_interop_threads(min(4, args.num_envs))
if gym.envs.registry.env_specs.get(args.envstr) is not None:
args.env = args.envstr
dummy_env_config = None
reward_fn = None
elif 'disentangled' in args.envstr.lower():
args.env, args.eval_env, dummy_env, state_dims = make_disentangled_fetch_env(args.envstr)
config.slot_state_dims = [np.arange(10)] + [10 + 12 * i + np.arange(12) for i in range(1)]
config.slot_action_dims = None
dummy_env_config = None
reward_fn = lambda s, a, ns, g: dummy_env.compute_reward(ns[:, 10:13], g, None)[:, None]
elif 'slide' in args.envstr.lower():
n = int(args.envstr.lower().replace('slide', ''))
args.env = lambda: SlideNEnv(n=n, distance_threshold=args.train_dt)
args.eval_env = lambda: SlideNEnv(n=n)
dummy_env_config = None
dummy_env = SlideNEnv(n=n)
reward_fn = lambda s, a, ns, g: dummy_env.compute_reward(ns[:, dummy_env.ag_dims], g, None)[:, None]
config.slot_state_dims = dummy_env.disentangled_idxs
config.slot_action_dims = None
config.slot_goal_dims = dummy_env.disentangled_goal_idxs
if args.relabel_type == 'online_attn':
model = SimpleStackedAttn(10 + 12 * n + 4,
10 + 12 * n,
num_attn_blocks=2,
num_hidden_layers=2,
num_hidden_units=128,
num_heads=5)
config.mask_module = CodaAttentionBasedMask(model=model, optimize_every=2, batch_size=512)
elif 'push' in args.envstr.lower():
n = int(args.envstr.lower().replace('push', ''))
args.env = lambda: PushNEnv(n=n, distance_threshold=args.train_dt)
args.eval_env = lambda: PushNEnv(n=n)
dummy_env_config = None
dummy_env = PushNEnv(n=n)
reward_fn = lambda s, a, ns, g: dummy_env.compute_reward(ns[:, dummy_env.ag_dims], g, None)[:, None]
config.slot_state_dims = dummy_env.disentangled_idxs
config.slot_goal_dims = dummy_env.disentangled_goal_idxs
else:
raise NotImplementedError
if type(args.env) is str:
env = lambda: gym.make(args.env)
else:
env = args.env
config.module_train_env = EnvModule(env, num_envs=config.num_envs, seed=config.seed)
config.module_eval_env = EnvModule(env, num_envs=config.num_eval_envs, name='eval_env', seed=config.seed + 1138)
e = config.module_eval_env
if config.slot_based_state and hasattr(config, 'slot_state_dims'):
e.state_dim = len(config.slot_state_dims[0])
config.actor = PytorchModel(
'actor', lambda: Actor(FCBody(e.state_dim + e.goal_dim, args.layers, nn.LayerNorm), e.action_dim, e.max_action))
config.critic = PytorchModel(
'critic', lambda: Critic(FCBody(e.state_dim + e.goal_dim + e.action_dim, args.layers, nn.LayerNorm), 1))
if e.goal_env:
config.never_done = True # NOTE: This is important in the standard Goal environments, which are never done
# add Coda buffer if using Coda
if args.relabel_type is not None:
del config.replay
config.module_replay = CodaBuffer(max_coda_ratio=args.max_coda_ratio,
make_coda_data_every=args.coda_every,
num_coda_source_transitions=20000,
num_coda_source_pairs=args.coda_source_pairs,
coda_samples_per_pair=args.coda_samples_per_pair,
coda_buffer_size=args.coda_buffer_size,
add_bad_dcs=args.add_bad_dcs,
coda_on_goal_components=args.coda_on_goal_components,
spriteworld_config=dummy_env_config,
reward_fn=reward_fn,
num_procs=min(args.num_envs, 4))
agent = mrl.config_to_agent(config)
# set up get_coda_mask function
if args.relabel_type is not None:
if args.relabel_type == 'ground_truth':
agent.get_coda_mask = get_true_abstract_mask_spriteworld
elif args.relabel_type == 'push_heuristic':
agent.get_coda_mask = batch_get_heuristic_mask_fetchpush
elif args.relabel_type == 'online_attn':
agent.get_coda_mask = partial(agent.coda_attention_model.get_mask, THRESH=args.thresh)
else:
raise NotImplementedError()
if args.checkpoint_dir is not None:
# If a checkpoint has been initialized load it.
if os.path.exists(os.path.join(args.checkpoint_dir, 'INITIALIZED')):
agent.load_from_checkpoint(args.checkpoint_dir)
if args.visualize_trained_agent:
print("Loading agent at epoch {}".format(0))
agent.load('checkpoint')
agent.eval_mode()
env = agent.eval_env
state = env.reset()
for _ in range(1000000):
env.render()
time.sleep(0.02)
action = agent.policy(state)
state, reward, done, info = env.step(action)
env.render()
print(reward[0])
else:
if args.save_embeddings:
s1_buff = agent.replay_buffer.buffer.BUFF.buffer_state
s2_buff = agent.replay_buffer.buffer.BUFF.buffer_next_state
s1_coda = agent.replay_buffer.coda_buffer.items['state']
s2_coda = agent.replay_buffer.coda_buffer.items['next_state']
num_eps = max(args.num_eval_envs * 3, 10)
res = np.mean(agent.eval(num_episodes=num_eps).rewards)
agent.logger.log_color(f'Initial test reward ({num_eps} eps):', '{:.2f}'.format(res))
for epoch in range(int(args.max_steps // args.epoch_len)):
t = time.time()
agent.train(num_steps=args.epoch_len)
# VIZUALIZE GOALS
if args.save_embeddings:
idxs = np.random.choice(len(s1_buff), size=min(len(s1_buff), 1000), replace=False)
last_idxs = np.arange(max(0, len(s1_buff) - args.epoch_len), len(s1_buff))
rands1 = s1_buff.get_batch(idxs)
rands1 = np.concatenate((rands1[:, 0, :3], rands1[:, 1, 10:13]), 1)
agent.logger.add_embedding('rand_s1s', rands1)
rands1 = s2_buff.get_batch(idxs)
rands1 = np.concatenate((rands1[:, 0, :3], rands1[:, 1, 10:13]), 1)
agent.logger.add_embedding('rand_s2s', rands1)
rands1 = s1_coda.get_batch(idxs)
rands1 = | np.concatenate((rands1[:, 0, :3], rands1[:, 1, 10:13]), 1) | numpy.concatenate |
#!/usr/bin/env python
# coding: utf-8
"""
run consensus analysis to identify overall pattern
analysis method developed by <NAME> and <NAME>
"""
import os
import sys
import argparse
import glob
import numpy
import nibabel
import nilearn.plotting
import nilearn.input_data
import matplotlib.pyplot as plt
from statsmodels.stats.multitest import multipletests
from narps import Narps, hypnums, hypotheses
from narps import NarpsDirs # noqa, flake8 issue
from utils import log_to_file, t_corr
def run_ttests(narps, logfile,
overwrite=True):
masker = nilearn.input_data.NiftiMasker(
mask_img=narps.dirs.MNI_mask)
results_dir = narps.dirs.dirs['consensus']
func_name = sys._getframe().f_code.co_name
log_to_file(
logfile, '%s' %
func_name)
if not os.path.exists(results_dir):
os.mkdir(results_dir)
for hyp in hypnums:
if not overwrite and os.path.exists(os.path.join(
results_dir,
'hypo%d_1-fdr.nii.gz' % hyp)):
print('using existing results')
continue
print('running consensus analysis for hypothesis', hyp)
maps = glob.glob(os.path.join(
narps.dirs.dirs['output'],
'zstat/*/hypo%d_unthresh.nii.gz' % hyp))
maps.sort()
data = masker.fit_transform(maps)
# get estimated mean, variance, and correlation for t_corr
img_mean = numpy.mean(data)
img_var = numpy.mean(numpy.var(data, 1))
cc = numpy.corrcoef(data)
log_to_file(
logfile,
'mean = %f, var = %f, mean_cc = %f' %
(img_mean, img_var,
numpy.mean(cc[numpy.triu_indices_from(cc, 1)])))
# perform t-test
tvals, pvals = t_corr(data,
res_mean=img_mean,
res_var=img_var,
Q=cc)
# move back into image format
timg = masker.inverse_transform(tvals)
timg.to_filename(os.path.join(results_dir, 'hypo%d_t.nii.gz' % hyp))
pimg = masker.inverse_transform(1-pvals)
pimg.to_filename(os.path.join(results_dir, 'hypo%d_1-p.nii.gz' % hyp))
fdr_results = multipletests(pvals[0, :], 0.05, 'fdr_tsbh')
log_to_file(
logfile,
"%d voxels significant at FDR corrected p<.05" %
numpy.sum(fdr_results[0]))
fdrimg = masker.inverse_transform(1 - fdr_results[1])
fdrimg.to_filename(os.path.join(
results_dir,
'hypo%d_1-fdr.nii.gz' % hyp))
# compute tau^2 per Tom's notes in CorrelatedMetaNotes.html
def tau(data, Q):
n = data.shape[0]
R = numpy.eye(n) - numpy.ones((n, 1)).dot(numpy.ones((1, n)))/n
sampvar_est = numpy.trace(R.dot(Q))
tau2 = numpy.zeros(data.shape[1])
for i in range(data.shape[1]):
Y = data[:, i]
tau2[i] = (1/sampvar_est)*Y.T.dot(R).dot(Y)
return(numpy.sqrt(tau2))
tau_est = tau(data, cc)
tauimg = masker.inverse_transform(tau_est)
tauimg.to_filename(os.path.join(
results_dir,
'hypo%d_tau.nii.gz' % hyp))
def mk_figures(narps, logfile, thresh=0.95):
func_name = sys._getframe().f_code.co_name
log_to_file(
logfile, '%s' %
func_name)
masker = nilearn.input_data.NiftiMasker(
mask_img=narps.dirs.MNI_mask)
fig, ax = plt.subplots(7, 1, figsize=(12, 24))
cut_coords = [-24, -10, 4, 18, 32, 52, 64]
for i, hyp in enumerate(hypnums):
pmap = os.path.join(
narps.dirs.dirs['consensus'],
'hypo%d_1-fdr.nii.gz' % hyp)
tmap = os.path.join(
narps.dirs.dirs['consensus'],
'hypo%d_t.nii.gz' % hyp)
pimg = nibabel.load(pmap)
timg = nibabel.load(tmap)
pdata = pimg.get_fdata()
tdata = timg.get_fdata()[:, :, :, 0]
threshdata = (pdata > thresh)*tdata
threshimg = nibabel.Nifti1Image(threshdata, affine=timg.affine)
nilearn.plotting.plot_stat_map(
threshimg,
threshold=0.1,
display_mode="z",
colorbar=True,
title='hyp %d:' % hyp+hypotheses[hyp],
vmax=8,
cmap='jet',
cut_coords=cut_coords,
axes=ax[i])
plt.savefig(os.path.join(
narps.dirs.dirs['figures'],
'consensus_map.pdf'), bbox_inches='tight')
plt.close(fig)
# create tau figures
fig, ax = plt.subplots(7, 1, figsize=(12, 24))
tauhist = {}
for i, hyp in enumerate(hypnums):
taumap = os.path.join(
narps.dirs.dirs['consensus'],
'hypo%d_tau.nii.gz' % hyp)
tauimg = nibabel.load(taumap)
taudata = masker.fit_transform(tauimg)
log_to_file(
logfile, 'hyp %d: median tau %0.3f, max tau %0.3f' %
(hyp, numpy.median(taudata), numpy.max(taudata)))
tauhist[i] = numpy.histogram(
taudata, bins= | numpy.arange(0, 5, 0.01) | numpy.arange |
#!/usr/bin/env python3
"""Plots data associated with Elastica simulations
Used to reproduce various figures and renderings (in-part)
from the paper:
Modeling and simulation of complex dynamic musculoskeletal architectures
Nature Communications, 2019
"""
__license__ = "MIT License, see LICENSE for details"
__copyright__ = "Copyright (C) 2019 MattiaLab"
# System imports
import argparse
import os
import sys
from itertools import tee
import matplotlib.style as mplstyle #
import numpy as np #
from matplotlib import pyplot as plt #
from matplotlib.colors import to_rgb
from matplotlib.patches import FancyArrowPatch
from mpl_toolkits.mplot3d import proj3d
from mpl_toolkits.mplot3d.art3d import Line3DCollection #
from scipy.linalg import norm #
# set the backend first
# import matplotlib # isort:skip
# matplotlib.use("TkAgg") # isort:skip
# from matplotlib.collections import LineCollection #
# Turned off because slow
# plt.rcParams['text.usetex'] = 'True'
# plt.rcParams['font.serif'] = 'Fira Sans'
plt.rcParams["font.size"] = 14
plt.rcParams["axes.labelsize"] = 14
plt.rcParams["axes.labelweight"] = "bold"
plt.rcParams["axes.titlesize"] = 16
plt.rcParams["xtick.labelsize"] = 12
plt.rcParams["ytick.labelsize"] = 12
mplstyle.use("seaborn-whitegrid")
# plt.rc('grid', color='#397939', linewidth=1, linestyle='--')
def pairwise(iterable):
"s -> (s0,s1), (s1,s2), (s2, s3), ..."
first, second = tee(iterable)
next(second, None)
return zip(first, second)
def set_axes_equal(axis, data=None):
"""Make axes of 3D plot have equal scale so that spheres appear as spheres,
cubes as cubes, etc.. This is one possible solution to Matplotlib's
ax.set_aspect('equal') and ax.axis('equal') not working for 3D.
Input
ax: a matplotlib axis, e.g., as output from plt.gca().
Credits: https://stackoverflow.com/a/50664367
"""
if data is None:
limits = np.array([axis.get_xlim3d(), axis.get_ylim3d(), axis.get_zlim3d()])
else:
limits = np.array(
[
[data[0, :].min(), data[0, :].max()],
[data[1, :].min(), data[1, :].max()],
[data[2, :].min(), data[2, :].max()],
]
)
origin = np.mean(limits, axis=1)
radius = 0.5 * np.max(np.abs(limits[:, 1] - limits[:, 0]))
axis.set_xlim3d([origin[0] - radius, origin[0] + radius])
axis.set_ylim3d([origin[1] - radius, origin[1] + radius])
axis.set_zlim3d([origin[2] - radius, origin[2] + radius])
def detect_files(input_folder, prefix, suffix):
""" Detect all files in the input folder
"""
if not os.path.isdir(input_folder):
raise FileNotFoundError("{} is not a valid folder".format(input_folder))
# Finds all files input_folder/prefix*.suffix
import re
# matches prefix__ (bignumber).suffix
exp = r"{prefix}[\s_]*(\d*){meta}{suffix}".format(
prefix=prefix, meta="\\", suffix=suffix
)
compiled_regexp = re.compile(exp)
matched_files = [f for f in os.listdir(input_folder) if compiled_regexp.search(f)]
matched_files.sort()
# Extract the filenumber as an integer
try:
file_tags = [int(compiled_regexp.match(f).group(1)) for f in matched_files]
except ValueError:
file_tags = []
# Put the full address
matched_files = [os.path.join(input_folder, f) for f in matched_files]
# returns matched files and matched file numbers as strings
return matched_files, file_tags
class Arrow3D(FancyArrowPatch):
"""3D Arrow plot for drawing vector, from https://stackoverflow.com/a/22867877"""
def __init__(self, xs, ys, zs, *args, **kwargs):
FancyArrowPatch.__init__(self, (0, 0), (0, 0), *args, **kwargs)
self._verts3d = xs, ys, zs
def draw(self, renderer):
xs3d, ys3d, zs3d = self._verts3d
xs, ys, zs = proj3d.proj_transform(xs3d, ys3d, zs3d, renderer.M)
self.set_positions((xs[0], ys[0]), (xs[1], ys[1]))
FancyArrowPatch.draw(self, renderer)
class CustomFormatter(
argparse.RawDescriptionHelpFormatter, argparse.ArgumentDefaultsHelpFormatter
):
pass
class FigProperties: # pylint: disable=R0903
width = 900
height = 600
dpi = 100
@staticmethod
def figsize():
return (
FigProperties.width / float(FigProperties.dpi),
FigProperties.height / float(FigProperties.dpi),
)
class DummyPlotter:
""" Placeholder when we need to skip plotting
"""
# pylint: disable=R0913
def __init__(
self, input_folder, output_folder, save_file, force_flag, display_flag
):
pass
def process(self):
pass
def plot(self, axis, data, color=(31 / 255, 119 / 255, 180 / 255)):
pass
def animate(self):
pass
class ThreeDimensionalPlotter:
""" Base class for all three-dimensional plotting
"""
def __init__(
self, input_folder, output_folder, save_file, force_flag, display_flag
):
""" Figure attributes """
self.fig = plt.figure(figsize=FigProperties.figsize())
self.ax = self.fig.add_subplot(111, projection="3d")
self.ax.w_xaxis.set_pane_color((1.0, 1.0, 1.0, 1.0))
self.ax.w_yaxis.set_pane_color((1.0, 1.0, 1.0, 1.0))
self.ax.w_zaxis.set_pane_color((1.0, 1.0, 1.0, 1.0))
self.ax.grid(True)
self.ax.set_xlabel("X")
self.ax.set_ylabel("Y")
self.ax.set_zlabel("Z")
""" Save file attributes """
self.output_folder = output_folder
self.savefile_name, self.savefile_ext = os.path.splitext(save_file)
self.display_flag = display_flag
# Assume its a png if no extension given by default
if not self.savefile_ext:
self.savefile_ext = ".png"
""" Source file attributes and search """
# Guaranteed to be sorted
ntypes_files = len(self.file_metadata)
# Get a collection (list of lists) to store all the source files
src_file_collection = [[] for i in range(ntypes_files)]
src_filetag_collection = [[] for i in range(ntypes_files)]
for index, (prefix, suffix, _) in enumerate(self.file_metadata):
src_file_collection[index], src_filetag_collection[index] = detect_files(
input_folder, prefix, suffix
)
for i, j in pairwise(range(ntypes_files)):
# These lists are ordered and the default comparison should be fine
assert (
src_filetag_collection[i] == src_filetag_collection[j]
), "Numbers don't match up"
# All collectinos are the same, pop only the last one
src_filetags = src_filetag_collection.pop()
tgt_files, tgt_filetags = detect_files(
self.output_folder, self.savefile_name, self.savefile_ext
)
# print(input_folder, src_files, src_filetags)
# print(output_folder, tgt_files, tgt_filetags)
# If uses forces to clear all images, process all files
if force_flag:
self.files_to_be_processed = src_file_collection
self.filetags_to_be_processed = src_filetags
# Else, rewrite files that only need to be updated
else:
if len(tgt_filetags) > len(src_filetags):
# if more targets already, then there's something fishy
# act as if the force_flag is set
self.files_to_be_processed = src_file_collection
self.filetags_to_be_processed = src_filetags
else:
# Calculate difference between the filetags in src and tgt
# if tgt is not empty
# # Get indices of sort list, see https://stackoverflow.com/a/6423325
# sort_src_indices = sorted(range(len(src_filetags))
# ,key=src_filetags.__getitem__)
# sort_srctags = [src_filetags[i] for i in sort_src_indices]
# sort_tgttags = sorted(tgt_filetags)
def index(a, x):
"""Locate the leftmost value exactly equal to x in a sorted list
See https://docs.python.org/3.7/library/bisect.html
"""
import bisect
i = bisect.bisect_left(a, x)
if i != len(a) and a[i] == x:
return i
return -1
# If tgttags is empty, default to -1
# else what is the next element beyond the last target tag?
src_index = (
-1 if not tgt_filetags else index(src_filetags, tgt_filetags[-1])
)
# print(src_index)
self.files_to_be_processed = [
sublist[src_index + 1 :] for sublist in src_file_collection
]
self.filetags_to_be_processed = src_filetags[src_index + 1 :]
# print(self.files_to_be_processed, self.filetags_to_be_processed)
def process(self):
""" Loads all data, plots them and stores them into appropriately
named figures.
"""
# Load color metadata first as list of rgb tuples
colors = [color for (_, _, color) in self.file_metadata]
if self.display_flag:
# Turn on interactive mode to persist figure
plt.ion()
# Show figure after persist
plt.show()
# From list of list (f) and list (g), get [f[i][0],f[i][1]] and g[i]
for *src_file_names, src_file_tag in zip(
*(self.files_to_be_processed), self.filetags_to_be_processed
):
for i_seq, (src_file, color) in enumerate(zip(src_file_names, colors)):
# Defaults loads to (ndata, 4) rather than (4,ndata)
data = np.loadtxt(src_file).T
self.plot(self.ax, data, color, i_seq)
# self.ax.set_title("test at {}".format(src_file_tag))
self.fig.canvas.draw()
if self.display_flag:
plt.pause(0.001)
# last column is source files
# src_file_tag = src_file_info[-1]
filename = "{name}_{tag:05d}{ext}".format(
name=self.savefile_name, tag=src_file_tag, ext=self.savefile_ext
)
# tight bounding box here screws up the video
self.fig.savefig(
os.path.join(self.output_folder, filename), dpi=FigProperties.dpi
)
# # Show only the last drawn figure to the user
# plt.show()
def plot(self, ax, data, color=(31 / 255, 119 / 255, 180 / 255), i_seq=None):
""" Plots 3D data
"""
# https://stackoverflow.com/a/34486703
# Plot centerline
if len(ax.lines) > i_seq:
ax.lines[i_seq]._verts3d = data[:3, :] # 0,1,2
else:
ax.plot(
data[0, :],
data[1, :],
data[2, :],
color=color,
marker="o",
markersize=data[3, 0] * 0.2, # set marker based on radius
linewidth=2.0,
)
pts_data, wire_data = calculate_cylinders(data)
# Now plot wireframes
# Each one adds two, so sequencing should reflect that
if len(ax.collections) > 2 * i_seq:
# First do pts_data
ax.collections[2 * i_seq]._segments3d = convert_to_collection(pts_data)
# Then do wire_data
ax.collections[2 * i_seq + 1]._segments3d = convert_to_collection(wire_data)
else:
# first instance
# transparency
metadata = {"colors": color + (0.5,), "linewidth": 1.0}
# ax.add_collection3d(convert_to_collection(pts_data, **metadata))
ax.add_collection3d(
Line3DCollection(convert_to_collection(pts_data), **metadata)
)
# transparency
metadata = {"colors": color + (0.3,), "linewidth": 0.5}
ax.add_collection3d(
Line3DCollection(convert_to_collection(wire_data), **metadata)
)
# def plot(self, ax, data, color=(31 / 255, 119 / 255, 180 / 255), i_seq=None):
# """ Plots 3D data
# """
# # https://stackoverflow.com/a/34486703
# # Plot centerline
# if ax.lines:
# for line in ax.lines:
# line._verts3d = data[:-1, :]
# else:
# ax.plot(
# data[0, :],
# data[1, :],
# data[2, :],
# color=color,
# marker="o",
# linewidth=3.0,
# )
# pts_data, wire_data = calculate_cylinders(data)
# # Now plot wireframes
# if ax.collections:
# # First do pts_data
# ax.collections[0]._segments3d = convert_to_collection(pts_data)
# # Then do wire_data
# ax.collections[1]._segments3d = convert_to_collection(wire_data)
# else:
# # first instance
# # transparency
# metadata = {"colors": color + (1.0,), "linewidth": 2.0}
# # ax.add_collection3d(convert_to_collection(pts_data, **metadata))
# ax.add_collection3d(
# Line3DCollection(convert_to_collection(pts_data), **metadata)
# )
# # # Add data to scatter
# # ax.scatter(data[:, 0],
# # data[:, 1],
# # data[:, 2],
# # color=colors[0],
# # marker="o")
# # transparency
# metadata = {"colors": color + (0.5,), "linewidth": 1.5}
# ax.add_collection3d(
# Line3DCollection(convert_to_collection(wire_data), **metadata)
# )
def animate(self):
""" Animates using ffmpeg the figures created by savefig
"""
import subprocess
# Test if ffmpeg present, else stop processing
ret_code = subprocess.call(["which", "ffmpeg"])
if ret_code != 0:
raise OSError("ffmpeg not found. Aborting now.")
else:
filenames = "{frame}_%05d{ext}".format(
frame=os.path.join(self.output_folder, self.savefile_name),
ext=self.savefile_ext,
)
# ffmpeg has its own glob matching facility
subprocess.call(
[
"ffmpeg",
"-y", # overwrites files
"-i",
filenames,
"-framerate",
"30",
"-crf",
"24",
"-pix_fmt",
"yuv420p",
"output_video.mp4",
]
)
def convert_to_collection(in_data, **kwargs):
""" Converts a (3,*) np array into a MPL LineCollection
"""
ndims = in_data.shape[0]
if ndims == 3:
points = np.array([in_data[0], in_data[1], in_data[2]]).T.reshape(-1, 1, 3)
segs = np.concatenate([points[:-1], points[1:]], axis=1)
# return Line3DCollection(segs, **kwargs)
elif ndims == 2:
points = np.array([in_data[0], in_data[1]]).T.reshape(-1, 1, 2)
segs = np.concatenate([points[:-1], points[1:]], axis=1)
# return LineCollection(segs, **kwargs)
else:
raise IndexError("Dimensions incorrect!")
return segs
def calculate_cylinders(in_data):
""" Calculates the cylinder coordinates given the centerline
in_data : (n_dim + 1, N) in size, last dimension for radius
"""
# print(in_data.shape)
# Split dimensions and radius
data = in_data[:-2, :]
# Last one is time now discounted
radius_data = in_data[-2, :-1]
n_dim = data.shape[0]
# Governing parameters
n_pts = data.shape[1]
n_axial = 2
n_theta = 20
n_wireframe_skip = 5
n_wireframe_skip = n_wireframe_skip if n_wireframe_skip < n_theta else 1
""" 1. Calculate tangent """
tan = np.diff(data)
# normalize
mag_tan = norm(tan, ord=2, axis=0)
tan /= mag_tan
""" 2. Calculate normal and binormal """
# Guess for binormal, fair enough to assume in z
binormal = np.array([0.0, 0.5, 0.5])
binormal /= norm(binormal)
# prepare to broadcast it to 2D
binormal = binormal[:, np.newaxis]
# make vector perpendicular to v
normal = np.cross(tan, np.tile(binormal, (1, n_pts - 1)), axisa=0, axisb=0, axisc=0)
# normalize
mag_n = norm(normal, ord=2, axis=0)
normal /= mag_n
# make unit vector perpendicular to v and n1
binormal = np.cross(tan, normal, axisa=0, axisb=0, axisc=0)
# Stack normal and binormal together for (2,ndim,N-1)
directors = np.vstack((binormal[np.newaxis, :, :], normal[np.newaxis, :, :]))
""" 3. Parametrize angles and centerline """
# surface ranges over t from 0 to length of axis
caxis = np.linspace(0.0, 1.0, n_axial)
# polar angle varies from 0 to 2*pi
theta = np.linspace(0, 2 * np.pi, n_theta)
""" 4. Direct them"""
# Idea here is to direct the centerline in the tangent direction
# and direct the cross section in the norm-binorm direction
# and then take a linear combination of both at every cross section
# scale t up according to mag_tan, to give (n_axial, N-1) array
# t = t.reshape(n_axial, 1) * mag_tan.reshape(1, -1)
caxis = | np.einsum("i,j->ij", caxis, mag_tan) | numpy.einsum |
import numpy as np
def fnmtf(X, k, l, num_iter=100, norm=False, orthogonal_strategy=False):
m, n = X.shape
U = np.random.rand(m, k)
S = np.random.rand(k, l)
V = np.random.rand(n, l)
error_best = np.inf
error = error_best
if norm:
X = Normalizer().fit_transform(X)
for _ in xrange(num_iter):
S = np.linalg.pinv(U.T.dot(U)).dot(U.T).dot(X).dot(V).dot(np.linalg.pinv(V.T.dot(V)))
# solve subproblem to update V
U_tilde = U.dot(S)
V_new = np.zeros(n*l).reshape(n, l)
for j in xrange(n):
errors = np.zeros(l)
for col_clust_ind in xrange(l):
errors[col_clust_ind] = ((X[:][:, j] - U_tilde[:][:, col_clust_ind])**2).sum()
ind = np.argmin(errors)
V_new[j][ind] = 1
V = V_new
if orthogonal_strategy:
while np.linalg.det(V.T.dot(V)) <= 0:
if np.isnan(np.sum(V)):
break
erros = (X - U.dot(S).dot(V.T)) ** 2
erros = np.sum(erros.dot(V), axis=0) / np.sum(V, axis=0)
erros[np.where(np.sum(V, axis=0) <= 1)] = -np.inf
quantidade = np.sum(V, axis=0)
indexMin = np.argmin(quantidade)
indexMax = np.argmax(erros)
indexes = np.nonzero(V[:, indexMax])[0]
end = len(indexes)
indexes_p = np.random.permutation(end)
V[indexes[indexes_p[0:np.floor(end/2.0)]], indexMax] = 0.0
V[indexes[indexes_p[0:np.floor(end/2.0)]], indexMin] = 1.0
# solve subproblem to update U
V_tilde = S.dot(V.T)
U_new = np.zeros(m*k).reshape(m, k)
for i in xrange(m):
errors = np.zeros(k)
for row_clust_ind in xrange(k):
errors[row_clust_ind] = ((X[i][:] - V_tilde[row_clust_ind][:])**2).sum()
ind = np.argmin(errors)
U_new[i][ind] = 1
U = U_new
if orthogonal_strategy:
while np.linalg.det(U.T.dot(U)) <= 0:
if np.isnan( np.sum(U) ):
break
erros = (X - U.dot(V_tilde)) ** 2
erros = np.sum(U.T.dot(erros), axis=1) / np.sum(U, axis=0)
erros[np.where(np.sum(U, axis=0) <= 1)] = -np.inf
quantidade = | np.sum(U, axis=0) | numpy.sum |
import tensorflow as tf
import numpy as np
import cv2
import argparse
from sklearn.utils import shuffle
snr = 10
def generate_sigma(target):
return 10 ** (-snr / 20.0) * np.sqrt(np.mean(np.sum(np.square(np.reshape(target, (np.shape(target)[0], -1))), -1)))
def denoise(target):
noise_sigma = generate_sigma(target)
noise = np.random.normal(loc=0, scale=noise_sigma, size=np.shape(target))/np.sqrt(np.prod(np.shape(target)[1:]))
noisy = target + noise
return noisy
def data_normalization(x):
x = x.astype('float32')
x = x - (x.max() + x.min())/2
x /= (x.max())
return x
def Dataset_preprocessing(dataset = 'MNIST', batch_size = 64):
if dataset == 'mnist':
nch = 1
r = 32
(train_images, _), (test_images, _) = tf.keras.datasets.mnist.load_data()
elif dataset == 'noisy_mnist':
(train_images, _), (test_images, _) = tf.keras.datasets.mnist.load_data()
r = 32
nch = 1
elif dataset == 'fmnist':
(train_images, _), (test_images, _) = tf.keras.datasets.fashion_mnist.load_data()
r = 32
nch = 1
elif dataset == 'cifar10':
(train_images, _), (test_images, _) = tf.keras.datasets.cifar10.load_data()
r = 32
nch = 3
elif dataset == 'svhn':
train_images, test_images = svhn()
nch = 3
r = 32
elif dataset == 'celeba':
celeba = np.load('/kaggle/working/celeb.npy')
celeba = shuffle(celeba)
train_images, test_images = np.split(celeba, [80000], axis=0)
nch = 3
r = 32
elif dataset == 'imagenet':
imagenet = np.load('/raid/Amir/Projects/datasets/Tiny_imagenet.npy')
imagenet = shuffle(imagenet)
train_images, test_images = np.split(imagenet, [80000], axis=0)
nch = 3
r = 64
elif dataset == 'rheo':
rheo = np.load('/raid/Amir/Projects/datasets/rheology.npy')
rheo = shuffle(rheo)
train_images, test_images = np.split(rheo, [1500], axis=0)
nch = 3
r = 64
elif dataset == 'chest':
chest = np.load('/raid/Amir/Projects/datasets/X_ray_dataset_128.npy')[:100000,:,:,0:1]
chest = shuffle(chest)
print(np.shape(chest))
train_images, test_images = | np.split(chest, [80000], axis=0) | numpy.split |
# -*- coding: utf-8 -*-
"""
Created on Fri Apr 12 16:25:57 2019
@author: <NAME>
"""
import numpy as np
import nibabel as nib
import os
import time
from eslearn.model_evaluator import ModelEvaluator
from eslearn.utils.lc_niiProcessor import NiiProcessor
from eslearn.base import BaseMachineLearning
from eslearn.machine_learning.classfication._base_classificaition import BaseClassification, PipelineSearch_
class ClassificationXiaowei(BaseMachineLearning, PipelineSearch_):
"""
Training model on given training data.
Then apply this mode to another testing data.
Last, evaluate the performance
If you encounter any problem, please contact <EMAIL>
"""
def __init__(self,
# =====================================================================
patients_path=r'D:\workstation_b\xiaowei\TOLC_20200811\training\BD_label1', # 训练组病人
hc_path=r'D:\workstation_b\xiaowei\TOLC_20200811\training\MDD_label0', # 训练组正常人
val_path=r'D:\workstation_b\xiaowei\TOLC_20200811\mix6', # 验证集数据
val_label=r'D:\workstation_b\xiaowei\TOLC_20200811\mix6_label.txt', # 验证数据的label文件
suffix='.nii',
mask=r'D:\workstation_b\xiaowei\TOLC3\dFC\TRA\MDD\StdzFC_ROI1_01367_resting7000.nii',
k=3,
save_directory = r'D:\workstation_b\xiaowei\TOLC_20200811'
# =====================================================================
):
super(BaseMachineLearning, self).__init__()
super(PipelineSearch_, self).__init__()
self.search_strategy = 'grid'
self.n_jobs = 2
self.k=k
self.verbose=False
self.patients_path=patients_path
self.hc_path=hc_path
self.val_path=val_path
self.val_label=val_label
self.suffix=suffix
self.mask=mask
self.save_directory = save_directory
print("SvcForGivenTrAndTe initiated")
def _load_data_infolder(self):
"""load training data and validation data and generate label for training data"""
print("loading...")
# train data
data1, _ = NiiProcessor().read_multi_nii(self.patients_path, self.suffix)
data1 = np.squeeze(np.array([np.array(data1).reshape(1,-1) for data1 in data1]))
data2,_ = NiiProcessor().read_multi_nii(self.hc_path, self.suffix)
data2 = np.squeeze(np.array([np.array(data2).reshape(1,-1) for data2 in data2]))
data = np.vstack([data1,data2])
# validation data
data_validation, self.name_val = NiiProcessor().read_multi_nii(self.val_path, self.suffix)
data_validation = np.squeeze(np.array([np.array(data_validation).reshape(1,-1) for data_validation in data_validation]))
# data in mask
mask, self.mask_obj = NiiProcessor().read_sigle_nii(self.mask)
self.mask_orig = mask>=0.1
self.mask_1d = | np.array(self.mask_orig) | numpy.array |
# Copyright (c) 2003-2019 by <NAME>
#
# TreeCorr is free software: redistribution and use in source and binary forms,
# with or without modification, are permitted provided that the following
# conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions, and the disclaimer given in the accompanying LICENSE
# file.
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions, and the disclaimer given in the documentation
# and/or other materials provided with the distribution.
from __future__ import print_function
import numpy as np
import treecorr
import os
import coord
import fitsio
from test_helper import get_script_name, do_pickle, assert_raises, CaptureLog, timer
from test_helper import is_ccw, is_ccw_3d
@timer
def test_log_binning():
import math
# Test some basic properties of the base class
def check_arrays(nnn):
np.testing.assert_almost_equal(nnn.bin_size * nnn.nbins, math.log(nnn.max_sep/nnn.min_sep))
np.testing.assert_almost_equal(nnn.ubin_size * nnn.nubins, nnn.max_u-nnn.min_u)
np.testing.assert_almost_equal(nnn.vbin_size * nnn.nvbins, nnn.max_v-nnn.min_v)
#print('logr = ',nnn.logr1d)
np.testing.assert_equal(nnn.logr1d.shape, (nnn.nbins,) )
np.testing.assert_almost_equal(nnn.logr1d[0], math.log(nnn.min_sep) + 0.5*nnn.bin_size)
np.testing.assert_almost_equal(nnn.logr1d[-1], math.log(nnn.max_sep) - 0.5*nnn.bin_size)
np.testing.assert_equal(nnn.logr.shape, (nnn.nbins, nnn.nubins, 2*nnn.nvbins) )
np.testing.assert_almost_equal(nnn.logr[:,0,0], nnn.logr1d)
np.testing.assert_almost_equal(nnn.logr[:,-1,-1], nnn.logr1d)
assert len(nnn.logr) == nnn.nbins
#print('u = ',nnn.u1d)
np.testing.assert_equal(nnn.u1d.shape, (nnn.nubins,) )
np.testing.assert_almost_equal(nnn.u1d[0], nnn.min_u + 0.5*nnn.ubin_size)
np.testing.assert_almost_equal(nnn.u1d[-1], nnn.max_u - 0.5*nnn.ubin_size)
np.testing.assert_equal(nnn.u.shape, (nnn.nbins, nnn.nubins, 2*nnn.nvbins) )
np.testing.assert_almost_equal(nnn.u[0,:,0], nnn.u1d)
np.testing.assert_almost_equal(nnn.u[-1,:,-1], nnn.u1d)
#print('v = ',nnn.v1d)
np.testing.assert_equal(nnn.v1d.shape, (2*nnn.nvbins,) )
np.testing.assert_almost_equal(nnn.v1d[0], -nnn.max_v + 0.5*nnn.vbin_size)
np.testing.assert_almost_equal(nnn.v1d[-1], nnn.max_v - 0.5*nnn.vbin_size)
np.testing.assert_almost_equal(nnn.v1d[nnn.nvbins], nnn.min_v + 0.5*nnn.vbin_size)
np.testing.assert_almost_equal(nnn.v1d[nnn.nvbins-1], -nnn.min_v - 0.5*nnn.vbin_size)
np.testing.assert_equal(nnn.v.shape, (nnn.nbins, nnn.nubins, 2*nnn.nvbins) )
np.testing.assert_almost_equal(nnn.v[0,0,:], nnn.v1d)
np.testing.assert_almost_equal(nnn.v[-1,-1,:], nnn.v1d)
def check_defaultuv(nnn):
assert nnn.min_u == 0.
assert nnn.max_u == 1.
assert nnn.nubins == np.ceil(1./nnn.ubin_size)
assert nnn.min_v == 0.
assert nnn.max_v == 1.
assert nnn.nvbins == np.ceil(1./nnn.vbin_size)
# Check the different ways to set up the binning:
# Omit bin_size
nnn = treecorr.NNNCorrelation(min_sep=5, max_sep=20, nbins=20, bin_type='LogRUV')
#print(nnn.min_sep,nnn.max_sep,nnn.bin_size,nnn.nbins)
#print(nnn.min_u,nnn.max_u,nnn.ubin_size,nnn.nubins)
#print(nnn.min_v,nnn.max_v,nnn.vbin_size,nnn.nvbins)
assert nnn.min_sep == 5.
assert nnn.max_sep == 20.
assert nnn.nbins == 20
check_defaultuv(nnn)
check_arrays(nnn)
# Specify min, max, n for u,v too.
nnn = treecorr.NNNCorrelation(min_sep=5, max_sep=20, nbins=20,
min_u=0.2, max_u=0.9, nubins=12,
min_v=0., max_v=0.2, nvbins=2)
#print(nnn.min_sep,nnn.max_sep,nnn.bin_size,nnn.nbins)
#print(nnn.min_u,nnn.max_u,nnn.ubin_size,nnn.nubins)
#print(nnn.min_v,nnn.max_v,nnn.vbin_size,nnn.nvbins)
assert nnn.min_sep == 5.
assert nnn.max_sep == 20.
assert nnn.nbins == 20
assert nnn.min_u == 0.2
assert nnn.max_u == 0.9
assert nnn.nubins == 12
assert nnn.min_v == 0.
assert nnn.max_v == 0.2
assert nnn.nvbins == 2
check_arrays(nnn)
# Omit min_sep
nnn = treecorr.NNNCorrelation(max_sep=20, nbins=20, bin_size=0.1)
#print(nnn.min_sep,nnn.max_sep,nnn.bin_size,nnn.nbins)
#print(nnn.min_u,nnn.max_u,nnn.ubin_size,nnn.nubins)
#print(nnn.min_v,nnn.max_v,nnn.vbin_size,nnn.nvbins)
assert nnn.bin_size == 0.1
assert nnn.max_sep == 20.
assert nnn.nbins == 20
check_defaultuv(nnn)
check_arrays(nnn)
# Specify max, n, bs for u,v too.
nnn = treecorr.NNNCorrelation(max_sep=20, nbins=20, bin_size=0.1,
max_u=0.9, nubins=3, ubin_size=0.05,
max_v=0.4, nvbins=4, vbin_size=0.05)
#print(nnn.min_sep,nnn.max_sep,nnn.bin_size,nnn.nbins)
#print(nnn.min_u,nnn.max_u,nnn.ubin_size,nnn.nubins)
#print(nnn.min_v,nnn.max_v,nnn.vbin_size,nnn.nvbins)
assert nnn.bin_size == 0.1
assert nnn.max_sep == 20.
assert nnn.nbins == 20
assert np.isclose(nnn.ubin_size, 0.05)
assert np.isclose(nnn.min_u, 0.75)
assert nnn.max_u == 0.9
assert nnn.nubins == 3
assert np.isclose(nnn.vbin_size, 0.05)
assert np.isclose(nnn.min_v, 0.2)
assert nnn.max_v == 0.4
assert nnn.nvbins == 4
check_arrays(nnn)
# Omit max_sep
nnn = treecorr.NNNCorrelation(min_sep=5, nbins=20, bin_size=0.1)
#print(nnn.min_sep,nnn.max_sep,nnn.bin_size,nnn.nbins)
#print(nnn.min_u,nnn.max_u,nnn.ubin_size,nnn.nubins)
#print(nnn.min_v,nnn.max_v,nnn.vbin_size,nnn.nvbins)
assert nnn.bin_size == 0.1
assert nnn.min_sep == 5.
assert nnn.nbins == 20
check_defaultuv(nnn)
check_arrays(nnn)
# Specify min, n, bs for u,v too.
nnn = treecorr.NNNCorrelation(min_sep=5, nbins=20, bin_size=0.1,
min_u=0.7, nubins=4, ubin_size=0.05,
min_v=0.2, nvbins=4, vbin_size=0.05)
#print(nnn.min_sep,nnn.max_sep,nnn.bin_size,nnn.nbins)
#print(nnn.min_u,nnn.max_u,nnn.ubin_size,nnn.nubins)
#print(nnn.min_v,nnn.max_v,nnn.vbin_size,nnn.nvbins)
assert nnn.min_sep == 5.
assert nnn.bin_size == 0.1
assert nnn.nbins == 20
assert nnn.min_u == 0.7
assert np.isclose(nnn.ubin_size, 0.05)
assert nnn.nubins == 4
assert nnn.min_v == 0.2
assert nnn.max_v == 0.4
assert np.isclose(nnn.vbin_size, 0.05)
assert nnn.nvbins == 4
check_arrays(nnn)
# Omit nbins
nnn = treecorr.NNNCorrelation(min_sep=5, max_sep=20, bin_size=0.1)
#print(nnn.min_sep,nnn.max_sep,nnn.bin_size,nnn.nbins)
#print(nnn.min_u,nnn.max_u,nnn.ubin_size,nnn.nubins)
#print(nnn.min_v,nnn.max_v,nnn.vbin_size,nnn.nvbins)
assert nnn.bin_size <= 0.1
assert nnn.min_sep == 5.
assert nnn.max_sep == 20.
check_defaultuv(nnn)
check_arrays(nnn)
# Specify min, max, bs for u,v too.
nnn = treecorr.NNNCorrelation(min_sep=5, max_sep=20, bin_size=0.1,
min_u=0.2, max_u=0.9, ubin_size=0.03,
min_v=0.1, max_v=0.3, vbin_size=0.07)
#print(nnn.min_sep,nnn.max_sep,nnn.bin_size,nnn.nbins)
#print(nnn.min_u,nnn.max_u,nnn.ubin_size,nnn.nubins)
#print(nnn.min_v,nnn.max_v,nnn.vbin_size,nnn.nvbins)
assert nnn.min_sep == 5.
assert nnn.max_sep == 20.
assert nnn.bin_size <= 0.1
assert nnn.min_u == 0.2
assert nnn.max_u == 0.9
assert nnn.nubins == 24
assert np.isclose(nnn.ubin_size, 0.7/24)
assert nnn.min_v == 0.1
assert nnn.max_v == 0.3
assert nnn.nvbins == 3
assert np.isclose(nnn.vbin_size, 0.2/3)
check_arrays(nnn)
# If only one of min/max v are set, respect that
nnn = treecorr.NNNCorrelation(min_sep=5, max_sep=20, bin_size=0.1,
min_u=0.2, ubin_size=0.03,
min_v=0.2, vbin_size=0.07)
#print(nnn.min_sep,nnn.max_sep,nnn.bin_size,nnn.nbins)
#print(nnn.min_u,nnn.max_u,nnn.ubin_size,nnn.nubins)
#print(nnn.min_v,nnn.max_v,nnn.vbin_size,nnn.nvbins)
assert nnn.min_u == 0.2
assert nnn.max_u == 1.
assert nnn.nubins == 27
assert np.isclose(nnn.ubin_size, 0.8/27)
assert nnn.min_v == 0.2
assert nnn.max_v == 1.
assert nnn.nvbins == 12
assert np.isclose(nnn.vbin_size, 0.8/12)
check_arrays(nnn)
nnn = treecorr.NNNCorrelation(min_sep=5, max_sep=20, bin_size=0.1,
max_u=0.2, ubin_size=0.03,
max_v=0.2, vbin_size=0.07)
#print(nnn.min_sep,nnn.max_sep,nnn.bin_size,nnn.nbins)
#print(nnn.min_u,nnn.max_u,nnn.ubin_size,nnn.nubins)
#print(nnn.min_v,nnn.max_v,nnn.vbin_size,nnn.nvbins)
assert nnn.min_u == 0.
assert nnn.max_u == 0.2
assert nnn.nubins == 7
assert np.isclose(nnn.ubin_size, 0.2/7)
assert nnn.min_v == 0.
assert nnn.max_v == 0.2
assert nnn.nvbins == 3
assert np.isclose(nnn.vbin_size, 0.2/3)
check_arrays(nnn)
# If only vbin_size is set for v, automatically figure out others.
# (And if necessary adjust the bin_size down a bit.)
nnn = treecorr.NNNCorrelation(min_sep=5, max_sep=20, bin_size=0.1,
ubin_size=0.3, vbin_size=0.3)
#print(nnn.min_sep,nnn.max_sep,nnn.bin_size,nnn.nbins)
#print(nnn.min_u,nnn.max_u,nnn.ubin_size,nnn.nubins)
#print(nnn.min_v,nnn.max_v,nnn.vbin_size,nnn.nvbins)
assert nnn.bin_size <= 0.1
assert nnn.min_sep == 5.
assert nnn.max_sep == 20.
assert nnn.min_u == 0.
assert nnn.max_u == 1.
assert nnn.nubins == 4
assert | np.isclose(nnn.ubin_size, 0.25) | numpy.isclose |
'''
Generate uv position map of 300W_LP.
'''
import os, sys
import numpy as np
import scipy.io as sio
import random as ran
from skimage.transform import SimilarityTransform
from skimage import io, util
import skimage.transform
from time import time
import cv2
import matplotlib.pyplot as plt
sys.path.append('..')
import face3d
from face3d import mesh
from face3d.morphable_model import MorphabelModel
def process_uv(uv_coords, uv_h = 256, uv_w = 256):
uv_coords[:,0] = uv_coords[:,0]*(uv_w - 1)
uv_coords[:,1] = uv_coords[:,1]*(uv_h - 1)
uv_coords[:,1] = uv_h - uv_coords[:,1] - 1
uv_coords = np.hstack((uv_coords, np.zeros((uv_coords.shape[0], 1)))) # add z
return uv_coords
def run_posmap_300W_LP(bfm, image_path, mat_path, save_folder, uv_h = 256, uv_w = 256, image_h = 256, image_w = 256):
# 1. load image and fitted parameters
image_name = image_path.strip().split('/')[-1]
image = io.imread(image_path)/255;
[h, w, c] = image.shape;
info = sio.loadmat(mat_path);
pose_para = info['Pose_Para'].T.astype(np.float32);
shape_para = info['Shape_Para'].astype(np.float32);
exp_para = info['Exp_Para'].astype(np.float32);
# 2. generate mesh;
# generate shape
vertices = bfm.generate_vertices(shape_para, exp_para);
# transform mesh
s = pose_para[-1, 0];
angles = pose_para[:3, 0];
t = pose_para[3:6, 0];
transformed_vertices = bfm.transform_3ddfa(vertices, s, angles, t)
projected_vertices = transformed_vertices.copy() # using stantard camera & orth projection as in 3DDFA
image_vertices = projected_vertices.copy()
image_vertices[:,1] = h - image_vertices[:,1] - 1
# 3. crop image with key points
kpt = image_vertices[bfm.kpt_ind, :].astype(np.int32)
left = np.min(kpt[:, 0])
right = np.max(kpt[:, 0])
top = np.min(kpt[:, 1])
bottom = np.max(kpt[:, 1])
center = np.array([right - (right - left) / 2.0,
bottom - (bottom - top) / 2.0])
old_size = (right - left + bottom - top)/2
size = int(old_size*1.5)
# random pertube. you can change the numbers
marg = old_size*0.1
t_x = np.random.rand()*marg*2 - marg
t_y = np.random.rand()*marg*2 - marg
center[0] = center[0]+t_x;
center[1] = center[1]+t_y
size = size*(np.random.rand()*0.2 + 0.9)
# crop and record the transform parameters
src_pts = np.array([[center[0]-size/2, center[1]-size/2], [center[0] - size/2, center[1]+size/2], [center[0]+size/2, center[1]-size/2]]);
DST_PTS = np.array([[0, 0], [0, image_h - 1], [image_w - 1, 0]]);
tform = skimage.transform.estimate_transform('similarity', src_pts, DST_PTS);
# transform face position(image vertices) along with 2d facial image
angle = np.random.rand() * 90 - 45;
rows, cols = image.shape[0], image.shape[1];
# rotation around center
center = np.array((cols, rows)) / 2. - 0.5;
tform1 = SimilarityTransform(translation=center);
tform2 = SimilarityTransform(rotation= | np.deg2rad(angle) | numpy.deg2rad |
import numpy as np
from .representations import *
########### I/O UTILITIES ##############
def fix_pyscf_l1(fock, frame, orbs):
""" pyscf stores l=1 terms in a xyz order, corresponding to (m=1, 0, -1).
this converts into a canonical form where m is sorted as (-1, 0,1) """
idx = []
iorb = 0;
atoms = list(frame.symbols)
for atype in atoms:
cur=()
for ia, a in enumerate(orbs[atype]):
n,l,m = a
if (n,l) != cur:
if l == 1:
idx += [iorb+1, iorb+2, iorb]
else:
idx += range(iorb, iorb+2*l+1)
iorb += 2*l+1
cur = (n,l)
return fock[idx][:,idx]
########### HAMILTONIAN MANIPULATION ###########
def lowdin_orthogonalize(fock, s):
"""
lowdin orthogonalization of a fock matrix computing the square root of the overlap matrix
"""
eva, eve = np.linalg.eigh(s)
sm12 = eve @ np.diag(1.0/np.sqrt(eva)) @ eve.T
return sm12 @ fock @ sm12
########## ORBITAL INDEXING ##############
def orbs_base(orbs):
# converts list of orbitals into an index to access different sub-blocks
norbs = 0
io_base = {}
el_dict = {}
for el in orbs.keys():
io_base[el] = norbs
cur_a = ()
for na, la, ma in orbs[el]:
if cur_a == (na,la): continue
cur_a = (na, la)
el_dict[(na+io_base[el], la)] = el
norbs+=1
return io_base, el_dict
############ matrix/block manipulations ###############
def matrix_to_blocks(fock, frame, orbs):
""" splits an atomic orbital matrix to (uncoupled momentum) orbital blocks. """
# maps atom types to different n indices
io_base, _ = orbs_base(orbs)
# prepares storage
diaglist = {}
offdlist_p = {}
offdlist_m = {}
heterolist = {}
# creates storage. these are the blocks of the matrix we'll have to fill up later
lorbs = []
for el_a in orbs.keys():
for ia, a in enumerate(orbs[el_a]):
na, la, ma = a
na += io_base[el_a] # adds element offset
for el_b in orbs.keys():
for ib, b in enumerate(orbs[el_b]):
nb, lb, mb = b
nb += io_base[el_b] # adds element offset
if ( (nb>na or (nb==na and lb>=la)) and
not (na,la,nb,lb) in lorbs ):
orb = (na,la,nb,lb)
lorbs.append(orb)
if el_a == el_b:
diaglist[orb] = []
offdlist_p[orb] = []
offdlist_m[orb] = []
else:
heterolist[orb] = []
# reads in and partitions into blocks
ki = 0
nat = len(frame.numbers)
for i in range(nat):
el_a = frame.symbols[i]
cur_a = ()
for ia, oa in enumerate(orbs[el_a]):
na, la, ma = oa
na += io_base[el_a]
# we read the Hamiltonian in blocks
if (cur_a == (na,la)): continue
cur_a = (na,la)
kj = 0
for j in range(nat):
el_b = frame.symbols[j]
cur_b = ()
for ib, ob in enumerate(orbs[el_b]):
nb, lb, mb = ob
nb += io_base[el_b] # adds element offset
if (cur_b == (nb,lb)): continue # only read at the beginning of each m block
cur_b = (nb,lb)
if (nb<na or (nb==na and lb<la)): continue
orb = (na,la,nb,lb)
blockij = fock[ki+ia:ki+ia+2*la+1, kj+ib:kj+ib+2*lb+1]
if (i==j):
diaglist[orb].append(blockij)
elif (i<j and el_a == el_b):
blockji= fock[kj+ia:kj+ia+2*la+1, ki+ib:ki+ib+2*lb+1]
offdlist_p[orb].append((blockij+blockji)/np.sqrt(2))
offdlist_m[orb].append((blockij-blockji)/np.sqrt(2))
elif(el_a != el_b):
heterolist[orb].append(blockij)
kj += len(orbs[el_b])
ki += len(orbs[el_a])
# stores as ndarray for more flexible indexing
for orb in lorbs:
for d in [diaglist, offdlist_p, offdlist_m, heterolist]:
if orb in d:
d[orb] = np.asarray(d[orb])
return dict( diag=diaglist, offd_p=offdlist_p, offd_m=offdlist_m, hete=heterolist)
def matrix_to_ij_indices(fock, frame, orbs):
""" Creates indices to the atoms involved in each block """
# maps atom types to different n indices
io_base, _ = orbs_base(orbs)
# prepares storage
diaglist = {}
offdlist_p = {}
offdlist_m = {}
heterolist = {}
# creates storage. these are the blocks of the matrix we'll have to fill up later
lorbs = []
for el_a in orbs.keys():
for ia, a in enumerate(orbs[el_a]):
na, la, ma = a
na += io_base[el_a] # adds element offset
for el_b in orbs.keys():
for ib, b in enumerate(orbs[el_b]):
nb, lb, mb = b
nb += io_base[el_b] # adds element offset
if ( (nb>na or (nb==na and lb>=la)) and
not (na,la,nb,lb) in lorbs ):
orb = (na,la,nb,lb)
lorbs.append(orb)
if el_a == el_b:
diaglist[orb] = []
offdlist_p[orb] = []
offdlist_m[orb] = []
else:
heterolist[orb] = []
# reads in and partitions into blocks
ki = 0
nat = len(frame.numbers)
for i in range(nat):
el_a = frame.symbols[i]
cur_a = ()
for ia, oa in enumerate(orbs[el_a]):
na, la, ma = oa
na += io_base[el_a]
# we read the Hamiltonian in blocks
if (cur_a == (na,la)): continue
cur_a = (na,la)
kj = 0
for j in range(nat):
el_b = frame.symbols[j]
cur_b = ()
for ib, ob in enumerate(orbs[el_b]):
nb, lb, mb = ob
nb += io_base[el_b] # adds element offset
if (cur_b == (nb,lb)): continue # only read at the beginning of each m block
cur_b = (nb,lb)
if (nb<na or (nb==na and lb<la)): continue
orb = (na,la,nb,lb)
blockij = (i,j)
if (i==j):
diaglist[orb].append(blockij)
elif (i<j and el_a == el_b):
offdlist_p[orb].append(blockij)
offdlist_m[orb].append(blockij)
elif(el_a != el_b):
heterolist[orb].append(blockij)
kj += len(orbs[el_b])
ki += len(orbs[el_a])
# stores as ndarray for more flexible indexing
for orb in lorbs:
for d in [diaglist, offdlist_p, offdlist_m, heterolist]:
if orb in d:
d[orb] = np.asarray(d[orb])
return dict( diag=diaglist, offd_p=offdlist_p, offd_m=offdlist_m, hete=heterolist)
def blocks_to_matrix(blocks, frame, orbs):
""" assembles (uncoupled momentum) orbital blocks into a matrix form
NB - the l terms are stored in canonical order, m=-l..l """
io_base, _ = orbs_base(orbs)
norbs = 0
for el in list(frame.symbols):
norbs+= len(orbs[el])
nat = len(list(frame.symbols))
unfock = np.zeros((norbs, norbs))
bidx = {}
for k in blocks.keys():
bidx[k] = {}
for bk in blocks[k].keys():
bidx[k][bk] = 0
cur_a = ()
ki = 0
nat = len(frame.numbers)
for i in range(nat):
el_a = frame.symbols[i]
cur_a = ()
for ia, oa in enumerate(orbs[el_a]):
na, la, ma = oa
na += io_base[el_a]
# we read the Hamiltonian in blocks
if (cur_a == (na,la)): continue
cur_a = (na,la)
kj = 0
for j in range(nat):
el_b = frame.symbols[j]
cur_b = ()
for ib, ob in enumerate(orbs[el_b]):
nb, lb, mb = ob
nb += io_base[el_b] # adds element offset
if (cur_b == (nb,lb)): continue # only read at the beginning of each m block
cur_b = (nb,lb)
if (nb<na or (nb==na and lb<la)): continue
orb = (na,la,nb,lb)
if (i==j):
blockij = blocks['diag'][orb][bidx['diag'][orb]]
unfock[ki+ia:ki+ia+2*la+1, kj+ib:kj+ib+2*lb+1] = blockij
unfock[ki+ib:ki+ib+2*lb+1, kj+ia:kj+ia+2*la+1] = blockij.T
bidx['diag'][orb] += 1
elif (el_a == el_b and i<j):
blockij = ( ( blocks['offd_p'][orb][bidx['offd_p'][orb]] if orb in blocks['offd_p'] else 0)
+ ( blocks['offd_m'][orb][bidx['offd_m'][orb]] if orb in blocks['offd_m'] else 0)
)/np.sqrt(2)
blockji = ( ( blocks['offd_p'][orb][bidx['offd_p'][orb]] if orb in blocks['offd_p'] else 0)
- ( blocks['offd_m'][orb][bidx['offd_m'][orb]] if orb in blocks['offd_m'] else 0)
)/np.sqrt(2)
unfock[ki+ia:ki+ia+2*la+1, kj+ib:kj+ib+2*lb+1] = blockij
unfock[kj+ib:kj+ib+2*lb+1, ki+ia:ki+ia+2*la+1] = blockij.T
unfock[kj+ia:kj+ia+2*la+1, ki+ib:ki+ib+2*lb+1] = blockji
unfock[ki+ib:ki+ib+2*lb+1, kj+ia:kj+ia+2*la+1] = blockji.T
if orb in bidx['offd_p']:
bidx['offd_p'][orb] += 1
if orb in bidx['offd_m']:
bidx['offd_m'][orb] += 1
elif (el_a != el_b):
blockij = blocks['hete'][orb][bidx['hete'][orb]]
unfock[ki+ia:ki+ia+2*la+1, kj+ib:kj+ib+2*lb+1] = blockij
unfock[kj+ib:kj+ib+2*lb+1, ki+ia:ki+ia+2*la+1] = blockij.T
bidx['hete'][orb] += 1
kj += len(orbs[el_b])
ki += len(orbs[el_a])
return unfock
def couple_blocks(dcoef, cg):
""" converts coefficients (fock matrix blocks) from uncoupled to coupled form """
dccoef = {}
for dk in dcoef.keys():
dccoef[dk] = {}
for k in dcoef[dk].keys():
n1, l1, n2, l2 = k
if len(dcoef[dk][k]) > 0:
# computes the coupled representation
coupled = [ next(iter(cg.couple(el).values())) for el in dcoef[dk][k] ]
# creates the dictionary
dccoef[dk][k] = {}
for L in coupled[0].keys():
# skips blocks that are zero because of symmetry
if (n1==n2 and l1==l2 and
( ( (dk=="diag" or dk=="offd_p") and (l1+l2+L)%2==1) or
(dk=="offd_m" and (l1+l2+L)%2==0) )
) : continue
dccoef[dk][k][L] = np.asarray([el[L] for el in coupled])
return dccoef
def decouple_blocks(dccoef, cg):
""" converts coefficients (fock matrix blocks) from coupled to uncoupled form """
dcoef = {}
for dk in dccoef.keys():
dcoef[dk] = {}
for k in dccoef[dk].keys():
decoup = []
if len(dccoef[dk][k])==0:
continue
nitems = len( list(dccoef[dk][k].values())[0])
for i in range(nitems):
coupled = {(k[1], k[3]): {}}
for L in dccoef[dk][k].keys():
coupled[(k[1], k[3])][L] = dccoef[dk][k][L][i]
decoup.append(cg.decouple(coupled))
dcoef[dk][k] = np.asarray(decoup)
return dcoef
def matrix_list_to_blocks(focks, frames, orbs, cg, progress = (lambda x: x)):
""" Computes coupled-momemtum blocks of the matrices for a bunch of frames,
collecting all the learning targets in a single list. Also returns indices
that allows extracting the blocks from each matrix. """
blocks = couple_blocks(matrix_to_blocks(focks[0], frames[0], orbs), cg)
slices = [{}]
for k in blocks.keys():
slices[0][k] = {}
for orb in blocks[k]:
if len(blocks[k][orb]) == 0:
slices[0][k][orb] = slice(0, 0)
continue
L0 = list(blocks[k][orb].keys())[0]
slices[0][k][orb] = slice(0, len(blocks[k][orb][L0]))
for ifr in progress(range(1,len(frames))):
fc = couple_blocks(matrix_to_blocks(focks[ifr], frames[ifr], orbs), cg)
slices.append({})
for k in fc.keys():
slices[-1][k] = {}
for orb in fc[k]:
if len(fc[k][orb]) == 0:
slices[-1][k][orb] = slice(0, 0)
continue
L0 = list(fc[k][orb].keys())[0]
if not orb in blocks[k]:
# extend the blocks if more orbital combinations appear
blocks[k][orb] = fc[k][orb]
slices[-1][k][orb] = slice(0, len(blocks[k][orb][L0]))
else:
slices[-1][k][orb] = slice(len(blocks[k][orb][L0]),
len(blocks[k][orb][L0])+len(fc[k][orb][L0]) )
for L in fc[k][orb]:
blocks[k][orb][L] = np.vstack([blocks[k][orb][L], fc[k][orb][L] ] )
return blocks, slices
def get_block_idx(frame_idx, slices):
""" returns a dictionary with the indices associated with
the hamiltonians of the frames in frame_idx """
idx_slices = { k:{} for k in slices[0].keys() }
for i in frame_idx:
for k in slices[i].keys():
for b in slices[i][k].keys():
if not b in idx_slices[k]:
idx_slices[k][b] = []
idx_slices[k][b] += list(range( slices[i][k][b].start, slices[i][k][b].stop))
return idx_slices
def coupled_block_slice(dccoef, slices):
dcoef = {}
for dk in dccoef.keys():
dcoef[dk] = {}
for orb in dccoef[dk].keys():
if type(slices) is dict:
if orb in slices[dk]:
sl = slices[dk][orb]
else:
continue
else:
sl = slices
dcoef[dk][orb] = {}
for L in dccoef[dk][orb]:
dcoef[dk][orb][L] = dccoef[dk][orb][L][sl]
return dcoef
def blocks_to_matrix_list(blocks, frames, slices, orbs, cg):
""" Transforms coupled-momentum blocks to a list of fock matrices. """
focks = []
ntot = 0
for ifr in range(len(slices)):
dec = decouple_blocks(coupled_block_slice(blocks, slices[ifr]), cg)
focks.append(blocks_to_matrix(dec, frames[ifr], orbs))
return focks
def block_to_feat_index(tblock, kblock, lblock, orbs):
obase = orbs_base(orbs)
if tblock != "hete":
fblock = (obase[1][kblock[0:2]], lblock, (1-2*(kblock[1]%2))*(1-2*(kblock[3]%2))*(1-2*(lblock%2)) )
else:
fblock = (obase[1][kblock[0:2]], obase[1][kblock[2:4]], lblock, (1-2*(kblock[1]%2))*(1-2*(kblock[3]%2))*(1-2*(lblock%2)))
return fblock
def merge_features(lblocks, axis=0, lowmem=False):
""" Takes a list of block dictionaries and consolidates into a single list """
# first we create block structure
rblocks = {}
for block in lblocks:
for k in block:
if not k in rblocks:
rblocks[k] = {}
else:
for b in block[k]:
if not b in rblocks[k] or len(rblocks[k][b])==0:
rblocks[k][b] = []
# and then we fill it
for k in rblocks:
for b in rblocks[k]:
nbl = []
for block in lblocks:
if len(block[k][b])>0:
nbl.append(block[k][b])
if lowmem:
# free memory associated with the constituent blocks to save memory as we accumulate the merged array
block[k][b] = 0
if len(nbl)>0:
rblocks[k][b] = np.concatenate(nbl, axis=axis)
return rblocks
def normalize_features(block, norm=1):
""" Takes a list of block dictionaries and normalize them (in place)"""
for k in block:
for b in block[k]:
nrm = np.sqrt((block[k][b].reshape((block[k][b].shape[0],-1))**2).sum(axis=1).mean(axis=0))
if nrm > 0.0:
block[k][b] *= norm/nrm
############### Error stats #########################
def hamiltonian_mse(fock1, fock2, scale=1.0):
""" Average element-wise error between Hamiltonians. Normalized so
that in the asymptotic limit (large system size, sparse Hamiltonian)
the error is independent on system size """
return ((fock1 - fock2)**2).flatten().sum() * scale
def hamiltonian_mse_blocks(blocks1, blocks2, scale=1.0):
""" Average element-wise error between Hamiltonians in block form.
Defined so that the sum over blocks equals the overall MSE in the matrix form.
"""
mse = {}
nel = 0
for k in blocks1.keys():
mse[k] = {}
for b in blocks1[k]:
na, la, nb, lb = b
mse[k][b] = 0
for l in blocks1[k][b]:
mse[k][b] += ((blocks1[k][b][l] - blocks2[k][b][l]).flatten()**2).sum()
if (nb!=na or lb!=la):
mse[k][b]*=2.0 # multiplicity
mse[k][b]*=scale
return mse
############### SAPH generation #########################
def compute_saph(fock, over, frame, orbs, sel_types, n_core, orthogonality_threshold=1e-8):
""" Computes symmetry-adapted projected Hamiltonian by projecting the
key molecular orbitals onto a smaller basis than the full Hamiltonian basis.
Assumes to be given the non-orthogonal Hamiltonian and the overlap matrix """
# first solves the non-orthogonal eigenvalue problem to get the target eigenvalues and eigenvectors
l, U = sp.linalg.eigh(fock, over)
# finds the selected basis indices for the given frame
sel_basis = []
sel_k = 0
tot_core = 0
for s in frame.symbols:
sel_basis.append(np.asarray(sel_types[s], dtype=int) + sel_k)
tot_core += n_core[s]
sel_k += len(orbs[s])
sel_basis = np.concatenate(sel_basis)
# first guess at MO selection - drop core states and pick the size
# of the selected basis plus some buffer which we use to sort out
# orthogonality problems
sel_mo = np.arange(tot_core, tot_core + len(sel_basis) + 8)
# these are the coefficients projected on the selected basis
V = (over[sel_basis] @ U[:, sel_mo])
u, s, vt = sp.linalg.svd(V, full_matrices=False)
# determines the relevant symmetry-adapted subspace
ovt = vt.copy()
osel_mo = []
# strategy is that we do Gram-Schmidt orthogonalization without renormalizing.
# when a MO cannot be described because it is fully linearly dependent on
# already selected MOs, it skips
for k in range(vt.shape[1]):
if (ovt[:, k]@ovt[:, k]) < orthogonality_threshold:
continue
osel_mo.append(sel_mo[k])
ovt[:, k] /= np.sqrt(ovt[:, k]@ovt[:, k])
for j in range(k+1,vt.shape[1]):
ovt[:, j] -= ovt[:, k] * (ovt[:, j]@ovt[:, k])
sel_mo = np.asarray(osel_mo[:len(sel_basis)], dtype=int)
# now we use the selected MOs to build a SAPH matrix with the same eigenvalues
# as the original one
V = (over[sel_basis] @ U[:, sel_mo])
u, s, vt = sp.linalg.svd(V)
o_V = u @ vt
return [email protected](l[sel_mo])@o_V.T
############## Features for Hamiltonian learning ############
def compute_hamiltonian_representations(frames, orbs, hypers, lmax, nu, cg, scale=1,
select_feats = None, half_hete = True, mp_feats = False,
rhoi_pca = None, rho2i_pca = None,
rhoij_rho2i_pca = None, rhoij_pca = None,
verbose = False
):
"""
Computes the full set of features needed to learn matrix elements up to lmax.
Options are fluid, but here are some that need an explanation:
select_feats = dict(type=["diag", "offd_m", "offd_p", "hete"], block = ('el1', ['el2',] L, pi) )
does the minimal amount of calculation to evaluate the selected block. other terms might be computed as well if they come for free.
"""
spex = SphericalExpansion(**hypers)
rhoi = compute_rhoi(frames, spex, hypers)
# compresses further the spherical expansion features across species
if rhoi_pca is not None:
rhoi = apply_rhoi_pca(rhoi, rhoi_pca)
# makes sure that the spex used for the pair terms uses adaptive species
hypers_ij = deepcopy(hypers)
hypers_ij["expansion_by_species_method"] = "structure wise"
spex_ij = SphericalExpansion(**hypers_ij)
tnat = 0
els = list(orbs.keys())
nel = len(els)
# prepare storage
elL = list(itertools.product(els,range(lmax+1),[-1,1]))
hetL = [ (els[i1], els[i2], L, pi) for i1 in range(nel) for i2 in range((i1+1 if half_hete else 0), nel) for L in range(lmax+1) for pi in [-1,1] ]
feats = dict(diag = { L: [] for L in elL },
offd_p = { L: [] for L in elL },
offd_m = { L: [] for L in elL },
hete = { L: [] for L in hetL },)
if rhoij_rho2i_pca is None and rho2i_pca is not None:
rhoij_rho2i_pca = rho2i_pca
#before = tracemalloc.take_snapshot()
for f in frames:
fnat = len(f.numbers)
frhoi = rhoi[tnat:tnat+fnat]*scale
fgij = compute_gij(f, spex_ij, hypers_ij)*scale
if (select_feats is None or select_feats["type"]!="diag") and nu == 2:
if mp_feats:
# note we abuse rhoij_rho2i_pca to fetch the rho1ijp pca compressor
rhonui, prhonui = compute_all_rho1ijp_lambda(frhoi, fgij, cg, rhoij_rho2i_pca)
else:
rhonui, prhonui = compute_all_rho2i_lambda(frhoi, cg, rhoij_rho2i_pca)
else:
rhonui, prhonui = frhoi, None
crhoi = None
for L in range(lmax+1):
if select_feats is not None and L>0 and select_feats["block"][-2] != L:
continue
if nu==0:
lrhonui, lprhonui = np.ones((fnat, 1, 2*L+1)), np.ones((1))
elif nu==1:
lrhonui, lprhonui = compute_rho1i_lambda(frhoi, L, cg)
else:
lrhonui, lprhonui = compute_rho2i_lambda(frhoi, L, cg)
if rho2i_pca is not None:
lrhonui, lprhonui = apply_rho2i_pca(lrhonui, lprhonui, rho2i_pca)
if select_feats is None or select_feats["type"]!="diag":
if nu==0:
lrhoij, prhoij = compute_rho0ij_lambda(rhonui, fgij, L, cg, prhonui)
elif nu==1:
if mp_feats:
lrhoij, prhoij = compute_rho1ijp_lambda(rhonui, fgij, L, cg, prhonui)
else:
lrhoij, prhoij = compute_rho1ij_lambda(rhonui, fgij, L, cg, prhonui)
else:
if mp_feats:
lrhoij, prhoij = compute_rho11ijp_lambda(frhoi, rhonui, L, cg, prhonui)
else:
lrhoij, prhoij = compute_rho2ij_lambda(rhonui, fgij, L, cg, prhonui)
if rhoij_pca is not None:
lrhoij, prhoij = apply_rhoij_pca(lrhoij, prhoij, rhoij_pca)
crhoi, pcrhoi = contract_rhoij(lrhoij, prhoij, f.symbols, els)
for i, el in enumerate(els):
iel = np.where(f.symbols==el)[0]
if len(iel) == 0:
continue
if select_feats is not None and el != select_feats["block"][0]:
continue
for pi in [-1,1]:
wherepi = np.where(lprhonui==pi)[0]
if len(wherepi)==0:
# add a vector of zeros
feats['diag'][(el, L, pi)].append(np.zeros(shape=(len(iel), 1, 2*L+1)))
continue
feats['diag'][(el, L, pi)].append(lrhonui[...,wherepi,:][iel].reshape((len(iel), -1, 2*L+1) ) )
if crhoi is not None:
wherepi = np.where(pcrhoi==pi)[0]
if len(wherepi)==0:
continue
feats['diag'][(el, L, pi)][-1] = np.concatenate([
feats['diag'][(el, L, pi)][-1],
crhoi[...,wherepi,:][iel].reshape( (len(iel), -1, 2*L+1) )
], axis=-2)
if select_feats is not None and select_feats["type"]=="diag":
continue
triu = np.triu_indices(len(iel), 1)
ij_up = (iel[triu[0]],iel[triu[1]]) # ij indices, i>j
ij_lw = (ij_up[1], ij_up[0]) # ij indices, i<j
lrhoij_p = (lrhoij[ij_up] + lrhoij[ij_lw])/np.sqrt(2)
lrhoij_m = (lrhoij[ij_up] - lrhoij[ij_lw])/np.sqrt(2)
for pi in [-1,1]:
if len(ij_up[0])==0:
continue
wherepi = np.where(prhoij==pi)[0];
if len(wherepi)==0:
feats['offd_p'][(el, L, pi)].append( np.zeros((lrhoij_p.shape[0], 1, 2*L+1)) )
feats['offd_m'][(el, L, pi)].append( np.zeros((lrhoij_p.shape[0], 1, 2*L+1)) )
continue
feats['offd_p'][(el, L, pi)].append(lrhoij_p[...,wherepi,:].reshape(lrhoij_p.shape[0], -1, 2*L+1))
feats['offd_m'][(el, L, pi)].append(lrhoij_m[...,wherepi,:].reshape(lrhoij_m.shape[0], -1, 2*L+1))
if select_feats is not None and select_feats["type"]!="hete":
continue
for elb in els[i+1:]:
ielb = np.where(f.symbols==elb)[0]
if len(ielb) == 0:
continue
if select_feats is not None and elb != select_feats["block"][1]:
continue
# combines rho_ij and rho_ji
lrhoij_het = lrhoij[iel][:,ielb]
lrhoij_het_rev = | np.swapaxes(lrhoij[ielb][:,iel],1,0) | numpy.swapaxes |
# -*- coding: utf-8 -*-
"""
Created on Sat May 22 16:47:59 2021
@author: leyuan
reference: https://github.com/ShangtongZhang/reinforcement-learning-an-introduction/blob/master/chapter06/windy_grid_world.py
"""
import time
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
import pandas as pd
from tqdm import tqdm
WORLD_HEIGHT = 7
WORLD_WIDTH = 10
# wind strength for each column
WIND = [0, 0, 0, 1, 1, 1, 2, 2, 1, 0]
# possible actions
UP = 0
DOWN = 1
LEFT = 2
RIGHT = 3
ACTIONS = [UP, DOWN, LEFT, RIGHT]
# probability for exploration
EPSILON = 0.1
# Sarsa step size
ALPHA = 0.5
# reward for each step
REWARD = -1.0
# start and goal position of the world, origin on top left corner,[height, width]
START = [3, 0]
GOAL = [3, 7]
def step(state, action):
'''
注意,这里的风力指的是出发位置的风力,比如是从一个风力为1的地方往左走了一步,
那么结果会比正常的向上多一步,而不管新到达的列的风力是多少
'''
i, j = state
if action == UP:
return [max(i - 1 - WIND[j], 0), j]
elif action == DOWN:
return [max(min(i + 1 - WIND[j], WORLD_HEIGHT - 1), 0), j]
elif action == LEFT:
return [max(i - WIND[j], 0), max(j - 1, 0)]
elif action == RIGHT:
return [max(i - WIND[j], 0), min(j + 1, WORLD_WIDTH - 1)]
else:
assert False, "action must be 'UP', 'DOWN', 'LEFT', 'RIGHT'."
# play for an episode
def episode(q_val):
# track the total time steps in this episode
timesteps = 0
# initialization
state = START
# choose an action based on the epsilon-greedy algorithm
if np.random.binomial(1, EPSILON) == 1:
action = np.random.choice(ACTIONS)
else:
values = q_val[state[0], state[1], :]
action = np.random.choice(np.where(values == np.max(values))[0])
#keep going until get to the goal state
while state != GOAL:
next_state = step(state, action)
if np.random.binomial(1, EPSILON) == 1:
next_action = np.random.choice(ACTIONS)
else:
values = q_val[next_state[0], next_state[1], :]
next_action = np.random.choice(np.where(values == np.max(values))[0])
# Sarsa update
q_val[state[0], state[1], action] += \
ALPHA * (REWARD + q_val[next_state[0], next_state[1], next_action]
- q_val[state[0], state[1], action])
state = next_state
action = next_action
timesteps += 1
return timesteps
def figure_6_3():
'''
书中的展示方式很奇怪,图片的纵轴是episode,横轴是每个episode所用step的累积求和,因为越到后面,
策略会逐渐收敛到最优,所以每一个episode所用的步数就会逐渐下降并稳定在一个值,所以整个曲线表现出来就是
斜率逐渐上升,其实横过来看就是增长趋于平缓,但是就是挺奇怪的
'''
q_value = np.zeros((WORLD_HEIGHT, WORLD_WIDTH, len(ACTIONS)))
episode_limit = 170
steps = []
ep = 0
while ep < episode_limit:
steps.append(episode(q_value))
ep += 1
steps = | np.cumsum(steps) | numpy.cumsum |
__doc__ = "a module that houses the priors for our inferences"
__author__ = "<EMAIL>"
#-------------------------------------------------
import numpy as np
import healpy as hp
### non-standard libraries
from gpr_isotropy.utils import (TWOPI, LOG2PI)
#-------------------------------------------------
class RoPrior(object):
"""
general class representing a prior
"""
_allowed_params = sorted([])
def __init__(self, nside, **params):
self._nside = nside
self._npix = hp.nside2npix(nside)
self.params = params ### automatically checks that these are the correct params
@property
def nside(self):
return self._nside
@property
def npix(self):
return self._npix
@property
def params(self):
return self._params
@params.setter
def params(self, new_params):
assert sorted(new_params.keys())==sorted(self._allowed_params), 'new parameters do not match allowed_params=%s'%(' '.join(self._allowed_params))
self._params = new_params
def __call__(self, *args):
return 0.
#-------------------------------------------------
### priors for Ro
class PosSemiDef(RoPrior):
"""
require Ro to be positive semi-definite (each element must be >= 0)
"""
def __call__(self, Ro):
return 0. if np.all(Ro>=0) else -np.infty
class LogNorm(RoPrior):
"""
log-normal prior for Ro, each direction separately
assumes
len(Ro) = len(mean) = len(stdv)
but can also handle cases where
mean is a float, int
or
var is a float, int
in which case it applies the same prior to all directions
"""
_allowed_params = sorted(['mean', 'var'])
def __init__(self, nside, **params):
RoPrior.__init__(self, nside, **params)
mean = self.params['mean']
var = self.params['var']
assert len(mean)==self._npix or isinstance(mean, (float, int)), 'bad shape for mean'
if isinstance(var, (float, int)):
self._norm = 0.5*N* | np.log(twopi) | numpy.log |
#!/usr/bin/env python
# pipescaler/core/misc.py
#
# Copyright (C) 2020-2021 <NAME>
# All rights reserved.
#
# This software may be modified and distributed under the terms of the
# BSD license.
from __future__ import annotations
from os import listdir
from os.path import basename, splitext
from typing import List, Optional, Set, Tuple, Union
import numpy as np
from PIL import Image
from scipy.ndimage import convolve
from pipescaler.common import DirectoryNotFoundError, NotAFileError, validate_input_path
from pipescaler.core.exceptions import UnsupportedImageModeError
def remove_palette_from_image(image: Image.Image):
palette = np.reshape(image.getpalette(), (-1, 3))
non_grayscale_colors = set(
np.where(
np.logical_or(
palette[:, 0] != palette[:, 1], palette[:, 1] != palette[:, 2]
)
)[0]
)
if "transparency" in image.info:
datum = | np.array(image) | numpy.array |
# Copyright 2019 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.
# ==============================================================================
"""CSR sparse matrix tests."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from scipy import sparse
from tensorflow.core.framework import tensor_pb2
from tensorflow.core.protobuf import config_pb2
from tensorflow.python.client import session
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import errors
from tensorflow.python.framework import ops
from tensorflow.python.framework import random_seed
from tensorflow.python.framework import sparse_tensor
from tensorflow.python.framework import tensor_shape
from tensorflow.python.framework import tensor_util
from tensorflow.python.framework import test_util
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import linalg_ops
from tensorflow.python.ops import map_fn
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import nn_ops
from tensorflow.python.ops import random_ops
from tensorflow.python.ops import sparse_ops
from tensorflow.python.ops import state_ops
from tensorflow.python.ops import variable_scope
from tensorflow.python.ops.linalg.sparse import sparse_csr_matrix_ops
from tensorflow.python.platform import test
from tensorflow.python.platform import tf_logging
CPU = "/device:CPU:0"
GPU = "/device:GPU:0"
def dense_to_csr_sparse_matrix(dense):
dense_t = ops.convert_to_tensor(dense)
locs = array_ops.stop_gradient(array_ops.where(math_ops.abs(dense_t) > 0))
return sparse_csr_matrix_ops.dense_to_csr_sparse_matrix(dense_t, locs)
def _swap(a, i, j):
a[i], a[j] = a[j], a[i]
def twist_matrix(matrix, permutation_indices):
"""Permute the rows and columns of a 2D or (batched) 3D Tensor."""
# Shuffle the rows and columns with the same permutation.
if matrix.shape.ndims == 2:
# Invert the permutation since `tf.gather` and `tf.gather_nd` need the
# mapping from each index `i` to the index that maps to `i`.
permutation_indices_inv = array_ops.invert_permutation(permutation_indices)
matrix = array_ops.gather(matrix, permutation_indices_inv, axis=0)
matrix = array_ops.gather(matrix, permutation_indices_inv, axis=1)
elif matrix.shape.ndims == 3:
permutation_indices_inv = map_fn.map_fn(array_ops.invert_permutation,
permutation_indices)
# For 3D Tensors, it's easy to shuffle the rows but not the columns. We
# permute the rows, transpose, permute the rows again, and transpose back.
batch_size = matrix.shape[0]
batch_indices = array_ops.broadcast_to(
math_ops.range(batch_size)[:, None], permutation_indices.shape)
for _ in range(2):
matrix = array_ops.gather_nd(
matrix,
array_ops.stack([batch_indices, permutation_indices_inv], axis=-1))
# Transpose the matrix, or equivalently, swap dimensions 1 and 2.
matrix = array_ops.transpose(matrix, perm=[0, 2, 1])
else:
raise ValueError("Input matrix must have rank 2 or 3. Got: {}".format(
matrix.shape.ndims))
return matrix
class CSRSparseMatrixOpsTest(test.TestCase):
@classmethod
def setUpClass(cls): # pylint: disable=g-missing-super-call
cls._gpu_available = test_util.is_gpu_available()
# TODO(ebrevdo): This will work once we find a way to get rendezvous
# working for CSRSparseMatrix and can remove the HostMemory
# annotations for the other ops.
@test_util.run_in_graph_and_eager_modes
def DISABLEDtestFromProto(self):
if not self._gpu_available:
return
a_indices = np.array([[0, 0], [2, 3]])
a_values = np.asarray([1.0, 5.0], dtype=np.float32)
a_dense_shape = np.asarray([5, 6], dtype=np.int64)
a_sparse_mat = sparse.coo_matrix((a_values,
(a_indices[:, 0], a_indices[:, 1])),
shape=a_dense_shape)
a_csr_mat = a_sparse_mat.tocsr()
a_col_inds = a_csr_mat.indices
a_row_ptrs = a_csr_mat.indptr
# Format of SparseMatrix:
# type_name == "tensorflow::CSRSparseMatrix"
# metadata == b (validated)
# tensors == [dense_shape, row_ptrs, col_indices, values]
dense_shape_proto = tensor_util.make_tensor_proto(a_dense_shape)
row_ptrs_proto = tensor_util.make_tensor_proto(a_row_ptrs)
col_inds_proto = tensor_util.make_tensor_proto(a_col_inds)
values_proto = tensor_util.make_tensor_proto(a_values)
variant_tensor_data = tensor_pb2.VariantTensorDataProto(
type_name="tensorflow::CSRSparseMatrix",
metadata=np.asarray(True).tobytes(),
tensors=[
dense_shape_proto, row_ptrs_proto, col_inds_proto, values_proto
])
tensor_proto = tensor_pb2.TensorProto(
dtype=dtypes.variant.as_datatype_enum,
tensor_shape=tensor_shape.TensorShape([]).as_proto())
tensor_proto.variant_val.extend([variant_tensor_data])
a_sm = constant_op.constant(tensor_proto)
a_rt = sparse_csr_matrix_ops.csr_sparse_matrix_to_dense(
a_sm, type=dtypes.float32)
self.evaluate(a_rt)
@test_util.run_in_graph_and_eager_modes
def testSparseTensorConversion(self):
a_indices = np.array([[0, 0], [2, 3], [2, 4], [3, 0]])
a_values = [1.0, 5.0, -1.0, -2.0]
a_dense_shape = [5, 6]
a_sparse_mat = sparse.coo_matrix((a_values,
(a_indices[:, 0], a_indices[:, 1])),
shape=a_dense_shape)
a_csr_mat = a_sparse_mat.tocsr()
# Convert 2D SparseTensor to CSR Matrix
a_st = sparse_tensor.SparseTensor(a_indices, a_values, a_dense_shape)
a_st = math_ops.cast(a_st, dtypes.float32)
a_sm = sparse_csr_matrix_ops.sparse_tensor_to_csr_sparse_matrix(
a_st.indices, a_st.values, a_st.dense_shape)
# Get row indices and columns for batch 0.
a_sm_row_ptrs, a_sm_col_inds, a_sm_values = (
sparse_csr_matrix_ops.csr_sparse_matrix_components(
a_sm, 0, type=a_st.dtype))
a_sm_row_ptrs_values, a_sm_col_inds_values, a_sm_values_values = (
self.evaluate((a_sm_row_ptrs, a_sm_col_inds, a_sm_values)))
self.assertAllEqual(a_csr_mat.indices, a_sm_col_inds_values)
self.assertAllEqual(a_csr_mat.indptr, a_sm_row_ptrs_values)
self.assertAllClose(a_values, a_sm_values_values)
# Convert CSR Matrix to 2D SparseTensor
a_st_rt = sparse_csr_matrix_ops.csr_sparse_matrix_to_sparse_tensor(
a_sm, type=a_st.dtype)
a_st_rt_value = self.evaluate(a_st_rt)
self.assertAllEqual(a_indices, a_st_rt_value.indices)
self.assertAllClose(a_values, a_st_rt_value.values)
self.assertAllEqual(a_dense_shape, a_st_rt_value.dense_shape)
# TODO(b/139491352): Add handle_data propagation to array_ops.identity.
@test_util.run_deprecated_v1
def testCSRSparseMatrixResourceVariable(self):
if not self._gpu_available:
return
sparsify = lambda m: m * (m > 0)
dense_shape = [53, 65, 127]
a_mats = sparsify(np.random.randn(*dense_shape)).astype(np.float32)
a_sm = dense_to_csr_sparse_matrix(a_mats)
with ops.device("/gpu:0"):
v = variable_scope.get_variable("sm", initializer=a_sm, use_resource=True)
v_id = array_ops.identity(v)
self.assertEqual(
sparse_csr_matrix_ops.dense_shape_and_type(v_id).shape, a_mats.shape)
a_rt = sparse_csr_matrix_ops.csr_sparse_matrix_to_dense(
v, type=dtypes.float32)
v_reassign = state_ops.assign(v, v_id).op
with self.assertRaisesOpError("Error while reading resource variable sm"):
self.evaluate(a_rt)
self.evaluate(v.initializer)
a_rt_value = self.evaluate(a_rt)
self.assertAllClose(a_mats, a_rt_value)
self.evaluate(v_reassign)
a_rt_reassigned_value = self.evaluate(a_rt)
self.assertAllClose(a_mats, a_rt_reassigned_value)
@test_util.run_in_graph_and_eager_modes
def testBatchSparseTensorConversion(self):
a_indices = np.array([[0, 0, 0], [0, 2, 3], [2, 0, 1]])
a_values = [1.0, 5.0, 6.0]
a_dense_shape = [3, 5, 6]
a_sparse_mats = [
sparse.coo_matrix(([1.0, 5.0], ([0, 2], [0, 3])),
shape=a_dense_shape[1:]),
sparse.coo_matrix(([], ([], [])), shape=a_dense_shape[1:]),
sparse.coo_matrix(([6.0], ([0], [1])), shape=a_dense_shape[1:])
]
a_csr_mats = [m.tocsr() for m in a_sparse_mats]
# Convert 3D SparseTensor to CSR Matrix
a_st = sparse_tensor.SparseTensor(a_indices, a_values, a_dense_shape)
a_st = math_ops.cast(a_st, dtypes.float32)
a_sm = sparse_csr_matrix_ops.sparse_tensor_to_csr_sparse_matrix(
a_st.indices, a_st.values, a_st.dense_shape)
# Get row indices and columns for batches.
a_sm_components = [
sparse_csr_matrix_ops.csr_sparse_matrix_components(
a_sm, i, type=a_st.dtype) for i in range(3)
]
a_sm_values = self.evaluate(a_sm_components)
for i, (a_sm_val, a_csr_mat) in enumerate(zip(a_sm_values, a_csr_mats)):
tf_logging.info("Comparing batch %d" % i)
self.assertAllEqual(a_csr_mat.indptr, a_sm_val.row_ptrs)
self.assertAllEqual(a_csr_mat.indices, a_sm_val.col_inds)
self.assertAllClose(a_csr_mat.data, a_sm_val.values)
# Convert CSR batched Matrix to 3D SparseTensor
a_st_rt = sparse_csr_matrix_ops.csr_sparse_matrix_to_sparse_tensor(
a_sm, type=a_st.dtype)
a_st_rt_value = self.evaluate(a_st_rt)
self.assertAllEqual(a_indices, a_st_rt_value.indices)
self.assertAllClose(a_values, a_st_rt_value.values)
self.assertAllEqual(a_dense_shape, a_st_rt_value.dense_shape)
@test_util.run_in_graph_and_eager_modes
def testLargeBatchSparseTensorConversion(self):
# Test two sets of conversions to check behavior of the ops in a
# concurrent environment (parallel executions of the ST -> SM ops).
sparsify = lambda m: m * (m > 0)
dense_shape = [53, 65, 127]
mats = [
sparsify(np.random.randn(*dense_shape)).astype(np.float32)
for _ in range(2)
]
csr_mats = [list(map(sparse.csr_matrix, mat)) for mat in mats]
mats_t = [ops.convert_to_tensor(mat) for mat in mats]
mats_locs = [array_ops.where(mat_t > 0) for mat_t in mats_t]
sparse_tensors = list()
for mat_t, mat_loc in zip(mats_t, mats_locs):
sparse_tensors.append(
sparse_tensor.SparseTensor(mat_loc,
array_ops.gather_nd(mat_t,
mat_loc), dense_shape))
sparse_matrices = [
sparse_csr_matrix_ops.sparse_tensor_to_csr_sparse_matrix(
st.indices, st.values, st.dense_shape) for st in sparse_tensors
]
sm_nnz = [
sparse_csr_matrix_ops.sparse_matrix_nnz(sm) for sm in sparse_matrices
]
# Get row indices and columns for batches.
sm_components = list()
for sm in sparse_matrices:
sm_components.append([
sparse_csr_matrix_ops.csr_sparse_matrix_components(
sm, i, type=dtypes.float32) for i in range(dense_shape[0])
])
sm_nnz_values, sm_values = self.evaluate((sm_nnz, sm_components))
for i, (sm_values_i, csr_mats_i) in enumerate(zip(sm_values, csr_mats)):
for b, (sm_val, csr_mat) in enumerate(zip(sm_values_i, csr_mats_i)):
tf_logging.info("Comparing matrix %d batch %d" % (i, b))
self.assertEqual(csr_mat.nnz, sm_nnz_values[i][b])
self.assertAllEqual(csr_mat.indptr, sm_val.row_ptrs)
self.assertAllEqual(csr_mat.indices, sm_val.col_inds)
self.assertAllClose(csr_mat.data, sm_val.values)
# Convert CSR batched Matrix to 3D SparseTensor
st_rt = [
sparse_csr_matrix_ops.csr_sparse_matrix_to_sparse_tensor(
sm, type=dtypes.float32) for sm in sparse_matrices
]
st_values, st_rt_values = self.evaluate((sparse_tensors, st_rt))
for (st_value, st_rt_value) in zip(st_values, st_rt_values):
self.assertAllEqual(st_value.indices, st_rt_value.indices)
self.assertAllClose(st_value.values, st_rt_value.values)
self.assertAllEqual(dense_shape, st_rt_value.dense_shape)
@test_util.run_in_graph_and_eager_modes
def testDenseConversion(self):
a_indices = np.array([[0, 0], [2, 3], [2, 4], [3, 0]])
a_values = np.array([1.0, 5.0, -1.0, -2.0]).astype(np.float32)
a_dense_shape = [5, 6]
a_sparse_mat = sparse.coo_matrix((a_values,
(a_indices[:, 0], a_indices[:, 1])),
shape=a_dense_shape)
a_csr_mat = a_sparse_mat.tocsr()
a_dense = a_sparse_mat.todense()
# Convert 2D SparseTensor to CSR Matrix
a_sm = dense_to_csr_sparse_matrix(a_dense)
# Get row indices and columns for batch 0.
a_sm_row_ptrs, a_sm_col_inds, a_sm_values = (
sparse_csr_matrix_ops.csr_sparse_matrix_components(
a_sm, 0, type=dtypes.float32))
a_sm_row_ptrs_values, a_sm_col_inds_values, a_sm_values_values = (
self.evaluate((a_sm_row_ptrs, a_sm_col_inds, a_sm_values)))
self.assertAllEqual(a_csr_mat.indices, a_sm_col_inds_values)
self.assertAllEqual(a_csr_mat.indptr, a_sm_row_ptrs_values)
self.assertAllClose(a_values, a_sm_values_values)
# Convert CSR Matrix to 2D dense matrix
a_rt = sparse_csr_matrix_ops.csr_sparse_matrix_to_dense(
a_sm, dtypes.float32)
a_rt_value = self.evaluate(a_rt)
self.assertAllEqual(a_dense, a_rt_value)
@test_util.run_in_graph_and_eager_modes
def testBatchDenseConversion(self):
a_dense_shape = [4, 5, 6]
a_sparse_mats = [
sparse.coo_matrix(([1.0, 5.0], ([0, 2], [0, 3])),
shape=a_dense_shape[1:]),
sparse.coo_matrix(([], ([], [])), shape=a_dense_shape[1:]),
sparse.coo_matrix(([6.0], ([0], [1])), shape=a_dense_shape[1:]),
sparse.coo_matrix(([], ([], [])), shape=a_dense_shape[1:]),
]
a_csr_mats = [m.tocsr() for m in a_sparse_mats]
a_dense = np.asarray([m.todense() for m in a_sparse_mats], dtype=np.float32)
# Convert 3D SparseTensor to CSR Matrix
a_sm = dense_to_csr_sparse_matrix(a_dense)
# Get row indices and columns for batches.
a_sm_components = [
sparse_csr_matrix_ops.csr_sparse_matrix_components(
a_sm, i, type=dtypes.float32) for i in range(3)
]
a_sm_values = self.evaluate(a_sm_components)
for i, (a_sm_val, a_csr_mat) in enumerate(zip(a_sm_values, a_csr_mats)):
tf_logging.info("Comparing batch %d" % i)
self.assertAllEqual(a_csr_mat.indptr, a_sm_val.row_ptrs)
self.assertAllEqual(a_csr_mat.indices, a_sm_val.col_inds)
self.assertAllClose(a_csr_mat.data, a_sm_val.values)
# Convert CSR batched Matrix to 3D SparseTensor
a_rt = sparse_csr_matrix_ops.csr_sparse_matrix_to_dense(
a_sm, type=dtypes.float32)
a_rt_value = self.evaluate(a_rt)
self.assertAllEqual(a_dense, a_rt_value)
@test_util.run_in_graph_and_eager_modes
def testLargeBatchDenseConversion(self):
# Test two sets of conversions to check behavior of the ops in a
# concurrent environment (parallel executions of the ST -> SM
# ops).
sparsify = lambda m: m * (m > 0)
dense_shape = [53, 65, 127]
mats = [
sparsify(np.random.randn(*dense_shape)).astype(np.float32)
for _ in range(2)
]
csr_mats = [[sparse.csr_matrix(m) for m in mat] for mat in mats]
mats_t = [ops.convert_to_tensor(mat) for mat in mats]
mats_locs = [array_ops.where(mat_t > 0) for mat_t in mats_t]
sparse_matrices = [
sparse_csr_matrix_ops.dense_to_csr_sparse_matrix(mat, mat_loc)
for (mat, mat_loc) in zip(mats_t, mats_locs)
]
sm_nnz = [
sparse_csr_matrix_ops.sparse_matrix_nnz(sm) for sm in sparse_matrices
]
# Get row indices and columns for batches.
sm_components = []
for sm in sparse_matrices:
sm_components.append([
sparse_csr_matrix_ops.csr_sparse_matrix_components(
sm, i, type=dtypes.float32) for i in range(dense_shape[0])
])
sm_nnz_values, sm_values = self.evaluate((sm_nnz, sm_components))
for i, (sm_values_i, csr_mats_i) in enumerate(zip(sm_values, csr_mats)):
for b, (sm_val, csr_mat) in enumerate(zip(sm_values_i, csr_mats_i)):
tf_logging.info("Comparing matrix %d batch %d" % (i, b))
self.assertEqual(csr_mat.nnz, sm_nnz_values[i][b])
self.assertAllEqual(csr_mat.indptr, sm_val.row_ptrs)
self.assertAllEqual(csr_mat.indices, sm_val.col_inds)
self.assertAllClose(csr_mat.data, sm_val.values)
# Convert CSR batched Matrix to 3D dense tensor
sm_rt = [
sparse_csr_matrix_ops.csr_sparse_matrix_to_dense(
sm, type=dtypes.float32) for sm in sparse_matrices
]
sm_rt_values = self.evaluate(sm_rt)
for (mat, sm_rt_value) in zip(mats, sm_rt_values):
self.assertAllEqual(mat, sm_rt_value)
@test_util.run_in_graph_and_eager_modes
def testSparseMatrixAdd(self):
if not self._gpu_available:
return
if test.is_built_with_rocm():
self.skipTest("sparse-matrix-add op not supported on ROCm")
a_indices = np.array([[0, 0], [2, 3]])
a_values = np.array([1.0, 5.0]).astype(np.float32)
a_dense_shape = [5, 6]
a_sparse_mat = sparse.coo_matrix((a_values,
(a_indices[:, 0], a_indices[:, 1])),
shape=a_dense_shape)
a_dense = a_sparse_mat.todense()
b_indices = np.array([[1, 0], [1, 4], [2, 3], [4, 1]])
b_values = np.array([1.0, 0.5, -5.0, 2.0]).astype(np.float32)
b_dense_shape = [5, 6]
b_sparse_mat = sparse.coo_matrix((b_values,
(b_indices[:, 0], b_indices[:, 1])),
shape=b_dense_shape)
b_dense = b_sparse_mat.todense()
for (alpha, beta) in [(1.0, 1.0), (1.0, -1.0), (0.25, 0.5)]:
a_sum_b_sparse_mat = alpha * a_sparse_mat + beta * b_sparse_mat
# Convert 2D SparseTensor to CSR Matrix
a_sm = dense_to_csr_sparse_matrix(a_dense)
b_sm = dense_to_csr_sparse_matrix(b_dense)
alpha = np.float32(alpha)
beta = np.float32(beta)
c_sm = sparse_csr_matrix_ops.sparse_matrix_add(
a_sm, b_sm, alpha=alpha, beta=beta)
c_dense = sparse_csr_matrix_ops.csr_sparse_matrix_to_dense(
c_sm, dtypes.float32)
c_dense_value = self.evaluate(c_dense)
self.assertAllClose(a_sum_b_sparse_mat.todense(), c_dense_value)
@test_util.run_in_graph_and_eager_modes
def testLargeBatchSparseMatrixAdd(self):
if not self._gpu_available:
return
if test.is_built_with_rocm():
self.skipTest("sparse-matrix-add op not supported on ROCm")
sparsify = lambda m: m * (m > 0)
dense_shape = [53, 65, 127]
a_mats = sparsify(np.random.randn(*dense_shape)).astype(np.float32)
b_mats = sparsify(np.random.randn(*dense_shape)).astype(np.float32)
for (alpha, beta) in [(1.0, 1.0), (1.0, -1.0), (0.25, 0.5)]:
tf_logging.info("testLargeBatchSparseMatrixAdd, comparing "
"alpha, beta (%d, %d)" % (alpha, beta))
a_sm = dense_to_csr_sparse_matrix(a_mats)
b_sm = dense_to_csr_sparse_matrix(b_mats)
alpha = np.float32(alpha)
beta = np.float32(beta)
c_sm = sparse_csr_matrix_ops.sparse_matrix_add(
a_sm, b_sm, alpha=alpha, beta=beta)
c_dense = sparse_csr_matrix_ops.csr_sparse_matrix_to_dense(
c_sm, dtypes.float32)
c_dense_value = self.evaluate(c_dense)
self.assertAllClose(c_dense_value, alpha * a_mats + beta * b_mats)
@test_util.run_in_graph_and_eager_modes
def testSparseMatrixMatMul(self):
for shapes in [[(5, 6), (6, 1)], [(5, 6), (6, 2)]]:
a_indices = np.array([[0, 0], [2, 3]])
a_values = np.array([1.0, 5.0]).astype(np.float32)
a_dense_shape = shapes[0]
a_sparse_mat = sparse.coo_matrix((a_values,
(a_indices[:, 0], a_indices[:, 1])),
shape=a_dense_shape)
a_dense = a_sparse_mat.todense()
# Will multiply sparse a (shape=shapes[0]) by dense b (shape=shapes[1]).
b = np.random.randn(*shapes[1]).astype(np.float32)
a_sm = dense_to_csr_sparse_matrix(a_dense)
c = sparse_csr_matrix_ops.sparse_matrix_mat_mul(a=a_sm, b=b)
c_value = self.evaluate(c)
expected_c_value = a_sparse_mat.dot(b)
self.assertAllClose(expected_c_value, c_value)
@test_util.run_in_graph_and_eager_modes
def testSparseMatrixMatMulConjugateOutput(self):
for shapes in [[(5, 6), (6, 1)], [(5, 6), (6, 2)]]:
a_indices = np.array([[0, 0], [2, 3]])
a_values = np.array([1.0 + 1.j, 5.0 - 2.j]).astype(np.complex64)
a_dense_shape = shapes[0]
a_sparse_mat = sparse.coo_matrix(
(a_values, (a_indices[:, 0], a_indices[:, 1])), shape=a_dense_shape)
a_dense = a_sparse_mat.todense()
# Will multiply sparse a (shape=shapes[0]) by dense b (shape=shapes[1]).
b = np.random.randn(*shapes[1]).astype(np.complex64)
a_sm = dense_to_csr_sparse_matrix(a_dense)
c = sparse_csr_matrix_ops.sparse_matrix_mat_mul(
a=a_sm, b=b, conjugate_output=True)
c_value = self.evaluate(c)
expected_c_value = self.evaluate(
math_ops.conj(test_util.matmul_without_tf32(a_dense, b)))
self.assertAllClose(expected_c_value, c_value)
@test_util.run_in_graph_and_eager_modes
def testLargeBatchSparseMatrixMatMul(self):
dtypes_to_test = [np.float32, np.complex64]
sparsify = lambda m: m * (m > 0)
for dtype in dtypes_to_test:
for (transpose_a, transpose_b) in ((False, False), (False, True),
(True, False), (True, True)):
for (adjoint_a, adjoint_b) in ((False, False), (False, True),
(True, False), (True, True)):
if (transpose_a and adjoint_a) or (transpose_b and adjoint_b):
continue
for shapes in [[[53, 127, 65], [53, 65, 1]],
[[53, 127, 1], [53, 1, 65]],
[[53, 127, 65], [53, 65, 127]]]:
a_dense_shape = shapes[0]
b_dense_shape = shapes[1]
if transpose_a or adjoint_a:
_swap(a_dense_shape, -2, -1)
if transpose_b or adjoint_b:
_swap(b_dense_shape, -2, -1)
a_mats = sparsify(
(np.random.randn(*a_dense_shape) +
1.j * np.random.randn(*a_dense_shape))).astype(dtype)
b_mats = (np.random.randn(*b_dense_shape) +
1.j * np.random.randn(*b_dense_shape)).astype(dtype)
tf_logging.info(
"testLargeBatchSparseMatrixMatMul transpose_a %s transpose_b "
"%s adjoint_a %s adjoint_b %s" %
(transpose_a, transpose_b, adjoint_a, adjoint_b))
a_sm = dense_to_csr_sparse_matrix(a_mats)
c_t = sparse_csr_matrix_ops.sparse_matrix_mat_mul(
a_sm,
b_mats,
transpose_output=False,
conjugate_output=False,
transpose_a=transpose_a,
transpose_b=transpose_b,
adjoint_a=adjoint_a,
adjoint_b=adjoint_b)
c_dense_t = test_util.matmul_without_tf32(
a_mats,
b_mats,
transpose_a=transpose_a,
transpose_b=transpose_b,
adjoint_a=adjoint_a,
adjoint_b=adjoint_b)
self.assertAllEqual(c_dense_t.shape, c_t.shape)
c_t_value, c_dense_t_value = self.evaluate((c_t, c_dense_t))
self.assertAllClose(
c_t_value, c_dense_t_value, rtol=1e-6, atol=2e-5)
@test_util.run_in_graph_and_eager_modes
def testLargeBatchSparseMatrixMatMulTransposed(self):
dtypes_to_test = [np.float32]
if not test.is_built_with_rocm():
# complex types is not supported on the ROCm platform
dtypes_to_test += [np.complex64]
if test.is_built_with_rocm():
# TODO(rocm): fix this
# This test is currently failing on the ROCm platform
# Ren-enable it once the fix is available
self.skipTest("hipSPARSE all failure on the ROCm platform")
sparsify = lambda m: m * (m > 0)
for dtype in dtypes_to_test:
for (transpose_a, transpose_b) in ((False, False), (False, True),
(True, False), (True, True)):
for (adjoint_a, adjoint_b) in ((False, False), (False, True),
(True, False), (True, True)):
if (transpose_a and adjoint_a) or (transpose_b and adjoint_b):
continue
for shapes in [[[53, 127, 65], [53, 65, 1]],
[[53, 127, 1], [53, 1, 65]],
[[53, 127, 65], [53, 65, 127]]]:
a_dense_shape = shapes[0]
b_dense_shape = shapes[1]
if transpose_a or adjoint_a:
_swap(a_dense_shape, -2, -1)
if transpose_b or adjoint_b:
_swap(b_dense_shape, -2, -1)
a_mats = sparsify(
(np.random.randn(*a_dense_shape) +
1.j * np.random.randn(*a_dense_shape))).astype(dtype)
b_mats = (np.random.randn(*b_dense_shape) +
1.j * np.random.randn(*b_dense_shape)).astype(dtype)
tf_logging.info(
"testLargeBatchSparseMatrixMatMul transpose_a %s transpose_b "
"%s adjoint_a %s adjoint_b %s" %
(transpose_a, transpose_b, adjoint_a, adjoint_b))
a_sm = dense_to_csr_sparse_matrix(a_mats)
c_t = sparse_csr_matrix_ops.sparse_matrix_mat_mul(
a_sm,
b_mats,
transpose_output=True,
conjugate_output=False,
transpose_a=transpose_a,
transpose_b=transpose_b,
adjoint_a=adjoint_a,
adjoint_b=adjoint_b)
# Example: t(adj(a) . b) = t(b) . conj(a)
c_dense_t = test_util.matmul_without_tf32(
math_ops.conj(b_mats) if adjoint_b else b_mats,
math_ops.conj(a_mats) if adjoint_a else a_mats,
transpose_a=not (transpose_b or adjoint_b),
transpose_b=not (transpose_a or adjoint_a),
adjoint_a=False,
adjoint_b=False)
self.assertAllEqual(c_t.shape, c_dense_t.shape)
c_t_value, c_dense_t_value = self.evaluate((c_t, c_dense_t))
self.assertAllClose(
c_t_value, c_dense_t_value, rtol=1e-6, atol=2e-5)
@test_util.run_in_graph_and_eager_modes
def testLargeBatchSparseMatrixMatMulConjugate(self):
if test.is_built_with_rocm():
# complex types are not yet supported on the ROCm platform
self.skipTest("complex type not supported on ROCm")
sparsify = lambda m: m * (m > 0)
a_dense_shape = [53, 65, 127]
b_dense_shape = [53, 127, 67]
a_mats = sparsify(
(np.random.randn(*a_dense_shape) +
1.j * np.random.randn(*a_dense_shape))).astype(np.complex64)
b_mats = (np.random.randn(*b_dense_shape) +
1.j * np.random.randn(*b_dense_shape)).astype(np.complex64)
a_sm = dense_to_csr_sparse_matrix(a_mats)
c_t = sparse_csr_matrix_ops.sparse_matrix_mat_mul(
a_sm, b_mats, conjugate_output=True)
c_dense_t = math_ops.conj(test_util.matmul_without_tf32(a_mats, b_mats))
self.assertAllEqual(c_t.shape, c_dense_t.shape)
c_t_value, c_dense_t_value = self.evaluate((c_t, c_dense_t))
self.assertAllClose(c_t_value, c_dense_t_value, atol=1e-5, rtol=1e-5)
@test_util.run_in_graph_and_eager_modes
def testSparseMatrixSparseMatMul(self):
a_indices = np.array([[0, 0], [2, 3]])
a_values = np.array([1.0, 5.0]).astype(np.float32)
a_dense_shape = [5, 6]
a_sparse_mat = sparse.coo_matrix((a_values,
(a_indices[:, 0], a_indices[:, 1])),
shape=a_dense_shape)
a_dense = a_sparse_mat.todense()
b_indices = np.array([[0, 0], [3, 0], [3, 1]])
b_values = np.array([2.0, 7.0, 8.0]).astype(np.float32)
b_dense_shape = [6, 7]
b_sparse_mat = sparse.coo_matrix((b_values,
(b_indices[:, 0], b_indices[:, 1])),
shape=b_dense_shape)
b_dense = b_sparse_mat.todense()
a_sm = dense_to_csr_sparse_matrix(a_dense)
b_sm = dense_to_csr_sparse_matrix(b_dense)
c_sm = sparse_csr_matrix_ops.sparse_matrix_sparse_mat_mul(
a=a_sm, b=b_sm, type=dtypes.float32)
c_sm_dense = sparse_csr_matrix_ops.csr_sparse_matrix_to_dense(
c_sm, dtypes.float32)
c_sm_dense_value = self.evaluate(c_sm_dense)
expected_c_value = a_sparse_mat.dot(b_sparse_mat).todense()
self.assertAllClose(expected_c_value, c_sm_dense_value)
@test_util.run_in_graph_and_eager_modes
def testSparseMatrixSparseMatMul_NumericZerosNotPruned(self):
# Tests that numeric zeros appearing from the sparse-sparse matrix
# multiplication are not pruned from the sparse structural
a_indices = | np.array([[0, 0], [0, 2]]) | numpy.array |
from __future__ import print_function, division
import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import trapz
import multiprocessing as mp
import h5py
def airy_func(wavelength, cos_th, d, F):
Q = (2. * F / np.pi)**2
airy = 1.0 / (1.0 + Q * np.sin(np.pi * 2.e6 * d * cos_th / wavelength)**2)
return airy
def doppler_calc(w0, mu, temp, v):
sigma = w0 * 3.2765e-5 * np.sqrt(temp / mu)
w = w0 * (1.0 - 3.336e-9 * v)
print(w, sigma, w0, mu, temp, v)
return sigma, w
def gaussian(wavelength, w, sigma, amp=1.):
norm = 1. / (sigma * np.sqrt(2.*np.pi))
exp = np.exp(-0.5 * (wavelength-w)**2 / sigma**2)
return amp * norm * exp
def lorentzian(wavelength, w, gamma, amp=1.):
A = (amp * 0.5 * gamma) / np.pi
return A / ((wavelength - w)**2 + (0.5 * gamma)**2)
def forward_model(r, L, d, F, w0, mu, amp, temp, v, nlambda=1024, sm_ang=False, nprocs=6):
sm_ang = False # you are never coming back!
if type(w0) in [list, tuple]:
if not all([type(x) in [list,tuple] for x in [mu, amp, temp, v]]):
raise ValueError('need to have a list for all spec params')
if not all([len(x) == len(w0) for x in [mu, amp, temp, v]]):
raise ValueError('spec params are not all the same length')
sigma = []
w = []
for i,ww in enumerate(w0):
s, l = doppler_calc(ww, mu[i], temp[i], v[i])
sigma.append(s)
w.append(l)
if nprocs > 1:
wavelength = np.linspace(min(w) - 10.*max(sigma), max(w) + 10.*max(sigma), nlambda)
else:
wavelength = np.linspace(min(w) - 10.*max(sigma), max(w) + 10.*max(sigma), nlambda)[:,np.newaxis]
spec = 0.0
for idx,ww in enumerate(w):
spec += gaussian(wavelength, ww, sigma[idx], amp[idx])
else:
if not all([type(x) not in [list,tuple] for x in [mu, amp, temp, v]]):
raise ValueError('need to have a list or not for all spec params')
sigma, w = doppler_calc(w0, mu, temp, v)
if nprocs > 1:
wavelength = | np.linspace(w - 10.*sigma, w + 10.*sigma, nlambda) | numpy.linspace |
# coding: utf8
import torch
import numpy as np
import os
import warnings
import pandas as pd
from time import time
import wandb
from clinicadl.tools.deep_learning.utils import timeSince
from clinicadl.tools.deep_learning.iotools import check_and_clean
from clinicadl.tools.deep_learning import EarlyStopping, save_checkpoint
from sklearn import metrics
#####################
# CNN train / test #
#####################
def train(model, train_loader, valid_loader, criterion, optimizer, resume, log_dir, model_dir, options, fi=None,
cnn_index=None,
num_cnn=None,
train_begin_time=None, lr_scheduler=None):
"""
Function used to train a CNN.
The best model and checkpoint will be found in the 'best_model_dir' of options.output_dir.
Args:
model: (Module) CNN to be trained
train_loader: (DataLoader) wrapper of the training dataset
valid_loader: (DataLoader) wrapper of the validation dataset
criterion: (loss) function to calculate the loss
optimizer: (torch.optim) optimizer linked to model parameters
resume: (bool) if True, a begun job is resumed
log_dir: (str) path to the folder containing the logs
model_dir: (str) path to the folder containing the models weights and biases
options: (Namespace) ensemble of other options given to the main script.
"""
from tensorboardX import SummaryWriter
from time import time
import wandb
if not resume:
check_and_clean(model_dir)
check_and_clean(log_dir)
# Create writers
writer_train = SummaryWriter(os.path.join(log_dir, 'train'))
writer_valid = SummaryWriter(os.path.join(log_dir, 'validation'))
# Initialize variables
best_valid_accuracy = 0.0
best_valid_loss = np.inf
epoch = options.beginning_epoch
model.train() # set the module to training mode
early_stopping = EarlyStopping('min', min_delta=options.tolerance, patience=options.patience)
mean_loss_valid = None
while epoch < options.epochs and not early_stopping.step(mean_loss_valid):
if fi is not None and options.n_splits is not None:
print("[%s]: At (%d/%d) fold (%d/%d) epoch." % (
timeSince(train_begin_time), fi, options.n_splits, epoch, options.epochs))
else:
print("[%s]: At (%d/%d) epoch." % (timeSince(train_begin_time), epoch, options.epochs))
model.zero_grad()
evaluation_flag = True
step_flag = True
tend = time()
total_time = 0
num_steps = len(train_loader)
for i, data in enumerate(train_loader, 0):
t0 = time()
total_time = total_time + t0 - tend
if options.gpu:
device = torch.device("cuda:{}".format(options.device))
imgs, labels, participant_id, session_id = data['image'].to(device), data['label'].to(device), data[
'participant_id'], data['session_id']
if options.model == 'ROI_GCN':
all_image = data['all_image'].to(device)
else:
imgs, labels, participant_id, session_id = data['image'], data['label'], data['participant_id'], data[
'session_id']
if options.model == 'ROI_GCN':
all_image = data['all_image']
if options.model == 'ROI_GCN':
# roi_image = data['roi_image'].to(device)
train_output = model(imgs, all_image, label_list=labels, id=participant_id, session=session_id, fi=fi,
epoch=epoch)
elif 'gcn' in options.model:
# roi_image = data['roi_image'].to(device)
train_output = model(imgs, label_list=labels, id=participant_id, session=session_id, fi=fi, epoch=epoch)
else:
train_output = model(imgs)
# train_output = model(imgs)
_, predict_batch = train_output.topk(1)
loss = criterion(train_output, labels)
# Back propagation
loss.backward()
# Clips gradient
if options.clip_grad:
grad_norm = torch.nn.utils.clip_grad_norm_(model.parameters(), options.clip_grad)
else:
grad_norm = get_grad_norm(model.parameters())
# for name, param in model.named_parameters():
# if param.requires_grad:
# if param.grad is not None:
# pass
# # print("{}, gradient: {}".format(name, param.grad.mean()))
# else:
# print("{} has not gradient".format(name))
# del imgs, labels
if (i + 1) % options.accumulation_steps == 0:
step_flag = False
optimizer.step()
optimizer.zero_grad()
lr_scheduler.step_update(epoch * num_steps + i)
wandb.log({'grad_norm': grad_norm})
del loss
# Evaluate the model only when no gradients are accumulated
if options.evaluation_steps != 0 and (i + 1) % options.evaluation_steps == 0:
evaluation_flag = False
print('Iteration %d' % i)
_, results_train = test(model, train_loader, options.gpu, criterion, device_index=options.device,
train_begin_time=train_begin_time)
mean_loss_train = results_train["total_loss"] / (len(train_loader) * train_loader.batch_size)
_, results_valid = test(model, valid_loader, options.gpu, criterion, device_index=options.device,
train_begin_time=train_begin_time)
mean_loss_valid = results_valid["total_loss"] / (len(valid_loader) * valid_loader.batch_size)
model.train()
global_step = i + epoch * len(train_loader)
if cnn_index is None:
writer_train.add_scalar('balanced_accuracy', results_train["balanced_accuracy"], global_step)
writer_train.add_scalar('loss', mean_loss_train, global_step)
writer_valid.add_scalar('balanced_accuracy', results_valid["balanced_accuracy"], global_step)
writer_valid.add_scalar('loss', mean_loss_valid, global_step)
wandb.log(
{'train_balanced_accuracy': results_train["balanced_accuracy"],
'train_loss': mean_loss_train,
'valid_balanced_accuracy': results_valid["balanced_accuracy"],
'valid_loss': mean_loss_valid,
'global_step': global_step})
print("[%s]: %s level training accuracy is %f at the end of iteration %d - fake mri count: %d"
% (timeSince(train_begin_time), options.mode, results_train["balanced_accuracy"], i,
data['num_fake_mri']))
print("[%s]: %s level validation accuracy is %f at the end of iteration %d - fake mri count: %d"
% (timeSince(train_begin_time), options.mode, results_valid["balanced_accuracy"], i,
data['num_fake_mri']))
else:
writer_train.add_scalar('{}_model_balanced_accuracy'.format(cnn_index),
results_train["balanced_accuracy"], global_step)
writer_train.add_scalar('{}_model_loss'.format(cnn_index), mean_loss_train, global_step)
writer_valid.add_scalar('{}_model_balanced_accuracy'.format(cnn_index),
results_valid["balanced_accuracy"], global_step)
writer_valid.add_scalar('{}_model_loss'.format(cnn_index), mean_loss_valid, global_step)
wandb.log(
{'{}_model_train_balanced_accuracy'.format(cnn_index): results_train["balanced_accuracy"],
'{}_model_train_loss'.format(cnn_index): mean_loss_train,
'{}_model_valid_balanced_accuracy'.format(cnn_index): results_valid["balanced_accuracy"],
'{}_model_valid_loss'.format(cnn_index): mean_loss_valid,
'global_step': global_step})
print(
"[{}]: ({}/{}) model {} level training accuracy is {} at the end of iteration {}-fake mri count:{}"
.format(timeSince(train_begin_time), cnn_index, num_cnn, options.mode,
results_train["balanced_accuracy"], i, data['num_fake_mri']))
print(
"[{}]: ({}/{}) model {} level validation accuracy is {} at the end of iteration {}-fake mri count:{}"
.format(timeSince(train_begin_time), cnn_index, num_cnn, options.mode,
results_valid["balanced_accuracy"], i, data['num_fake_mri']))
tend = time()
print('[{}]: Mean time per batch loading (train):'.format(timeSince(train_begin_time)),
total_time / len(train_loader) * train_loader.batch_size)
learn_rate = optimizer.param_groups[0]['lr']
print('lr:{}'.format(learn_rate))
wandb.log({'lr': learn_rate})
# If no step has been performed, raise Exception
if step_flag:
raise Exception('The model has not been updated once in the epoch. The accumulation step may be too large.')
# If no evaluation has been performed, warn the user
elif evaluation_flag and options.evaluation_steps != 0:
warnings.warn('Your evaluation steps are too big compared to the size of the dataset.'
'The model is evaluated only once at the end of the epoch')
# Always test the results and save them once at the end of the epoch
model.zero_grad()
print('[%s]: Last checkpoint at the end of the epoch %d' % (timeSince(train_begin_time), epoch))
_, results_train = test(model, train_loader, options.gpu, criterion, device_index=options.device,
train_begin_time=train_begin_time, model_options=options)
mean_loss_train = results_train["total_loss"] / (len(train_loader) * train_loader.batch_size)
_, results_valid = test(model, valid_loader, options.gpu, criterion, device_index=options.device,
train_begin_time=train_begin_time, model_options=options)
mean_loss_valid = results_valid["total_loss"] / (len(valid_loader) * valid_loader.batch_size)
model.train()
global_step = (epoch + 1) * len(train_loader)
if cnn_index is None:
writer_train.add_scalar('balanced_accuracy', results_train["balanced_accuracy"], global_step)
writer_train.add_scalar('loss', mean_loss_train, global_step)
writer_valid.add_scalar('balanced_accuracy', results_valid["balanced_accuracy"], global_step)
writer_valid.add_scalar('loss', mean_loss_valid, global_step)
wandb.log(
{'train_balanced_accuracy': results_train["balanced_accuracy"],
'train_loss': mean_loss_train,
'valid_balanced_accuracy': results_valid["balanced_accuracy"],
'valid_loss': mean_loss_valid,
'global_step': global_step})
print("[%s]: %s level training accuracy is %f at the end of iteration %d"
% (timeSince(train_begin_time), options.mode, results_train["balanced_accuracy"], i))
print("[%s]: %s level validation accuracy is %f at the end of iteration %d"
% (timeSince(train_begin_time), options.mode, results_valid["balanced_accuracy"], i))
else:
writer_train.add_scalar('{}_model_balanced_accuracy'.format(cnn_index),
results_train["balanced_accuracy"], global_step)
writer_train.add_scalar('{}_model_loss'.format(cnn_index), mean_loss_train, global_step)
writer_valid.add_scalar('{}_model_balanced_accuracy'.format(cnn_index),
results_valid["balanced_accuracy"], global_step)
writer_valid.add_scalar('{}_model_loss'.format(cnn_index), mean_loss_valid, global_step)
wandb.log(
{'{}_model_train_balanced_accuracy'.format(cnn_index): results_train["balanced_accuracy"],
'{}_model_train_loss'.format(cnn_index): mean_loss_train,
'{}_model_valid_balanced_accuracy'.format(cnn_index): results_valid["balanced_accuracy"],
'{}_model_valid_loss'.format(cnn_index): mean_loss_valid,
'global_step': global_step})
print("[%s]: %s model %s level training accuracy is %f at the end of iteration %d"
% (timeSince(train_begin_time), cnn_index, options.mode, results_train["balanced_accuracy"], i))
print("[%s]: %s model %s level validation accuracy is %f at the end of iteration %d"
% (timeSince(train_begin_time), cnn_index, options.mode, results_valid["balanced_accuracy"], i))
accuracy_is_best = results_valid["balanced_accuracy"] > best_valid_accuracy
loss_is_best = mean_loss_valid < best_valid_loss
best_valid_accuracy = max(results_valid["balanced_accuracy"], best_valid_accuracy)
best_valid_loss = min(mean_loss_valid, best_valid_loss)
save_checkpoint({'model': model.state_dict(),
'epoch': epoch,
'valid_loss': mean_loss_valid,
'valid_acc': results_valid["balanced_accuracy"]},
accuracy_is_best, loss_is_best,
model_dir)
# Save optimizer state_dict to be able to reload
save_checkpoint({'optimizer': optimizer.state_dict(),
'epoch': epoch,
'name': options.optimizer,
},
False, False,
model_dir,
filename='optimizer.pth.tar')
epoch += 1
os.remove(os.path.join(model_dir, "optimizer.pth.tar"))
os.remove(os.path.join(model_dir, "checkpoint.pth.tar"))
def evaluate_prediction(y, y_pred):
"""
Evaluates different metrics based on the list of true labels and predicted labels.
Args:
y: (list) true labels
y_pred: (list) corresponding predictions
Returns:
(dict) ensemble of metrics
"""
# print(max(y))
if max(y) == 2:
true_class_0 = np.sum((y_pred == 0) & (y == 0))
true_class_1 = np.sum((y_pred == 1) & (y == 1))
true_class_2 = np.sum((y_pred == 2) & (y == 2))
false_class_0 = np.sum((y_pred != 0) & (y == 0))
false_class_1 = np.sum((y_pred != 1) & (y == 1))
false_class_2 = np.sum((y_pred != 2) & (y == 2))
right_class_0 = true_class_0 / (true_class_0 + false_class_0)
right_class_1 = true_class_1 / (true_class_1 + false_class_1)
right_class_2 = true_class_2 / (true_class_2 + false_class_2)
balanced_accuracy = (right_class_0 + right_class_1 + right_class_2) / 3
accuracy = metrics.accuracy_score(y, y_pred)
f1_score = metrics.f1_score(y, y_pred, average='micro')
recall = metrics.recall_score(y, y_pred, average='micro')
precision = metrics.precision_score(y, y_pred, average='micro')
# print('y:{}'.format(y))
# print('y_pred:{}'.format(y_pred))
# print('y:{}'.format(y.shape))
# print('y_pred:{}'.format(y_pred.shape))
# roc_auc = metrics.roc_auc_score(y, y_pred, average='micro', multi_class='ovr')
sensitivity = recall
specificity = 0.0
ppv = precision
npv = 0.0
else:
true_positive = np.sum((y_pred == 1) & (y == 1))
true_negative = np.sum((y_pred == 0) & (y == 0))
false_positive = | np.sum((y_pred == 1) & (y == 0)) | numpy.sum |
"""Bonus Brush Module
This file contains a widget class that allows the user to design their own brush.
Usage:
To use this module, import it and instantiate is as you wish:
from Paint4Brains.GUI.BonusBrush import BonusBrush
brush = BonusBrush()
It then has to be made visible using:
brush.setVisible(True)
"""
from PyQt5.QtWidgets import QVBoxLayout, QHBoxLayout, QLabel, QLineEdit, QPushButton, QWidget, QSizePolicy
from PyQt5.QtCore import Qt, QSize
from PyQt5 import QtGui
from PyQt5.QtGui import QIcon
import numpy as np
import pyqtgraph as pg
import sys
import os
dot = np.array([[1]]).astype(np.int8)
eraser = | np.array([[-1]]) | numpy.array |
import sys
sys.path.append('..')
from neml import interpolate, solvers, models, elasticity, ri_flow, hardening, surfaces, visco_flow, general_flow, creep
from common import *
import unittest
import numpy as np
import numpy.linalg as la
class CommonMatModel(object):
"""
Tests that could be applied to all material models
"""
def test_tangent_proportional_strain(self):
t_n = 0.0
strain_n = np.zeros((6,))
stress_n = np.zeros((6,))
hist_n = self.model.init_store()
u_n = 0.0
p_n = 0.0
for i,m in enumerate(np.linspace(0,1,self.nsteps)):
t_np1 = self.tfinal * m
strain_np1 = self.efinal * m
stress_np1, hist_np1, A_np1, u_np1, p_np1 = self.model.update_sd(
strain_np1, strain_n, self.T, self.T, t_np1, t_n, stress_n, hist_n,
u_n, p_n)
dfn = lambda e: self.model.update_sd(e,
strain_n, self.T, self.T, t_np1, t_n, stress_n, hist_n, u_n, p_n)[0]
num_A = differentiate(dfn, strain_np1, eps = 1.0e-9)
if not np.allclose(num_A, A_np1, rtol = 1e-3, atol = 1e-1):
print(A_np1)
print(num_A)
self.assertTrue(np.allclose(num_A, A_np1, rtol = 1.0e-3, atol = 1.0e-1))
strain_n = strain_np1
stress_n = stress_np1
hist_n = hist_np1
u_n = u_np1
p_n = p_np1
def test_elastic_proportional_strain(self):
t_n = 0.0
strain_n = np.zeros((6,))
stress_n = np.zeros((6,))
hist_n = self.model.init_store()
u_n = 0.0
p_n = 0.0
for i,m in enumerate(np.linspace(0,1,self.nsteps)):
t_np1 = self.tfinal * m
strain_np1 = self.efinal * m
stress_np1, hist_np1, A_np1, u_np1, p_np1 = self.model.update_sd(
strain_np1, strain_n, self.T, self.T, t_np1, t_n, stress_n, hist_n,
u_n, p_n)
estrain = self.model.elastic_strains(stress_np1, self.T, hist_np1)
S = self.elastic.S(self.T)
estrain_num = np.dot(S, stress_np1)
self.assertTrue(np.allclose(estrain, estrain_num))
strain_n = strain_np1
stress_n = stress_np1
hist_n = hist_np1
u_n = u_np1
p_n = p_np1
class TestLinearElastic(CommonMatModel, unittest.TestCase):
"""
Linear elasticity, as a benchmark
"""
def setUp(self):
self.hist0 = np.array([])
self.E = 92000.0
self.nu = 0.3
self.mu = self.E/(2*(1+self.nu))
self.K = self.E/(3*(1-2*self.nu))
self.elastic = elasticity.IsotropicLinearElasticModel(self.mu,
"shear", self.K, "bulk")
self.model = models.SmallStrainElasticity(self.elastic)
self.efinal = np.array([0.1,-0.05,0.02,-0.03,0.1,-0.15])
self.tfinal = 10.0
self.T = 300.0
self.nsteps = 10
class CommonJacobian(object):
"""
Common jacobian tests
"""
def gen_strain(self):
return np.array([0.01,-0.01,0.02,0.03,-0.005,0.01])
def gen_T(self):
return 500.0
def gen_time(self):
return 1.25
def gen_start_strain(self):
return np.zeros((6,))
def gen_start_time(self):
return 0.0
def gen_start_stress(self):
return np.zeros((6,))
def test_jacobian(self):
e_np1 = self.gen_strain()
T_np1 = self.gen_T()
h_n = self.gen_hist()
t_np1 = self.gen_time()
ts = self.model.make_trial_state(e_np1, self.gen_start_strain(), T_np1, T_np1,
t_np1, self.gen_start_time(), self.gen_start_stress(), h_n)
x = self.gen_x()
R, J = self.model.RJ(x, ts)
dfn = lambda y: self.model.RJ(y, ts)[0]
nJ = differentiate(dfn, x)
self.assertTrue(np.allclose(J, nJ, rtol = 1.0e-3, atol = 1e-1))
class TestPerfectPlasticity(unittest.TestCase, CommonMatModel, CommonJacobian):
"""
Test J2 perfect plasticity
"""
def setUp(self):
self.hist0 = np.zeros((0,))
self.E = 92000.0
self.nu = 0.3
self.mu = self.E/(2*(1+self.nu))
self.K = self.E/(3*(1-2*self.nu))
self.s0 = 180.0
self.elastic = elasticity.IsotropicLinearElasticModel(self.mu,
"shear", self.K, "bulk")
surface = surfaces.IsoJ2()
self.model = models.SmallStrainPerfectPlasticity(self.elastic, surface,
self.s0)
self.efinal = np.array([0.1,-0.05,0.02,-0.03,0.1,-0.15])
self.tfinal = 10.0
self.T = 300.0
self.nsteps = 10
def test_properties(self):
self.assertTrue(np.isclose(self.model.ys(self.T), self.s0))
def gen_hist(self):
return np.zeros((0,))
def gen_x(self):
return np.array([50.0,100.0,-25.0,150.0,200.0,-50.0] + list([0.25]))
class TestRIAPlasticityCombinedLinearLinear(unittest.TestCase, CommonMatModel, CommonJacobian):
"""
Test combined isotropic/kinematic hardening with linear rules
"""
def setUp(self):
self.hist0 = np.zeros((13,))
self.E = 92000.0
self.nu = 0.3
self.mu = self.E/(2*(1+self.nu))
self.K = self.E/(3*(1-2*self.nu))
self.s0 = 180.0
self.Kp = 1000.0
self.H = 1000.0
self.elastic = elasticity.IsotropicLinearElasticModel(self.mu,
"shear", self.K, "bulk")
surface = surfaces.IsoKinJ2()
iso = hardening.LinearIsotropicHardeningRule(self.s0, self.Kp)
kin = hardening.LinearKinematicHardeningRule(self.H)
hrule = hardening.CombinedHardeningRule(iso, kin)
flow = ri_flow.RateIndependentAssociativeFlow(surface, hrule)
self.model = models.SmallStrainRateIndependentPlasticity(self.elastic, flow)
self.efinal = np.array([0.1,-0.05,0.02,-0.03,0.1,-0.15])
self.tfinal = 10.0
self.T = 300.0
self.nsteps = 10
def gen_hist(self):
h = np.array(range(1,14)) / 15.0
h[:6] = make_dev(h[:6])
h[7:] = make_dev(h[7:])
return h
def gen_x(self):
return np.array(list(self.gen_hist()) + list([0.25]))
class TestRIAPlasticityJ2Linear(unittest.TestCase, CommonMatModel, CommonJacobian):
"""
Test the rate-independent plasticity algorithm with a linearly
isotropically hardening yield surface.
"""
def setUp(self):
self.hist0 = np.zeros((7,))
self.E = 92000.0
self.nu = 0.3
self.mu = self.E/(2*(1+self.nu))
self.K = self.E/(3*(1-2*self.nu))
self.s0 = 180.0
self.Kp = self.E / 100
self.elastic = elasticity.IsotropicLinearElasticModel(self.mu,
"shear", self.K, "bulk")
surface = surfaces.IsoJ2()
hrule = hardening.LinearIsotropicHardeningRule(self.s0, self.Kp)
flow = ri_flow.RateIndependentAssociativeFlow(surface, hrule)
self.model = models.SmallStrainRateIndependentPlasticity(self.elastic, flow)
self.efinal = np.array([0.1,-0.05,0.02,-0.03,0.1,-0.15])
self.tfinal = 10.0
self.T = 300.0
self.nsteps = 10
def gen_hist(self):
return np.array(range(1,8)) / 8.0
def gen_x(self):
return np.array(range(1,9)) / 9.0
class TestRIAPlasticityJ2Voce(unittest.TestCase, CommonMatModel, CommonJacobian):
"""
Test the rate-independent plasticity algorithm with a Voce
isotropically hardening yield surface.
"""
def setUp(self):
self.hist0 = np.zeros((7,))
self.E = 92000.0
self.nu = 0.3
self.mu = self.E/(2*(1+self.nu))
self.K = self.E/(3*(1-2*self.nu))
self.s0 = 180.0
self.R = 150.0
self.d = 10.0
self.elastic = elasticity.IsotropicLinearElasticModel(self.mu,
"shear", self.K, "bulk")
surface = surfaces.IsoJ2()
hrule = hardening.VoceIsotropicHardeningRule(self.s0, self.R, self.d)
flow = ri_flow.RateIndependentAssociativeFlow(surface, hrule)
self.model = models.SmallStrainRateIndependentPlasticity(self.elastic, flow)
self.efinal = np.array([0.1,-0.05,0.02,-0.03,0.1,-0.15])
self.tfinal = 10.0
self.T = 300.0
self.nsteps = 10
def gen_hist(self):
return np.array(range(1,8)) / 8.0
def gen_x(self):
return np.array(range(1,9)) / 9.0
class TestRIChabocheLinear(unittest.TestCase, CommonMatModel, CommonJacobian):
"""
Test Chaboche with linear isotropic hardening
"""
def setUp(self):
self.hist0 = np.zeros((13,))
self.E = 92000.0
self.nu = 0.3
self.mu = self.E/(2*(1+self.nu))
self.K = self.E/(3*(1-2*self.nu))
self.s0 = 180.0
self.Kp = 1000.0
self.n = 2
self.cs = [10.0, 2.0]
self.rs = [5.0, 1.0]
self.gmodels = [hardening.ConstantGamma(g) for g in self.rs]
self.As = [0.0] * self.n
self.ns = [1.0] * self.n
self.elastic = elasticity.IsotropicLinearElasticModel(self.mu,
"shear", self.K, "bulk")
surface = surfaces.IsoKinJ2()
iso = hardening.LinearIsotropicHardeningRule(self.s0, self.Kp)
hmodel = hardening.Chaboche(iso, self.cs, self.gmodels,
self.As, self.ns)
flow = ri_flow.RateIndependentNonAssociativeHardening(surface, hmodel)
self.model = models.SmallStrainRateIndependentPlasticity(self.elastic, flow)
self.efinal = np.array([0.1,-0.05,0.02,-0.03,0.1,-0.15])
self.tfinal = 10.0
self.T = 300.0
self.nsteps = 30
def gen_hist(self):
h = np.array(range(1,6+1+6*self.n+1)) / (8*self.n)
h[:6] = make_dev(h[:6])
for i in range(self.n):
h[7+i*6:7+(i+1)*6] = make_dev(h[7+i*6:7+(i+1)*6])
return h
def gen_x(self):
return np.array(list(self.gen_hist()) + [0.1])
# Something funny with the Jacobian here
class TestCreepPlasticityJ2LinearPowerLaw(unittest.TestCase, CommonMatModel):
"""
Test the combined creep/plasticity algorithm with J2 plasticity with
isotropic hardening and power law creep
"""
def setUp(self):
self.hist0 = np.zeros((13,))
self.A = 1.85e-10
self.n = 2.5
self.smodel = creep.PowerLawCreep(self.A, self.n)
self.cmodel = creep.J2CreepModel(self.smodel)
self.E = 150000.0
self.nu = 0.3
self.sY = 200.0
self.H = self.E / 50.0
self.elastic = elasticity.IsotropicLinearElasticModel(self.E, "youngs",
self.nu, "poissons")
self.surface = surfaces.IsoJ2()
self.iso = hardening.LinearIsotropicHardeningRule(self.sY, self.H)
self.flow = ri_flow.RateIndependentAssociativeFlow(self.surface, self.iso)
self.pmodel = models.SmallStrainRateIndependentPlasticity(self.elastic,
self.flow)
self.model = models.SmallStrainCreepPlasticity(self.elastic, self.pmodel,
self.cmodel)
self.efinal = np.array([0.1,-0.05,0.02,-0.03,0.1,-0.15])
self.tfinal = 10.0
self.T = 300.0
self.nsteps = 10
def gen_hist(self):
return np.array(range(1,7) + [1.0] + range(1,7)) / 7.0
def gen_x(self):
return np.array(range(1,7)) / 7.0
def gen_start_stress(self):
return np.zeros((6,)) + 100.0
def gen_start_strain(self):
return np.zeros((6,)) + 0.01
class TestCreepPlasticityPerfect(unittest.TestCase, CommonMatModel):
"""
Test the combined creep/plasticity algorithm with J2 plasticity with
perfect plasticity
"""
def setUp(self):
self.hist0 = | np.zeros((6,)) | numpy.zeros |
from __future__ import print_function, division, absolute_import
import copy as copylib
import sys
# unittest only added in 3.4 self.subTest()
if sys.version_info[0] < 3 or sys.version_info[1] < 4:
import unittest2 as unittest
else:
import unittest
# unittest.mock is not available in 2.7 (though unittest2 might contain it?)
try:
import unittest.mock as mock
except ImportError:
import mock
import matplotlib
matplotlib.use('Agg') # fix execution of tests involving matplotlib on travis
import numpy as np
import imgaug as ia
import imgaug.augmenters as iaa
from imgaug.testutils import reseed
import imgaug.random as iarandom
NP_VERSION = np.__version__
IS_NP_117_OR_HIGHER = (
NP_VERSION.startswith("2.")
or NP_VERSION.startswith("1.25")
or NP_VERSION.startswith("1.24")
or NP_VERSION.startswith("1.23")
or NP_VERSION.startswith("1.22")
or NP_VERSION.startswith("1.21")
or NP_VERSION.startswith("1.20")
or NP_VERSION.startswith("1.19")
or NP_VERSION.startswith("1.18")
or NP_VERSION.startswith("1.17")
)
class _Base(unittest.TestCase):
def setUp(self):
reseed()
class TestConstants(_Base):
def test_supports_new_np_rng_style_is_true(self):
assert iarandom.SUPPORTS_NEW_NP_RNG_STYLE is IS_NP_117_OR_HIGHER
def test_global_rng(self):
iarandom.get_global_rng() # creates global RNG upon first call
assert iarandom.GLOBAL_RNG is not None
class TestRNG(_Base):
@mock.patch("imgaug.random.normalize_generator_")
def test___init___calls_normalize_mocked(self, mock_norm):
_ = iarandom.RNG(0)
mock_norm.assert_called_once_with(0)
def test___init___with_rng(self):
rng1 = iarandom.RNG(0)
rng2 = iarandom.RNG(rng1)
assert rng2.generator is rng1.generator
@mock.patch("imgaug.random.get_generator_state")
def test_state_getter_mocked(self, mock_get):
mock_get.return_value = "mock"
rng = iarandom.RNG(0)
result = rng.state
assert result == "mock"
mock_get.assert_called_once_with(rng.generator)
@mock.patch("imgaug.random.RNG.set_state_")
def test_state_setter_mocked(self, mock_set):
rng = iarandom.RNG(0)
state = {"foo"}
rng.state = state
mock_set.assert_called_once_with(state)
@mock.patch("imgaug.random.set_generator_state_")
def test_set_state__mocked(self, mock_set):
rng = iarandom.RNG(0)
state = {"foo"}
result = rng.set_state_(state)
assert result is rng
mock_set.assert_called_once_with(rng.generator, state)
@mock.patch("imgaug.random.set_generator_state_")
def test_use_state_of__mocked(self, mock_set):
rng1 = iarandom.RNG(0)
rng2 = mock.MagicMock()
state = {"foo"}
rng2.state = state
result = rng1.use_state_of_(rng2)
assert result == rng1
mock_set.assert_called_once_with(rng1.generator, state)
@mock.patch("imgaug.random.get_global_rng")
def test_is_global__is_global__rng_mocked(self, mock_get):
rng1 = iarandom.RNG(0)
rng2 = iarandom.RNG(rng1.generator)
mock_get.return_value = rng2
assert rng1.is_global_rng() is True
@mock.patch("imgaug.random.get_global_rng")
def test_is_global_rng__is_not_global__mocked(self, mock_get):
rng1 = iarandom.RNG(0)
# different instance with same state/seed should still be viewed as
# different by the method
rng2 = iarandom.RNG(0)
mock_get.return_value = rng2
assert rng1.is_global_rng() is False
@mock.patch("imgaug.random.get_global_rng")
def test_equals_global_rng__is_global__mocked(self, mock_get):
rng1 = iarandom.RNG(0)
rng2 = iarandom.RNG(0)
mock_get.return_value = rng2
assert rng1.equals_global_rng() is True
@mock.patch("imgaug.random.get_global_rng")
def test_equals_global_rng__is_not_global__mocked(self, mock_get):
rng1 = iarandom.RNG(0)
rng2 = iarandom.RNG(1)
mock_get.return_value = rng2
assert rng1.equals_global_rng() is False
@mock.patch("imgaug.random.generate_seed_")
def test_generate_seed__mocked(self, mock_gen):
rng = iarandom.RNG(0)
mock_gen.return_value = -1
seed = rng.generate_seed_()
assert seed == -1
mock_gen.assert_called_once_with(rng.generator)
@mock.patch("imgaug.random.generate_seeds_")
def test_generate_seeds__mocked(self, mock_gen):
rng = iarandom.RNG(0)
mock_gen.return_value = [-1, -2]
seeds = rng.generate_seeds_(2)
assert seeds == [-1, -2]
mock_gen.assert_called_once_with(rng.generator, 2)
@mock.patch("imgaug.random.reset_generator_cache_")
def test_reset_cache__mocked(self, mock_reset):
rng = iarandom.RNG(0)
result = rng.reset_cache_()
assert result is rng
mock_reset.assert_called_once_with(rng.generator)
@mock.patch("imgaug.random.derive_generators_")
def test_derive_rng__mocked(self, mock_derive):
gen = iarandom.convert_seed_to_generator(0)
mock_derive.return_value = [gen]
rng = iarandom.RNG(0)
result = rng.derive_rng_()
assert result.generator is gen
mock_derive.assert_called_once_with(rng.generator, 1)
@mock.patch("imgaug.random.derive_generators_")
def test_derive_rngs__mocked(self, mock_derive):
gen1 = iarandom.convert_seed_to_generator(0)
gen2 = iarandom.convert_seed_to_generator(1)
mock_derive.return_value = [gen1, gen2]
rng = iarandom.RNG(0)
result = rng.derive_rngs_(2)
assert result[0].generator is gen1
assert result[1].generator is gen2
mock_derive.assert_called_once_with(rng.generator, 2)
@mock.patch("imgaug.random.is_generator_equal_to")
def test_equals_mocked(self, mock_equal):
mock_equal.return_value = "foo"
rng1 = iarandom.RNG(0)
rng2 = iarandom.RNG(1)
result = rng1.equals(rng2)
assert result == "foo"
mock_equal.assert_called_once_with(rng1.generator, rng2.generator)
def test_equals_identical_generators(self):
rng1 = iarandom.RNG(0)
rng2 = iarandom.RNG(rng1)
assert rng1.equals(rng2)
def test_equals_with_similar_generators(self):
rng1 = iarandom.RNG(0)
rng2 = iarandom.RNG(0)
assert rng1.equals(rng2)
def test_equals_with_different_generators(self):
rng1 = iarandom.RNG(0)
rng2 = iarandom.RNG(1)
assert not rng1.equals(rng2)
def test_equals_with_advanced_generator(self):
rng1 = iarandom.RNG(0)
rng2 = iarandom.RNG(0)
rng2.advance_()
assert not rng1.equals(rng2)
@mock.patch("imgaug.random.advance_generator_")
def test_advance__mocked(self, mock_advance):
rng = iarandom.RNG(0)
result = rng.advance_()
assert result is rng
mock_advance.assert_called_once_with(rng.generator)
@mock.patch("imgaug.random.copy_generator")
def test_copy_mocked(self, mock_copy):
rng1 = iarandom.RNG(0)
rng2 = iarandom.RNG(1)
mock_copy.return_value = rng2.generator
result = rng1.copy()
assert result.generator is rng2.generator
mock_copy.assert_called_once_with(rng1.generator)
@mock.patch("imgaug.random.RNG.copy")
@mock.patch("imgaug.random.RNG.is_global_rng")
def test_copy_unless_global_rng__is_global__mocked(self, mock_is_global,
mock_copy):
rng = iarandom.RNG(0)
mock_is_global.return_value = True
mock_copy.return_value = "foo"
result = rng.copy_unless_global_rng()
assert result is rng
mock_is_global.assert_called_once_with()
assert mock_copy.call_count == 0
@mock.patch("imgaug.random.RNG.copy")
@mock.patch("imgaug.random.RNG.is_global_rng")
def test_copy_unless_global_rng__is_not_global__mocked(self, mock_is_global,
mock_copy):
rng = iarandom.RNG(0)
mock_is_global.return_value = False
mock_copy.return_value = "foo"
result = rng.copy_unless_global_rng()
assert result is "foo"
mock_is_global.assert_called_once_with()
mock_copy.assert_called_once_with()
def test_duplicate(self):
rng = iarandom.RNG(0)
rngs = rng.duplicate(1)
assert rngs == [rng]
def test_duplicate_two_entries(self):
rng = iarandom.RNG(0)
rngs = rng.duplicate(2)
assert rngs == [rng, rng]
@mock.patch("imgaug.random.create_fully_random_generator")
def test_create_fully_random_mocked(self, mock_create):
gen = iarandom.convert_seed_to_generator(0)
mock_create.return_value = gen
rng = iarandom.RNG.create_fully_random()
mock_create.assert_called_once_with()
assert rng.generator is gen
@mock.patch("imgaug.random.derive_generators_")
def test_create_pseudo_random__mocked(self, mock_get):
rng_glob = iarandom.get_global_rng()
rng = iarandom.RNG(0)
mock_get.return_value = [rng.generator]
result = iarandom.RNG.create_pseudo_random_()
assert result.generator is rng.generator
mock_get.assert_called_once_with(rng_glob.generator, 1)
@mock.patch("imgaug.random.polyfill_integers")
def test_integers_mocked(self, mock_func):
mock_func.return_value = "foo"
rng = iarandom.RNG(0)
result = rng.integers(low=0, high=1, size=(1,), dtype="int64",
endpoint=True)
assert result == "foo"
mock_func.assert_called_once_with(
rng.generator, low=0, high=1, size=(1,), dtype="int64",
endpoint=True)
@mock.patch("imgaug.random.polyfill_random")
def test_random_mocked(self, mock_func):
mock_func.return_value = "foo"
rng = iarandom.RNG(0)
out = np.zeros((1,), dtype="float64")
result = rng.random(size=(1,), dtype="float64", out=out)
assert result == "foo"
mock_func.assert_called_once_with(
rng.generator, size=(1,), dtype="float64", out=out)
# TODO below test for generator methods are all just mock-based, add
# non-mocked versions
def test_choice_mocked(self):
self._test_sampling_func("choice", a=[1, 2, 3], size=(1,),
replace=False, p=[0.1, 0.2, 0.7])
def test_bytes_mocked(self):
self._test_sampling_func("bytes", length=[10])
def test_shuffle_mocked(self):
mock_gen = mock.MagicMock()
rng = iarandom.RNG(0)
rng.generator = mock_gen
rng.shuffle([1, 2, 3])
mock_gen.shuffle.assert_called_once_with([1, 2, 3])
def test_permutation_mocked(self):
mock_gen = mock.MagicMock()
rng = iarandom.RNG(0)
rng.generator = mock_gen
mock_gen.permutation.return_value = "foo"
result = rng.permutation([1, 2, 3])
assert result == "foo"
mock_gen.permutation.assert_called_once_with([1, 2, 3])
def test_beta_mocked(self):
self._test_sampling_func("beta", a=1.0, b=2.0, size=(1,))
def test_binomial_mocked(self):
self._test_sampling_func("binomial", n=10, p=0.1, size=(1,))
def test_chisquare_mocked(self):
self._test_sampling_func("chisquare", df=2, size=(1,))
def test_dirichlet_mocked(self):
self._test_sampling_func("dirichlet", alpha=0.1, size=(1,))
def test_exponential_mocked(self):
self._test_sampling_func("exponential", scale=1.1, size=(1,))
def test_f_mocked(self):
self._test_sampling_func("f", dfnum=1, dfden=2, size=(1,))
def test_gamma_mocked(self):
self._test_sampling_func("gamma", shape=1, scale=1.2, size=(1,))
def test_geometric_mocked(self):
self._test_sampling_func("geometric", p=0.5, size=(1,))
def test_gumbel_mocked(self):
self._test_sampling_func("gumbel", loc=0.1, scale=1.1, size=(1,))
def test_hypergeometric_mocked(self):
self._test_sampling_func("hypergeometric", ngood=2, nbad=4, nsample=6,
size=(1,))
def test_laplace_mocked(self):
self._test_sampling_func("laplace", loc=0.5, scale=1.5, size=(1,))
def test_logistic_mocked(self):
self._test_sampling_func("logistic", loc=0.5, scale=1.5, size=(1,))
def test_lognormal_mocked(self):
self._test_sampling_func("lognormal", mean=0.5, sigma=1.5, size=(1,))
def test_logseries_mocked(self):
self._test_sampling_func("logseries", p=0.5, size=(1,))
def test_multinomial_mocked(self):
self._test_sampling_func("multinomial", n=5, pvals=0.5, size=(1,))
def test_multivariate_normal_mocked(self):
self._test_sampling_func("multivariate_normal", mean=0.5, cov=1.0,
size=(1,), check_valid="foo", tol=1e-2)
def test_negative_binomial_mocked(self):
self._test_sampling_func("negative_binomial", n=10, p=0.5, size=(1,))
def test_noncentral_chisquare_mocked(self):
self._test_sampling_func("noncentral_chisquare", df=0.5, nonc=1.0,
size=(1,))
def test_noncentral_f_mocked(self):
self._test_sampling_func("noncentral_f", dfnum=0.5, dfden=1.5,
nonc=2.0, size=(1,))
def test_normal_mocked(self):
self._test_sampling_func("normal", loc=0.5, scale=1.0, size=(1,))
def test_pareto_mocked(self):
self._test_sampling_func("pareto", a=0.5, size=(1,))
def test_poisson_mocked(self):
self._test_sampling_func("poisson", lam=1.5, size=(1,))
def test_power_mocked(self):
self._test_sampling_func("power", a=0.5, size=(1,))
def test_rayleigh_mocked(self):
self._test_sampling_func("rayleigh", scale=1.5, size=(1,))
def test_standard_cauchy_mocked(self):
self._test_sampling_func("standard_cauchy", size=(1,))
def test_standard_exponential_np117_mocked(self):
fname = "standard_exponential"
arr = np.zeros((1,), dtype="float16")
args = []
kwargs = {"size": (1,), "dtype": "float16", "method": "foo",
"out": arr}
mock_gen = mock.MagicMock()
getattr(mock_gen, fname).return_value = "foo"
rng = iarandom.RNG(0)
rng.generator = mock_gen
rng._is_new_rng_style = True
result = getattr(rng, fname)(*args, **kwargs)
assert result == "foo"
getattr(mock_gen, fname).assert_called_once_with(*args, **kwargs)
def test_standard_exponential_np116_mocked(self):
fname = "standard_exponential"
arr_out = np.zeros((1,), dtype="float16")
arr_result = np.ones((1,), dtype="float16")
def _side_effect(x):
return arr_result
args = []
kwargs = {"size": (1,), "dtype": "float16", "method": "foo",
"out": arr_out}
kwargs_subcall = {"size": (1,)}
mock_gen = mock.MagicMock()
mock_gen.astype.side_effect = _side_effect
getattr(mock_gen, fname).return_value = mock_gen
rng = iarandom.RNG(0)
rng.generator = mock_gen
rng._is_new_rng_style = False
result = getattr(rng, fname)(*args, **kwargs)
getattr(mock_gen, fname).assert_called_once_with(*args,
**kwargs_subcall)
mock_gen.astype.assert_called_once_with("float16")
assert np.allclose(result, arr_result)
assert np.allclose(arr_out, arr_result)
def test_standard_gamma_np117_mocked(self):
fname = "standard_gamma"
arr = np.zeros((1,), dtype="float16")
args = []
kwargs = {"shape": 1.0, "size": (1,), "dtype": "float16", "out": arr}
mock_gen = mock.MagicMock()
getattr(mock_gen, fname).return_value = "foo"
rng = iarandom.RNG(0)
rng.generator = mock_gen
rng._is_new_rng_style = True
result = getattr(rng, fname)(*args, **kwargs)
assert result == "foo"
getattr(mock_gen, fname).assert_called_once_with(*args, **kwargs)
def test_standard_gamma_np116_mocked(self):
fname = "standard_gamma"
arr_out = np.zeros((1,), dtype="float16")
arr_result = np.ones((1,), dtype="float16")
def _side_effect(x):
return arr_result
args = []
kwargs = {"shape": 1.0, "size": (1,), "dtype": "float16",
"out": arr_out}
kwargs_subcall = {"shape": 1.0, "size": (1,)}
mock_gen = mock.MagicMock()
mock_gen.astype.side_effect = _side_effect
getattr(mock_gen, fname).return_value = mock_gen
rng = iarandom.RNG(0)
rng.generator = mock_gen
rng._is_new_rng_style = False
result = getattr(rng, fname)(*args, **kwargs)
getattr(mock_gen, fname).assert_called_once_with(*args,
**kwargs_subcall)
mock_gen.astype.assert_called_once_with("float16")
assert np.allclose(result, arr_result)
assert np.allclose(arr_out, arr_result)
def test_standard_normal_np117_mocked(self):
fname = "standard_normal"
arr = np.zeros((1,), dtype="float16")
args = []
kwargs = {"size": (1,), "dtype": "float16", "out": arr}
mock_gen = mock.MagicMock()
getattr(mock_gen, fname).return_value = "foo"
rng = iarandom.RNG(0)
rng.generator = mock_gen
rng._is_new_rng_style = True
result = getattr(rng, fname)(*args, **kwargs)
assert result == "foo"
getattr(mock_gen, fname).assert_called_once_with(*args, **kwargs)
def test_standard_normal_np116_mocked(self):
fname = "standard_normal"
arr_out = np.zeros((1,), dtype="float16")
arr_result = np.ones((1,), dtype="float16")
def _side_effect(x):
return arr_result
args = []
kwargs = {"size": (1,), "dtype": "float16", "out": arr_out}
kwargs_subcall = {"size": (1,)}
mock_gen = mock.MagicMock()
mock_gen.astype.side_effect = _side_effect
getattr(mock_gen, fname).return_value = mock_gen
rng = iarandom.RNG(0)
rng.generator = mock_gen
rng._is_new_rng_style = False
result = getattr(rng, fname)(*args, **kwargs)
getattr(mock_gen, fname).assert_called_once_with(*args,
**kwargs_subcall)
mock_gen.astype.assert_called_once_with("float16")
assert np.allclose(result, arr_result)
assert np.allclose(arr_out, arr_result)
def test_standard_t_mocked(self):
self._test_sampling_func("standard_t", df=1.5, size=(1,))
def test_triangular_mocked(self):
self._test_sampling_func("triangular", left=1.0, mode=1.5, right=2.0,
size=(1,))
def test_uniform_mocked(self):
self._test_sampling_func("uniform", low=0.5, high=1.5, size=(1,))
def test_vonmises_mocked(self):
self._test_sampling_func("vonmises", mu=1.0, kappa=1.5, size=(1,))
def test_wald_mocked(self):
self._test_sampling_func("wald", mean=0.5, scale=1.0, size=(1,))
def test_weibull_mocked(self):
self._test_sampling_func("weibull", a=1.0, size=(1,))
def test_zipf_mocked(self):
self._test_sampling_func("zipf", a=1.0, size=(1,))
@classmethod
def _test_sampling_func(cls, fname, *args, **kwargs):
mock_gen = mock.MagicMock()
getattr(mock_gen, fname).return_value = "foo"
rng = iarandom.RNG(0)
rng.generator = mock_gen
result = getattr(rng, fname)(*args, **kwargs)
assert result == "foo"
getattr(mock_gen, fname).assert_called_once_with(*args, **kwargs)
#
# outdated methods from RandomState
#
def test_rand_mocked(self):
self._test_sampling_func_alias("rand", "random", 1, 2, 3)
def test_randint_mocked(self):
self._test_sampling_func_alias("randint", "integers", 0, 100)
def randn(self):
self._test_sampling_func_alias("randn", "standard_normal", 1, 2, 3)
def random_integers(self):
self._test_sampling_func_alias("random_integers", "integers", 1, 2)
def random_sample(self):
self._test_sampling_func_alias("random_sample", "uniform", (1, 2, 3))
def tomaxint(self):
self._test_sampling_func_alias("tomaxint", "integers", (1, 2, 3))
def test_rand(self):
result = iarandom.RNG(0).rand(10, 20, 3)
assert result.dtype.name == "float32"
assert result.shape == (10, 20, 3)
assert np.all(result >= 0.0)
assert np.all(result <= 1.0)
assert np.any(result > 0.0)
assert np.any(result < 1.0)
def test_randint(self):
result = iarandom.RNG(0).randint(10, 100, size=(10, 20, 3))
assert result.dtype.name == "int32"
assert result.shape == (10, 20, 3)
assert np.all(result >= 10)
assert np.all(result <= 99)
assert np.any(result > 10)
assert np.any(result < 99)
def test_randn(self):
result = iarandom.RNG(0).randn(10, 50, 3)
assert result.dtype.name == "float32"
assert result.shape == (10, 50, 3)
assert np.any(result > 0.5)
assert np.any(result < -0.5)
assert np.average(np.logical_or(result < 2.0, result > -2.0)) > 0.5
def test_random_integers(self):
result = iarandom.RNG(0).random_integers(10, 100, size=(10, 20, 3))
assert result.dtype.name == "int32"
assert result.shape == (10, 20, 3)
assert np.all(result >= 10)
assert np.all(result <= 100)
assert np.any(result > 10)
assert np.any(result < 100)
def test_random_integers__no_high(self):
result = iarandom.RNG(0).random_integers(100, size=(10, 20, 3))
assert result.dtype.name == "int32"
assert result.shape == (10, 20, 3)
assert np.all(result >= 1)
assert np.all(result <= 100)
assert np.any(result > 1)
assert np.any(result < 100)
def test_random_sample(self):
result = iarandom.RNG(0).random_sample((10, 20, 3))
assert result.dtype.name == "float64"
assert result.shape == (10, 20, 3)
assert np.all(result >= 0.0)
assert np.all(result <= 1.0)
assert np.any(result > 0.0)
assert np.any(result < 1.0)
def test_tomaxint(self):
result = iarandom.RNG(0).tomaxint((10, 200, 3))
assert result.dtype.name == "int32"
assert result.shape == (10, 200, 3)
assert np.all(result >= 0)
assert np.any(result > 10000)
@classmethod
def _test_sampling_func_alias(cls, fname_alias, fname_subcall, *args,
**kwargs):
rng = iarandom.RNG(0)
mock_func = mock.Mock()
mock_func.return_value = "foo"
setattr(rng, fname_subcall, mock_func)
result = getattr(rng, fname_alias)(*args, **kwargs)
assert result == "foo"
assert mock_func.call_count == 1
class Test_supports_new_numpy_rng_style(_Base):
def test_call(self):
assert iarandom.supports_new_numpy_rng_style() is IS_NP_117_OR_HIGHER
class Test_get_global_rng(_Base):
def test_call(self):
iarandom.seed(0)
rng = iarandom.get_global_rng()
expected = iarandom.RNG(0)
assert rng is not None
assert rng.equals(expected)
class Test_seed(_Base):
@mock.patch("imgaug.random._seed_np117_")
@mock.patch("imgaug.random._seed_np116_")
def test_mocked_call(self, mock_np116, mock_np117):
iarandom.seed(1)
if IS_NP_117_OR_HIGHER:
mock_np117.assert_called_once_with(1)
assert mock_np116.call_count == 0
else:
mock_np116.assert_called_once_with(1)
assert mock_np117.call_count == 0
def test_integrationtest(self):
iarandom.seed(1)
assert iarandom.GLOBAL_RNG.equals(iarandom.RNG(1))
def test_seed_affects_augmenters_created_after_its_call(self):
image = np.full((50, 50, 3), 128, dtype=np.uint8)
images_aug = []
for _ in np.arange(5):
iarandom.seed(100)
aug = iaa.AdditiveGaussianNoise(scale=50, per_channel=True)
images_aug.append(aug(image=image))
# assert all images identical
for other_image_aug in images_aug[1:]:
assert np.array_equal(images_aug[0], other_image_aug)
# but different seed must lead to different image
iarandom.seed(101)
aug = iaa.AdditiveGaussianNoise(scale=50, per_channel=True)
image_aug = aug(image=image)
assert not np.array_equal(images_aug[0], image_aug)
def test_seed_affects_augmenters_created_before_its_call(self):
image = np.full((50, 50, 3), 128, dtype=np.uint8)
images_aug = []
for _ in np.arange(5):
aug = iaa.AdditiveGaussianNoise(scale=50, per_channel=True)
iarandom.seed(100)
images_aug.append(aug(image=image))
# assert all images identical
for other_image_aug in images_aug[1:]:
assert np.array_equal(images_aug[0], other_image_aug)
# but different seed must lead to different image
aug = iaa.AdditiveGaussianNoise(scale=50, per_channel=True)
iarandom.seed(101)
image_aug = aug(image=image)
assert not np.array_equal(images_aug[0], image_aug)
class Test_normalize_generator(_Base):
@mock.patch("imgaug.random.normalize_generator_")
def test_mocked_call(self, mock_subfunc):
mock_subfunc.return_value = "foo"
inputs = ["bar"]
result = iarandom.normalize_generator(inputs)
assert mock_subfunc.call_count == 1
assert mock_subfunc.call_args[0][0] is not inputs
assert mock_subfunc.call_args[0][0] == inputs
assert result == "foo"
class Test_normalize_generator_(_Base):
@mock.patch("imgaug.random._normalize_generator_np117_")
@mock.patch("imgaug.random._normalize_generator_np116_")
def test_mocked_call(self, mock_np116, mock_np117):
mock_np116.return_value = "np116"
mock_np117.return_value = "np117"
result = iarandom.normalize_generator_(None)
if IS_NP_117_OR_HIGHER:
assert result == "np117"
mock_np117.assert_called_once_with(None)
assert mock_np116.call_count == 0
else:
assert result == "np116"
mock_np116.assert_called_once_with(None)
assert mock_np117.call_count == 0
def test_called_with_none(self):
result = iarandom.normalize_generator_(None)
assert result is iarandom.get_global_rng().generator
@unittest.skipIf(not IS_NP_117_OR_HIGHER,
"SeedSequence does not exist in numpy <=1.16")
def test_called_with_seed_sequence(self):
seedseq = np.random.SeedSequence(0)
result = iarandom.normalize_generator_(seedseq)
expected = np.random.Generator(
iarandom.BIT_GENERATOR(np.random.SeedSequence(0)))
assert iarandom.is_generator_equal_to(result, expected)
@unittest.skipIf(not IS_NP_117_OR_HIGHER,
"BitGenerator does not exist in numpy <=1.16")
def test_called_with_bit_generator(self):
bgen = iarandom.BIT_GENERATOR(np.random.SeedSequence(0))
result = iarandom.normalize_generator_(bgen)
assert result.bit_generator is bgen
@unittest.skipIf(not IS_NP_117_OR_HIGHER,
"Generator does not exist in numpy <=1.16")
def test_called_with_generator(self):
gen = np.random.Generator(
iarandom.BIT_GENERATOR(np.random.SeedSequence(0))
)
result = iarandom.normalize_generator_(gen)
assert result is gen
def test_called_with_random_state(self):
rs = np.random.RandomState(0)
result = iarandom.normalize_generator_(rs)
if IS_NP_117_OR_HIGHER:
seed = iarandom.generate_seed_(np.random.RandomState(0))
expected = iarandom.convert_seed_to_generator(seed)
assert iarandom.is_generator_equal_to(result, expected)
else:
assert result is rs
def test_called_int(self):
seed = 0
result = iarandom.normalize_generator_(seed)
expected = iarandom.convert_seed_to_generator(seed)
assert iarandom.is_generator_equal_to(result, expected)
class Test_convert_seed_to_generator(_Base):
@mock.patch("imgaug.random._convert_seed_to_generator_np117")
@mock.patch("imgaug.random._convert_seed_to_generator_np116")
def test_mocked_call(self, mock_np116, mock_np117):
mock_np116.return_value = "np116"
mock_np117.return_value = "np117"
result = iarandom.convert_seed_to_generator(1)
if IS_NP_117_OR_HIGHER:
assert result == "np117"
mock_np117.assert_called_once_with(1)
assert mock_np116.call_count == 0
else:
assert result == "np116"
mock_np116.assert_called_once_with(1)
assert mock_np117.call_count == 0
def test_call(self):
gen = iarandom.convert_seed_to_generator(1)
if IS_NP_117_OR_HIGHER:
expected = np.random.Generator(
iarandom.BIT_GENERATOR(np.random.SeedSequence(1)))
assert iarandom.is_generator_equal_to(gen, expected)
else:
expected = np.random.RandomState(1)
assert iarandom.is_generator_equal_to(gen, expected)
class Test_convert_seed_sequence_to_generator(_Base):
@unittest.skipIf(not IS_NP_117_OR_HIGHER,
"SeedSequence does not exist in numpy <=1.16")
def test_call(self):
seedseq = np.random.SeedSequence(1)
gen = iarandom.convert_seed_sequence_to_generator(seedseq)
expected = np.random.Generator(
iarandom.BIT_GENERATOR(np.random.SeedSequence(1)))
assert iarandom.is_generator_equal_to(gen, expected)
class Test_create_pseudo_random_generator_(_Base):
def test_call(self):
global_gen = copylib.deepcopy(iarandom.get_global_rng().generator)
gen = iarandom.create_pseudo_random_generator_()
expected = iarandom.convert_seed_to_generator(
iarandom.generate_seed_(global_gen))
assert iarandom.is_generator_equal_to(gen, expected)
class Test_create_fully_random_generator(_Base):
@mock.patch("imgaug.random._create_fully_random_generator_np117")
@mock.patch("imgaug.random._create_fully_random_generator_np116")
def test_mocked_call(self, mock_np116, mock_np117):
mock_np116.return_value = "np116"
mock_np117.return_value = "np117"
result = iarandom.create_fully_random_generator()
if IS_NP_117_OR_HIGHER:
assert result == "np117"
mock_np117.assert_called_once_with()
assert mock_np116.call_count == 0
else:
assert result == "np116"
mock_np116.assert_called_once_with()
assert mock_np117.call_count == 0
@unittest.skipIf(not IS_NP_117_OR_HIGHER,
"Function uses classes from numpy 1.17+")
def test_np117_mocked(self):
dummy_bitgen = np.random.SFC64(1)
with mock.patch("numpy.random.SFC64") as mock_bitgen:
mock_bitgen.return_value = dummy_bitgen
result = iarandom._create_fully_random_generator_np117()
assert mock_bitgen.call_count == 1
assert iarandom.is_generator_equal_to(
result, np.random.Generator(dummy_bitgen))
def test_np116_mocked(self):
dummy_rs = np.random.RandomState(1)
with mock.patch("numpy.random.RandomState") as mock_rs:
mock_rs.return_value = dummy_rs
result = iarandom._create_fully_random_generator_np116()
assert mock_rs.call_count == 1
assert iarandom.is_generator_equal_to(result, np.random.RandomState(1))
class Test_generate_seed_(_Base):
@mock.patch("imgaug.random.generate_seeds_")
def test_mocked_call(self, mock_seeds):
gen = iarandom.convert_seed_to_generator(0)
_ = iarandom.generate_seed_(gen)
mock_seeds.assert_called_once_with(gen, 1)
class Test_generate_seeds_(_Base):
@mock.patch("imgaug.random.polyfill_integers")
def test_mocked_call(self, mock_integers):
gen = iarandom.convert_seed_to_generator(0)
_ = iarandom.generate_seeds_(gen, 10)
mock_integers.assert_called_once_with(
gen, iarandom.SEED_MIN_VALUE, iarandom.SEED_MAX_VALUE, size=(10,))
def test_call(self):
gen = iarandom.convert_seed_to_generator(0)
seeds = iarandom.generate_seeds_(gen, 2)
assert len(seeds) == 2
assert ia.is_np_array(seeds)
assert seeds.dtype.name == "int32"
class Test_copy_generator(_Base):
@mock.patch("imgaug.random._copy_generator_np116")
def test_mocked_call_with_random_state(self, mock_np116):
mock_np116.return_value = "np116"
gen = np.random.RandomState(1)
gen_copy = iarandom.copy_generator(gen)
assert gen_copy == "np116"
mock_np116.assert_called_once_with(gen)
@unittest.skipIf(not IS_NP_117_OR_HIGHER,
"Function uses classes from numpy 1.17+")
@mock.patch("imgaug.random._copy_generator_np117")
def test_mocked_call_with_generator(self, mock_np117):
mock_np117.return_value = "np117"
gen = np.random.Generator(iarandom.BIT_GENERATOR(1))
gen_copy = iarandom.copy_generator(gen)
assert gen_copy == "np117"
mock_np117.assert_called_once_with(gen)
def test_call_with_random_state(self):
gen = | np.random.RandomState(1) | numpy.random.RandomState |
# encoding=utf8
import os
import numpy as np
import FukuML.Utility as utility
import FukuML.SupportVectorMachine as svm
import FukuML.LogisticRegression as logistic_regression
import FukuML.MLBase as ml
class ProbabilisticSVM(ml.Learner):
def __init__(self):
"""init"""
self.status = 'empty'
self.train_X = []
self.train_Y = []
self.W = []
self.data_num = 0
self.data_demension = 0
self.test_X = []
self.test_Y = []
self.feature_transform_mode = ''
self.feature_transform_degree = 1
self.feed_mode = 'batch'
self.step_eta = 0.126
self.updates = 2000
self.svm_kernel = 'soft_gaussian_kernel'
self.gamma = 1
self.C = 0.1
self.svm_processor = ''
self.logistic_processor = ''
def load_train_data(self, input_data_file=''):
self.status = 'load_train_data'
if (input_data_file == ''):
input_data_file = os.path.normpath(os.path.join(os.path.join(os.getcwd(), os.path.dirname(__file__)), "dataset/logistic_regression_train.dat"))
else:
if (os.path.isfile(input_data_file) is not True):
print("Please make sure input_data_file path is correct.")
return self.train_X, self.train_Y
self.train_X, self.train_Y = utility.DatasetLoader.load(input_data_file)
return self.train_X, self.train_Y
def load_test_data(self, input_data_file=''):
if (input_data_file == ''):
input_data_file = os.path.normpath(os.path.join(os.path.join(os.getcwd(), os.path.dirname(__file__)), "dataset/logistic_regression_test.dat"))
else:
if (os.path.isfile(input_data_file) is not True):
print("Please make sure input_data_file path is correct.")
return self.test_X, self.test_Y
self.test_X, self.test_Y = utility.DatasetLoader.load(input_data_file)
if (self.feature_transform_mode == 'polynomial') or (self.feature_transform_mode == 'legendre'):
self.test_X = self.test_X[:, 1:]
self.test_X = utility.DatasetLoader.feature_transform(
self.test_X,
self.feature_transform_mode,
self.feature_transform_degree
)
return self.test_X, self.test_Y
def set_param(self, feed_mode='batch', step_eta=0.126, updates=2000, C=0.1):
self.feed_mode = feed_mode
self.step_eta = step_eta
self.updates = updates
self.C = C
return self.feed_mode, self.step_eta, self.updates, self.C
def init_W(self, mode='normal'):
if (self.status != 'load_train_data') and (self.status != 'train'):
print("Please load train data first.")
return self.W
self.status = 'init'
self.data_num = len(self.train_Y)
self.data_demension = len(self.train_X[0])
self.W = np.zeros(self.data_demension)
return self.W
def score_function(self, x, W):
svm_process_x = self.svm_score(x)
svm_process_x = [1] + [svm_process_x]
score = self.logistic_processor.theta(np.inner(svm_process_x, self.logistic_processor.W))
return score
def error_function(self, x, y, W):
svm_process_x = self.svm_score(x)
svm_process_x = [1] + [svm_process_x]
error = np.log(1 + np.exp((-1) * y * | np.inner(svm_process_x, self.logistic_processor.W) | numpy.inner |
from model import Multi_Model
import pickle
from PIL import Image
import re
import os
from torchvision.transforms.transforms import CenterCrop, Compose, Normalize, Resize, ToTensor
from transformers import BertModel, BertConfig, BertTokenizer, AdamW, get_cosine_schedule_with_warmup
from tqdm import tqdm
import torch.nn as nn
from torch.autograd import Variable, Function
from torch.utils.data import Dataset, DataLoader
import torch.nn.functional as F
import numpy as np
import warnings
from torch import LongTensor
import torch
import time
from sklearn.metrics import accuracy_score, classification_report,recall_score
warnings.filterwarnings('ignore')
class Config():
def __init__(self):
self.batch_size = 64
self.epochs = 5
self.bert_path = "./bert_model/"
self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
class FakeNewsDataset(Dataset):
def __init__(self,input_three,event,image,label) :
self.event = LongTensor(list(event))
self.image = torch.FloatTensor([np.array(i) for i in image])
self.label = LongTensor(list(label))
self.input_three = list()
self.input_three.append( LongTensor(input_three[0]))
self.input_three.append(LongTensor(input_three[1]))
self.input_three.append(LongTensor(input_three[2]))
def __len__(self):
return len(self.label)
def __getitem__(self,idx):
return self.input_three[0][idx],self.input_three[1][idx],self.input_three[2][idx],self.image[idx],self.event[idx],self.label[idx]
def readImage(filepath_list):
"""读取所有图片"""
#if os.path.exists('./pickles/'):
# return pickle.load(open('./pickles/images.pkl','rb'))
image_list = dict()
data_transforms = Compose(transforms=[
Resize(256),
CenterCrop(224),
ToTensor(),
Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
])
for path in list(filepath_list):
for i, filename in enumerate(os.listdir(path)):
try:
im = Image.open(os.path.join(path, filename)).convert('RGB')
im = data_transforms(im)
image_list[filename.split('/')[-1].split('.')[0].lower()] = im
except Exception as e:
print("[-] Error {} when handling {}".format(e, filename))
# print("[+] Length of `image_list`: {}".format(len(image_list)))
pickle.dump(image_list,open("./pickles/images.pkl","wb"))
print("dump successful")
return image_list
def cleanSST(string):
string = re.sub(u"[,。 :,.;|-“”——_/nbsp+&;@、《》~()())#O!:【】]", "", string)
return string.strip().lower()
def load_id(path):
result = {}
for p in path:
id = pickle.load(open(p,'rb'))
print(len(id))
result = dict(id,**result)
print(len(result))
return result
def load_text_image():
result_path ='./pickles/four_data.pkl'
if os.path.exists('./pickles/'):
return pickle.load(open(result_path,'rb'))
text = []
image = []
event = []
label = []
text_list = ['./weibo/tweets/test_nonrumor.txt','./weibo/tweets/test_rumor.txt',
'./weibo/tweets/train_nonrumor.txt','./weibo/tweets/train_rumor.txt']
image_list = ['./weibo/rumor_images/','./weibo/nonrumor_images/']
post_id_path = ['./weibo/train_id.pickle','./weibo/test_id.pickle','./weibo/validate_id.pickle']
all_id = load_id(post_id_path)
#all_images = readImage(image_list) #{id:image}
#print('read images ok')
for index,filename in enumerate(text_list):
print(index,' text read ok')
with open(filename, 'r',encoding='utf-8') as f:
for i, line in tqdm(enumerate(f)):
#event : load post id and transform it to event
if i %3 == 0 :
post_id = str(line).split('|')[0]
if post_id in all_id.keys():
event.append(all_id[post_id])
allowed = True
else:
allowed = False
#image : only capture the first image which is in weibo dataset
if i %3 == 1 and allowed:
image.append(line.strip())
'''for image_id in line.strip().split('|'):
image_id = image_id.split("/")[-1].split(".")[0]
if image_id in all_images:
image.append(all_images[image_id])
break'''
#text : just remove special chacters and strip,do not tokenize
if i%3 ==2 and allowed:
text.append(cleanSST(line))
#label
if (index+1) % 2 == 1: # non-rumor -> 0
y = 0
else: # rumor -> 1
y = 1
label.append(y)
allowed = False
print('read all features ok')
print(len(text),len(event),len(image),len(label))
pickle.dump([text,image , event ,label ],open(result_path,'wb'))
return text , image,event ,label
def imageurl_image(images):
all_images = pickle.load(open('./pickles/images.pkl','rb'))
image = []
mask = []
for line in images :
flag = 0
for image_id in line.strip().split('|'):
#print(image_id)
image_id = image_id.split("/")[-1].split(".")[0]
#print(image_id)
if image_id in all_images:
image.append(all_images[image_id])
flag = 1
break
mask.append(flag)
#else:
#print(line,image_id,'not find')
print("preprocess images pk :",len(image))
return mask,image
def filter(l,mask):
result = []
for index,i in enumerate(l):
if mask[index]:
result.append(i)
return result
def token_text(text):
max_len = 50
tokenizer = BertTokenizer.from_pretrained('bert-base-chinese') # 初始化分词器
input_ids, input_masks, input_types, = [], [], []
for line in text :
encode_dict = tokenizer.encode_plus(text=line, max_length=max_len,
padding='max_length', truncation=True)
#dec:https://www.cnblogs.com/douzujun/p/13572694.html
input_ids.append(encode_dict['input_ids'])
input_types.append(encode_dict['token_type_ids'])
input_masks.append(encode_dict['attention_mask'])
return [input_ids,input_types,input_masks]
def get_parameter_number(model):
# 打印模型参数量
total_num = sum(p.numel() for p in model.parameters())
trainable_num = sum(p.numel() for p in model.parameters() if p.requires_grad)
return 'Total parameters: {}, Trainable parameters: {}'.format(total_num, trainable_num)
def evaluate(multi_model,vali_dataloader,device):
multi_model.eval()
val_true, val_pred = [], []
with torch.no_grad():
for index,(batch_text0,batch_text1,batch_text2,batch_image,batch_event,batch_label) in enumerate(vali_dataloader):
batch_text0 = batch_text0.to(device)
batch_text1 = batch_text1.to(device)
batch_text2 = batch_text2.to(device)
batch_image = batch_image.to(device)
batch_event = batch_event.to(device)
batch_label = batch_label.to(device)
y_pred = multi_model(batch_text0,batch_text1,batch_text2,batch_image)
y_pred = torch.argmax(y_pred, dim=1).detach().cpu().numpy().tolist()
val_pred.extend(y_pred)
val_true.extend(batch_label.squeeze().cpu().numpy().tolist())
return accuracy_score(val_true, val_pred) #返回accuracy
def predict():
config = Config()
data_transforms = Compose(transforms=[
Resize(256),
CenterCrop(224),
ToTensor(),
Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
])
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
text = input("fake news:")
image_path = input("image path:")
multi_model = Multi_Model(config.bert_path)
multi_model.load_state_dict(torch.load('best_multi_bert_model.pth'))
im = Image.open(image_path).convert('RGB')
im = data_transforms(im)
# 该文件夹下存放三个文件('vocab.txt', 'pytorch_model.bin', 'config.json')
tokenizer = BertTokenizer.from_pretrained('bert-base-chinese')
input_ids, input_masks, input_types, = [], [], []
encode_dict = tokenizer.encode_plus(text=cleanSST(text), max_length=50,
padding='max_length', truncation=True)
input_ids.append(encode_dict['input_ids'])
input_types.append(encode_dict['token_type_ids'])
input_masks.append(encode_dict['attention_mask'])
label_pred = multi_model(LongTensor(input_ids),LongTensor(input_types),LongTensor(input_masks),[np.array(im)])
y_pred = torch.argmax(label_pred, dim=1).detach().cpu().numpy().tolist()
print(y_pred)
train_acc_vector = []
vali_acc_vector = []
def train_val_test():
#train , test , validate
config = Config()
text , image,event ,label = pickle.load(open("./pickles/all_data.pkl",'rb'))
train_len = int(0.6 * len(label))
test_len = int(0.2*len(label) )
validate_len = len(label) - train_len - test_len
print("train:{} test:{} validate:{}".format(train_len,test_len,validate_len))
print("fake news:{} Real news:{}".format(sum(label),len(label)-sum(label)))
text = np.array(text)
image = np.array(image)
event = np.array(event)
label = np.array(label)
idxes = np.arange(len(label))
np.random.seed(2019) # 固定种子
np.random.shuffle(idxes)
print("load dataset")
train_dataset = FakeNewsDataset(np.array([text[0][idxes[:train_len]],text[1][idxes[:train_len]],text[2][idxes[:train_len]]]),
event[idxes[:train_len]],image[[idxes[:train_len]]],label[idxes[:train_len]])
pickle.dump(train_dataset,open('./pickles/train_dataset.pkl','wb'))
test_dataset = FakeNewsDataset( | np.array([text[0][idxes[train_len:test_len+train_len]],text[1][idxes[train_len:test_len+train_len]],text[2][idxes[train_len:test_len+train_len]]]) | numpy.array |
import numpy as np
import csv
import cv2
from keras.models import Sequential
from keras.layers import Dense, Flatten
def load_data():
lines = []
with open('Data/driving_log.csv') as csvfile:
reader = csv.reader(csvfile)
for line in reader:
lines.append(line)
images = []
measurements = []
for line in lines:
source_path = line[0]
filename = source_path.split('/')[-1]
current_path = 'Data/IMG/'+filename
image = cv2.imread(current_path)
images.append(image)
measurement = float(line[3])
measurements.append(measurement)
X_train = np.array(images)
y_train = | np.array(measurements) | numpy.array |
#!/usr/bin/env python3
import rospy
from humanoid_league_msgs.msg import \
ObstacleInImageArray, BallInImageArray, \
GoalPostInImageArray
from geometry_msgs.msg import Point, PolygonStamped
from sensor_msgs.msg import Image
from cv_bridge import CvBridge
import numpy as np
import math
import cv2
import yaml
import os
import sys
import signal
import time
import pickle
class Evaluation(object):
def __init__(self):
"""
Describes the evaluation of a single class on a single image
"""
self.received_message = False # boolean signaling whether a message of the type was received
self.pixel_mask_rates = None
self.duration = None
class ImageMeasurement(object):
def __init__(self, image_data, eval_classes):
"""
Describes the evaluation of a single image.
It stores the annotations, Evaluation (see Evaluation class) for each class in the image.
"""
self.evaluations = dict()
self.image_data = image_data
for eval_class in eval_classes:
self.evaluations[eval_class] = Evaluation()
def serialize(self):
return {
'evaluations': {
'classes': {eval_class: vars(self.evaluations[eval_class]) for eval_class in self.evaluations.keys() if self.evaluations[eval_class].received_message},
'max_latency': self.get_max_duration(),
},
'image_data': self.image_data,
}
def get_max_duration(self):
# returns the maximal duration a measurement in the image took
max_duration = 0
for evaluation in self.evaluations.values():
if evaluation.duration is not None and evaluation.duration > max_duration:
max_duration = evaluation.duration
return max_duration
class Evaluator(object):
def __init__(self):
self._set_sim_time_param()
rospy.init_node("bitbots_vision_evaluator")
self._set_sim_time_param()
self._evaluated_classes = list()
# Subscribe to all vision outputs
self._ball_sub = None
if rospy.get_param("~listen_balls", False):
rospy.loginfo('listening for balls in image...')
self._evaluated_classes.append('ball')
self._ball_sub = rospy.Subscriber(rospy.get_param("~balls_topic", "balls_in_image"),
BallInImageArray,
self._balls_callback,
queue_size=1,
tcp_nodelay=True)
self._line_sub = None
if rospy.get_param("~listen_lines", False):
rospy.loginfo('listening for lines in image...')
self._evaluated_classes.append('line')
self._line_sub = rospy.Subscriber(rospy.get_param("~lines_topic", "line_mask_in_image"),
Image,
self._lines_callback,
queue_size=1,
tcp_nodelay=True)
self._obstacle_sub = None
if rospy.get_param("~listen_obstacles", False):
rospy.loginfo('listening for obstacles in image...')
self._evaluated_classes.append('robot_red')
self._evaluated_classes.append('robot_blue')
self._evaluated_classes.append('obstacle')
self._obstacle_sub = rospy.Subscriber(rospy.get_param("~obstacles_topic", "obstacles_in_image"),
ObstacleInImageArray,
self._obstacles_callback,
queue_size=1,
tcp_nodelay=True)
self._goalpost_sub = None
if rospy.get_param("~listen_goalposts", False):
rospy.loginfo('listening for goalposts in image...')
self._evaluated_classes.append('goalpost')
self._goalpost_sub = rospy.Subscriber(rospy.get_param("~goalpost_topic", "goal_posts_in_image"),
GoalPostInImageArray,
self._goalpost_callback,
queue_size=1,
tcp_nodelay=True)
self._field_boundary_sub = None
if rospy.get_param("~listen_field_boundary", False):
rospy.loginfo('listening for field_boundary in image...')
self._evaluated_classes.append('field edge')
self._field_boundary_sub = rospy.Subscriber(rospy.get_param("~field_boundary_topic", "field_boundary_in_image"),
PolygonStamped,
self._field_boundary_callback,
queue_size=1,
tcp_nodelay=True)
# make image publisher
self._image_pub = rospy.Publisher(
rospy.get_param("~image_publish_topic", "image_raw"),
Image,
queue_size=1,
latch=True)
# Get parameters
self._loop_images = rospy.get_param("~loop_images", False)
self._image_path = rospy.get_param("~folder_path")
self._line_thickness = rospy.get_param("~line_thickness")
# Enfore wall clock
self._set_sim_time_param()
self.bridge = CvBridge()
# Stores the messurement envs (ImageMeasurement) containing labels and metris for each image ()
self._measurements = dict()
# Stop-Stuff
self._stop = False # stop flag to handle kills
signal.signal(signal.SIGINT, self._kill_callback)
signal.signal(signal.SIGTERM, self._kill_callback)
# Read label YAML file
self._label_filename = rospy.get_param('~label_file_name')
rospy.loginfo('Reading label-file \"{}\"...'.format(self._label_filename))
# Read labels (sort out usw.)
self._images = self._read_labels(self._label_filename)
rospy.loginfo('Done reading label-file.')
# An unforgivable curse to differ between robot colors based on blurred/concealed/...
self._classify_robots()
# Filter and format labels
rospy.loginfo('Validating labels of {} images...'.format(len(self._images)))
self._images = self._analyze_labels(self._images)
rospy.loginfo('Labels of {} images are valid'.format(len(self._images)))
# Init image counter and set the image send time
self._current_image_counter = 0
self._image_send_time = rospy.Time.now()
self._image_count = len(self._images) # number of images (important for loop stuff)
self._image_shape = None # tuple (height, width)
self._label_shape = None # tuple (height, width)
# A lock which checks if there is eval processing done at the moment
self._lock = 0
# A time which checks for updates and serves the images if all classes arrived or
# if a timeout is raised
self._react_timer = rospy.Timer(rospy.Duration(0.2), self._react_callback)
# Send first image
self._send_image()
rospy.spin()
def _kill_callback(self, a, b):
# the rest of the process is handled in the send_image method
self._stop = True
def _react_callback(self, event):
# Executes any kind of stop
if self._stop:
rospy.loginfo('Stopping the evaluator.')
# stop timer
self._react_timer.shutdown()
# write measurements to file
self._write_measurements_to_file()
# stop the spinner
rospy.signal_shutdown('killed.')
sys.exit(0)
# Is raised if we didnt process a image in 2 Seconds.
# This is the case if we havent got all responses and therefore are not sending the new image for 2 Seconds
timeout = (rospy.Time.now() - self._image_send_time).to_sec() > 2.0
if timeout: rospy.logwarn("Stoped waiting for responses. Maybe some detections are lost")
# Check if the timeout is due or if all desired responses have been collected and processed.
# It also skips if a lock is present
if (self._recieved_all_messages_for_image(self._current_image_counter) or timeout) and not self._lock:
# Increse image counter
self._current_image_counter += 1
# Reset timeout timer
self._image_send_time = rospy.Time.now()
# Send image
self._send_image()
def _get_image_name(self):
"""
Returns the name of the currently processed image
"""
return self._images[self._current_image_counter]['name']
def _get_current_labels(self):
"""
Returns the annotations of the currently processed image
"""
return self._images[self._current_image_counter]['annotations']
def _send_image(self):
"""
Sends an Image to the Vision
"""
# handle stop at end of image list
if self._current_image_counter >= self._image_count: # iterated through all images
rospy.loginfo('iterated through all images.')
self._stop = True
return
# Get image name/id
name = self._get_image_name()
rospy.loginfo(f"Process image '{name}''")
# Read image file
imgpath = os.path.join(self._image_path, name)
image = cv2.imread(imgpath)
if image is None:
rospy.logwarn('Could not open image {} at path {}'.format(name, self._image_path))
return
# Setting label size as used by the imagetagger before we do the resizeing
if self._label_shape is None:
self._label_shape = image.shape[:-1]
# Set the resized image size as expected by the vision
if self._image_shape is None:
self._image_shape = np.array((
rospy.get_param("~image_resolution_y"),
rospy.get_param("~image_resolution_x")))
# resize the image
image = cv2.resize(image, tuple( | np.flip(self._image_shape) | numpy.flip |
# -*- coding: utf-8 -*-
from __future__ import (absolute_import, division, print_function,
unicode_literals)
from future.builtins import * # NOQA
import math
import os
import pickle
import unittest
from copy import deepcopy
import warnings
import numpy as np
import numpy.ma as ma
from obspy import Stream, Trace, UTCDateTime, __version__, read, read_inventory
from obspy.core import Stats
from obspy.core.compatibility import mock
from obspy.core.util.testing import ImageComparison
from obspy.io.xseed import Parser
class TraceTestCase(unittest.TestCase):
"""
Test suite for obspy.core.trace.Trace.
"""
@staticmethod
def __remove_processing(tr):
"""
Removes all processing information in the trace object.
Useful for testing.
"""
if "processing" not in tr.stats:
return
del tr.stats.processing
def test_init(self):
"""
Tests the __init__ method of the Trace class.
"""
# NumPy ndarray
tr = Trace(data=np.arange(4))
self.assertEqual(len(tr), 4)
# NumPy masked array
data = np.ma.array([0, 1, 2, 3], mask=[True, True, False, False])
tr = Trace(data=data)
self.assertEqual(len(tr), 4)
# other data types will raise
self.assertRaises(ValueError, Trace, data=[0, 1, 2, 3])
self.assertRaises(ValueError, Trace, data=(0, 1, 2, 3))
self.assertRaises(ValueError, Trace, data='1234')
def test_setattr(self):
"""
Tests the __setattr__ method of the Trace class.
"""
# NumPy ndarray
tr = Trace()
tr.data = np.arange(4)
self.assertEqual(len(tr), 4)
# NumPy masked array
tr = Trace()
tr.data = np.ma.array([0, 1, 2, 3], mask=[True, True, False, False])
self.assertEqual(len(tr), 4)
# other data types will raise
tr = Trace()
self.assertRaises(ValueError, tr.__setattr__, 'data', [0, 1, 2, 3])
self.assertRaises(ValueError, tr.__setattr__, 'data', (0, 1, 2, 3))
self.assertRaises(ValueError, tr.__setattr__, 'data', '1234')
def test_len(self):
"""
Tests the __len__ and count methods of the Trace class.
"""
trace = Trace(data=np.arange(1000))
self.assertEqual(len(trace), 1000)
self.assertEqual(trace.count(), 1000)
def test_mul(self):
"""
Tests the __mul__ method of the Trace class.
"""
tr = Trace(data=np.arange(10))
st = tr * 5
self.assertEqual(len(st), 5)
# you may only multiply using an integer
self.assertRaises(TypeError, tr.__mul__, 2.5)
self.assertRaises(TypeError, tr.__mul__, '1234')
def test_div(self):
"""
Tests the __div__ method of the Trace class.
"""
tr = Trace(data=np.arange(1000))
st = tr / 5
self.assertEqual(len(st), 5)
self.assertEqual(len(st[0]), 200)
# you may only multiply using an integer
self.assertRaises(TypeError, tr.__div__, 2.5)
self.assertRaises(TypeError, tr.__div__, '1234')
def test_ltrim(self):
"""
Tests the ltrim method of the Trace class.
"""
# set up
trace = Trace(data=np.arange(1000))
start = UTCDateTime(2000, 1, 1, 0, 0, 0, 0)
trace.stats.starttime = start
trace.stats.sampling_rate = 200.0
end = UTCDateTime(2000, 1, 1, 0, 0, 4, 995000)
# verify
trace.verify()
# UTCDateTime/int/float required
self.assertRaises(TypeError, trace._ltrim, '1234')
self.assertRaises(TypeError, trace._ltrim, [1, 2, 3, 4])
# ltrim 100 samples
tr = deepcopy(trace)
tr._ltrim(0.5)
tr.verify()
np.testing.assert_array_equal(tr.data[0:5],
np.array([100, 101, 102, 103, 104]))
self.assertEqual(len(tr.data), 900)
self.assertEqual(tr.stats.npts, 900)
self.assertEqual(tr.stats.sampling_rate, 200.0)
self.assertEqual(tr.stats.starttime, start + 0.5)
self.assertEqual(tr.stats.endtime, end)
# ltrim 202 samples
tr = deepcopy(trace)
tr._ltrim(1.010)
tr.verify()
np.testing.assert_array_equal(tr.data[0:5],
np.array([202, 203, 204, 205, 206]))
self.assertEqual(len(tr.data), 798)
self.assertEqual(tr.stats.npts, 798)
self.assertEqual(tr.stats.sampling_rate, 200.0)
self.assertEqual(tr.stats.starttime, start + 1.010)
self.assertEqual(tr.stats.endtime, end)
# ltrim to UTCDateTime
tr = deepcopy(trace)
tr._ltrim(UTCDateTime(2000, 1, 1, 0, 0, 1, 10000))
tr.verify()
np.testing.assert_array_equal(tr.data[0:5],
np.array([202, 203, 204, 205, 206]))
self.assertEqual(len(tr.data), 798)
self.assertEqual(tr.stats.npts, 798)
self.assertEqual(tr.stats.sampling_rate, 200.0)
self.assertEqual(tr.stats.starttime, start + 1.010)
self.assertEqual(tr.stats.endtime, end)
# some sanity checks
# negative start time as datetime
tr = deepcopy(trace)
tr._ltrim(start - 1, pad=True)
tr.verify()
self.assertEqual(tr.stats.starttime, start - 1)
np.testing.assert_array_equal(trace.data, tr.data[200:])
self.assertEqual(tr.stats.endtime, trace.stats.endtime)
# negative start time as integer
tr = deepcopy(trace)
tr._ltrim(-100, pad=True)
tr.verify()
self.assertEqual(tr.stats.starttime, start - 100)
delta = 100 * trace.stats.sampling_rate
np.testing.assert_array_equal(trace.data, tr.data[int(delta):])
self.assertEqual(tr.stats.endtime, trace.stats.endtime)
# start time > end time
tr = deepcopy(trace)
tr._ltrim(trace.stats.endtime + 100)
tr.verify()
self.assertEqual(tr.stats.starttime,
trace.stats.endtime + 100)
np.testing.assert_array_equal(tr.data, np.empty(0))
self.assertEqual(tr.stats.endtime, tr.stats.starttime)
# start time == end time
tr = deepcopy(trace)
tr._ltrim(5)
tr.verify()
self.assertEqual(tr.stats.starttime,
trace.stats.starttime + 5)
np.testing.assert_array_equal(tr.data, np.empty(0))
self.assertEqual(tr.stats.endtime, tr.stats.starttime)
# start time == end time
tr = deepcopy(trace)
tr._ltrim(5.1)
tr.verify()
self.assertEqual(tr.stats.starttime,
trace.stats.starttime + 5.1)
np.testing.assert_array_equal(tr.data, np.empty(0))
self.assertEqual(tr.stats.endtime, tr.stats.starttime)
def test_rtrim(self):
"""
Tests the rtrim method of the Trace class.
"""
# set up
trace = Trace(data=np.arange(1000))
start = UTCDateTime(2000, 1, 1, 0, 0, 0, 0)
trace.stats.starttime = start
trace.stats.sampling_rate = 200.0
end = UTCDateTime(2000, 1, 1, 0, 0, 4, 995000)
trace.verify()
# UTCDateTime/int/float required
self.assertRaises(TypeError, trace._rtrim, '1234')
self.assertRaises(TypeError, trace._rtrim, [1, 2, 3, 4])
# rtrim 100 samples
tr = deepcopy(trace)
tr._rtrim(0.5)
tr.verify()
np.testing.assert_array_equal(tr.data[-5:],
np.array([895, 896, 897, 898, 899]))
self.assertEqual(len(tr.data), 900)
self.assertEqual(tr.stats.npts, 900)
self.assertEqual(tr.stats.sampling_rate, 200.0)
self.assertEqual(tr.stats.starttime, start)
self.assertEqual(tr.stats.endtime, end - 0.5)
# rtrim 202 samples
tr = deepcopy(trace)
tr._rtrim(1.010)
tr.verify()
np.testing.assert_array_equal(tr.data[-5:],
np.array([793, 794, 795, 796, 797]))
self.assertEqual(len(tr.data), 798)
self.assertEqual(tr.stats.npts, 798)
self.assertEqual(tr.stats.sampling_rate, 200.0)
self.assertEqual(tr.stats.starttime, start)
self.assertEqual(tr.stats.endtime, end - 1.010)
# rtrim 1 minute via UTCDateTime
tr = deepcopy(trace)
tr._rtrim(UTCDateTime(2000, 1, 1, 0, 0, 3, 985000))
tr.verify()
np.testing.assert_array_equal(tr.data[-5:],
np.array([793, 794, 795, 796, 797]))
self.assertEqual(len(tr.data), 798)
self.assertEqual(tr.stats.npts, 798)
self.assertEqual(tr.stats.sampling_rate, 200.0)
self.assertEqual(tr.stats.starttime, start)
self.assertEqual(tr.stats.endtime, end - 1.010)
# some sanity checks
# negative end time
tr = deepcopy(trace)
t = UTCDateTime(1999, 12, 31)
tr._rtrim(t)
tr.verify()
self.assertEqual(tr.stats.endtime, t)
np.testing.assert_array_equal(tr.data, np.empty(0))
# negative end time with given seconds
tr = deepcopy(trace)
tr._rtrim(100)
tr.verify()
self.assertEqual(tr.stats.endtime, trace.stats.endtime - 100)
np.testing.assert_array_equal(tr.data, np.empty(0))
self.assertEqual(tr.stats.endtime, tr.stats.starttime)
# end time > start time
tr = deepcopy(trace)
t = UTCDateTime(2001)
tr._rtrim(t)
tr.verify()
self.assertEqual(tr.stats.endtime, t)
np.testing.assert_array_equal(tr.data, np.empty(0))
self.assertEqual(tr.stats.endtime, tr.stats.starttime)
# end time > start time given seconds
tr = deepcopy(trace)
tr._rtrim(5.1)
tr.verify()
delta = int(math.floor(round(5.1 * trace.stats.sampling_rate, 7)))
endtime = trace.stats.starttime + trace.stats.delta * \
(trace.stats.npts - delta - 1)
self.assertEqual(tr.stats.endtime, endtime)
np.testing.assert_array_equal(tr.data, np.empty(0))
# end time == start time
# returns one sample!
tr = deepcopy(trace)
tr._rtrim(4.995)
tr.verify()
np.testing.assert_array_equal(tr.data, np.array([0]))
self.assertEqual(len(tr.data), 1)
self.assertEqual(tr.stats.npts, 1)
self.assertEqual(tr.stats.sampling_rate, 200.0)
self.assertEqual(tr.stats.starttime, start)
self.assertEqual(tr.stats.endtime, start)
def test_rtrim_with_padding(self):
"""
Tests the _rtrim() method of the Trace class with padding. It has
already been tested in the two sided trimming tests. This is just to
have an explicit test. Also tests issue #429.
"""
# set up
trace = Trace(data=np.arange(10))
start = UTCDateTime(2000, 1, 1, 0, 0, 0, 0)
trace.stats.starttime = start
trace.stats.sampling_rate = 1.0
trace.verify()
# Pad with no fill_value will mask the additional values.
tr = trace.copy()
end = tr.stats.endtime
tr._rtrim(end + 10, pad=True)
self.assertEqual(tr.stats.endtime, trace.stats.endtime + 10)
np.testing.assert_array_equal(tr.data[0:10], np.arange(10))
# Check that the first couple of entries are not masked.
self.assertFalse(tr.data[0:10].mask.any())
# All the other entries should be masked.
self.assertTrue(tr.data[10:].mask.all())
# Pad with fill_value.
tr = trace.copy()
end = tr.stats.endtime
tr._rtrim(end + 10, pad=True, fill_value=-33)
self.assertEqual(tr.stats.endtime, trace.stats.endtime + 10)
# The first ten entries should not have changed.
np.testing.assert_array_equal(tr.data[0:10], np.arange(10))
# The rest should be filled with the fill_value.
np.testing.assert_array_equal(tr.data[10:], np.ones(10) * -33)
def test_trim(self):
"""
Tests the trim method of the Trace class.
"""
# set up
trace = Trace(data=np.arange(1001))
start = UTCDateTime(2000, 1, 1, 0, 0, 0, 0)
trace.stats.starttime = start
trace.stats.sampling_rate = 200.0
end = UTCDateTime(2000, 1, 1, 0, 0, 5, 0)
trace.verify()
# rtrim 100 samples
trace.trim(0.5, 0.5)
trace.verify()
np.testing.assert_array_equal(trace.data[-5:],
np.array([896, 897, 898, 899, 900]))
np.testing.assert_array_equal(trace.data[:5],
np.array([100, 101, 102, 103, 104]))
self.assertEqual(len(trace.data), 801)
self.assertEqual(trace.stats.npts, 801)
self.assertEqual(trace.stats.sampling_rate, 200.0)
self.assertEqual(trace.stats.starttime, start + 0.5)
self.assertEqual(trace.stats.endtime, end - 0.5)
# start time should be before end time
self.assertRaises(ValueError, trace.trim, end, start)
def test_trim_all_does_not_change_dtype(self):
"""
If a Trace is completely trimmed, e.g. no data samples are remaining,
the dtype should remain unchanged.
A trace with no data samples is not really senseful but the dtype
should not be changed anyways.
"""
# Choose non native dtype.
tr = Trace(np.arange(100, dtype=np.int16))
tr.trim(UTCDateTime(10000), UTCDateTime(20000))
# Assert the result.
self.assertEqual(len(tr.data), 0)
self.assertEqual(tr.data.dtype, np.int16)
def test_add_trace_with_gap(self):
"""
Tests __add__ method of the Trace class.
"""
# set up
tr1 = Trace(data=np.arange(1000))
tr1.stats.sampling_rate = 200
start = UTCDateTime(2000, 1, 1, 0, 0, 0, 0)
tr1.stats.starttime = start
tr2 = Trace(data=np.arange(0, 1000)[::-1])
tr2.stats.sampling_rate = 200
tr2.stats.starttime = start + 10
# verify
tr1.verify()
tr2.verify()
# add
trace = tr1 + tr2
# stats
self.assertEqual(trace.stats.starttime, start)
self.assertEqual(trace.stats.endtime, start + 14.995)
self.assertEqual(trace.stats.sampling_rate, 200)
self.assertEqual(trace.stats.npts, 3000)
# data
self.assertEqual(len(trace), 3000)
self.assertEqual(trace[0], 0)
self.assertEqual(trace[999], 999)
self.assertTrue(ma.is_masked(trace[1000]))
self.assertTrue(ma.is_masked(trace[1999]))
self.assertEqual(trace[2000], 999)
self.assertEqual(trace[2999], 0)
# verify
trace.verify()
def test_add_trace_with_overlap(self):
"""
Tests __add__ method of the Trace class.
"""
# set up
tr1 = Trace(data=np.arange(1000))
tr1.stats.sampling_rate = 200
start = UTCDateTime(2000, 1, 1, 0, 0, 0, 0)
tr1.stats.starttime = start
tr2 = Trace(data=np.arange(0, 1000)[::-1])
tr2.stats.sampling_rate = 200
tr2.stats.starttime = start + 4
# add
trace = tr1 + tr2
# stats
self.assertEqual(trace.stats.starttime, start)
self.assertEqual(trace.stats.endtime, start + 8.995)
self.assertEqual(trace.stats.sampling_rate, 200)
self.assertEqual(trace.stats.npts, 1800)
# data
self.assertEqual(len(trace), 1800)
self.assertEqual(trace[0], 0)
self.assertEqual(trace[799], 799)
self.assertTrue(trace[800].mask)
self.assertTrue(trace[999].mask)
self.assertEqual(trace[1000], 799)
self.assertEqual(trace[1799], 0)
# verify
trace.verify()
def test_add_same_trace(self):
"""
Tests __add__ method of the Trace class.
"""
# set up
tr1 = Trace(data=np.arange(1001))
# add
trace = tr1 + tr1
# should return exact the same values
self.assertEqual(trace.stats, tr1.stats)
np.testing.assert_array_equal(trace.data, tr1.data)
# verify
trace.verify()
def test_add_trace_within_trace(self):
"""
Tests __add__ method of the Trace class.
"""
# set up
tr1 = Trace(data=np.arange(1001))
tr1.stats.sampling_rate = 200
start = UTCDateTime(2000, 1, 1, 0, 0, 0, 0)
tr1.stats.starttime = start
tr2 = Trace(data=np.arange(201))
tr2.stats.sampling_rate = 200
tr2.stats.starttime = start + 1
# add
trace = tr1 + tr2
# should return exact the same values like trace 1
self.assertEqual(trace.stats, tr1.stats)
mask = np.zeros(len(tr1)).astype(np.bool_)
mask[200:401] = True
np.testing.assert_array_equal(trace.data.mask, mask)
np.testing.assert_array_equal(trace.data.data[:200], tr1.data[:200])
np.testing.assert_array_equal(trace.data.data[401:], tr1.data[401:])
# add the other way around
trace = tr2 + tr1
# should return exact the same values like trace 1
self.assertEqual(trace.stats, tr1.stats)
np.testing.assert_array_equal(trace.data.mask, mask)
np.testing.assert_array_equal(trace.data.data[:200], tr1.data[:200])
np.testing.assert_array_equal(trace.data.data[401:], tr1.data[401:])
# verify
trace.verify()
def test_add_gap_and_overlap(self):
"""
Test order of merging traces.
"""
# set up
tr1 = Trace(data=np.arange(1000))
tr1.stats.sampling_rate = 200
start = UTCDateTime(2000, 1, 1, 0, 0, 0, 0)
tr1.stats.starttime = start
tr2 = Trace(data=np.arange(1000)[::-1])
tr2.stats.sampling_rate = 200
tr2.stats.starttime = start + 4
tr3 = Trace(data=np.arange(1000)[::-1])
tr3.stats.sampling_rate = 200
tr3.stats.starttime = start + 12
# overlap
overlap = tr1 + tr2
self.assertEqual(len(overlap), 1800)
mask = np.zeros(1800).astype(np.bool_)
mask[800:1000] = True
np.testing.assert_array_equal(overlap.data.mask, mask)
np.testing.assert_array_equal(overlap.data.data[:800], tr1.data[:800])
np.testing.assert_array_equal(overlap.data.data[1000:], tr2.data[200:])
# overlap + gap
overlap_gap = overlap + tr3
self.assertEqual(len(overlap_gap), 3400)
mask = np.zeros(3400).astype(np.bool_)
mask[800:1000] = True
mask[1800:2400] = True
np.testing.assert_array_equal(overlap_gap.data.mask, mask)
np.testing.assert_array_equal(overlap_gap.data.data[:800],
tr1.data[:800])
np.testing.assert_array_equal(overlap_gap.data.data[1000:1800],
tr2.data[200:])
np.testing.assert_array_equal(overlap_gap.data.data[2400:], tr3.data)
# gap
gap = tr2 + tr3
self.assertEqual(len(gap), 2600)
mask = np.zeros(2600).astype(np.bool_)
mask[1000:1600] = True
np.testing.assert_array_equal(gap.data.mask, mask)
np.testing.assert_array_equal(gap.data.data[:1000], tr2.data)
np.testing.assert_array_equal(gap.data.data[1600:], tr3.data)
def test_add_into_gap(self):
"""
Test __add__ method of the Trace class
Adding a trace that fits perfectly into gap in a trace
"""
my_array = np.arange(6, dtype=np.int32)
stats = Stats()
stats.network = 'VI'
stats['starttime'] = UTCDateTime(2009, 8, 5, 0, 0, 0)
stats['npts'] = 0
stats['station'] = 'IKJA'
stats['channel'] = 'EHZ'
stats['sampling_rate'] = 1
bigtrace = Trace(data=np.array([], dtype=np.int32), header=stats)
bigtrace_sort = bigtrace.copy()
stats['npts'] = len(my_array)
my_trace = Trace(data=my_array, header=stats)
stats['npts'] = 2
trace1 = Trace(data=my_array[0:2].copy(), header=stats)
stats['starttime'] = UTCDateTime(2009, 8, 5, 0, 0, 2)
trace2 = Trace(data=my_array[2:4].copy(), header=stats)
stats['starttime'] = UTCDateTime(2009, 8, 5, 0, 0, 4)
trace3 = Trace(data=my_array[4:6].copy(), header=stats)
tr1 = bigtrace
tr2 = bigtrace_sort
for method in [0, 1]:
# Random
bigtrace = tr1.copy()
bigtrace = bigtrace.__add__(trace1, method=method)
bigtrace = bigtrace.__add__(trace3, method=method)
bigtrace = bigtrace.__add__(trace2, method=method)
# Sorted
bigtrace_sort = tr2.copy()
bigtrace_sort = bigtrace_sort.__add__(trace1, method=method)
bigtrace_sort = bigtrace_sort.__add__(trace2, method=method)
bigtrace_sort = bigtrace_sort.__add__(trace3, method=method)
for tr in (bigtrace, bigtrace_sort):
self.assertTrue(isinstance(tr, Trace))
self.assertFalse(isinstance(tr.data, np.ma.masked_array))
self.assertTrue((bigtrace_sort.data == my_array).all())
fail_pattern = "\n\tExpected %s\n\tbut got %s"
failinfo = fail_pattern % (my_trace, bigtrace_sort)
failinfo += fail_pattern % (my_trace.data, bigtrace_sort.data)
self.assertEqual(bigtrace_sort, my_trace, failinfo)
failinfo = fail_pattern % (my_array, bigtrace.data)
self.assertTrue((bigtrace.data == my_array).all(), failinfo)
failinfo = fail_pattern % (my_trace, bigtrace)
failinfo += fail_pattern % (my_trace.data, bigtrace.data)
self.assertEqual(bigtrace, my_trace, failinfo)
for array_ in (bigtrace.data, bigtrace_sort.data):
failinfo = fail_pattern % (my_array.dtype, array_.dtype)
self.assertEqual(my_array.dtype, array_.dtype, failinfo)
def test_slice(self):
"""
Tests the slicing of trace objects.
"""
tr = Trace(data=np.arange(10, dtype=np.int32))
mempos = tr.data.ctypes.data
t = tr.stats.starttime
tr1 = tr.slice(t + 2, t + 8)
tr1.data[0] = 10
self.assertEqual(tr.data[2], 10)
self.assertEqual(tr.data.ctypes.data, mempos)
self.assertEqual(tr.data[2:9].ctypes.data, tr1.data.ctypes.data)
self.assertEqual(tr1.data.ctypes.data - 8, mempos)
# Test the processing information for the slicing. The sliced trace
# should have a processing information showing that it has been
# trimmed. The original trace should have nothing.
tr = Trace(data=np.arange(10, dtype=np.int32))
tr2 = tr.slice(tr.stats.starttime)
self.assertNotIn("processing", tr.stats)
self.assertIn("processing", tr2.stats)
self.assertIn("trim", tr2.stats.processing[0])
def test_slice_no_starttime_or_endtime(self):
"""
Tests the slicing of trace objects with no start time or end time
provided. Compares results against the equivalent trim() operation
"""
tr_orig = Trace(data=np.arange(10, dtype=np.int32))
tr = tr_orig.copy()
# two time points outside the trace and two inside
t1 = tr.stats.starttime - 2
t2 = tr.stats.starttime + 2
t3 = tr.stats.endtime - 3
t4 = tr.stats.endtime + 2
# test 1: only removing data at left side
tr_trim = tr_orig.copy()
tr_trim.trim(starttime=t2)
self.assertEqual(tr_trim, tr.slice(starttime=t2))
tr2 = tr.slice(starttime=t2, endtime=t4)
self.__remove_processing(tr_trim)
self.__remove_processing(tr2)
self.assertEqual(tr_trim, tr2)
# test 2: only removing data at right side
tr_trim = tr_orig.copy()
tr_trim.trim(endtime=t3)
self.assertEqual(tr_trim, tr.slice(endtime=t3))
tr2 = tr.slice(starttime=t1, endtime=t3)
self.__remove_processing(tr_trim)
self.__remove_processing(tr2)
self.assertEqual(tr_trim, tr2)
# test 3: not removing data at all
tr_trim = tr_orig.copy()
tr_trim.trim(starttime=t1, endtime=t4)
tr2 = tr.slice()
self.__remove_processing(tr_trim)
self.__remove_processing(tr2)
self.assertEqual(tr_trim, tr2)
tr2 = tr.slice(starttime=t1)
self.__remove_processing(tr_trim)
self.__remove_processing(tr2)
self.assertEqual(tr_trim, tr2)
tr2 = tr.slice(endtime=t4)
self.__remove_processing(tr2)
self.assertEqual(tr_trim, tr2)
tr2 = tr.slice(starttime=t1, endtime=t4)
self.__remove_processing(tr2)
self.assertEqual(tr_trim, tr2)
tr_trim.trim()
tr2 = tr.slice()
self.__remove_processing(tr_trim)
self.__remove_processing(tr2)
self.assertEqual(tr_trim, tr2)
tr2 = tr.slice(starttime=t1)
self.__remove_processing(tr_trim)
self.__remove_processing(tr2)
self.assertEqual(tr_trim, tr2)
tr2 = tr.slice(endtime=t4)
self.__remove_processing(tr_trim)
self.__remove_processing(tr2)
self.assertEqual(tr_trim, tr2)
tr2 = tr.slice(starttime=t1, endtime=t4)
self.__remove_processing(tr_trim)
self.__remove_processing(tr2)
self.assertEqual(tr_trim, tr2)
# test 4: removing data at left and right side
tr_trim = tr_orig.copy()
tr_trim.trim(starttime=t2, endtime=t3)
self.assertEqual(tr_trim, tr.slice(t2, t3))
self.assertEqual(tr_trim, tr.slice(starttime=t2, endtime=t3))
# test 5: no data left after operation
tr_trim = tr_orig.copy()
tr_trim.trim(starttime=t4)
tr2 = tr.slice(starttime=t4)
self.__remove_processing(tr_trim)
self.__remove_processing(tr2)
self.assertEqual(tr_trim, tr2)
tr2 = tr.slice(starttime=t4, endtime=t4 + 1)
self.__remove_processing(tr_trim)
self.__remove_processing(tr2)
self.assertEqual(tr_trim, tr2)
def test_slice_nearest_sample(self):
"""
Tests slicing with the nearest sample flag set to on or off.
"""
tr = Trace(data=np.arange(6))
# Samples at:
# 0 10 20 30 40 50
tr.stats.sampling_rate = 0.1
# Nearest sample flag defaults to true.
tr2 = tr.slice(UTCDateTime(4), UTCDateTime(44))
self.assertEqual(tr2.stats.starttime, UTCDateTime(0))
self.assertEqual(tr2.stats.endtime, UTCDateTime(40))
tr2 = tr.slice(UTCDateTime(8), UTCDateTime(48))
self.assertEqual(tr2.stats.starttime, UTCDateTime(10))
self.assertEqual(tr2.stats.endtime, UTCDateTime(50))
# Setting it to False changes the returned values.
tr2 = tr.slice(UTCDateTime(4), UTCDateTime(44), nearest_sample=False)
self.assertEqual(tr2.stats.starttime, UTCDateTime(10))
self.assertEqual(tr2.stats.endtime, UTCDateTime(40))
tr2 = tr.slice(UTCDateTime(8), UTCDateTime(48), nearest_sample=False)
self.assertEqual(tr2.stats.starttime, UTCDateTime(10))
self.assertEqual(tr2.stats.endtime, UTCDateTime(40))
def test_trim_floating_point(self):
"""
Tests the slicing of trace objects.
"""
# Create test array that allows for easy testing.
tr = Trace(data=np.arange(11))
org_stats = deepcopy(tr.stats)
org_data = deepcopy(tr.data)
# Save memory position of array.
mem_pos = tr.data.ctypes.data
# Just some sanity tests.
self.assertEqual(tr.stats.starttime, UTCDateTime(0))
self.assertEqual(tr.stats.endtime, UTCDateTime(10))
# Create temp trace object used for testing.
st = tr.stats.starttime
# This is supposed to include the start and end times and should
# therefore cut right at 2 and 8.
temp = deepcopy(tr)
temp.trim(st + 2.1, st + 7.1)
# Should be identical.
temp2 = deepcopy(tr)
temp2.trim(st + 2.0, st + 8.0)
self.assertEqual(temp.stats.starttime, UTCDateTime(2))
self.assertEqual(temp.stats.endtime, UTCDateTime(7))
self.assertEqual(temp.stats.npts, 6)
self.assertEqual(temp2.stats.npts, 7)
# self.assertEqual(temp.stats, temp2.stats)
np.testing.assert_array_equal(temp.data, temp2.data[:-1])
# Create test array that allows for easy testing.
# Check if the data is the same.
self.assertNotEqual(temp.data.ctypes.data, tr.data[2:9].ctypes.data)
np.testing.assert_array_equal(tr.data[2:8], temp.data)
# Using out of bounds times should not do anything but create
# a copy of the stats.
temp = deepcopy(tr)
temp.trim(st - 2.5, st + 200)
# The start and end times should not change.
self.assertEqual(temp.stats.starttime, UTCDateTime(0))
self.assertEqual(temp.stats.endtime, UTCDateTime(10))
self.assertEqual(temp.stats.npts, 11)
# Alter the new stats to make sure the old one stays intact.
temp.stats.starttime = UTCDateTime(1000)
self.assertEqual(org_stats, tr.stats)
# Check if the data address is not the same, that is it is a copy
self.assertNotEqual(temp.data.ctypes.data, tr.data.ctypes.data)
np.testing.assert_array_equal(tr.data, temp.data)
# Make sure the original Trace object did not change.
np.testing.assert_array_equal(tr.data, org_data)
self.assertEqual(tr.data.ctypes.data, mem_pos)
self.assertEqual(tr.stats, org_stats)
# Use more complicated times and sampling rate.
tr = Trace(data=np.arange(111))
tr.stats.starttime = UTCDateTime(111.11111)
tr.stats.sampling_rate = 50.0
org_stats = deepcopy(tr.stats)
org_data = deepcopy(tr.data)
# Save memory position of array.
mem_pos = tr.data.ctypes.data
# Create temp trace object used for testing.
temp = deepcopy(tr)
temp.trim(UTCDateTime(111.22222), UTCDateTime(112.99999),
nearest_sample=False)
# Should again be identical. XXX NOT!
temp2 = deepcopy(tr)
temp2.trim(UTCDateTime(111.21111), UTCDateTime(113.01111),
nearest_sample=False)
np.testing.assert_array_equal(temp.data, temp2.data[1:-1])
# Check stuff.
self.assertEqual(temp.stats.starttime, UTCDateTime(111.23111))
self.assertEqual(temp.stats.endtime, UTCDateTime(112.991110))
# Check if the data is the same.
temp = deepcopy(tr)
temp.trim(UTCDateTime(0), UTCDateTime(1000 * 1000))
self.assertNotEqual(temp.data.ctypes.data, tr.data.ctypes.data)
# starttime must be in conformance with sampling rate
t = UTCDateTime(111.11111)
self.assertEqual(temp.stats.starttime, t)
delta = int((tr.stats.starttime - t) * tr.stats.sampling_rate + .5)
np.testing.assert_array_equal(tr.data, temp.data[delta:delta + 111])
# Make sure the original Trace object did not change.
np.testing.assert_array_equal(tr.data, org_data)
self.assertEqual(tr.data.ctypes.data, mem_pos)
self.assertEqual(tr.stats, org_stats)
def test_trim_floating_point_with_padding_1(self):
"""
Tests the slicing of trace objects with the use of the padding option.
"""
# Create test array that allows for easy testing.
tr = Trace(data=np.arange(11))
org_stats = deepcopy(tr.stats)
org_data = deepcopy(tr.data)
# Save memory position of array.
mem_pos = tr.data.ctypes.data
# Just some sanity tests.
self.assertEqual(tr.stats.starttime, UTCDateTime(0))
self.assertEqual(tr.stats.endtime, UTCDateTime(10))
# Create temp trace object used for testing.
st = tr.stats.starttime
# Using out of bounds times should not do anything but create
# a copy of the stats.
temp = deepcopy(tr)
temp.trim(st - 2.5, st + 200, pad=True)
self.assertEqual(temp.stats.starttime.timestamp, -2.0)
self.assertEqual(temp.stats.endtime.timestamp, 200)
self.assertEqual(temp.stats.npts, 203)
mask = np.zeros(203).astype(np.bool_)
mask[:2] = True
mask[13:] = True
np.testing.assert_array_equal(temp.data.mask, mask)
# Alter the new stats to make sure the old one stays intact.
temp.stats.starttime = UTCDateTime(1000)
self.assertEqual(org_stats, tr.stats)
# Check if the data address is not the same, that is it is a copy
self.assertNotEqual(temp.data.ctypes.data, tr.data.ctypes.data)
np.testing.assert_array_equal(tr.data, temp.data[2:13])
# Make sure the original Trace object did not change.
np.testing.assert_array_equal(tr.data, org_data)
self.assertEqual(tr.data.ctypes.data, mem_pos)
self.assertEqual(tr.stats, org_stats)
def test_trim_floating_point_with_padding_2(self):
"""
Use more complicated times and sampling rate.
"""
tr = Trace(data=np.arange(111))
tr.stats.starttime = UTCDateTime(111.11111)
tr.stats.sampling_rate = 50.0
org_stats = deepcopy(tr.stats)
org_data = deepcopy(tr.data)
# Save memory position of array.
mem_pos = tr.data.ctypes.data
# Create temp trace object used for testing.
temp = deepcopy(tr)
temp.trim(UTCDateTime(111.22222), UTCDateTime(112.99999),
nearest_sample=False)
# Should again be identical.#XXX not
temp2 = deepcopy(tr)
temp2.trim(UTCDateTime(111.21111), UTCDateTime(113.01111),
nearest_sample=False)
np.testing.assert_array_equal(temp.data, temp2.data[1:-1])
# Check stuff.
self.assertEqual(temp.stats.starttime, UTCDateTime(111.23111))
self.assertEqual(temp.stats.endtime, UTCDateTime(112.991110))
# Check if the data is the same.
temp = deepcopy(tr)
temp.trim(UTCDateTime(0), UTCDateTime(1000 * 1000), pad=True)
self.assertNotEqual(temp.data.ctypes.data, tr.data.ctypes.data)
# starttime must be in conformance with sampling rate
t = UTCDateTime(1969, 12, 31, 23, 59, 59, 991110)
self.assertEqual(temp.stats.starttime, t)
delta = int((tr.stats.starttime - t) * tr.stats.sampling_rate + .5)
np.testing.assert_array_equal(tr.data, temp.data[delta:delta + 111])
# Make sure the original Trace object did not change.
np.testing.assert_array_equal(tr.data, org_data)
self.assertEqual(tr.data.ctypes.data, mem_pos)
self.assertEqual(tr.stats, org_stats)
def test_add_sanity(self):
"""
Test sanity checks in __add__ method of the Trace object.
"""
tr = Trace(data=np.arange(10))
# you may only add a Trace object
self.assertRaises(TypeError, tr.__add__, 1234)
self.assertRaises(TypeError, tr.__add__, '1234')
self.assertRaises(TypeError, tr.__add__, [1, 2, 3, 4])
# trace id
tr2 = Trace()
tr2.stats.station = 'TEST'
self.assertRaises(TypeError, tr.__add__, tr2)
# sample rate
tr2 = Trace()
tr2.stats.sampling_rate = 20
self.assertRaises(TypeError, tr.__add__, tr2)
# calibration factor
tr2 = Trace()
tr2.stats.calib = 20
self.assertRaises(TypeError, tr.__add__, tr2)
# data type
tr2 = Trace()
tr2.data = np.arange(10, dtype=np.float32)
self.assertRaises(TypeError, tr.__add__, tr2)
def test_add_overlaps_default_method(self):
"""
Test __add__ method of the Trace object.
"""
# 1
# overlapping trace with differing data
# Trace 1: 0000000
# Trace 2: 1111111
tr1 = Trace(data=np.zeros(7))
tr2 = Trace(data=np.ones(7))
tr2.stats.starttime = tr1.stats.starttime + 5
# 1 + 2 : 00000--11111
tr = tr1 + tr2
self.assertTrue(isinstance(tr.data, np.ma.masked_array))
self.assertEqual(tr.data.tolist(),
[0, 0, 0, 0, 0, None, None, 1, 1, 1, 1, 1])
# 2 + 1 : 00000--11111
tr = tr2 + tr1
self.assertTrue(isinstance(tr.data, np.ma.masked_array))
self.assertEqual(tr.data.tolist(),
[0, 0, 0, 0, 0, None, None, 1, 1, 1, 1, 1])
# 2
# overlapping trace with same data
# Trace 1: 0000000
# Trace 2: 0000000
tr1 = Trace(data=np.zeros(7))
tr2 = Trace(data=np.zeros(7))
tr2.stats.starttime = tr1.stats.starttime + 5
# 1 + 2 : 000000000000
tr = tr1 + tr2
self.assertTrue(isinstance(tr.data, np.ndarray))
np.testing.assert_array_equal(tr.data, np.zeros(12))
# 2 + 1 : 000000000000
tr = tr2 + tr1
self.assertTrue(isinstance(tr.data, np.ndarray))
np.testing.assert_array_equal(tr.data, np.zeros(12))
# 3
# contained trace with same data
# Trace 1: 1111111111
# Trace 2: 11
tr1 = Trace(data=np.ones(10))
tr2 = Trace(data=np.ones(2))
tr2.stats.starttime = tr1.stats.starttime + 5
# 1 + 2 : 1111111111
tr = tr1 + tr2
self.assertTrue(isinstance(tr.data, np.ndarray))
np.testing.assert_array_equal(tr.data, np.ones(10))
# 2 + 1 : 1111111111
tr = tr2 + tr1
self.assertTrue(isinstance(tr.data, np.ndarray))
np.testing.assert_array_equal(tr.data, np.ones(10))
# 4
# contained trace with differing data
# Trace 1: 0000000000
# Trace 2: 11
tr1 = Trace(data=np.zeros(10))
tr2 = Trace(data=np.ones(2))
tr2.stats.starttime = tr1.stats.starttime + 5
# 1 + 2 : 00000--000
tr = tr1 + tr2
self.assertTrue(isinstance(tr.data, np.ma.masked_array))
self.assertEqual(tr.data.tolist(),
[0, 0, 0, 0, 0, None, None, 0, 0, 0])
# 2 + 1 : 00000--000
tr = tr2 + tr1
self.assertTrue(isinstance(tr.data, np.ma.masked_array))
self.assertEqual(tr.data.tolist(),
[0, 0, 0, 0, 0, None, None, 0, 0, 0])
# 5
# completely contained trace with same data until end
# Trace 1: 1111111111
# Trace 2: 1111111111
tr1 = Trace(data=np.ones(10))
tr2 = Trace(data=np.ones(10))
# 1 + 2 : 1111111111
tr = tr1 + tr2
self.assertTrue(isinstance(tr.data, np.ndarray))
np.testing.assert_array_equal(tr.data, np.ones(10))
# 6
# completely contained trace with differing data
# Trace 1: 0000000000
# Trace 2: 1111111111
tr1 = Trace(data=np.zeros(10))
tr2 = Trace(data=np.ones(10))
# 1 + 2 : ----------
tr = tr1 + tr2
self.assertTrue(isinstance(tr.data, np.ma.masked_array))
self.assertEqual(tr.data.tolist(), [None] * 10)
def test_add_with_different_sampling_rates(self):
"""
Test __add__ method of the Trace object.
"""
# 1 - different sampling rates for the same channel should fail
tr1 = Trace(data=np.zeros(5))
tr1.stats.sampling_rate = 200
tr2 = Trace(data=np.zeros(5))
tr2.stats.sampling_rate = 50
self.assertRaises(TypeError, tr1.__add__, tr2)
self.assertRaises(TypeError, tr2.__add__, tr1)
# 2 - different sampling rates for the different channels works
tr1 = Trace(data=np.zeros(5))
tr1.stats.sampling_rate = 200
tr1.stats.channel = 'EHE'
tr2 = Trace(data=np.zeros(5))
tr2.stats.sampling_rate = 50
tr2.stats.channel = 'EHZ'
tr3 = Trace(data=np.zeros(5))
tr3.stats.sampling_rate = 200
tr3.stats.channel = 'EHE'
tr4 = Trace(data=np.zeros(5))
tr4.stats.sampling_rate = 50
tr4.stats.channel = 'EHZ'
# same sampling rate and ids should not fail
tr1 + tr3
tr3 + tr1
tr2 + tr4
tr4 + tr2
def test_add_with_different_datatypes_or_id(self):
"""
Test __add__ method of the Trace object.
"""
# 1 - different data types for the same channel should fail
tr1 = Trace(data=np.zeros(5, dtype=np.int32))
tr2 = Trace(data=np.zeros(5, dtype=np.float32))
self.assertRaises(TypeError, tr1.__add__, tr2)
self.assertRaises(TypeError, tr2.__add__, tr1)
# 2 - different sampling rates for the different channels works
tr1 = Trace(data=np.zeros(5, dtype=np.int32))
tr1.stats.channel = 'EHE'
tr2 = Trace(data=np.zeros(5, dtype=np.float32))
tr2.stats.channel = 'EHZ'
tr3 = Trace(data=np.zeros(5, dtype=np.int32))
tr3.stats.channel = 'EHE'
tr4 = Trace(data=np.zeros(5, dtype=np.float32))
tr4.stats.channel = 'EHZ'
# same data types and ids should not fail
tr1 + tr3
tr3 + tr1
tr2 + tr4
tr4 + tr2
# adding traces with different ids should raise
self.assertRaises(TypeError, tr1.__add__, tr2)
self.assertRaises(TypeError, tr3.__add__, tr4)
self.assertRaises(TypeError, tr2.__add__, tr1)
self.assertRaises(TypeError, tr4.__add__, tr3)
def test_comparisons(self):
"""
Tests all rich comparison operators (==, !=, <, <=, >, >=)
The latter four are not implemented due to ambiguous meaning and bounce
an error.
"""
# create test traces
tr0 = Trace(np.arange(3))
tr1 = Trace(np.arange(3))
tr2 = Trace(np.arange(3), {'station': 'X'})
tr3 = Trace(np.arange(3), {'processing':
["filter:lowpass:{'freq': 10}"]})
tr4 = Trace(np.arange(5))
tr5 = Trace(np.arange(5), {'station': 'X'})
tr6 = Trace(np.arange(5), {'processing':
["filter:lowpass:{'freq': 10}"]})
tr7 = Trace(np.array([1, 1, 1]))
# tests that should raise a NotImplementedError (i.e. <=, <, >=, >)
self.assertRaises(NotImplementedError, tr1.__lt__, tr1)
self.assertRaises(NotImplementedError, tr1.__le__, tr1)
self.assertRaises(NotImplementedError, tr1.__gt__, tr1)
self.assertRaises(NotImplementedError, tr1.__ge__, tr1)
self.assertRaises(NotImplementedError, tr1.__lt__, tr2)
self.assertRaises(NotImplementedError, tr1.__le__, tr2)
self.assertRaises(NotImplementedError, tr1.__gt__, tr2)
self.assertRaises(NotImplementedError, tr1.__ge__, tr2)
# normal tests
self.assertEqual(tr0 == tr0, True)
self.assertEqual(tr0 == tr1, True)
self.assertEqual(tr0 == tr2, False)
self.assertEqual(tr0 == tr3, False)
self.assertEqual(tr0 == tr4, False)
self.assertEqual(tr0 == tr5, False)
self.assertEqual(tr0 == tr6, False)
self.assertEqual(tr0 == tr7, False)
self.assertEqual(tr5 == tr0, False)
self.assertEqual(tr5 == tr1, False)
self.assertEqual(tr5 == tr2, False)
self.assertEqual(tr5 == tr3, False)
self.assertEqual(tr5 == tr4, False)
self.assertEqual(tr5 == tr5, True)
self.assertEqual(tr5 == tr6, False)
self.assertEqual(tr3 == tr6, False)
self.assertEqual(tr0 != tr0, False)
self.assertEqual(tr0 != tr1, False)
self.assertEqual(tr0 != tr2, True)
self.assertEqual(tr0 != tr3, True)
self.assertEqual(tr0 != tr4, True)
self.assertEqual(tr0 != tr5, True)
self.assertEqual(tr0 != tr6, True)
self.assertEqual(tr0 != tr7, True)
self.assertEqual(tr5 != tr0, True)
self.assertEqual(tr5 != tr1, True)
self.assertEqual(tr5 != tr2, True)
self.assertEqual(tr5 != tr3, True)
self.assertEqual(tr5 != tr4, True)
self.assertEqual(tr5 != tr5, False)
self.assertEqual(tr5 != tr6, True)
self.assertEqual(tr3 != tr6, True)
# some weirder tests against non-Trace objects
for object in [0, 1, 0.0, 1.0, "", "test", True, False, [], [tr0],
set(), set(tr0), {}, {"test": "test"}, [], None, ]:
self.assertEqual(tr0 == object, False)
self.assertEqual(tr0 != object, True)
def test_nearest_sample(self):
"""
This test case shows that the libmseed is actually flooring the
starttime to the next sample value, regardless if it is the nearest
sample. The flag nearest_sample=True tries to avoids this and
rounds it to the next actual possible sample point.
"""
# set up
trace = Trace(data=np.empty(10000))
trace.stats.starttime = UTCDateTime("2010-06-20T20:19:40.000000Z")
trace.stats.sampling_rate = 200.0
# ltrim
tr = deepcopy(trace)
t = UTCDateTime("2010-06-20T20:19:51.494999Z")
tr._ltrim(t - 3, nearest_sample=True)
# see that it is actually rounded to the next sample point
self.assertEqual(tr.stats.starttime,
UTCDateTime("2010-06-20T20:19:48.495000Z"))
# Lots of tests follow that thoroughly check the cutting behavior
# using nearest_sample=True/False
# rtrim
tr = deepcopy(trace)
t = UTCDateTime("2010-06-20T20:19:51.494999Z")
tr._rtrim(t + 7, nearest_sample=True)
# see that it is actually rounded to the next sample point
self.assertEqual(tr.stats.endtime,
UTCDateTime("2010-06-20T20:19:58.495000Z"))
tr = deepcopy(trace)
t = UTCDateTime("2010-06-20T20:19:51.495000Z")
tr._rtrim(t + 7, nearest_sample=True)
# see that it is actually rounded to the next sample point
self.assertEqual(tr.stats.endtime,
UTCDateTime("2010-06-20T20:19:58.495000Z"))
tr = deepcopy(trace)
t = UTCDateTime("2010-06-20T20:19:51.495111Z")
tr._rtrim(t + 7, nearest_sample=True)
# see that it is actually rounded to the next sample point
self.assertEqual(tr.stats.endtime,
UTCDateTime("2010-06-20T20:19:58.495000Z"))
tr = deepcopy(trace)
t = UTCDateTime("2010-06-20T20:19:51.497501Z")
tr._rtrim(t + 7, nearest_sample=True)
# see that it is actually rounded to the next sample point
self.assertEqual(tr.stats.endtime,
UTCDateTime("2010-06-20T20:19:58.500000Z"))
# rtrim
tr = deepcopy(trace)
t = UTCDateTime("2010-06-20T20:19:51.494999Z")
tr._rtrim(t + 7, nearest_sample=False)
# see that it is actually rounded to the next sample point
self.assertEqual(tr.stats.endtime,
UTCDateTime("2010-06-20T20:19:58.490000Z"))
tr = deepcopy(trace)
t = UTCDateTime("2010-06-20T20:19:51.495000Z")
tr._rtrim(t + 7, nearest_sample=False)
# see that it is actually rounded to the next sample point
self.assertEqual(tr.stats.endtime,
UTCDateTime("2010-06-20T20:19:58.495000Z"))
tr = deepcopy(trace)
t = UTCDateTime("2010-06-20T20:19:51.495111Z")
tr._rtrim(t + 7, nearest_sample=False)
# see that it is actually rounded to the next sample point
self.assertEqual(tr.stats.endtime,
UTCDateTime("2010-06-20T20:19:58.495000Z"))
tr = deepcopy(trace)
t = UTCDateTime("2010-06-20T20:19:51.497500Z")
tr._rtrim(t + 7, nearest_sample=False)
# see that it is actually rounded to the next sample point
self.assertEqual(tr.stats.endtime,
UTCDateTime("2010-06-20T20:19:58.495000Z"))
def test_masked_array_to_string(self):
"""
Masked arrays should be marked using __str__.
"""
st = read()
overlaptrace = st[0].copy()
overlaptrace.stats.starttime += 1
st.append(overlaptrace)
st.merge()
out = st[0].__str__()
self.assertTrue(out.endswith('(masked)'))
def test_detrend(self):
"""
Test detrend method of trace
"""
t = np.arange(10)
data = 0.1 * t + 1.
tr = Trace(data=data.copy())
tr.detrend(type='simple')
np.testing.assert_array_almost_equal(tr.data, np.zeros(10))
tr.data = data.copy()
tr.detrend(type='linear')
np.testing.assert_array_almost_equal(tr.data, np.zeros(10))
data = np.zeros(10)
data[3:7] = 1.
tr.data = data.copy()
tr.detrend(type='simple')
np.testing.assert_almost_equal(tr.data[0], 0.)
np.testing.assert_almost_equal(tr.data[-1], 0.)
tr.data = data.copy()
tr.detrend(type='linear')
np.testing.assert_almost_equal(tr.data[0], -0.4)
np.testing.assert_almost_equal(tr.data[-1], -0.4)
def test_differentiate(self):
"""
Test differentiation method of trace
"""
t = np.linspace(0., 1., 11)
data = 0.1 * t + 1.
tr = Trace(data=data)
tr.stats.delta = 0.1
tr.differentiate(method='gradient')
np.testing.assert_array_almost_equal(tr.data, np.ones(11) * 0.1)
def test_integrate(self):
"""
Test integration method of trace
"""
data = np.ones(101) * 0.01
tr = Trace(data=data)
tr.stats.delta = 0.1
tr.integrate()
# Assert time and length of resulting array.
self.assertEqual(tr.stats.starttime, UTCDateTime(0))
self.assertEqual(tr.stats.npts, 101)
np.testing.assert_array_almost_equal(
tr.data, np.concatenate([[0.0], np.cumsum(data)[:-1] * 0.1]))
def test_issue_317(self):
"""
Tests times after breaking a stream into parts and merging it again.
"""
# create a sample trace
org_trace = Trace(data=np.arange(22487))
org_trace.stats.starttime = UTCDateTime()
org_trace.stats.sampling_rate = 0.999998927116
num_pakets = 10
# break org_trace into set of contiguous packet data
traces = []
packet_length = int(np.size(org_trace.data) / num_pakets)
delta_time = org_trace.stats.delta
tstart = org_trace.stats.starttime
tend = tstart + delta_time * float(packet_length - 1)
for i in range(num_pakets):
tr = Trace(org_trace.data, org_trace.stats)
tr = tr.slice(tstart, tend)
traces.append(tr)
tstart = tr.stats.endtime + delta_time
tend = tstart + delta_time * float(packet_length - 1)
# reconstruct original trace by adding together packet traces
sum_trace = traces[0].copy()
npts = traces[0].stats.npts
for i in range(1, len(traces)):
sum_trace = sum_trace.__add__(traces[i].copy(), method=0,
interpolation_samples=0,
fill_value='latest',
sanity_checks=True)
# check npts
self.assertEqual(traces[i].stats.npts, npts)
self.assertEqual(sum_trace.stats.npts, (i + 1) * npts)
# check data
np.testing.assert_array_equal(traces[i].data,
np.arange(i * npts, (i + 1) * npts))
np.testing.assert_array_equal(sum_trace.data,
np.arange(0, (i + 1) * npts))
# check delta
self.assertEqual(traces[i].stats.delta, org_trace.stats.delta)
self.assertEqual(sum_trace.stats.delta, org_trace.stats.delta)
# check sampling rates
self.assertAlmostEqual(traces[i].stats.sampling_rate,
org_trace.stats.sampling_rate)
self.assertAlmostEqual(sum_trace.stats.sampling_rate,
org_trace.stats.sampling_rate)
# check end times
self.assertEqual(traces[i].stats.endtime, sum_trace.stats.endtime)
def test_verify(self):
"""
Tests verify method.
"""
# empty Trace
tr = Trace()
tr.verify()
# Trace with a single sample (issue #357)
tr = Trace(data=np.array([1]))
tr.verify()
# example Trace
tr = read()[0]
tr.verify()
def test_percent_in_str(self):
"""
Tests if __str__ method is working with percent sign (%).
"""
tr = Trace()
tr.stats.station = '%t3u'
self.assertTrue(tr.__str__().startswith(".%t3u.. | 1970"))
def test_taper(self):
"""
Test taper method of trace
"""
data = np.ones(10)
tr = Trace(data=data)
tr.taper(max_percentage=0.05, type='cosine')
for i in range(len(data)):
self.assertLessEqual(tr.data[i], 1.)
self.assertGreaterEqual(tr.data[i], 0.)
def test_taper_onesided(self):
"""
Test onesided taper method of trace
"""
data = np.ones(11)
tr = Trace(data=data)
# overlong taper - raises UserWarning - ignoring
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always", UserWarning)
tr.taper(max_percentage=None, side="left")
self.assertEqual(len(w), 1)
self.assertEqual(w[0].category, UserWarning)
self.assertTrue(tr.data[:5].sum() < 5.)
self.assertEqual(tr.data[6:].sum(), 5.)
data = np.ones(11)
tr = Trace(data=data)
# overlong taper - raises UserWarning - ignoring
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always", UserWarning)
tr.taper(max_percentage=None, side="right")
self.assertEqual(len(w), 1)
self.assertEqual(w[0].category, UserWarning)
self.assertEqual(tr.data[:5].sum(), 5.)
self.assertTrue(tr.data[6:].sum() < 5.)
def test_taper_length(self):
npts = 11
type_ = "hann"
data = np.ones(npts)
tr = Trace(data=data, header={'sampling': 1.})
# test an overlong taper request, still works but raises UserWarning
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always", UserWarning)
tr.taper(max_percentage=0.7, max_length=int(npts / 2) + 1)
self.assertEqual(len(w), 1)
self.assertEqual(w[0].category, UserWarning)
data = np.ones(npts)
tr = Trace(data=data, header={'sampling': 1.})
# first 3 samples get tapered
tr.taper(max_percentage=None, type=type_, side="left", max_length=3)
# last 5 samples get tapered
tr.taper(max_percentage=0.5, type=type_, side="right", max_length=None)
self.assertTrue(np.all(tr.data[:3] < 1.))
self.assertTrue(np.all(tr.data[3:6] == 1.))
self.assertTrue(np.all(tr.data[6:] < 1.))
data = np.ones(npts)
tr = Trace(data=data, header={'sampling': 1.})
# first 3 samples get tapered
tr.taper(max_percentage=0.5, type=type_, side="left", max_length=3)
# last 3 samples get tapered
tr.taper(max_percentage=0.3, type=type_, side="right", max_length=5)
self.assertTrue(np.all(tr.data[:3] < 1.))
self.assertTrue(np.all(tr.data[3:8] == 1.))
self.assertTrue(np.all(tr.data[8:] < 1.))
def test_times(self):
"""
Test if the correct times array is returned for normal traces and
traces with gaps.
"""
tr = Trace(data=np.ones(100))
tr.stats.sampling_rate = 20
delta = tr.stats.delta
start = UTCDateTime(2000, 1, 1, 0, 0, 0, 0)
tr.stats.starttime = start
tm = tr.times()
self.assertAlmostEqual(tm[-1], tr.stats.endtime - tr.stats.starttime)
tr.data = np.ma.ones(100)
tr.data[30:40] = np.ma.masked
tm = tr.times()
self.assertTrue(np.alltrue(tr.data.mask == tm.mask))
# test relative with reftime
tr.data = np.ones(100)
shift = 9.5
reftime = start - shift
got = tr.times(reftime=reftime)
self.assertEqual(len(got), tr.stats.npts)
expected = np.arange(shift, shift + 4.5 * delta, delta)
np.testing.assert_allclose(got[:5], expected, rtol=1e-8)
# test other options
got = tr.times("utcdatetime")
expected = np.array([
UTCDateTime(2000, 1, 1, 0, 0),
UTCDateTime(2000, 1, 1, 0, 0, 0, 50000),
UTCDateTime(2000, 1, 1, 0, 0, 0, 100000),
UTCDateTime(2000, 1, 1, 0, 0, 0, 150000),
UTCDateTime(2000, 1, 1, 0, 0, 0, 200000)], dtype=UTCDateTime)
self.assertTrue(isinstance(got[0], UTCDateTime))
np.testing.assert_allclose(
[t_.timestamp for t_ in got[:5]],
[t_.timestamp for t_ in expected], rtol=1e-17)
got = tr.times("timestamp")
expected = np.arange(0, 4.5 * delta, delta) + 946684800.0
np.testing.assert_allclose(got[:5], expected, rtol=1e-17)
got = tr.times("matplotlib")
expected = np.array([
730120.00000000000000000000, 730120.00000057870056480169,
730120.00000115740112960339, 730120.00000173610169440508,
730120.00000231480225920677])
np.testing.assert_allclose(got[:5], expected, rtol=1e-17)
def test_modulo_operation(self):
"""
Method for testing the modulo operation. Mainly tests part not covered
by the doctests.
"""
tr = Trace(data=np.arange(25))
# Wrong type raises.
self.assertRaises(TypeError, tr.__mod__, 5.0)
self.assertRaises(TypeError, tr.__mod__, "123")
# Needs to be a positive integer.
self.assertRaises(ValueError, tr.__mod__, 0)
self.assertRaises(ValueError, tr.__mod__, -11)
# If num is more then the number of samples, a copy will be returned.
st = tr % 500
self.assertEqual(tr, st[0])
self.assertEqual(len(st), 1)
self.assertFalse(tr.data is st[0].data)
def test_plot(self):
"""
Tests plot method if matplotlib is installed
"""
tr = Trace(data=np.arange(25))
tr.plot(show=False)
def test_spectrogram(self):
"""
Tests spectrogram method if matplotlib is installed
"""
tr = Trace(data=np.arange(25))
tr.stats.sampling_rate = 20
tr.spectrogram(show=False)
def test_raise_masked(self):
"""
Tests that detrend() raises in case of a masked array. (see #498)
"""
x = np.arange(10)
x = np.ma.masked_inside(x, 3, 4)
tr = Trace(x)
self.assertRaises(NotImplementedError, tr.detrend)
def test_split(self):
"""
Tests split method of the Trace class.
"""
# set up
tr1 = Trace(data=np.arange(1000))
tr1.stats.sampling_rate = 200
start = UTCDateTime(2000, 1, 1, 0, 0, 0, 0)
tr1.stats.starttime = start
tr2 = Trace(data=np.arange(0, 1000)[::-1])
tr2.stats.sampling_rate = 200
tr2.stats.starttime = start + 10
# add will create new trace with masked array
trace = tr1 + tr2
self.assertTrue(isinstance(trace.data, np.ma.masked_array))
# split
self.assertTrue(isinstance(trace, Trace))
st = trace.split()
self.assertTrue(isinstance(st, Stream))
self.assertEqual(len(st[0]), 1000)
self.assertEqual(len(st[1]), 1000)
# check if have no masked arrays
self.assertFalse(isinstance(st[0].data, np.ma.masked_array))
self.assertFalse(isinstance(st[1].data, np.ma.masked_array))
def test_split_empty_masked_array(self):
"""
Test split method with a masked array without any data.
"""
tr = Trace(data=np.ma.masked_all(100))
self.assertTrue(isinstance(tr.data, np.ma.masked_array))
self.assertTrue(isinstance(tr, Trace))
st = tr.split()
self.assertTrue(isinstance(st, Stream))
self.assertEqual(len(st), 0)
def test_split_masked_array_without_actually_masked_values(self):
"""
Tests splitting a masked array without actually masked data.
"""
# First non masked.
tr = Trace(data=np.arange(100))
st = tr.copy().split()
self.assertEqual(len(st), 1)
self.assertEqual(tr, st[0])
self.assertFalse(isinstance(st[0].data, np.ma.masked_array))
# Now the same thing but with an initially masked array but no
# masked values.
tr = Trace(data=np.ma.arange(100))
self.assertFalse(tr.data.mask)
st = tr.copy().split()
self.assertEqual(len(st), 1)
self.assertEqual(tr, st[0])
self.assertFalse(isinstance(st[0].data, np.ma.masked_array))
def test_simulate_evalresp(self):
"""
Tests that trace.simulate calls evalresp with the correct network,
station, location and channel information.
"""
tr = read()[0]
# Wrap in try/except as it of course will fail because the mocked
# function returns None.
try:
with mock.patch("obspy.signal.invsim.evalresp") as patch:
tr.simulate(seedresp={"filename": "RESP.dummy",
"units": "VEL",
"date": tr.stats.starttime})
except Exception:
pass
self.assertEqual(patch.call_count, 1)
_, kwargs = patch.call_args
# Make sure that every item of the trace is passed to the evalresp
# function.
for key in ["network", "station", "location", "channel"]:
self.assertEqual(
kwargs[key if key != "location" else "locid"], tr.stats[key],
msg="'%s' did not get passed on to evalresp" % key)
def test_issue_540(self):
"""
Trim with pad=True and given fill value should not return a masked
NumPy array.
"""
# fill_value = None
tr = read()[0]
self.assertEqual(len(tr), 3000)
tr.trim(starttime=tr.stats.starttime - 0.01,
endtime=tr.stats.endtime + 0.01, pad=True, fill_value=None)
self.assertEqual(len(tr), 3002)
self.assertTrue(isinstance(tr.data, np.ma.masked_array))
self.assertIs(tr.data[0], np.ma.masked)
self.assertTrue(tr.data[1] is not np.ma.masked)
self.assertTrue(tr.data[-2] is not np.ma.masked)
self.assertIs(tr.data[-1], np.ma.masked)
# fill_value = 999
tr = read()[0]
self.assertEqual(len(tr), 3000)
tr.trim(starttime=tr.stats.starttime - 0.01,
endtime=tr.stats.endtime + 0.01, pad=True, fill_value=999)
self.assertEqual(len(tr), 3002)
self.assertFalse(isinstance(tr.data, np.ma.masked_array))
self.assertEqual(tr.data[0], 999)
self.assertEqual(tr.data[-1], 999)
# given fill_value but actually no padding at all
tr = read()[0]
self.assertEqual(len(tr), 3000)
tr.trim(starttime=tr.stats.starttime,
endtime=tr.stats.endtime, pad=True, fill_value=-999)
self.assertEqual(len(tr), 3000)
self.assertFalse(isinstance(tr.data, np.ma.masked_array))
def test_resample(self):
"""
Tests the resampling of traces.
"""
tr = read()[0]
self.assertEqual(tr.stats.sampling_rate, 100.0)
self.assertEqual(tr.stats.npts, 3000)
tr_2 = tr.copy().resample(sampling_rate=50.0)
self.assertEqual(tr_2.stats.endtime, tr.stats.endtime - 1.0 / 100.0)
self.assertEqual(tr_2.stats.sampling_rate, 50.0)
self.assertEqual(tr_2.stats.starttime, tr.stats.starttime)
tr_3 = tr.copy().resample(sampling_rate=10.0)
self.assertEqual(tr_3.stats.endtime, tr.stats.endtime - 9.0 / 100.0)
self.assertEqual(tr_3.stats.sampling_rate, 10.0)
self.assertEqual(tr_3.stats.starttime, tr.stats.starttime)
tr_4 = tr.copy()
tr_4.data = np.require(tr_4.data,
dtype=tr_4.data.dtype.newbyteorder('>'))
tr_4 = tr_4.resample(sampling_rate=10.0)
self.assertEqual(tr_4.stats.endtime, tr.stats.endtime - 9.0 / 100.0)
self.assertEqual(tr_4.stats.sampling_rate, 10.0)
self.assertEqual(tr_4.stats.starttime, tr.stats.starttime)
def test_method_chaining(self):
"""
Tests that method chaining works for all methods on the Trace object
where it is sensible.
"""
# This essentially just checks that the methods are chainable. The
# methods are tested elsewhere and a full test would be a lot of work
# with questionable return.
tr = read()[0]
temp_tr = tr.trim(tr.stats.starttime + 1)\
.verify()\
.filter("lowpass", freq=2.0)\
.simulate(paz_remove={'poles': [-0.037004 + 0.037016j,
-0.037004 - 0.037016j,
-251.33 + 0j],
'zeros': [0j, 0j],
'gain': 60077000.0,
'sensitivity': 2516778400.0})\
.trigger(type="zdetect", nsta=20)\
.decimate(factor=2, no_filter=True)\
.resample(tr.stats.sampling_rate / 2.0)\
.differentiate()\
.integrate()\
.detrend()\
.taper(max_percentage=0.05, type='cosine')\
.normalize()
self.assertIs(temp_tr, tr)
self.assertTrue(isinstance(tr, Trace))
self.assertGreater(tr.stats.npts, 0)
# Use the processing chain to check the results. The trim() methods
# does not have an entry in the processing chain.
pr = tr.stats.processing
self.assertIn("trim", pr[0])
self.assertTrue("filter" in pr[1] and "lowpass" in pr[1])
self.assertIn("simulate", pr[2])
self.assertIn("trigger", pr[3])
self.assertIn("decimate", pr[4])
self.assertIn("resample", pr[5])
self.assertIn("differentiate", pr[6])
self.assertIn("integrate", pr[7])
self.assertIn("detrend", pr[8])
self.assertIn("taper", pr[9])
self.assertIn("normalize", pr[10])
def test_skip_empty_trace(self):
tr = read()[0]
t = tr.stats.endtime + 10
tr.trim(t, t + 10)
tr.detrend()
tr.resample(400)
tr.differentiate()
tr.integrate()
tr.taper(max_percentage=0.1)
def test_issue_695(self):
x = np.zeros(12)
data = [x.reshape((12, 1)),
x.reshape((1, 12)),
x.reshape((2, 6)),
x.reshape((6, 2)),
x.reshape((2, 2, 3)),
x.reshape((1, 2, 2, 3)),
x[0][()], # 0-dim array
]
for d in data:
self.assertRaises(ValueError, Trace, data=d)
def test_remove_response(self):
"""
Test remove_response() method against simulate() with equivalent
parameters to check response removal from Response object read from
StationXML against pure evalresp providing an external RESP file.
"""
tr1 = read()[0]
tr2 = tr1.copy()
# deconvolve from dataless with simulate() via Parser from
# dataless/RESP
parser = Parser("/path/to/dataless.seed.BW_RJOB")
tr1.simulate(seedresp={"filename": parser, "units": "VEL"},
water_level=60, pre_filt=(0.1, 0.5, 30, 50), sacsim=True,
pitsasim=False)
# deconvolve from StationXML with remove_response()
tr2.remove_response(pre_filt=(0.1, 0.5, 30, 50))
np.testing.assert_array_almost_equal(tr1.data, tr2.data)
def test_remove_polynomial_response(self):
"""
"""
from obspy import read_inventory
path = os.path.dirname(__file__)
# blockette 62, stage 0
tr = read()[0]
tr.stats.network = 'IU'
tr.stats.station = 'ANTO'
tr.stats.location = '30'
tr.stats.channel = 'LDO'
tr.stats.starttime = UTCDateTime("2010-07-23T00:00:00")
# remove response
del tr.stats.response
filename = os.path.join(path, 'data', 'stationxml_IU.ANTO.30.LDO.xml')
inv = read_inventory(filename, format='StationXML')
tr.attach_response(inv)
tr.remove_response()
# blockette 62, stage 1 + blockette 58, stage 2
tr = read()[0]
tr.stats.network = 'BK'
tr.stats.station = 'CMB'
tr.stats.location = ''
tr.stats.channel = 'LKS'
tr.stats.starttime = UTCDateTime("2004-06-16T00:00:00")
# remove response
del tr.stats.response
filename = os.path.join(path, 'data', 'stationxml_BK.CMB.__.LKS.xml')
inv = read_inventory(filename, format='StationXML')
tr.attach_response(inv)
# raises UserWarning: Stage gain not defined - ignoring
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always", UserWarning)
tr.remove_response()
self.assertEqual(len(w), 1)
self.assertEqual(w[0].category, UserWarning)
def test_processing_info_remove_response_and_sensitivity(self):
"""
Tests adding processing info for remove_response() and
remove_sensitivity().
See #1247.
"""
# remove_sensitivity() with response object attached to the trace.
tr = read()[0]
self.assertNotIn("processing", tr.stats)
tr.remove_sensitivity()
self.assertIn("processing", tr.stats)
self.assertEqual(len(tr.stats.processing), 1)
self.assertTrue(tr.stats.processing[0].endswith(
"remove_sensitivity(inventory=None)"))
# With passed inventory object.
tr = read()[0]
self.assertNotIn("processing", tr.stats)
tr.remove_sensitivity(inventory=read_inventory())
self.assertIn("processing", tr.stats)
self.assertEqual(len(tr.stats.processing), 1)
self.assertIn("remove_sensitivity(inventory=<obspy.core.inventory."
"inventory.Inventory object ", tr.stats.processing[0])
# remove_response()
tr = read()[0]
self.assertNotIn("processing", tr.stats)
tr.remove_response()
self.assertIn("processing", tr.stats)
self.assertEqual(len(tr.stats.processing), 1)
self.assertIn("remove_response(", tr.stats.processing[0])
self.assertIn("inventory=None", tr.stats.processing[0])
# With passed inventory object.
tr = read()[0]
self.assertNotIn("processing", tr.stats)
tr.remove_response(inventory=read_inventory())
self.assertIn("processing", tr.stats)
self.assertEqual(len(tr.stats.processing), 1)
self.assertIn("remove_response(", tr.stats.processing[0])
self.assertIn("inventory=<obspy.core.inventory.inventory.Inventory "
"object", tr.stats.processing[0])
def test_processing_information(self):
"""
Test case for the automatic processing information.
"""
tr = read()[0]
trimming_starttime = tr.stats.starttime + 1
tr.trim(trimming_starttime)
tr.filter("lowpass", freq=2.0)
tr.simulate(paz_remove={
'poles': [-0.037004 + 0.037016j, -0.037004 - 0.037016j,
-251.33 + 0j],
'zeros': [0j, 0j],
'gain': 60077000.0,
'sensitivity': 2516778400.0})
tr.trigger(type="zdetect", nsta=20)
tr.decimate(factor=2, no_filter=True)
tr.resample(tr.stats.sampling_rate / 2.0)
tr.differentiate()
tr.integrate()
tr.detrend()
tr.taper(max_percentage=0.05, type='cosine')
tr.normalize()
pr = tr.stats.processing
self.assertIn("trim", pr[0])
self.assertEqual(
"ObsPy %s: trim(endtime=None::fill_value=None::"
"nearest_sample=True::pad=False::starttime=%s)" % (
__version__, repr(trimming_starttime)),
pr[0])
self.assertIn("filter", pr[1])
self.assertIn("simulate", pr[2])
self.assertIn("trigger", pr[3])
self.assertIn("decimate", pr[4])
self.assertIn("resample", pr[5])
self.assertIn("differentiate", pr[6])
self.assertIn("integrate", pr[7])
self.assertIn("detrend", pr[8])
self.assertIn("taper", pr[9])
self.assertIn("normalize", pr[10])
def test_no_processing_info_for_failed_operations(self):
"""
If an operation fails, no processing information should be attached
to the Trace object.
"""
# create test Trace
tr = Trace(data=np.arange(20))
self.assertFalse("processing" in tr.stats)
# This decimation by a factor of 7 in this case would change the
# end time of the time series. Therefore it fails.
self.assertRaises(ValueError, tr.decimate, 7, strict_length=True)
# No processing should be applied yet.
self.assertFalse("processing" in tr.stats)
# Test the same but this time with an already existing processing
# information.
tr = Trace(data= | np.arange(20) | numpy.arange |
import numpy as np
from topocalc.gradient import gradient_d8
from topocalc.horizon import horizon
def d2r(a):
"""Angle to radians
Arguments:
a {float} -- angle in degrees
Returns:
v {float} -- angle in radians
"""
v = a * np.pi / 180
v = round(v, 6) # just for testing at the moment
return v
def viewf(dem, spacing, nangles=72, sin_slope=None, aspect=None):
"""
Calculate the sky view factor of a dem.
The sky view factor from equation 7b from Dozier and Frew 1990
.. math::
V_d \approx \frac{1}{2\pi} \int_{0}^{2\pi}\left [ cos(S) sin^2{H_\phi}
+ sin(S)cos(\phi-A) \times \left ( H_\phi - sin(H_\phi) cos(H_\phi)
\right )\right ] d\phi
terrain configuration factor (tvf) is defined as:
(1 + cos(slope))/2 - sky view factor
Based on the paper Dozier and Frew, 1990 and modified from
the Image Processing Workbench code base (Frew, 1990). The
Python version of sky view factor will be an almost exact
replication of the IPW command `viewf` minus rounding errors
from type and linear quantization.
Args:
dem: numpy array for the DEM
spacing: grid spacing of the DEM
nangles: number of angles to estimate the horizon, defaults
to 72 angles
sin_slope: optional, will calculate if not provided
sin(slope) with range from 0 to 1
aspect: optional, will calculate if not provided
Aspect as radians from south (aspect 0 is toward
the south) with range from -pi to pi, with negative
values to the west and positive values to the east.
Returns:
svf: sky view factor
tcf: terrain configuration factor
""" # noqa
if dem.ndim != 2:
raise ValueError('viewf input of dem is not a 2D array')
if nangles < 16:
raise ValueError('viewf number of angles should be 16 or greater')
if sin_slope is not None:
if np.max(sin_slope) > 1:
raise ValueError('slope must be sin(slope) with range from 0 to 1')
# calculate the gradient if not provided
# The slope is returned as radians so convert to sin(S)
if sin_slope is None:
slope, aspect = gradient_d8(
dem, dx=spacing, dy=spacing, aspect_rad=True)
sin_slope = np.sin(slope)
# -180 is North
angles = | np.linspace(-180, 180, num=nangles, endpoint=False) | numpy.linspace |
import numpy as np
import copy
from scipy.special import expit, softmax
from common.wbf_postprocess import weighted_boxes_fusion
def yolo_decode(prediction, anchors, num_classes, input_dims, scale_x_y=None, use_softmax=False):
'''Decode final layer features to bounding box parameters.'''
batch_size = np.shape(prediction)[0]
num_anchors = len(anchors)
grid_size = np.shape(prediction)[1:3]
#check if stride on height & width are same
assert input_dims[0]//grid_size[0] == input_dims[1]//grid_size[1], 'model stride mismatch.'
stride = input_dims[0] // grid_size[0]
prediction = np.reshape(prediction,
(batch_size, grid_size[0] * grid_size[1] * num_anchors, num_classes + 5))
################################
# generate x_y_offset grid map
grid_y = np.arange(grid_size[0])
grid_x = np.arange(grid_size[1])
x_offset, y_offset = np.meshgrid(grid_x, grid_y)
x_offset = np.reshape(x_offset, (-1, 1))
y_offset = np.reshape(y_offset, (-1, 1))
x_y_offset = np.concatenate((x_offset, y_offset), axis=1)
x_y_offset = np.tile(x_y_offset, (1, num_anchors))
x_y_offset = np.reshape(x_y_offset, (-1, 2))
x_y_offset = np.expand_dims(x_y_offset, 0)
################################
# Log space transform of the height and width
anchors = np.tile(anchors, (grid_size[0] * grid_size[1], 1))
anchors = np.expand_dims(anchors, 0)
box_xy = (expit(prediction[..., :2]) + x_y_offset) / np.array(grid_size)[::-1]
box_wh = (np.exp(prediction[..., 2:4]) * anchors) / np.array(input_dims)[::-1]
# Sigmoid objectness scores
objectness = expit(prediction[..., 4]) # p_o (objectness score)
objectness = np.expand_dims(objectness, -1) # To make the same number of values for axis 0 and 1
if use_softmax:
# Softmax class scores
class_scores = softmax(prediction[..., 5:], axis=-1)
else:
# Sigmoid class scores
class_scores = expit(prediction[..., 5:])
return np.concatenate([box_xy, box_wh, objectness, class_scores], axis=2)
def yolo_correct_boxes(predictions, img_shape, model_image_size):
'''rescale predicition boxes back to original image shape'''
box_xy = predictions[..., :2]
box_wh = predictions[..., 2:4]
objectness = np.expand_dims(predictions[..., 4], -1)
class_scores = predictions[..., 5:]
# model_image_size & image_shape should be (height, width) format
model_image_size = np.array(model_image_size, dtype='float32')
image_shape = np.array(img_shape, dtype='float32')
height, width = image_shape
new_shape = np.round(image_shape * np.min(model_image_size/image_shape))
offset = (model_image_size-new_shape)/2./model_image_size
scale = model_image_size/new_shape
# reverse offset/scale to match (w,h) order
offset = offset[..., ::-1]
scale = scale[..., ::-1]
box_xy = (box_xy - offset) * scale
box_wh *= scale
# Convert centoids to top left coordinates
box_xy -= box_wh / 2
# Scale boxes back to original image shape.
image_wh = image_shape[..., ::-1]
box_xy *= image_wh
box_wh *= image_wh
return np.concatenate([box_xy, box_wh, objectness, class_scores], axis=2)
def yolo_handle_predictions(predictions, image_shape, max_boxes=100, confidence=0.1, iou_threshold=0.4, use_cluster_nms=False, use_wbf=False):
boxes = predictions[:, :, :4]
box_confidences = np.expand_dims(predictions[:, :, 4], -1)
box_class_probs = predictions[:, :, 5:]
# filter boxes with confidence threshold
box_scores = box_confidences * box_class_probs
box_classes = np.argmax(box_scores, axis=-1)
box_class_scores = np.max(box_scores, axis=-1)
pos = np.where(box_class_scores >= confidence)
boxes = boxes[pos]
classes = box_classes[pos]
scores = box_class_scores[pos]
if use_cluster_nms:
# use Fast/Cluster NMS for boxes postprocess
n_boxes, n_classes, n_scores = fast_cluster_nms_boxes(boxes, classes, scores, iou_threshold, confidence=confidence)
elif use_wbf:
# use Weighted-Boxes-Fusion for boxes postprocess
n_boxes, n_classes, n_scores = weighted_boxes_fusion([boxes], [classes], [scores], image_shape, weights=None, iou_thr=iou_threshold)
else:
# Boxes, Classes and Scores returned from NMS
n_boxes, n_classes, n_scores = nms_boxes(boxes, classes, scores, iou_threshold, confidence=confidence)
if n_boxes:
boxes = np.concatenate(n_boxes)
classes = np.concatenate(n_classes).astype('int32')
scores = np.concatenate(n_scores)
boxes, classes, scores = filter_boxes(boxes, classes, scores, max_boxes)
return boxes, classes, scores
else:
return [], [], []
def box_iou(boxes):
"""
Calculate IoU value of 1st box with other boxes of a box array
Parameters
----------
boxes: bbox numpy array, shape=(N, 4), xywh
x,y are top left coordinates
Returns
-------
iou: numpy array, shape=(N-1,)
IoU value of boxes[1:] with boxes[0]
"""
# get box coordinate and area
x = boxes[:, 0]
y = boxes[:, 1]
w = boxes[:, 2]
h = boxes[:, 3]
areas = w * h
# check IoU
inter_xmin = np.maximum(x[1:], x[0])
inter_ymin = np.maximum(y[1:], y[0])
inter_xmax = np.minimum(x[1:] + w[1:], x[0] + w[0])
inter_ymax = np.minimum(y[1:] + h[1:], y[0] + h[0])
inter_w = np.maximum(0.0, inter_xmax - inter_xmin + 1)
inter_h = np.maximum(0.0, inter_ymax - inter_ymin + 1)
inter = inter_w * inter_h
iou = inter / (areas[1:] + areas[0] - inter)
return iou
def box_diou(boxes):
"""
Calculate DIoU value of 1st box with other boxes of a box array
Reference Paper:
"Distance-IoU Loss: Faster and Better Learning for Bounding Box Regression"
https://arxiv.org/abs/1911.08287
Parameters
----------
boxes: bbox numpy array, shape=(N, 4), xywh
x,y are top left coordinates
Returns
-------
diou: numpy array, shape=(N-1,)
IoU value of boxes[1:] with boxes[0]
"""
# get box coordinate and area
x = boxes[:, 0]
y = boxes[:, 1]
w = boxes[:, 2]
h = boxes[:, 3]
areas = w * h
# check IoU
inter_xmin = np.maximum(x[1:], x[0])
inter_ymin = np.maximum(y[1:], y[0])
inter_xmax = np.minimum(x[1:] + w[1:], x[0] + w[0])
inter_ymax = np.minimum(y[1:] + h[1:], y[0] + h[0])
inter_w = np.maximum(0.0, inter_xmax - inter_xmin + 1)
inter_h = np.maximum(0.0, inter_ymax - inter_ymin + 1)
inter = inter_w * inter_h
iou = inter / (areas[1:] + areas[0] - inter)
# box center distance
x_center = x + w/2
y_center = y + h/2
center_distance = np.power(x_center[1:] - x_center[0], 2) + np.power(y_center[1:] - y_center[0], 2)
# get enclosed area
enclose_xmin = np.minimum(x[1:], x[0])
enclose_ymin = np.minimum(y[1:], y[0])
enclose_xmax = np.maximum(x[1:] + w[1:], x[0] + w[0])
enclose_ymax = np.maximum(x[1:] + w[1:], x[0] + w[0])
enclose_w = np.maximum(0.0, enclose_xmax - enclose_xmin + 1)
enclose_h = np.maximum(0.0, enclose_ymax - enclose_ymin + 1)
# get enclosed diagonal distance
enclose_diagonal = np.power(enclose_w, 2) + np.power(enclose_h, 2)
# calculate DIoU, add epsilon in denominator to avoid dividing by 0
diou = iou - 1.0 * (center_distance) / (enclose_diagonal + np.finfo(float).eps)
return diou
def nms_boxes(boxes, classes, scores, iou_threshold, confidence=0.1, use_diou=True, is_soft=False, use_exp=False, sigma=0.5):
nboxes, nclasses, nscores = [], [], []
for c in set(classes):
# handle data for one class
inds = np.where(classes == c)
b = boxes[inds]
c = classes[inds]
s = scores[inds]
# make a data copy to avoid breaking
# during nms operation
b_nms = copy.deepcopy(b)
c_nms = copy.deepcopy(c)
s_nms = copy.deepcopy(s)
while len(s_nms) > 0:
# pick the max box and store, here
# we also use copy to persist result
i = np.argmax(s_nms, axis=-1)
nboxes.append(copy.deepcopy(b_nms[i]))
nclasses.append(copy.deepcopy(c_nms[i]))
nscores.append(copy.deepcopy(s_nms[i]))
# swap the max line and first line
b_nms[[i,0],:] = b_nms[[0,i],:]
c_nms[[i,0]] = c_nms[[0,i]]
s_nms[[i,0]] = s_nms[[0,i]]
if use_diou:
iou = box_diou(b_nms)
#iou = box_diou_matrix(b_nms, b_nms)[0][1:]
else:
iou = box_iou(b_nms)
#iou = box_iou_matrix(b_nms, b_nms)[0][1:]
# drop the last line since it has been record
b_nms = b_nms[1:]
c_nms = c_nms[1:]
s_nms = s_nms[1:]
if is_soft:
# Soft-NMS
if use_exp:
# score refresh formula:
# score = score * exp(-(iou^2)/sigma)
s_nms = s_nms * np.exp(-(iou * iou) / sigma)
else:
# score refresh formula:
# score = score * (1 - iou) if iou > threshold
depress_mask = np.where(iou > iou_threshold)[0]
s_nms[depress_mask] = s_nms[depress_mask]*(1-iou[depress_mask])
keep_mask = np.where(s_nms >= confidence)[0]
else:
# normal Hard-NMS
keep_mask = np.where(iou <= iou_threshold)[0]
# keep needed box for next loop
b_nms = b_nms[keep_mask]
c_nms = c_nms[keep_mask]
s_nms = s_nms[keep_mask]
# reformat result for output
nboxes = [np.array(nboxes)]
nclasses = [np.array(nclasses)]
nscores = [np.array(nscores)]
return nboxes, nclasses, nscores
def box_iou_matrix(boxes1, boxes2):
"""
Calculate IoU matrix for two box array.
Both sets of boxes are expected to be in (x, y, w, h) format.
Reference implementation:
https://github.com/pytorch/vision/blob/master/torchvision/ops/boxes.py
Arguments:
boxes1 (np.array[N, 4])
boxes2 (np.array[M, 4])
Returns:
iou (np.array[N, M]): the NxM matrix containing the pairwise
IoU values for every element in boxes1 and boxes2
"""
def box_area(box):
# box = 4xN
return box[2] * box[3]
area1 = box_area(boxes1.T)
area2 = box_area(boxes2.T)
inter_min = np.maximum(boxes1[:, None, :2], boxes2[:, :2]) # [N,M,2]
inter_max = np.minimum(boxes1[:, None, :2]+boxes1[:, None, 2:], boxes2[:, :2]+boxes2[:, 2:]) # [N,M,2]
inter = np.maximum(inter_max - inter_min, 0).prod(axis=-1) # [N,M]
iou = inter / (area1[:, None] + area2 - inter) # iou = inter / (area1 + area2 - inter)
return iou
def box_diou_matrix(boxes1, boxes2):
"""
Calculate DIoU matrix for two box array.
Both sets of boxes are expected to be in (x, y, w, h) format.
Arguments:
boxes1 (np.array[N, 4])
boxes2 (np.array[M, 4])
Returns:
diou (np.array[N, M]): the NxM matrix containing the pairwise
IoU values for every element in boxes1 and boxes2
"""
iou = box_iou_matrix(boxes1, boxes2)
# box center distance
center_distance = (boxes1[:, None, :2]+boxes1[:, None, 2:]/2) - (boxes2[:, :2]+boxes2[:, 2:]/2) # [N,M,2]
center_distance = np.power(center_distance[..., 0], 2) + np.power(center_distance[..., 1], 2) # [N,M]
# get enclosed area
enclose_min = np.minimum(boxes1[:, None, :2], boxes2[:, :2]) # [N,M,2]
enclose_max = np.maximum(boxes1[:, None, :2]+boxes1[:, None, 2:], boxes2[:, :2]+boxes2[:, 2:]) # [N,M,2]
enclose_wh = np.maximum(enclose_max - enclose_min, 0) # [N,M,2]
enclose_wh = np.maximum(enclose_max - enclose_min, 0) # [N,M,2]
# get enclosed diagonal distance matrix
enclose_diagonal = np.power(enclose_wh[..., 0], 2) + np.power(enclose_wh[..., 1], 2) # [N,M]
# calculate DIoU, add epsilon in denominator to avoid dividing by 0
diou = iou - 1.0 * np.true_divide(center_distance, enclose_diagonal + np.finfo(float).eps)
return diou
def fast_cluster_nms_boxes(boxes, classes, scores, iou_threshold, confidence=0.1, use_cluster=True, use_diou=True, use_weighted=True, use_matrix_nms=False, use_spm=False):
"""
Fast NMS/Cluster NMS/Matrix NMS bbox post process
Reference Paper:
1. "YOLACT: Real-time Instance Segmentation"
https://arxiv.org/abs/1904.02689
2. "Enhancing Geometric Factors in Model Learning and Inference for Object Detection and Instance Segmentation"
https://arxiv.org/abs/2005.03572
3. "SOLOv2: Dynamic, Faster and Stronger"
https://arxiv.org/abs/2003.10152
4. Blogpost on zhihu:
https://zhuanlan.zhihu.com/p/157900024
Parameters
----------
boxes: bbox numpy array, shape=(N, 4), xywh
x,y are top left coordinates
classes: bbox class index numpy array, shape=(N, 1)
scores: bbox score numpy array, shape=(N, 1)
iou_threshold:
Returns
-------
nboxes: NMSed bbox numpy array, shape=(N, 4), xywh
x,y are top left coordinates
nclasses: NMSed bbox class index numpy array, shape=(N, 1)
nscores: NMSed bbox score numpy array, shape=(N, 1)
"""
nboxes, nclasses, nscores = [], [], []
for c in set(classes):
# handle data for one class
inds = np.where(classes == c)
b = boxes[inds]
c = classes[inds]
s = scores[inds]
# make a data copy to avoid breaking
# during nms operation
b_nms = copy.deepcopy(b)
c_nms = copy.deepcopy(c)
s_nms = copy.deepcopy(s)
# ascend sort boxes according to scores
sorted_indices = np.argsort(s_nms)
sorted_indices = sorted_indices[::-1]
b_nms = b_nms[sorted_indices]
c_nms = c_nms[sorted_indices]
s_nms = s_nms[sorted_indices]
# number of boxes for one class
num_boxes = b_nms.shape[0]
# get IoU/DIoU matrix (upper triangular matrix)
if use_diou:
iou_matrix = box_diou_matrix(b_nms, b_nms)
else:
iou_matrix = box_iou_matrix(b_nms, b_nms)
iou_matrix = np.triu(iou_matrix, k=1)
max_iou = np.max(iou_matrix, axis=0)
updated_iou_matrix = copy.deepcopy(iou_matrix)
# Cluster loop
if use_cluster:
for i in range(200):
prev_iou_matrix = copy.deepcopy(updated_iou_matrix)
max_iou = np.max(prev_iou_matrix, axis=0)
keep_diag = np.diag((max_iou < iou_threshold).astype(np.float32))
updated_iou_matrix = np.dot(keep_diag, iou_matrix)
if (prev_iou_matrix == updated_iou_matrix).all():
break
if use_matrix_nms:
# Matrix NMS
max_iou_expand = np.tile(max_iou, (num_boxes, 1)).T #(num_boxes)x(num_boxes)
def get_decay_factor(method='gauss', sigma=0.5):
if method == 'gauss':
# gaussian decay
decay_factor = np.exp(-(iou_matrix**2 - max_iou_expand**2) / sigma)
else:
# linear decay
decay_factor = (1 - iou_matrix) / (1 - max_iou_expand)
# decay factor: 1xN
decay_factor = np.min(decay_factor, axis=0)
# clamp decay factor to <= 1
decay_factor = np.minimum(decay_factor, 1.0)
return decay_factor
# decay factor for box score
decay_factor = get_decay_factor()
# apply decay factor to punish box score,
# and filter box with confidence threshold
s_matrix_decay = s_nms * decay_factor
keep_mask = s_matrix_decay >= confidence
elif use_spm:
# apply SPM(Score Penalty Mechanism)
if use_diou:
# TODO: Cluster SPM distance NMS couldn't achieve good result, may need to double check
# currently we fallback to normal SPM
#
# Reference:
# https://github.com/Zzh-tju/CIoU/blob/master/layers/functions/detection.py
# https://zhuanlan.zhihu.com/p/157900024
#diou_matrix = box_diou_matrix(b_nms, b_nms)
#flag = (updated_iou_matrix >= 0).astype(np.float32)
#penalty_coef = np.prod(np.minimum(np.exp(-(updated_iou_matrix**2)/0.2) + diou_matrix*((updated_iou_matrix>0).astype(np.float32)), flag), axis=0)
penalty_coef = np.prod(np.exp(-(updated_iou_matrix**2)/0.2), axis=0)
else:
penalty_coef = np.prod(np.exp(-(updated_iou_matrix**2)/0.2), axis=0)
s_spm = penalty_coef * s_nms
keep_mask = s_spm >= confidence
else:
# filter low score box with iou_threshold
keep_mask = max_iou < iou_threshold
if use_weighted:
# generate weights matrix with box score and final IoU matrix
weights = (updated_iou_matrix*(updated_iou_matrix>iou_threshold).astype(np.float32) + np.eye(num_boxes)) * (s_nms.reshape((1, num_boxes)))
# convert box format to (xmin,ymin,xmax,ymax) for weighted average,
# and expand to NxN array
xmin_expand = np.tile(b_nms[:,0], (num_boxes, 1)) #(num_boxes)x(num_boxes)
ymin_expand = np.tile(b_nms[:,1], (num_boxes, 1)) #(num_boxes)x(num_boxes)
xmax_expand = np.tile(b_nms[:,0]+b_nms[:,2], (num_boxes, 1)) #(num_boxes)x(num_boxes)
ymax_expand = np.tile(b_nms[:,1]+b_nms[:,3], (num_boxes, 1)) #(num_boxes)x(num_boxes)
# apply weighted average to all the candidate boxes
weightsum = weights.sum(axis=1)
xmin_expand = np.true_divide((xmin_expand*weights).sum(axis=1), weightsum)
ymin_expand = np.true_divide((ymin_expand*weights).sum(axis=1), weightsum)
xmax_expand = np.true_divide((xmax_expand*weights).sum(axis=1), weightsum)
ymax_expand = np.true_divide((ymax_expand*weights).sum(axis=1), weightsum)
# stack the weighted average boxes and convert back to (x,y,w,h)
b_nms = np.stack([xmin_expand, ymin_expand, xmax_expand-xmin_expand, ymax_expand-ymin_expand], axis=1)
# keep NMSed boxes
b_nms = b_nms[keep_mask]
c_nms = c_nms[keep_mask]
s_nms = s_nms[keep_mask]
# merge NMSed boxes to final result
if len(nboxes) == 0:
nboxes = np.asarray(copy.deepcopy(b_nms))
nclasses = np.asarray(copy.deepcopy(c_nms))
nscores = np.asarray(copy.deepcopy(s_nms))
else:
nboxes = np.append(nboxes, copy.deepcopy(b_nms), axis=0)
nclasses = np.append(nclasses, copy.deepcopy(c_nms), axis=0)
nscores = np.append(nscores, copy.deepcopy(s_nms), axis=0)
# reformat result for output
nboxes = [np.array(nboxes)]
nclasses = [ | np.array(nclasses) | numpy.array |
#!/usr/bin/env python
import numpy as np
import sys
import os
Res31 = {'ALA': 'A', 'CYS': 'C', 'ASP': 'D', 'GLU': 'E', 'PHE': 'F',
'GLY': 'G', 'HIS': 'H', 'ILE': 'I', 'LYS': 'K', 'LEU': 'L',
'MET': 'M', 'ASN': 'N', 'PRO': 'P', 'GLN': 'Q', 'ARG': 'R',
'SER': 'S', 'THR': 'T', 'VAL': 'V', 'TRP': 'W', 'TYR': 'Y',
'ASX': 'N', 'GLX': 'Q', 'UNK': 'X', 'INI': 'K', 'AAR': 'R',
'ACE': 'X', 'ACY': 'G', 'AEI': 'T', 'AGM': 'R', 'ASQ': 'D',
'AYA': 'A', 'BHD': 'D', 'CAS': 'C', 'CAY': 'C', 'CEA': 'C',
'CGU': 'E', 'CME': 'C', 'CMT': 'C', 'CSB': 'C', 'CSD': 'C',
'CSE': 'C', 'CSO': 'C', 'CSP': 'C', 'CSS': 'C', 'CSW': 'C',
'CSX': 'C', 'CXM': 'M', 'CYG': 'C', 'CYM': 'C', 'DOH': 'D',
'EHP': 'F', 'FME': 'M', 'FTR': 'W', 'GL3': 'G', 'H2P': 'H',
'HIC': 'H', 'HIP': 'H', 'HTR': 'W', 'HYP': 'P', 'KCX': 'K',
'LLP': 'K', 'LLY': 'K', 'LYZ': 'K', 'M3L': 'K', 'MEN': 'N',
'MGN': 'Q', 'MHO': 'M', 'MHS': 'H', 'MIS': 'S', 'MLY': 'K',
'MLZ': 'K', 'MSE': 'M', 'NEP': 'H', 'NPH': 'C', 'OCS': 'C',
'OCY': 'C', 'OMT': 'M', 'OPR': 'R', 'PAQ': 'Y', 'PCA': 'Q',
'PHD': 'D', 'PRS': 'P', 'PTH': 'Y', 'PYX': 'C', 'SEP': 'S',
'SMC': 'C', 'SME': 'M', 'SNC': 'C', 'SNN': 'D', 'SVA': 'S',
'TPO': 'T', 'TPQ': 'Y', 'TRF': 'W', 'TRN': 'W', 'TRO': 'W',
'TYI': 'Y', 'TYN': 'Y', 'TYQ': 'Y', 'TYS': 'Y', 'TYY': 'Y',
'YOF': 'Y', 'FOR': 'X', '---': '-', 'PTR': 'Y', 'LCX': 'K',
'SEC': 'D', 'MCL': 'K', 'LDH': 'K'}
Res20 = ['ALA', 'ARG', 'ASN', 'ASP', 'CYS', 'GLN', 'GLU', 'GLY', 'HIS', 'ILE',
'LEU', 'LYS', 'MET', 'PHE', 'PRO', 'SER', 'THR', 'TRP', 'TYR', 'VAL']
Res13 = {'A': 'ALA', 'R': 'ARG', 'N': 'ASN', 'D': 'ASP', 'C': 'CYS',
'Q': 'GLN', 'E': 'GLU', 'G': 'GLY', 'H': 'HIS', 'I': 'ILE',
'L': 'LEU', 'K': 'LYS', 'M': 'MET', 'F': 'PHE', 'P': 'PRO',
'S': 'SER', 'T': 'THR', 'W': 'TRP', 'Y': 'TYR', 'V': 'VAL',
'X': 'UNK'}
seqcode1 = "-ARNDCQEGHILKMFPSTWYVX"
code_dict = {'-': 0, 'A': 1, 'R': 2, 'N': 3, 'D': 4, 'C': 5, 'Q': 6,
'E': 7, 'G': 8, 'H': 9, 'I': 10, 'L': 11, 'K': 12,
'M': 13, 'F': 14, 'P': 15, 'S': 16, 'T': 17, 'W': 18,
'Y': 19, 'V': 20, 'X': 21}
Ntype = 21
# Secondary Structure
COIL = ['S', 'T', ' ', '_'] # ' ' == '_'
HELIX = ['H', 'G', 'I']
STRAND = ['E', 'B']
SS8toSS3 = {'S': 'C', 'T': 'C', ' ': 'C', '_': 'C',
'H': 'H', 'G': 'H', 'I': 'H', 'E': 'E', 'B': 'E'}
# Solvent Accessibility
MAXACC = {'X': 180, 'A': 115, 'R': 225, 'N': 160, 'D': 150, 'C': 135, 'Q': 180,
'E': 190, 'G': 75, 'H': 195, 'I': 175, 'L': 170, 'K': 200, 'M': 185,
'F': 210, 'P': 145, 'S': 115, 'T': 140, 'W': 255, 'Y': 230, 'V': 155,
'B': 155, 'Z': 185}
THR3 = [0.09, 0.36]
# Amino Acid hydrophobicity
# ref http://stevegallik.org/cellbiologyolm_Ex02_P03.html
# Eisenberg and Weiss; Dngleman; Kyte and Doolittle; Hoop and Woods; Janin
AA_hydrophobicity = {
'I': [0.73, 3.1, 4.5, -1.8, 0.7],
'F': [0.61, 3.7, 2.8, -2.5, 0.5],
'V': [0.54, 2.6, 4.2, -1.5, 0.6],
'L': [0.53, 2.8, 3.8, -1.8, 0.5],
'W': [0.37, 1.9, -0.9, -3.4, 0.3],
'M': [0.26, 3.4, 1.9, -1.3, 0.4],
'A': [0.25, 1.6, 1.8, -0.5, 0.3],
'G': [0.16, 1.0, -0.4, 0.0, 0.3],
'C': [0.04, 2.0, 2.5, -1.0, 0.9],
'Y': [0.02, -0.7, -1.3, -2.3, -0.4],
'P': [-0.07, -0.2, -1.6, 0.0, -0.3],
'T': [-0.18, 1.2, -0.7, -0.4, -0.2],
'S': [-0.26, 0.6, -0.8, 0.3, -0.1],
'H': [-0.40, -3.0, -3.2, -0.5, -0.1],
'E': [-0.62, -8.2, -3.5, 3.0, -0.7],
'N': [-0.64, -4.8, -3.5, 0.2, -0.5],
'Q': [-0.69, -4.1, -3.5, 0.2, -0.7],
'D': [-0.72, -9.2, -3.5, 3.0, -0.6],
'K': [-1.10, -8.8, -3.9, 3.0, -1.8],
'R': [-1.80, -12.3, -4.5, 3.0, -1.4],
'X': [0.0, 0.0, 0.0, 0.0, 0.0]
}
# Amino Acid charge -1, 0, 1
AA_charge = {
'A': 0, 'V': 0, 'I': 0, 'L': 0, 'M': 0, 'F': 0, 'Y': 0, 'W': 0,
'C': 0, 'G': 0, 'P': 0,
'S': 0, 'T': 0, 'N': 0, 'Q': 0,
'D': -1, 'E': -1,
'R': 1, 'H': 1, 'K': 1,
'X': 0
}
# SS: C, H, E
SS3_dict = {'C': 0, 'H': 1, 'E': 2}
SS8_dict = {'S': 0, 'T': 1, ' ': 2, '_': 2,
'H': 3, 'G': 4, 'I': 5, 'E': 6, 'B': 7}
# SA: B, I, E
SA3_dict = {'B': 0, 'I': 1, 'E': 2}
def set_ss3(ss):
# if ss in COIL :
# return 'C'
# elif ss in HELIX :
# return 'H'
# elif ss in STRAND:
# return 'E'
return SS8toSS3[ss]
def set_sa3(rsa):
if rsa < THR3[0]:
return 'B'
elif rsa < THR3[1]:
return 'I'
else:
return 'E'
def creator(q, data, Nproc):
for d in data:
idx = d[0]
da = d[1]
q.put((idx, da))
for i in range(0, Nproc):
q.put('DONE')
def read_fasta(file_name):
fp = open(file_name)
lines = fp.readlines()
fp.close()
seq = ""
check = 0
for line in lines:
if line.startswith(">"):
if check == 1:
break
check = 0
continue
seq += line.strip()
return seq
def read_msa0(file_name, Nres):
fp = open(file_name)
lines = fp.readlines()
fp.close()
msa = list()
msa2 = list()
pasinfo = list()
Npasinfo = 0
for line in lines:
if line[0] == ">":
mm2 = np.zeros(Nres, dtype=int)
lis = line.strip().split("/")
inifin = lis[1]
inifin_list = inifin.strip().split(",")
pcheck = 0
for inifin2 in inifin_list:
inifin3 = inifin2.strip().split("-")
ini = int(inifin3[0])
fin = int(inifin3[1])
if ((ini > 20) or (fin < Nres-20)):
pcheck = 1
for i in range(ini-1, fin):
mm2[i] = 1
msa2 += [mm2]
pasinfo += [pcheck]
Npasinfo += 1
continue
else:
mm = np.zeros(Nres, dtype=int)
for i in range(0, Nres):
cc = line[i]
if cc not in code_dict:
j = 21
else:
j = code_dict[cc]
mm[i] = j
msa += [mm]
msa = np.concatenate([msa])
msa2 = np.concatenate([msa2])
pasinfo = np.array(pasinfo)
return msa, msa2, pasinfo
def read_msa(file_name, Nres):
fp = open(file_name)
lines = fp.readlines()
fp.close()
Npasinfo = 0
Nmsa = 0
PAS = np.zeros([Nres, Nres], dtype=np.float32)
# Nsig[i][0]: left_gap &right_gap
# Nsig[i][1]: left_gap
# Nsig[i][2]: right_gap
Nsig = np.zeros([Nres, 3], dtype=np.long)
for line in lines:
if line[0] == ">":
Nmsa += 1
lis = line.strip().split("/")
inifin = lis[1]
inifin_list = inifin.strip().split(",")
# pcheck = 0
for inifin2 in inifin_list:
inifin3 = inifin2.strip().split("-")
ini = int(inifin3[0])
fin = int(inifin3[1])
# if ((ini > 20) or (fin < Nres-20)):
# pcheck = 1
PAS[ini-1:fin, ini-1:fin] += 1
Npasinfo += 1
Nsig[ini-1][0] += 1
Nsig[fin-1][0] += 1
Nsig[ini-1][1] += 1
Nsig[fin-1][2] += 1
if Npasinfo != 0:
PAS = PAS/Npasinfo
return PAS, Nsig, Npasinfo, Nmsa
def cal_sig(Nsig, Nres, Nmsa):
Nsite5 = np.zeros([Nres, 3], np.long)
Nsig5 = np.zeros([Nres, 3], np.long)
psig5 = np.zeros([Nres, 3], np.float32)
msig5 = np.zeros([Nres, 3], np.float32)
fsite5 = np.zeros([Nres, 3], np.float32)
if Nmsa < 1:
return fsite5, psig5, msig5
for i in range(0, Nres):
ini = i - 5
fin = i + 5
if(ini < 0):
ini = 0
if(fin > Nres-1):
fin = Nres-1
Nsig5[i][1] = Nsig[ini:fin+1, 1].sum()
Nsig5[i][2] = Nsig[ini:fin+1, 2].sum()
Nsig5[i][0] = Nsig5[i][1] + Nsig5[i][2]
Nsite5[i][1] = Nsig[ini:fin+1, 1].astype(np.bool).sum()
Nsite5[i][2] = Nsig[ini:fin+1, 2].astype(np.bool).sum()
Nsite5[i][0] = Nsite5[i][1] + Nsite5[i][2]
fsite5[:, 1:3] = Nsite5[:, 1:3] / 11.0
fsite5[:, 0] = Nsite5[:, 0] / 22.0
ggap = 20 * Nres // 100
if (ggap < 20):
ggap = 20
if ggap > 100:
ggap = 100
ini = ggap
fin = Nres - ggap
max_sig5 = Nsig5[ini:fin].max(axis=0)
for k in range(0, 3):
if max_sig5[k] == 0:
max_sig5[k] = Nsig5[:, k].max()
psig5[:, 1:3] = Nsig5[:, 1:3] / float(Nmsa)
psig5[:, 0] = Nsig5[:, 0] / (2.0 * float(Nmsa))
msig5[:, 0] = Nsig5[:, 0] / float(max_sig5[0])
msig5[:, 1] = Nsig5[:, 1] / float(max_sig5[1])
msig5[:, 2] = Nsig5[:, 2] / float(max_sig5[2])
psig5 = psig5.clip(-1.0, 1.0)
msig5 = msig5.clip(-1.0, 1.0)
return fsite5, psig5, msig5
def read_ck2(file_name):
fp = open(file_name)
lines = fp.readlines()
fp.close()
Nres = int(lines[0].strip())
# seq = lines[1].strip()
Nat = 20
profile = np.zeros([Nres, Nat], dtype=np.float32)
for i, line in enumerate(lines[2:]):
lis = line.strip().split()
for j in range(Nat):
profile[i][j] = float(lis[j])
return profile
def read_ccmpred(file_name, Nres):
fp = open(file_name)
lines = fp.readlines()
fp.close()
ccmpred = np.zeros([Nres, Nres], dtype=np.float32)
for i, line in enumerate(lines):
lis = line.strip().split()
for j, ll in enumerate(lis):
ccmpred[i][j] = ll
for i in range(Nres):
for j in range(i, i+12):
if j < Nres:
ccmpred[i][j] = 0.0
ccmpred[j][i] = 0.0
return ccmpred
def cal_ccm_cut(ccmpred, Nres):
sum1 = 0
sum2 = 0
Nedge = 0
for i in range(Nres):
for j in range(i+12, Nres):
Nedge += 1
sum1 += ccmpred[i][j]
sum2 += pow(ccmpred[j][i], 2)
avg1 = sum1/Nedge
avg2 = sum2/Nedge
dd = avg2-pow(avg1, 2)
stddev = np.sqrt(dd)
ccm_cut = avg1+2*stddev
return ccm_cut
def cal_ccm_community(ccmpred, ccm_cut, Nres):
community = np.zeros([Nres], dtype=np.float32)
community0 = np.zeros([Nres], dtype=np.float32)
sum_con = 0
for i in range(Nres):
for j in range(i+1, Nres):
if ccmpred[i][j] >= ccm_cut:
sum_con += ccmpred[i][j]
M = sum_con
if M == 0.0:
return community0
ddd1 = 0
ddd2 = M
dm1 = 0
dm2 = 2*M
for k in range(Nres):
dd1 = 0
dd2 = 0
dd0 = 0
for i in range(0, k):
if(ccmpred[k][i] >= ccm_cut):
dd1 += ccmpred[k][i]
dd0 += ccmpred[k][i]
for i in range(k+1, Nres):
if(ccmpred[k][i] >= ccm_cut):
dd2 += ccmpred[k][i]
dd0 += ccmpred[k][i]
ddd1 += dd1
ddd2 -= dd2
dm1 += dd0
dm2 -= dd0
community1 = ddd1/M+ddd2/M
community2 = pow(dm1/(2*M), 2)+pow(dm2/(2*M), 2)
community[k] = community1-community2
for i in range(Nres):
if i == 0:
community0[i] = community[i]/2.0
continue
community0[i] = (community[i-1]+community[i])/2.0
return community0
def write_pas(out_file, PAS, Nres):
fp = open(out_file, "w")
for i in range(Nres):
for j in range(Nres):
line_out = "%4d %4d %6.4f\n" % (i+1, j+1, PAS[i][j])
fp.write(line_out)
fp.close()
def cal_pas_sum(PAS, Nres):
PASsumN = np.zeros(Nres, dtype=np.float32)
PASsumC = np.zeros(Nres, dtype=np.float32)
PASdiag = np.zeros(Nres, dtype=np.float32)
for i in range(0, Nres):
PASsumN[i] += PAS[i, :i+1].sum()/(i+1)
PASsumC[i] += PAS[i, i+1:].sum()/(Nres-i)
PASdiag[i] = PAS[i, i]
return PASsumN, PASsumC, PASdiag
def write_pas_sum(out_file, PASsumN, PASsumC, PASdiag, Nres):
fp = open(out_file, "w")
for i in range(Nres):
line_out = "%4d %6.4f %6.4f %6.4f\n" % (
i+1, PASsumN[i], PASsumC[i], PASdiag[i])
fp.write(line_out)
fp.close()
def write_ccm(out_file, ccmpred, Nres, ccm_cut):
fp = open(out_file, "w")
for i in range(Nres):
for j in range(Nres):
if ccmpred[i][j] >= ccm_cut:
line_out = "%4d %4d %6.4f\n" % (i+1, j+1, ccmpred[i][j])
else:
line_out = "%4d %4d %6.4f\n" % (i+1, j+1, 0.0)
fp.write(line_out)
fp.close()
return
def write_community(out_file, community, Nres):
fp = open(out_file, "w")
for i in range(Nres):
line_out = "%4d %6.4f\n" % (i+1, community[i])
fp.write(line_out)
fp.close()
return
def read_pdb(pdb_file):
n_file = open(pdb_file)
lines = n_file.readlines()
n_file.close()
chain = dict()
old_chain_id = ""
for line in lines:
if line[:6] == 'ATOM ':
chain_id = line[21]
if chain_id != old_chain_id:
CA_dict = dict()
CB_dict = dict()
res_dict = dict()
atom_dict = dict()
atom_map = dict()
old_chain_id = chain_id
chain[chain_id] = dict()
idx = 0
chain[chain_id]['CA_dict'] = CA_dict
chain[chain_id]['CB_dict'] = CB_dict
chain[chain_id]['res_dict'] = res_dict
chain[chain_id]['atom_dict'] = atom_dict
chain[chain_id]['atom_map'] = atom_map
chain[chain_id]['seq'] = ""
iseq = line[22:27].strip()
atom = line[12:16].strip()
res = line[17:20]
coor = np.array([float(line[30:38]), float(
line[38:46]), float(line[46:54])])
if iseq not in res_dict:
res_dict[iseq] = res
chain[chain_id]['seq'] += Res31[res]
idx += 1
atom_map[idx] = iseq
if res not in Res20:
print(iseq, res)
if iseq not in atom_dict:
atom_dict[iseq] = [line]
else:
atom_dict[iseq] += [line]
if atom == "CA":
CA_dict[iseq] = coor
if res != "GLY":
if atom == "CB":
CB_dict[iseq] = coor
elif atom == "CA":
CB_dict[iseq] = coor
return chain
def read_amap(amap_file):
map_dict = dict()
map_dict2 = dict()
fa_map = dict()
fp = open(amap_file)
lines = fp.readlines()
fp.close()
for line in lines:
line_arr = line.split()
fa_map[int(line_arr[0])] = line_arr[1]
map_dict[int(line_arr[0])] = (line_arr[6], line_arr[2])
if line_arr[6] == "-":
continue
map_dict2[line_arr[6]] = int(line_arr[0])
return map_dict, map_dict2, fa_map
def gen_mask(map_dict, Nres):
keys = sorted(map_dict.keys())
mask = np.ones([Nres], dtype=np.float32)
for i in keys:
j0 = map_dict[i][1]
# j = map_dict[i][0]
if j0 == "-":
ini = i-2
if ini < 0:
ini = 0
fin = i+1
mask[ini:fin] = 0
mask = | np.array(mask, dtype=np.float32) | numpy.array |
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 17 16:20:02 2019
@author: lmassoul032513
"""
import pytest
import pandas as pd
import numpy as np
from copy import deepcopy
from sklearn.utils import check_random_state
from aikit.datasets.datasets import load_dataset, DatasetEnum
from aikit.enums import TypeOfProblem, TypeOfVariables, StepCategories
from aikit.ml_machine.ml_machine import (
AutoMlConfig,
JobConfig,
RandomModelGenerator,
AutoMlResultReader,
MlJobManager,
MlJobRunner,
_create_all_combinations,
random_list_generator,
)
from aikit.ml_machine.model_graph import convert_graph_to_code
from aikit.model_definition import sklearn_model_from_param
from aikit.ml_machine.ml_machine_guider import AutoMlModelGuider
from aikit.ml_machine.data_persister import FolderDataPersister
from aikit.tools.graph_helper import get_terminal_nodes
def loader(num_only=False):
if num_only:
np.random.seed(123)
dfX = pd.DataFrame(np.random.randn(100, 10), columns=["COL_%d" % d for d in range(10)])
y = 1 * (np.random.randn(100) > 0)
return dfX, y
else:
dfX, y, _, _, _ = load_dataset(DatasetEnum.titanic)
return dfX, y
def get_automl_config(num_only):
dfX, y = loader(num_only)
auto_ml_config = AutoMlConfig(dfX, y)
auto_ml_config.guess_everything()
return dfX, y, auto_ml_config
def test_AutoMlConfig_raise_if_wrong_nb_oberservations():
dfX = pd.DataFrame({"a": [0, 1, 2, 3, 4, 5], "b": [0, 10, 20, 30, 40, 50]})
y = np.array([0, 0, 0, 1, 1, 1])
auto_ml_config = AutoMlConfig(dfX, y[0:3])
with pytest.raises(ValueError):
auto_ml_config.guess_everything() # raise because y doesn't have the correct number of observations
def test_AutoMlConfig_raise_multioutput():
dfX = pd.DataFrame({"a": [0, 1, 2, 3, 4, 5], "b": [0, 10, 20, 30, 40, 50]})
y = | np.array([0, 0, 0, 1, 1, 1]) | numpy.array |
import numpy as np
from scipy.stats import gengamma
import os as os
from random import sample
from abc import ABC, abstractmethod
from YGRW.data_interp import JumpDistFromAngle, AngleFromAngle
from math import sqrt
CUR_DIR = os.path.dirname(__file__)
DATA_DIR = os.path.join(CUR_DIR, "data")
deg = np.pi / 180
# ------------------------
# Abstract classes
# ------------------------
class Stepper(ABC):
"""
Abstract class which implements generate_step and generate_bound_step methods
for subsequent steppers to work off of.
"""
def __init__(self):
pass
@abstractmethod
def generate_step(self, *args, **kwargs):
raise NotImplementedError
def generate_bound_step(self, *args, **kwargs):
"""
If a child class does not have this method defined,
call child class' generate step method.
"""
return self.generate_step(*args, **kwargs)
class AngleStepper(ABC):
"""
Abstract class for generating an angle of a step- used to complement steppers like UniformSteps
which yield a step length but not a direction.
Generates an angle for a successive step defined with respect to the previous
step along [-180, 180] where clockwise is positive and counterclockwise is
negative. In other words, an angle of 0 would correspond to no change in angle,
+- 90 degrees correspond to right and left respectively, and -180 and 180 are
both antiparallel to the previous angle.
"""
def __init__(self):
pass
@abstractmethod
def generate_angle(self, *args, **kwargs):
raise NotImplementedError
# ------------------------
# Specific Stepper classes
# ------------------------
class FBMSteps(Stepper):
def __init__(
self,
step_batchsize: int = 200,
gamma: float = 0.00375,
alpha: float = 0.448,
bound_gamma: float = 0.00075,
bound_alpha: float = 0.373,
dt: float = 1,
boundstepper: Stepper = None,
):
"""
Stepper which generates steps consistent with Fractional Brownian Motion (i.e. correlated Gaussian noise with
no driving force in the overdamped limit).
Based on the algorithm of
<NAME> and <NAME>,
SIAM J. Sci. Comput., 18(4), 1088–1107.
https://doi.org/10.1137/S1064827592240555
Parameters
----------
step_batchsize: Number of steps of random correlated noise to generate.
gamma: scales the stepsizes during 'unbound' diffusion (in nucleoplasm, or near periphery but unbounded)
alpha: controls degree of correlation / anti-correlation during 'unbound' diffusion
bound_gamma: scales the stepsizes during 'bound' diffusion (when in 'bound zone' near periphery and bound state begins)
bound_alpha: controls degree of correlation / anti-correlation during 'bound' diffusion
dt: constant time-step
boundstepper: Can allow for a seperate stepper to be used for 'bound' diffusion
"""
self.gamma = gamma
self.alpha = alpha
self.bound_gamma = bound_gamma
self.bound_alpha = bound_alpha
self.dt = dt
self.cur_step = 0
self.real_step = 0
self.step_batchsize = step_batchsize
(self.pre_x, self.pre_y) = self.generate_correlated_noise()
self.boundstepper = boundstepper
# preprocess hurst exponent for movement regimens
H = self.alpha / 2
bound_H = self.bound_alpha / 2
# preprocess msd normalization for movement regimens
self.norm_msd = sqrt(2 * self.gamma) * self.dt ** H
self.bound_norm_msd = sqrt(2 * self.bound_gamma) * self.dt ** bound_H
super().__init__()
def generate_step(self, *args, **kwargs):
# If the trajectory exhausts the generated steps, regenerate
if self.cur_step >= self.step_batchsize:
adj_batchsize = self.step_batchsize - self.real_step
if adj_batchsize <= 0:
adj_batchsize = self.step_batchsize
self.regenerate_correlated_noise()
# normalize noise to the expected MSD
dx = self.norm_msd * self.pre_x[self.cur_step]
dy = self.norm_msd * self.pre_y[self.cur_step]
self.real_step += 1
self.cur_step += 1
return np.array([dx, dy])
def generate_bound_step(self, *args, **kwargs):
if self.boundstepper == None:
if self.cur_step >= self.step_batchsize:
adj_batchsize = self.step_batchsize - self.real_step
if adj_batchsize <= 0:
adj_batchsize = self.step_batchsize
self.regenerate_correlated_noise()
# normalize noise to the expected bound MSD
dx = self.bound_norm_msd * self.pre_x[self.cur_step]
dy = self.bound_norm_msd * self.pre_y[self.cur_step]
# When a different bound stepper is called, it will be employed here
else:
(dx, dy) = self.boundstepper.generate_bound_step()
self.real_step += 1
self.cur_step += 1
return np.array([dx, dy])
def generate_correlated_noise(
self,
steps: int = None,
fle_random_seed: int = None,
):
"""
Generates a series of correlated noise values.
Based on the implementation by <NAME> in
<NAME>, <NAME>, <NAME>, and <NAME>,
Cell 158, 339–352, 2014
https://doi.org/10.1016/j.cell.2014.05.036
Which is based on the algorithm of
<NAME> and <NAME>,
SIAM J. Sci. Comput., 18(4), 1088–1107.
https://doi.org/10.1137/S1064827592240555
Parameters
----------
steps: number of time steps
dt
gamma
alpha: Correlation parameter. 1 is no correlation, [1,2] is positive correlation,
(0,1) is anticorrelation.
Returns
-------
"""
if steps is None:
steps = self.step_batchsize
# Compute correlation vector R.
pre_r = np.zeros(shape=(steps + 1))
pre_r[0] = 1.0
for k in range(1, steps + 1):
fd_addition = (
(k + 1) ** self.alpha - 2 * (k ** self.alpha) + (k - 1) ** self.alpha
) / 2
pre_r[k] = fd_addition
nrel = len(pre_r)
r = np.zeros(2 * nrel - 2)
r[:nrel] = pre_r
reverse_r = np.flip(pre_r)
r[nrel - 1 :] = reverse_r[:-1]
# Fourier transform pre-computed values earlier
# Corresponds to step a on page 1091 of Dietrich & Newsam,
s = np.real(np.fft.fft(r)) / (2 * steps)
strans = np.lib.scimath.sqrt(s)
if fle_random_seed:
np.random.seed(fle_random_seed)
# Generate randomly distributed points in the complex plane (step b)
randnorm_complex = np.random.normal(size=(2 * steps)) + 1j * np.random.normal(
size=(2 * steps)
)
# Compute FFT: (step c),
second_fft_x = np.fft.fft(np.multiply(strans, randnorm_complex))
randnorm_complex = np.random.normal(size=(2 * steps)) + 1j * np.random.normal(
size=(2 * steps)
)
second_fft_y = np.fft.fft(np.multiply(strans, randnorm_complex))
# Scale results for final use.
# Hurst exponent
# H = self.alpha / 2
# bound_H = self.bound_alpha / 2
# Length scale for process
# norm_msd = sqrt(2 * self.gamma) * self.dt ** H
# bound_norm_msd = sqrt(2 * self.bound_gamma) * self.dt ** bound_H
# If gamma is ordinarily in m^2/s,
# to convert to m^2/ s^alpha,
# multiply by 1 s / s^alpha,
# 1 s /
# Store correlated noise values. Step d.
# x_sreps = norm_msd * np.real(second_fft_x[0:steps])
# y_steps = norm_msd * np.real(second_fft_y[0:steps])
# bound_x_steps = bound_norm_msd * np.real(second_fft_x[0:steps])
# bound_y_steps = bound_norm_msd * np.real(second_fft_y[0:steps])
x_noise = np.real(second_fft_x[0:steps])
y_noise = np.real(second_fft_y[0:steps])
return x_noise, y_noise
def regenerate_correlated_noise(self, batch_size: int = None):
"""
If the number of steps in the current batch have been exhausted, or an external circumstance dictates the
generation of new noise, this produces a new set of correlated noise.
Assigns noise 'in-place' as class attribute.
Please note that this causes the previous noise correlations to be 'forgotten'
and so the new noise batch will not contain any correlations with the previous batch- it is, in effect,
a completely new noise source.
Parameters
----------
batch_size: Number of steps in correlated noise to generate
Returns
-------
"""
if batch_size is None:
# Adjusts batch size of generation
temp_batch_size = self.step_batchsize - self.real_step
# Sometimes batches become too small for fft
if temp_batch_size < 100:
temp_batch_size = 100
batch_size = temp_batch_size
(self.pre_x, self.pre_y) = self.generate_correlated_noise(steps=batch_size)
self.cur_step = 0
class UniformSteps(Stepper):
def __init__(self, lower: float = -1, upper: float = 1):
self.lower = lower
self.upper = upper
super().__init__()
def generate_step(self, prev_step=None, prev_angle=None):
return np.random.uniform(self.lower, self.upper, size=2)
def generate_bound_step(self, prev_step=None, prev_angle=None):
return np.random.uniform(self.lower, self.upper, size=2)
class GaussianSteps(Stepper):
def __init__(self, mu: float = 0, sig: float = 1):
self.mu = mu
self.sig = sig
super().__init__()
def generate_step(self, prev_step=None, prev_angle=None):
return np.random.normal(loc=self.mu, scale=self.sig, size=2)
def generate_bound_step(self, prev_step=None, prev_angle=None):
return np.random.normal(loc=self.mu, scale=self.sig / 2, size=2)
class GaussianDragSteps(Stepper):
def __init__(
self,
mu: float = 0,
sig: float = 1,
bound_mu: float = None,
bound_sig: float = None,
spring_constant: float = -0.5,
):
"""
Stepper which generates steps in a uniform direction with a 'drag'
that will apply (spring constant)*(the previous step) returning to the previous
direction on top of a uniformly drawn angle and step size. Should be a negative
number ranging from [-1,0] to yield an anticorrelated random walk; if positive,
will yield a 'persistent random walk' that will cause the previous step
to be *added* to the next step.
Parameters
----------
shape
rate
bound_shape
bound_rate
spring_constant
"""
self.mu = mu
self.sig = sig
self.spring_constant = spring_constant
self.bound_mu = bound_mu or mu
self.bound_sig = bound_sig or sig
super().__init__()
def generate_step(self, prev_step=None, prev_angle=None):
x_drag, y_drag = compute_drag(prev_step, self.spring_constant)
x_step, y_step = np.random.normal(loc=self.mu, scale=self.sig, size=2)
return np.array((x_step + x_drag, y_step + y_drag))
def generate_bound_step(self, prev_step=None, prev_angle=None):
x_drag, y_drag = compute_drag(prev_step, self.spring_constant)
x_step, y_step = np.random.normal(loc=self.mu, scale=self.sig, size=2)
return np.array((x_step + x_drag, y_step + y_drag))
class GammaSteps(Stepper):
def __init__(
self,
shape: float = 3,
rate: float = 45,
bound_shape: float = 2.7,
bound_rate: float = 72,
):
self.shape = shape
self.scale = 1 / rate
self.bound_shape = bound_shape or shape
self.bound_scale = 1 / bound_rate or 1 / rate
super().__init__()
def generate_step(self, prev_step=None, prev_angle=None):
# TODO incorporate anglestepper
magnitude = np.random.gamma(shape=self.shape, scale=self.scale, size=1)
angle = np.random.uniform(low=-180, high=180, size=1)
x_step = np.cos(angle * deg) * magnitude
y_step = np.sin(angle * deg) * magnitude
return np.array((x_step, y_step))
def generate_bound_step(self, prev_step=None, prev_angle=None):
magnitude = np.random.gamma(
shape=self.bound_shape, scale=self.bound_scale, size=1
)
angle = np.random.uniform(low=-180, high=180, size=1)
x_step = np.cos(angle * deg) * magnitude
y_step = | np.sin(angle * deg) | numpy.sin |
import json
import tensorflow as tf
import tensorflow.compat.v1 as tf1
from tensorflow.keras import initializers
import numpy as np
from mpi4py import MPI
from gpt2_keras.builder.gpt2parallelize import GPT2, MultiLayerPerceptron
from gpt2_keras.builder import original_gpt2
from gpt2_keras.builder.builderParallel import build
# from .builder.builder import build
from gpt2_keras.encoder import get_encoder
from preprocess_test import preprocess
import pickle
import time
print("import success")
comm = MPI.COMM_WORLD
rank = comm.Get_rank()
size = comm.Get_size()
batch_size = 1
word_embedding = 768
max_seq_length = 500
num_decoder = 12
DECODER_TAG = 1000
ZSLICE_TAG = 10000
# !!!!!!!!! UNCOMMENT BELOW WHEN RUNNING ON AWS
print(size)
assert size >= 12 # Let us program for the case where each core can get at least one MLP layer each
# (There are 12 MLPs in GPT-2)
start_time = time.time()
try:
if rank == 0: # If this is the master, start building the GPT2 model
with open("./models/124M/hparams.json") as f:
config = json.load(f)
model_dir = "./models/"
model_name = "124M"
enc = get_encoder(model_name, model_dir)
gpt2= build(config, "./models/124M/model.ckpt", name='gpt2')
corpus = preprocess(
filepath="../data/target_texts/the_circular_ruins_lines.txt",
model_dir="./models/",
model_name="124M")
# print(corpus)
# Once the build is complete, take all the MLPs in the Decoder blocks
embedding_layer = gpt2.layers[0]
transformer_model = gpt2.layers[1]
#print("length of the layers:", len(transformer_model.layers)) # 13, including the normalization layer
MLPs = [] # list of MLP layers( to be precise, their config dicts) in all decoder blocks
ATTNs = []
for decoderblock in transformer_model.layers[:-1]: # The last layer is the Layer Normalization
#point-to-point communication
ser = tf.keras.layers.serialize(decoderblock.mlp)
# print(ser)
MLPs.append(ser)
ATTNs.append(decoderblock.attention)
# Broadcast all the MLPs to everyone (much more efficient than simple copy of the entire Transformer)
comm.bcast(MLPs, root=0) # The MLPs are broadcast from rank=0
# for worker_num, MLP in enumerate(MLPs): # The last layer is the Layer Normalization
# #point-to-point communication
# #Send
# continue_forward = True
# comm.isend(MLPs[worker_num], dest=worker_num+1, tag=worker_num+1)
#Start doing forward runs
# For simplicity, let's train for the case where 1 line = 1 instance of a batch
"""
partition_size = len(corpus) // 3
corpuss = [
corpus[:partition_size],
corpus[partition_size: partition_size*2],
corpus[partition_size*2:]
]
"""
epochs = 10
tf1.keras.backend.set_floatx('float64')
for ith_epoch in range(epochs):
# for corp in corpuss:
embedded = embedding_layer(corpus)
for i in range(num_decoder): #
prev_decoder_output = None
if i ==0:
A1 = ATTNs[i](embedded)
# print(A1.shape) # (104, 500, 768) == (batch, max_seq, embed_size)
#Evenly Send out partintioned Z matrix to ALL THE WORKERS. That is, each worker gets max_seq(=500) / size
Z1 = embedded + A1
# print(Z1.shape) # (104, 500, 768) == (batch, max_seq, embed_size)
Z1 = transformer_model.layers[0].mlp.layer_norm(Z1)
print( | np.array(Z1) | numpy.array |
import sys
import os
import glob
import numpy as np
import re
import xarray as xr
import datetime as dt
from itertools import product
from multiprocessing import Pool, cpu_count, current_process
from classified_cset.utils import LoopTimer
class Groupby:
# note: adapted from https://github.com/esantorella/hdfe. MIT license required upon publication
def __init__(self, keys):
self.keys, self.keys_as_int = np.unique(keys, return_inverse = True)
self.n_keys = max(self.keys_as_int) + 1
self.set_indices()
def set_indices(self):
self.indices = [[] for i in range(self.n_keys)]
for i, k in enumerate(self.keys_as_int):
self.indices[k].append(i)
self.indices = [np.array(elt) for elt in self.indices]
def apply(self, function, vector, broadcast=False):
if broadcast:
result = np.zeros(len(vector))
for idx in self.indices:
result[idx] = function(vector[idx])
else:
result = np.zeros(self.n_keys)
for k, idx in enumerate(self.indices):
result[k] = function(vector[idx])
return result
def read_file(f):
data = xr.open_dataset(f)
year = data.time_vars.isel(yr_day_utc=0).values
day = data.time_vars.isel(yr_day_utc=1).values
utc = data.time_vars.isel(yr_day_utc=2).values
total_secs = (utc*3600)
secs = total_secs//1
msecs = 1000*total_secs%1
dtime = np.datetime64(f'{ | np.median(year) | numpy.median |
import numpy as np
from sklearn.utils import murmurhash3_32
# Number feature.
class NumEmbedMatrix(object):
def __init__(self, size=20000, dim=5, bound=0.1):
self.matrix = None
self.dim = dim
self.size = size
self.bound = bound
def create(self, seed=6):
if self.matrix is None:
np.random.seed(seed)
self.matrix = np.random.uniform(-self.bound, self.bound, (self.size, self.dim))
def clean(self):
self.matrix = None
def get_embedding(self, token, seed=6):
max_length = 5
if self.matrix is None:
self.create(seed)
if len(token) <= max_length and token.isdigit():
hash_index = murmurhash3_32(token, positive=True) % self.size
return self.matrix[hash_index]
else:
return np.zeros(self.dim)
GlobalNumEmbedding = NumEmbedMatrix()
# encode a list of tokens
def encode_num_in_ltokens(tokens):
array_list = []
for token in tokens:
array_list.append(GlobalNumEmbedding.get_embedding(token))
# assert len(array_list) == len(tokens)
num_encoding = | np.stack(array_list, axis=0) | numpy.stack |
from numpy import concatenate, zeros
from scipy.linalg import toeplitz
import matplotlib.pyplot as plt
import torch
import torch.nn as nn
from numpy import concatenate, zeros
from scipy.linalg import toeplitz
import torch
from torch import nn
import numpy as np
import matplotlib as mat
mat.use("TkAgg")
import matplotlib.pyplot as plt
import time
from torch.autograd import Variable
import cv2
torch.manual_seed(1) # reproducible
hidden_siz = 50
hidden_lay = 1
LR = 0.02 # learning rate
class LSNN(nn.Module):
def __init__(self):
super(LSNN, self).__init__()
self.lstm = nn.LSTM(
input_size=5,
hidden_size=hidden_siz,
num_layers=hidden_lay,
batch_first=True,
)
self.hidden = (torch.autograd.Variable(torch.zeros(hidden_lay, 1, hidden_siz)),torch.autograd.Variable(torch.zeros(hidden_lay, 1, hidden_siz)))
self.out = nn.Linear(hidden_siz, 1)
def forward(self,x):
# x (batch, time_step, input_size)
# h_state (n_layers, batch, hidden_size)
# r_out (batch, time_step, output_size)
r_out,self.hidden= self.lstm(x,self.hidden)
self.hidden=(Variable(self.hidden[0]),Variable(self.hidden[1]))
outs = []
for time_step in range(r_out.size(1)):
outs.append(self.out(r_out[:, time_step, :]))
return torch.stack(outs, dim=1)
lstmNN = LSNN()
optimizer = torch.optim.Adam(lstmNN.parameters(), lr=LR) # optimize all rnn parameters
loss_func = nn.MSELoss()
loss_list = []
prediction_list = []
for step in range(80-6):
steps = np.linspace(0, 100, 100, dtype=np.float32)
if step == 0:
x_np = toeplitz(concatenate([[1.], zeros(99)]),concatenate([[1.,1.,1.], zeros(97)]))[step: 5, :]
y_np = toeplitz(concatenate([[1.], zeros(99)]),concatenate([[1.,1.,1.], zeros(97)]))[5:6, :]
else:
x_np = concatenate([
toeplitz(concatenate([[1.], zeros(99)]),concatenate([[1.,1.,1.], zeros(97)]))[step: step+4, :],
prediction.view(1,100).data.numpy()])
y_np = toeplitz(concatenate([[1.], zeros(99)]),concatenate([[1.,1.,1.], | zeros(97) | numpy.zeros |
# coding: utf-8
import sys
import os
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
__all__ = ['Ackley','Sphere','Rosenbrock','Beale','GoldsteinPrice','Booth',
'BukinN6','Matyas','LeviN13','ThreeHumpCamel','Easom','Eggholder',
'McCormick','SchafferN2','SchafferN4','StyblinskiTang','DeJongsF1',
'DeJongsF2','DeJongsF3','DeJongsF4','DeJongsF5','Ellipsoid','KTablet',
'FiveWellPotential','WeightedSphere','HyperEllipsodic',
'SumOfDifferentPower','Griewank','Michalewicz','Perm','Rastrigin',
'Schwefel','SixHumpCamel','Shuberts','XinSheYang','Zakharov']
__oneArgument__ = ['Beale','GoldsteinPrice','Booth','BukinN6','Matyas','LeviN13',
'ThreeHumpCamel','Easom','Eggholder','McCormick','SchafferN2',
'SchafferN4','DeJongsF3','DeJongsF4','DeJongsF5',
'FiveWellPotential','SixHumpCamel','Shuberts']
__twoArgument__ = ['Ackley','Sphere','Rosenbrock','StyblinskiTang','DeJongsF1',
'DeJongsF2','Ellipsoid','KTablet','WeightedSphere',
'HyperEllipsodic','SumOfDifferentPower','Griewank',
'Michalewicz','Rastrigin','Schwefel','XinSheYang','Zakharov']
__threeArgument__ = ['Perm']
##### Basic function #####
class OptimalBasic:
def __init__(self, variable_num):
self.variable_num = variable_num
self.max_search_range = np.array([0]*self.variable_num)
self.min_search_range = np.array([0]*self.variable_num)
self.optimal_solution = np.array([0]*self.variable_num)
self.global_optimum_solution = 0
self.plot_place = 0.25
self.func_name = ''
self.save_dir = os.path.dirname(os.path.abspath(__file__))+'\\img\\'
if(os.path.isdir(self.save_dir) == False):
os.mkdir(self.save_dir)
def get_global_optimum_solution(self):
return self.global_optimum_solution
def get_optimal_solution(self):
return self.optimal_solution
def get_search_range(self):
return [self.max_search_range, self.min_search_range]
def get_func_val(self, variables):
return -1
def plot(self):
x = np.arange(self.min_search_range[0],self.max_search_range[0], self.plot_place, dtype=np.float32)
y = np.arange(self.min_search_range[1],self.max_search_range[1], self.plot_place, dtype=np.float32)
X, Y = np.meshgrid(x,y)
Z = []
for xy_list in zip(X,Y):
z = []
for xy_input in zip(xy_list[0],xy_list[1]):
tmp = list(xy_input)
tmp.extend(list(self.optimal_solution[0:self.variable_num-2]))
z.append(self.get_func_val(np.array(tmp)))
Z.append(z)
Z = np.array(Z)
fig = plt.figure()
ax = Axes3D(fig)
ax.plot_wireframe(X,Y,Z)
plt.show()
def save_fig(self):
x = np.arange(self.min_search_range[0],self.max_search_range[0], self.plot_place, dtype=np.float32)
y = np.arange(self.min_search_range[1],self.max_search_range[1], self.plot_place, dtype=np.float32)
X, Y = np.meshgrid(x,y)
Z = []
for xy_list in zip(X,Y):
z = []
for xy_input in zip(xy_list[0],xy_list[1]):
tmp = list(xy_input)
tmp.extend(list(self.optimal_solution[0:self.variable_num-2]))
z.append(self.get_func_val(np.array(tmp)))
Z.append(z)
Z = np.array(Z)
fig = plt.figure()
ax = Axes3D(fig)
ax.plot_wireframe(X,Y,Z)
plt.savefig(self.save_dir+self.func_name+'.png')
plt.close()
##### Optimization benchmark function group #####
##### Class Ackley function #####
class Ackley(OptimalBasic):
def __init__(self,variable_num):
super().__init__(variable_num)
self.max_search_range = np.array([32.768]*self.variable_num)
self.min_search_range = np.array([-32.768]*self.variable_num)
self.optimal_solution = np.array([0]*self.variable_num)
self.global_optimum_solution = 0
self.func_name = 'Ackley'
def get_func_val(self, variables):
tmp1 = 20.-20.*np.exp(-0.2*np.sqrt(1./self.variable_num*np.sum(np.square(variables))))
tmp2 = np.e-np.exp(1./self.variable_num*np.sum(np.cos(variables*2.*np.pi)))
return tmp1+tmp2
##### Class Sphere function #####
class Sphere(OptimalBasic):
def __init__(self, variable_num):
super().__init__(variable_num)
self.max_search_range = np.array([1000]*self.variable_num) # nearly inf
self.min_search_range = np.array([-1000]*self.variable_num) # nearly inf
self.optimal_solution = np.array([1]*self.variable_num)
self.global_optimum_solution = 0
self.plot_place = 10
self.func_name = 'Sphere'
def get_func_val(self, variables):
return np.sum(np.square(variables))
##### Class Rosenbrock function #####
class Rosenbrock(OptimalBasic):
def __init__(self, variable_num):
super().__init__(variable_num)
self.max_search_range = np.array([5]*self.variable_num)
self.min_search_range = np.array([-5]*self.variable_num)
self.optimal_solution = np.array([1]*self.variable_num)
self.global_optimum_solution = 0
self.plot_place = 0.25
self.func_name = 'Rosenbrock'
def get_func_val(self, variables):
f = 0
for i in range(self.variable_num-1):
f += 100*np.power(variables[i+1]-np.power(variables[i],2),2)+np.power(variables[i]-1,2)
return f
##### Class Beale function #####
class Beale(OptimalBasic):
def __init__(self):
super().__init__(2)
self.max_search_range = np.array([4.5]*self.variable_num)
self.min_search_range = np.array([-4.5]*self.variable_num)
self.optimal_solution = np.array([3.,0.5])
self.global_optimum_solution = 0
self.plot_place = 0.25
self.func_name = 'Beale'
def get_func_val(self, variables):
tmp1 = np.power(1.5 - variables[0] + variables[0] * variables[1],2)
tmp2 = np.power(2.25 - variables[0] + variables[0] * np.power(variables[1],2),2)
tmp3 = np.power(2.625 - variables[0] + variables[0] * np.power(variables[1],3),2)
return tmp1+tmp2+tmp3
##### Class Goldstein-Price function #####
class GoldsteinPrice(OptimalBasic):
def __init__(self):
super().__init__(2)
self.max_search_range = np.array([2.]*self.variable_num)
self.min_search_range = np.array([-2.]*self.variable_num)
self.optimal_solution = np.array([0.,-1.])
self.global_optimum_solution = 3
self.plot_place = 0.25
self.func_name = 'GoldsteinPrice'
def get_func_val(self, variables):
tmp1 = (1+np.power(variables[0]+variables[1]+1,2)*(19-14*variables[0]+3*np.power(variables[0],2)-14*variables[1]+6*variables[0]*variables[1]+3*np.power(variables[1],2)))
tmp2 = (30+(np.power(2*variables[0]-3*variables[1],2)*(18-32*variables[0]+12*np.power(variables[0],2)+48*variables[1]-36*variables[0]*variables[1]+27*np.power(variables[1],2))))
return tmp1*tmp2
##### Class Booth function #####
class Booth(OptimalBasic):
def __init__(self):
super().__init__(2)
self.max_search_range = np.array([10.]*self.variable_num)
self.min_search_range = np.array([-10.]*self.variable_num)
self.optimal_solution = np.array([1.,-3.])
self.global_optimum_solution = 0
self.func_name = 'Booth'
def get_func_val(self, variables):
tmp1 = np.power(variables[0]+2*variables[1]-7,2)
tmp2 = np.power(2*variables[0]+variables[1]-5,2)
return tmp1+tmp2
##### Class Bukin function N.6 #####
class BukinN6(OptimalBasic):
def __init__(self):
super().__init__(2)
self.max_search_range = np.array([-5.,3.])
self.min_search_range = np.array([-15.,-3.])
self.optimal_solution = np.array([-10.,1.])
self.global_optimum_solution = 0
self.func_name = 'BukinN6'
def get_func_val(self, variables):
tmp1 = 100*np.sqrt(np.absolute(variables[1]-0.01*np.power(variables[1],2)))
tmp2 = 0.01*np.absolute(variables[0]+10)
return tmp1+tmp2
##### Class Matyas function #####
class Matyas(OptimalBasic):
def __init__(self):
super().__init__(2)
self.max_search_range = np.array([10.]*self.variable_num)
self.min_search_range = np.array([-10.]*self.variable_num)
self.optimal_solution = np.array([0.,0.])
self.global_optimum_solution = 0
self.func_name = 'Matyas'
def get_func_val(self, variables):
tmp1 = 0.26*(np.power(variables[0],2)+np.power(variables[1],2))
tmp2 = 0.48*variables[0]*variables[1]
return tmp1-tmp2
##### Class Levi function N.13 #####
class LeviN13(OptimalBasic):
def __init__(self):
super().__init__(2)
self.max_search_range = np.array([10.]*self.variable_num)
self.min_search_range = np.array([-10.]*self.variable_num)
self.optimal_solution = np.array([1.,1.])
self.global_optimum_solution = 0
self.func_name = 'LeviN13'
def get_func_val(self, variables):
tmp1 = np.power(np.sin(3*np.pi*variables[0]),2)
tmp2 = np.power(variables[0]-1,2)*(1+np.power(np.sin(3*np.pi*variables[1]),2))
tmp3 = np.power(variables[1]-1,2)*(1+np.power(np.sin(2*np.pi*variables[1]),2))
return tmp1+tmp2+tmp3
##### Class Three-hump camel function #####
class ThreeHumpCamel(OptimalBasic):
def __init__(self):
super().__init__(2)
self.max_search_range = np.array([5.]*self.variable_num)
self.min_search_range = np.array([-5.]*self.variable_num)
self.optimal_solution = np.array([0.,0.])
self.global_optimum_solution = 0
self.func_name = 'ThreeHumpCamel'
def get_func_val(self, variables):
return 2*np.power(variables[0],2)-1.05*np.power(variables[0],4)+np.power(variables[0],6)/6+variables[0]*variables[1]+np.power(variables[1],2)
##### Class Easom function #####
class Easom(OptimalBasic):
def __init__(self):
super().__init__(2)
self.max_search_range = np.array([100.]*self.variable_num)
self.min_search_range = np.array([-100.]*self.variable_num)
self.optimal_solution = np.array([np.pi,np.pi])
self.global_optimum_solution = -1
self.plot_place = 10
self.func_name = 'Easom'
def get_func_val(self, variables):
return -1.0*np.cos(variables[0])*np.cos(variables[1])*np.exp(-(np.power(variables[0]-np.pi,2)+np.power(variables[1]-np.pi,2)))
##### Class Eggholder function #####
class Eggholder(OptimalBasic):
def __init__(self):
super().__init__(2)
self.max_search_range = np.array([512.]*self.variable_num)
self.min_search_range = np.array([-512.]*self.variable_num)
self.optimal_solution = np.array([512.,404.2319])
self.global_optimum_solution = -959.6407
self.plot_place = 5
self.func_name = 'Eggholder'
def get_func_val(self, variables):
tmp1 = -(variables[1]+47)*np.sin(np.sqrt(np.absolute(variables[1]+variables[0]/2+47)))
tmp2 = -variables[0]*np.sin(np.sqrt(np.absolute(variables[0]-(variables[1]+47))))
return tmp1+tmp2
##### Class McCormick function #####
class McCormick(OptimalBasic):
def __init__(self):
super().__init__(2)
self.max_search_range = np.array([4.]*self.variable_num)
self.min_search_range = np.array([-1.5,-3.])
self.optimal_solution = np.array([-0.54719,-1.54719])
self.global_optimum_solution = -1.9133
self.func_name = 'McCormick'
def get_func_val(self, variables):
tmp1 = np.sin(variables[0]+variables[1])+np.power(variables[0]-variables[1],2)
tmp2 = -1.5*variables[0]+2.5*variables[1]+1
return tmp1+tmp2
##### Class Schaffer function N.2 #####
class SchafferN2(OptimalBasic):
def __init__(self):
super().__init__(2)
self.max_search_range = np.array([100.]*self.variable_num)
self.min_search_range = np.array([-100]*self.variable_num)
self.optimal_solution = np.array([0.,0.])
self.global_optimum_solution = 0
self.plot_place = 10
self.func_name = 'SchafferN2'
def get_func_val(self, variables):
tmp1 = np.power(np.sin(np.power(variables[0],2)-np.power(variables[1],2)),2)-0.5
tmp2 = np.power(1+0.001*(np.power(variables[0],2)+np.power(variables[1],2)),2)
return 0.5+tmp1/tmp2
##### Class Schaffer function N.4 #####
class SchafferN4(OptimalBasic):
def __init__(self):
super().__init__(2)
self.max_search_range = np.array([100.]*self.variable_num)
self.min_search_range = np.array([-100]*self.variable_num)
self.optimal_solution = np.array([0.,1.25313])
self.global_optimum_solution = 0
self.plot_place = 10
self.func_name = 'SchafferN4'
def get_func_val(self, variables):
tmp1 = np.power(np.cos(np.sin(np.absolute(np.power(variables[0],2)-np.power(variables[1],2)))),2)-0.5
tmp2 = np.power(1+0.001*(np.power(variables[0],2)+np.power(variables[1],2)),2)
return 0.5+tmp1/tmp2
##### Class Styblinski-Tang function #####
class StyblinskiTang(OptimalBasic):
def __init__(self,variable_num):
super().__init__(variable_num)
self.max_search_range = np.array([5.]*self.variable_num)
self.min_search_range = np.array([-5.]*self.variable_num)
self.optimal_solution = np.array([-2.903534]*self.variable_num)
self.global_optimum_solution = -39.166165*self.variable_num
self.func_name = 'StyblinskiTang'
def get_func_val(self, variables):
tmp1 = 0
for i in range(self.variable_num):
tmp1 += np.power(variables[i],4)-16*np.power(variables[i],2)+5*variables[i]
return tmp1/2
##### Class De Jong's function F1 #####
class DeJongsF1(Sphere):
def __init__(self,variable_num):
super().__init__(variable_num)
self.func_name = 'DeJongsF1'
##### Class De Jong's function F2 #####
class DeJongsF2(Rosenbrock):
def __init__(self,variable_num):
super().__init__(variable_num)
self.func_name = 'DeJongsF2'
##### Class De Jong's function F3 #####
class DeJongsF3(OptimalBasic):
def __init__(self):
super().__init__(5)
self.max_search_range = np.array([5.12]*self.variable_num)
self.min_search_range = np.array([-5.12]*self.variable_num)
self.optimal_solution = np.array([-5.12]*self.variable_num)
self.global_optimum_solution = 0
self.func_name = 'DeJongsF3'
def get_func_val(self, variables):
tmp1 = 0
for i in range(self.variable_num):
tmp1 += np.floor(variables[i])
return tmp1
##### Class De Jong's function F4 #####
class DeJongsF4(OptimalBasic):
def __init__(self):
super().__init__(30)
self.max_search_range = np.array([1.28]*self.variable_num)
self.min_search_range = np.array([-1.28]*self.variable_num)
self.optimal_solution = np.array([0.]*self.variable_num)
self.global_optimum_solution = np.random.normal(0,1)
self.func_name = 'DeJongsF4'
def get_func_val(self, variables):
tmp1 = 0
for i in range(self.variable_num):
tmp1 += (i+1)*np.power(variables[i],4)
return tmp1 + np.random.normal(0, 1)
##### Class De Jong's function F5 #####
class DeJongsF5(OptimalBasic):
def __init__(self):
super().__init__(25)
self.max_search_range = np.array([65.536]*self.variable_num)
self.min_search_range = np.array([-65.536]*self.variable_num)
self.optimal_solution = np.array([-32.32]*self.variable_num)
self.global_optimum_solution = 1.
self.plot_place = 1.5
self.func_name = 'DeJongsF5'
def get_func_val(self, variables):
A = np.zeros([2,25])
a = [-32,16,0,16,32]
A[0,:] = np.tile(a,(1,5))
tmp = []
for x in a:
tmp_list = [x]*5
tmp.extend(tmp_list)
A[1,:] = tmp
sum = 0
for i in range(self.variable_num):
a1i = A[0,i]
a2i = A[1,i]
term1 = i
term2 = np.power(variables[0]-a1i,6)
term3 = np.power(variables[1]-a2i,6)
new = 1/(term1+term2+term3)
sum += new
return 1/(0.002+sum)
##### Class Ellipsoid function #####
class Ellipsoid(OptimalBasic):
def __init__(self,variable_num):
super().__init__(variable_num)
self.max_search_range = np.array([5.12]*self.variable_num)
self.min_search_range = np.array([-5.12]*self.variable_num)
self.optimal_solution = np.array([0.]*self.variable_num)
self.global_optimum_solution = 0.
self.func_name = 'Ellipsoid'
def get_func_val(self, variables):
tmp = 0
for i in range(self.variable_num):
tmp += np.power(np.power(1000,i/(self.variable_num-1))*variables[i],2)
return tmp
##### Class k-tablet function #####
class KTablet(OptimalBasic):
def __init__(self,variable_num):
super().__init__(variable_num)
self.max_search_range = np.array([5.12]*self.variable_num)
self.min_search_range = np.array([-5.12]*self.variable_num)
self.optimal_solution = np.array([0.]*self.variable_num)
self.global_optimum_solution = 0.
self.func_name = 'KTablet'
def get_func_val(self, variables):
tmp = 0
k = int(self.variable_num/4)
for i in range(k):
tmp += variables[i]
for i in range(k,self.variable_num):
tmp += np.power(100*variables[i],2)
return tmp
##### Class Five-well potential function #####
# Not yet checked to do working properly
class FiveWellPotential(OptimalBasic):
def __init__(self):
super().__init__(2)
self.max_search_range = np.array([20.]*self.variable_num)
self.min_search_range = np.array([-20.]*self.variable_num)
self.optimal_solution = np.array([4.92,-9.89])
self.global_optimum_solution = -1.4616
self.plot_place = 1
self.func_name = 'FiveWellPotential'
def get_func_val(self, variables):
tmp1 = []
tmp1.append(1-1/(1+0.05*np.power(np.power(variables[0],2)+(variables[1]-10),2)))
tmp1.append(-1/(1+0.05*(np.power(variables[0]-10,2)+np.power(variables[1],2))))
tmp1.append(-1/(1+0.03*(np.power(variables[0]+10,2)+np.power(variables[1],2))))
tmp1.append(-1/(1+0.05*(np.power(variables[0]-5,2)+np.power(variables[1]+10,2))))
tmp1.append(-1/(1+0.1*(np.power(variables[0]+5,2)+np.power(variables[1]+10,2))))
tmp1_sum = 0
for x in tmp1:
tmp1_sum += x
tmp2 = 1+0.0001*np.power((np.power(variables[0],2)+np.power(variables[1],2)),1.2)
return tmp1_sum*tmp2
##### Class Weighted Sphere function or hyper ellipsodic function #####
class WeightedSphere(OptimalBasic):
def __init__(self,variable_num):
super().__init__(variable_num)
self.max_search_range = np.array([5.12]*self.variable_num)
self.min_search_range = np.array([-5.12]*self.variable_num)
self.optimal_solution = np.array([0.]*self.variable_num)
self.global_optimum_solution = 0.
self.func_name = 'WeightedSphere'
def get_func_val(self, variables):
tmp = 0
for i in range(self.variable_num):
tmp += (i+1)*np.power(variables[i],2)
return tmp
class HyperEllipsodic(WeightedSphere):
def __init__(self,variable_num):
super().__init__(variable_num)
self.func_name = 'HyperEllipsodic'
##### Class Sum of different power function #####
class SumOfDifferentPower(OptimalBasic):
def __init__(self,variable_num):
super().__init__(variable_num)
self.max_search_range = np.array([1.]*self.variable_num)
self.min_search_range = np.array([-1.]*self.variable_num)
self.optimal_solution = np.array([0.]*self.variable_num)
self.global_optimum_solution = 0.
self.func_name = 'SumOfDifferentPower'
def get_func_val(self, variables):
tmp = 0
for i in range(self.variable_num):
tmp += np.power(np.absolute(variables[i]),i+2)
return tmp
##### Class Griewank function #####
class Griewank(OptimalBasic):
def __init__(self,variable_num):
super().__init__(variable_num)
self.max_search_range = np.array([600.]*self.variable_num)
self.min_search_range = np.array([-600.]*self.variable_num)
self.optimal_solution = np.array([0.]*self.variable_num)
self.global_optimum_solution = 0.
self.plot_place = 10.
self.func_name = 'Griewank'
def get_func_val(self, variables):
tmp1 = 0
tmp2 = 1
for i in range(self.variable_num):
tmp1 += np.power(variables[i],2)
tmp2 = tmp2*np.cos(variables[i]/np.sqrt(i+1))
return tmp1/4000-tmp2
##### Class Michalewicz function #####
class Michalewicz(OptimalBasic):
def __init__(self,variable_num):
super().__init__(variable_num)
self.max_search_range = np.array([np.pi]*self.variable_num)
self.min_search_range = np.array([0.]*self.variable_num)
self.optimal_solution = np.array([0.]*self.variable_num)
self.global_optimum_solution = -1.8013 # In case of variable_num == 2
self.plot_place = 0.1
self.func_name = 'Michalewicz'
def get_func_val(self, variables):
m = 10
tmp1 = 0
for i in range(self.variable_num):
tmp1 += np.sin(variables[i])*np.power(np.sin((i+1)*np.power(variables[i],2)/np.pi),2*m)
return -tmp1
##### Class Perm function #####
class Perm(OptimalBasic):
def __init__(self,variable_num,beta):
super().__init__(variable_num)
self.beta = beta
self.max_search_range = np.array([1.]*self.variable_num)
self.min_search_range = np.array([-1.]*self.variable_num)
tmp = []
for i in range(self.variable_num):
tmp.append(1/(i+1))
self.optimal_solution = np.array(tmp)
self.global_optimum_solution = 0.
self.plot_place = 0.1
self.func_name = 'Perm'
def get_func_val(self, variables):
tmp1 = 0
tmp2 = 0
for j in range(self.variable_num):
for i in range(self.variable_num):
tmp1 += (i+1+self.beta)*(np.power(variables[i],j+1)-np.power(1/(i+1),j+1))
tmp2 += np.power(tmp1,2)
tmp1 = 0
return tmp2
##### Class Rastrigin function #####
class Rastrigin(OptimalBasic):
def __init__(self,variable_num):
super().__init__(variable_num)
self.max_search_range = np.array([5.12]*self.variable_num)
self.min_search_range = np.array([-5.12]*self.variable_num)
self.optimal_solution = np.array([0.]*self.variable_num)
self.global_optimum_solution = 0.
self.func_name = 'Rastrigin'
def get_func_val(self, variables):
tmp1 = 10 * self.variable_num
tmp2 = 0
for i in range(self.variable_num):
tmp2 += np.power(variables[i],2)-10*np.cos(2*np.pi*variables[i])
return tmp1+tmp2
##### Class Schwefel function #####
class Schwefel(OptimalBasic):
def __init__(self,variable_num):
super().__init__(variable_num)
self.max_search_range = np.array([500.]*self.variable_num)
self.min_search_range = np.array([-500.]*self.variable_num)
self.optimal_solution = np.array([420.9687]*self.variable_num)
self.global_optimum_solution = -418.9829
self.plot_place = 10.
self.func_name = 'Schwefel'
def get_func_val(self, variables):
tmp = 0
for i in range(self.variable_num):
tmp += variables[i]*np.sin(np.sqrt(np.absolute(variables[i])))
return -tmp
##### Class Six-hump camel function #####
class SixHumpCamel(OptimalBasic):
def __init__(self):
super().__init__(2)
self.max_search_range = np.array([3.,2.])
self.min_search_range = np.array([-3.,-2.])
self.optimal_solution = np.array([-0.0898,0.7126])
self.global_optimum_solution = -1.0316
self.func_name = 'SixHumpCamel'
def get_func_val(self, variables):
return 4-2.1*np.power(variables[0],2)+1/3* | np.power(variables[0],4) | numpy.power |
# -*- coding: utf-8 -*-
"""
Copyright (c) 2020, University of Southampton
All rights reserved.
Licensed under the BSD 3-Clause License.
See LICENSE.md file in the project root for full license information.
"""
import matplotlib.pyplot as plt
import numpy as np
from numba import njit
from scipy import optimize
@njit
def exp_curve(x: np.ndarray, a: float, b: float, c: float) -> np.ndarray:
"""Compute exponent value with respect to a distance value
Parameters
-----------
x : np.ndarray
distance value
a : float
coefficient
b : float
coefficient
c : float
coefficient
Returns
--------
np.ndarray
"""
return a * np.exp(b * x) + c
@njit
def residual_exp_curve(params: np.ndarray, x: np.ndarray, y: np.ndarray):
"""Compute residuals with respect to init params
Parameters
-----------
params : numpy.ndarray
array of init params
x : numpy.ndarray
array of distance values
y : numpy.ndarray
array of intensity values
Returns
--------
numpy.ndarray
residual
"""
residual = exp_curve(x, params[0], params[1], params[2]) - y
return residual
# compute attenuation correction parameters through regression
def curve_fitting(
altitudes: np.ndarray, intensities: np.ndarray
) -> np.ndarray:
"""Compute attenuation coefficients with respect to distance values
Parameters
-----------
altitudes : list
list of distance values
intensities : list
list of intensity values
Returns
--------
numpy.ndarray
parameters
"""
altitudes = altitudes[np.isfinite(altitudes)]
intensities = intensities[ | np.isfinite(intensities) | numpy.isfinite |
import numpy as np
import scipy.spatial.distance as ssd
from shapely.geometry.polygon import Polygon
from shapely.ops import nearest_points
import gym
from gym import spaces
from gym.utils import seeding
from traffic.constants import *
class Car:
def __init__(self, idx, length, width, color, max_accel, max_speed, max_rotation, expose_level):
self._idx = idx
self._length = length
self._width = width
self._color = color
self._arr_color = (0.8, 0.8, 0.8)
self._max_accel = max_accel
self._max_speed = max_speed
self._max_rotation = max_rotation
self._expose_level = expose_level
self._position = None
self._velocity = None
self._rotation = None
self._action = None
self.seed()
def seed(self, seed=None):
self.np_random, seed = seeding.np_random(seed)
return [seed]
def observation_space(self, cars, road, include_x=False):
if include_x:
high = [
np.inf, np.inf, self._max_speed,
self._max_speed
]
# px, py,vx,vy
else:
high = [np.inf, self._max_speed,
self._max_speed]
# py, vx, vy
for car in cars:
if car is self:
continue
high += [np.inf, np.inf,
self._max_speed, self._max_speed]
# relatvie px1,py,vx,vy
high = np.array(high)
low = -high
return spaces.Box(low=low, high=high, dtype=np.float32)
def action_space(self):
return spaces.Box(low=-self._max_accel, high=self._max_accel, shape=(2,),
dtype=np.float32)
@property
def length(self):
return self._length
@property
def width(self):
return self._width
@property
def position(self):
assert self._position is not None
return self._position
@property
def velocity(self):
assert self._velocity is not None
return self._velocity
@property
def rotation(self):
assert self._rotation is not None
return self._rotation
@property
def heading(self):
assert self._velocity is not None
return np.arctan2(self._velocity[1],self._velocity[0])
def set_position(self, x_2):
assert x_2.shape == (2,)
self._position = np.array(x_2)
return self._position
def set_velocity(self, v_2):
assert v_2.shape == (2,)
self._velocity = np.array(v_2)
speed = np.linalg.norm(self._velocity)
if speed > self._max_speed:
self._velocity = self._velocity / speed * self._max_speed
return self._velocity
def set_rotation(self, rotation):
self._rotation = rotation
return self._rotation
def observe(self, cars, road, include_x=False):
if include_x:
ob = self.position
else:
ob = np.array(self.position[1])
ob = | np.append(ob, self.velocity) | numpy.append |
# -*- coding: UTF-8 -*-
from ZUI_MDP_solution import *
from unittest import TestCase
import itertools as it
import numpy as np
import numpy.testing as nptest
# Taken from http://www.neuraldump.net/2017/06/how-to-suppress-python-unittest-warnings/.
def ignore_warnings(test_func):
def do_test(self, *args, **kwargs):
with warnings.catch_warnings():
warnings.simplefilter("ignore")
test_func(self, *args, **kwargs)
return do_test
class TestGridWorld2x2(TestCase):
rtol = 1e-4 # relative tolerance for comparing two floats
def setUp(self):
self.gw = GridWorld.get_world('2x2')
def test_is_obstacle_at(self):
self.assertFalse(self.gw._is_obstacle([0, 0]))
self.assertFalse(self.gw._is_obstacle([0, 1]))
self.assertFalse(self.gw._is_obstacle([1, 0]))
self.assertFalse(self.gw._is_obstacle([1, 1]))
def test_is_on_grid_true(self):
self.assertTrue(self.gw._is_on_grid([0, 0]),msg='The point [{},{}] should be on the grid.'.format(0, 0))
self.assertTrue(self.gw._is_on_grid([1, 1]), msg='The point [{},{}] should be on the grid.'.format(1, 1))
def test_is_on_grid_false(self):
for point in ([-1,0], [-2,-2], [2,0], [0,2], [5,5], [0,-1]):
self.assertFalse(self.gw._is_on_grid(point),msg='The point [{}] should not be on the grid.'.format(point))
def test_transition_proba(self):
true_transition_proba = np.load('./test_data/test_gw_2x2_transition_proba.npy')
nptest.assert_allclose(self.gw.transition_proba,true_transition_proba,rtol=self.rtol)
def test_Q_from_V_zeros(self):
V = np.zeros((self.gw.n_states + 1,))
desired_Q = np.array([[-0.04, -0.04, -0.04, -0.04],
[1., 1., 1., 1.],
[-0.04, -0.04, -0.04, -0.04],
[-1., -1., -1., -1.],
[0., 0., 0., 0.]])
nptest.assert_allclose(self.gw.Q_from_V(V=V), desired_Q, rtol=self.rtol)
def test_Q_from_V_ones(self):
V = np.ones((self.gw.n_states + 1,))
desired_Q = np.array([[0.96, 0.96, 0.96, 0.96],
[2., 2., 2., 2.],
[0.96, 0.96, 0.96, 0.96],
[0., 0., 0., 0.],
[1., 1., 1., 1.]])
nptest.assert_allclose(self.gw.Q_from_V(V=V), desired_Q, rtol=self.rtol)
def test_Q_from_V_init(self):
V = np.max(self.gw.rewards,axis=1)
desired_Q = np.array([[0.024, 0.752, 0.024, -0.08],
[1., 1., 1., 1.],
[-0.176, -0.848, -0.176, -0.08],
[-1., -1., -1., -1.],
[0., 0., 0., 0.]])
nptest.assert_allclose(self.gw.Q_from_V(V=V), desired_Q, rtol=self.rtol)
def test_Q2V_single(self):
desired_V = np.array([0.752, 1., -0.08, -1., 0.])
Q = np.array([[0.024, 0.752, 0.024, -0.08],
[1., 1., 1., 1.],
[-0.176, -0.848, -0.176, -0.08],
[-1., -1., -1., -1.],
[0., 0., 0., 0.]])
actual_V = self.gw.Q2V(Q)
self.assertEqual(actual_V.shape, (self.gw.n_states + 1,), msg='Q2V should return array V of'
' shape {} but has returned V with shape {}.'.format(
self.gw.n_states + 1,
actual_V.shape))
actual_V = self.gw.Q2V(Q)
nptest.assert_allclose(actual_V, desired_V, rtol=self.rtol)
def test_Q2V(self):
desired_V = np.array([0.752, 1., -0.08, -1., 0.])
Q = np.array([[0.024, 0.752, 0.024, -0.08],
[1., 1., 1., 1.],
[-0.176, -0.848, -0.176, -0.08],
[-1., -1., -1., -1.],
[0., 0., 0., 0.]])
actual_V = self.gw.Q2V(Q)
self.assertEqual(actual_V.shape, (self.gw.n_states + 1,), msg='Q2V should return array V of'
' shape {} but has returned V with shape {}.'.format(
self.gw.n_states + 1,
actual_V.shape))
actual_V = self.gw.Q2V(Q)
nptest.assert_allclose(actual_V, desired_V, rtol=self.rtol)
def test_Q2Vbypolicy(self):
desired_V = np.array([0.9178081, 1., 0.66027364, -1., 0., ])
Q = np.array([[0.88602712, 0.9178081, 0.67999927, 0.85205443],
[1., 1., 1., 1.],
[0.66027364, -0.6821919, 0.45424578, 0.64602658],
[-1., -1., -1., -1.],
[0., 0., 0., 0.]])
policy = np.array([1, 0, 0, 0, 0], dtype=int)
actual_V = self.gw.Q2Vbypolicy(Q,policy)
self.assertEqual(actual_V.shape, (self.gw.n_states + 1,), msg='Q2Vbypolicy should return array V of'
' shape {} but has returned V with shape {}.'.format(
self.gw.n_states + 1,
actual_V.shape))
nptest.assert_allclose(actual_V, desired_V, rtol=self.rtol)
def test_Q2policy(self):
Q = np.array([[0.88602712, 0.9178081, 0.67999927, 0.85205443],
[1., 1., 1., 1.],
[0.66027364, -0.6821919, 0.45424578, 0.64602658],
[-1., -1., -1., -1.],
[0., 0., 0., 0.]])
desired_policy = np.array([1, 0, 0, 0, 0], dtype=int)
actual_policy = self.gw.Q2policy(Q)
self.assertEqual(actual_policy.shape, (self.gw.n_states + 1,), msg='Q2policy should return array policy of'
' shape {} but has returned V with shape {}.'.format(
self.gw.n_states + 1,
actual_policy.shape))
nptest.assert_allclose(actual_policy, desired_policy, rtol=self.rtol)
@ignore_warnings
def test_value_iteration_single_iter(self):
actual_Q = self.gw.value_iteration(max_iter=1)
desired_Q = np.array([[0.024, 0.752, 0.024, -0.08],
[1., 1., 1., 1.],
[-0.176, -0.848, -0.176, -0.08],
[-1., -1., -1., -1.],
[0., 0., 0., 0.]])
desired_Q_shape = (self.gw.n_states + 1,self.gw.n_actions)
self.assertEqual(actual_Q.shape, desired_Q_shape,
msg='Value_iteration should return array Q of'
' shape {} but has returned V with shape {}.'.format(
desired_Q_shape,
actual_Q.shape))
nptest.assert_allclose(actual_Q, desired_Q, rtol=self.rtol)
def test_value_iteration(self):
desired_Q = np.array([[0.88602712, 0.9178081, 0.67999927, 0.85205443],
[1., 1., 1., 1.],
[0.66027364, -0.6821919, 0.45424578, 0.64602658],
[-1., -1., -1., -1.],
[0., 0., 0., 0.]])
actual_Q = self.gw.value_iteration()
nptest.assert_allclose(actual_Q, desired_Q, rtol=self.rtol)
def test_policy_iteration_policy_only(self):
actual_policy = self.gw.Q2policy(self.gw.policy_iteration())
desired_Q = np.array([[0.88602712, 0.9178081, 0.67999927, 0.85205443],
[1., 1., 1., 1.],
[0.66027364, -0.6821919, 0.45424578, 0.64602658],
[-1., -1., -1., -1.],
[0., 0., 0., 0.]])
desired_policy = self.gw.Q2policy(desired_Q)
nptest.assert_allclose(actual_policy, desired_policy, rtol=self.rtol)
def test_policy_iteration(self):
actual_Q = self.gw.policy_iteration()
desired_Q = np.array([[0.88602712, 0.9178081, 0.67999927, 0.85205443],
[1., 1., 1., 1.],
[0.66027364, -0.6821919, 0.45424578, 0.64602658],
[-1., -1., -1., -1.],
[0., 0., 0., 0.]])
desired_Q_shape = (self.gw.n_states + 1, self.gw.n_actions)
self.assertEqual(actual_Q.shape, desired_Q_shape,
msg='Policy_iteration should return array Q of'
' shape {} but has returned V with shape {}.'.format(
desired_Q_shape,
actual_Q.shape))
nptest.assert_allclose(actual_Q, desired_Q, rtol=self.rtol)
class TestGridWorld3x3(TestCase):
rtol = 1e-3 # relative tolerance for comparing two floats
def setUp(self):
self.gw = GridWorld.get_world('3x3')
def test_is_obstacle_at(self):
for i,j in it.product(range(self.gw.n_rows),range(self.gw.n_columns)):
self.assertFalse(self.gw._is_obstacle([i, j]), msg='No obstacle should be at [{},{}].'.format(i,j))
def test_is_on_grid_true(self):
for i,j in it.product(range(self.gw.n_rows),range(self.gw.n_columns)):
self.assertTrue(self.gw._is_on_grid([i, j]),msg='The point [{},{}] should be on the grid.'.format(i, j))
def test_is_on_grid_false(self):
for point in ([-1,0], [-2,-2], [3,0], [0,3], [5,5], [0,-1]):
self.assertFalse(self.gw._is_on_grid(point),msg='The point [{}] should not be on the grid.'.format(point))
def test_transition_proba(self):
true_transition_proba = np.load('./test_data/test_gw_3x3_transition_proba.npy')
nptest.assert_allclose(self.gw.transition_proba,true_transition_proba,rtol=self.rtol)
def test_Q2V_single(self):
desired_V = np.load('./test_data/test_gw_3x3_V_single_iter.npy')
Q = np.load('./test_data/test_gw_3x3_Q_single_iter.npy')
actual_V = self.gw.Q2V(Q)
self.assertEqual(actual_V.shape, (self.gw.n_states + 1,), msg='Q2V should return array V of'
' shape {} but has returned V with shape {}.'.format(
self.gw.n_states + 1,
actual_V.shape))
actual_V = self.gw.Q2V(Q)
nptest.assert_allclose(actual_V, desired_V, rtol=self.rtol)
def test_Q2V(self):
desired_V = np.load('./test_data/test_gw_3x3_V.npy')
Q = np.load('./test_data/test_gw_3x3_Q.npy')
actual_V = self.gw.Q2V(Q)
self.assertEqual(actual_V.shape, (self.gw.n_states + 1,), msg='Q2V should return array V of'
' shape {} but has returned V with shape {}.'.format(
self.gw.n_states + 1,
actual_V.shape))
actual_V = self.gw.Q2V(Q)
nptest.assert_allclose(actual_V, desired_V, rtol=self.rtol)
def test_Q2Vbypolicy(self):
desired_V = np.load('./test_data/test_gw_3x3_V.npy')
Q = np.load('./test_data/test_gw_3x3_Q.npy')
policy = np.array([1, 1, 0, 0, 3, 0, 0, 3, 2, 0],dtype=int)
actual_V = self.gw.Q2Vbypolicy(Q, policy)
self.assertEqual(actual_V.shape, (self.gw.n_states + 1,), msg='Q2Vbypolicy should return array V of'
' shape {} but has returned V with shape {}.'.format(
self.gw.n_states + 1,
actual_V.shape))
nptest.assert_allclose(actual_V, desired_V, rtol=self.rtol)
def test_Q2policy(self):
Q = np.load('./test_data/test_gw_3x3_Q.npy')
desired_policy = np.array([1, 1, 0, 0, 3, 0, 0, 3, 2, 0],dtype=int)
actual_policy = self.gw.Q2policy(Q)
self.assertEqual(actual_policy.shape, (self.gw.n_states + 1,), msg='Q2policy should return array policy of'
' shape {} but has returned V with shape {}.'.format(
self.gw.n_states + 1,
actual_policy.shape))
nptest.assert_allclose(actual_policy, desired_policy, rtol=self.rtol)
@ignore_warnings
def test_value_iteration_single_iter(self):
actual_Q = self.gw.value_iteration(max_iter=1)
desired_Q = np.load('./test_data/test_gw_3x3_Q_single_iter.npy')
desired_Q_shape = (self.gw.n_states + 1,self.gw.n_actions)
self.assertEqual(actual_Q.shape, desired_Q_shape,
msg='Value_iteration should return array Q of'
' shape {} but has returned V with shape {}.'.format(
desired_Q_shape,
actual_Q.shape))
nptest.assert_allclose(actual_Q, desired_Q, rtol=self.rtol)
def test_value_iteration(self):
desired_Q = np.load('./test_data/test_gw_3x3_Q.npy')
desired_Q_shape = (self.gw.n_states + 1, self.gw.n_actions)
actual_Q = self.gw.value_iteration()
nptest.assert_allclose(actual_Q, desired_Q, rtol=self.rtol)
def test_policy_iteration_policy_only(self):
actual_policy = self.gw.Q2policy(self.gw.policy_iteration())
desired_Q = np.load('./test_data/test_gw_3x3_Q.npy')
desired_policy = self.gw.Q2policy(desired_Q)
#actual_policy = self.gw.Q2policy(actual_Q)
nptest.assert_allclose(actual_policy, desired_policy, rtol=self.rtol)
def test_policy_iteration(self):
actual_Q = self.gw.policy_iteration()
desired_Q = np.load('./test_data/test_gw_3x3_Q.npy')
desired_Q_shape = (self.gw.n_states + 1, self.gw.n_actions)
self.assertEqual(actual_Q.shape, desired_Q_shape,
msg='Policy_iteration should return array Q of'
' shape {} but has returned V with shape {}.'.format(
desired_Q_shape,
actual_Q.shape))
nptest.assert_allclose(actual_Q, desired_Q, rtol=self.rtol)
class TestGridWorld3x4(TestCase):
rtol = 1e-3 # relative tolerance for comparing two floats
def setUp(self):
self.gw = GridWorld.get_world('3x4')
def test_is_obstacle_at(self):
for i,j in it.product(range(self.gw.n_rows),range(self.gw.n_columns)):
if i == 1 and j == 1:
continue
self.assertFalse(self.gw._is_obstacle([i, j]), msg='No obstacle should be at [{},{}].'.format(i,j))
self.assertTrue(self.gw._is_obstacle([1, 1]), msg='An obstacle should be at [{},{}].'.format(1, 1))
def test_is_on_grid_true(self):
for i,j in it.product(range(self.gw.n_rows),range(self.gw.n_columns)):
self.assertTrue(self.gw._is_on_grid([i, j]),msg='The point [{},{}] should be on the grid.'.format(i, j))
def test_is_on_grid_false(self):
for point in ([-1,0], [-2,-2], [3,0], [0,4], [5,5], [0,-1]):
self.assertFalse(self.gw._is_on_grid(point),msg='The point [{}] should not be on the grid.'.format(point))
def test_transition_proba(self):
true_transition_proba = np.load('./test_data/test_gw_3x4_transition_proba.npy')
nptest.assert_allclose(self.gw.transition_proba,true_transition_proba,rtol=self.rtol)
def test_Q2V_single(self):
desired_V = np.load('./test_data/test_gw_3x4_V_single_iter.npy')
Q = np.load('./test_data/test_gw_3x4_Q_single_iter.npy')
actual_V = self.gw.Q2V(Q)
self.assertEqual(actual_V.shape, (self.gw.n_states + 1,), msg='Q2V should return array V of'
' shape {} but has returned V with shape {}.'.format(
self.gw.n_states + 1,
actual_V.shape))
actual_V = self.gw.Q2V(Q)
nptest.assert_allclose(actual_V, desired_V, rtol=self.rtol)
def test_Q2V(self):
desired_V = np.load('./test_data/test_gw_3x4_V.npy')
Q = np.load('./test_data/test_gw_3x4_Q.npy')
actual_V = self.gw.Q2V(Q)
self.assertEqual(actual_V.shape, (self.gw.n_states + 1,), msg='Q2V should return array V of'
' shape {} but has returned V with shape {}.'.format(
self.gw.n_states + 1,
actual_V.shape))
actual_V = self.gw.Q2V(Q)
nptest.assert_allclose(actual_V, desired_V, rtol=self.rtol)
def test_Q2policy(self):
Q = np.load('./test_data/test_gw_3x4_Q.npy')
desired_policy = np.array([1, 1, 1, 0, 0, 0, 0, 0, 0, 3, 3, 3, 0],dtype=int)
actual_policy = self.gw.Q2policy(Q)
self.assertEqual(actual_policy.shape, (self.gw.n_states + 1,), msg='Q2policy should return array policy of'
' shape {} but has returned V with shape {}.'.format(
self.gw.n_states + 1,
actual_policy.shape))
nptest.assert_allclose(actual_policy, desired_policy, rtol=self.rtol)
def test_Q2Vbypolicy(self):
desired_V = np.load('./test_data/test_gw_3x4_V.npy')
Q = np.load('./test_data/test_gw_3x4_Q.npy')
policy = np.array([1, 1, 1, 0, 0, 0, 0, 0, 0, 3, 3, 3, 0],dtype=int)
actual_V = self.gw.Q2Vbypolicy(Q, policy)
self.assertEqual(actual_V.shape, (self.gw.n_states + 1,), msg='Q2Vbypolicy should return array V of'
' shape {} but has returned V with shape {}.'.format(
self.gw.n_states + 1,
actual_V.shape))
nptest.assert_allclose(actual_V, desired_V, rtol=self.rtol)
@ignore_warnings
def test_value_iteration_single_iter(self):
actual_Q = self.gw.value_iteration(max_iter=1)
desired_Q = np.load('./test_data/test_gw_3x4_Q_single_iter.npy')
desired_Q_shape = (self.gw.n_states + 1,self.gw.n_actions)
self.assertEqual(actual_Q.shape, desired_Q_shape,
msg='Value_iteration should return array Q of'
' shape {} but has returned V with shape {}.'.format(
desired_Q_shape,
actual_Q.shape))
nptest.assert_allclose(actual_Q, desired_Q, rtol=self.rtol)
def test_value_iteration(self):
desired_Q = np.load('./test_data/test_gw_3x4_Q.npy')
desired_Q_shape = (self.gw.n_states + 1, self.gw.n_actions)
actual_Q = self.gw.value_iteration()
nptest.assert_allclose(actual_Q, desired_Q, rtol=self.rtol)
def test_policy_iteration_policy_only(self):
actual_policy = self.gw.Q2policy(self.gw.policy_iteration())
desired_Q = np.load('./test_data/test_gw_3x4_Q.npy')
desired_policy = self.gw.Q2policy(desired_Q)
#actual_policy = self.gw.Q2policy(actual_Q)
nptest.assert_allclose(actual_policy, desired_policy, rtol=self.rtol)
def test_policy_iteration(self):
actual_Q = self.gw.policy_iteration()
desired_Q = np.load('./test_data/test_gw_3x4_Q.npy')
desired_Q_shape = (self.gw.n_states + 1, self.gw.n_actions)
self.assertEqual(actual_Q.shape, desired_Q_shape,
msg='Policy_iteration should return array Q of'
' shape {} but has returned V with shape {}.'.format(
desired_Q_shape,
actual_Q.shape))
nptest.assert_allclose(actual_Q, desired_Q, rtol=self.rtol)
class TestGridWorld4x4(TestCase):
rtol = 1e-3 # relative tolerance for comparing two floats
atol = 1e-08 # absolute tolerance for comparing two floats
def setUp(self):
self.gw = GridWorld.get_world('4x4')
def test_is_obstacle_at(self):
for i,j in it.product(range(self.gw.n_rows),range(self.gw.n_columns)):
if (i,j) in [(1,1),(2,2)]:
continue
self.assertFalse(self.gw._is_obstacle([i, j]), msg='No obstacle should be at [{},{}].'.format(i,j))
self.assertTrue(self.gw._is_obstacle([1, 1]), msg='An obstacle should be at [{},{}].'.format(1, 1))
def test_is_on_grid_true(self):
for i,j in it.product(range(self.gw.n_rows),range(self.gw.n_columns)):
self.assertTrue(self.gw._is_on_grid([i, j]),msg='The point [{},{}] should be on the grid.'.format(i, j))
def test_is_on_grid_false(self):
for point in ([-1,0], [-2,-2], [4,0], [0,4], [5,5], [0,-1]):
self.assertFalse(self.gw._is_on_grid(point),msg='The point [{}] should not be on the grid.'.format(point))
def test_transition_proba(self):
true_transition_proba = np.load('./test_data/test_gw_4x4_transition_proba.npy')
nptest.assert_allclose(self.gw.transition_proba,true_transition_proba,rtol=self.rtol, atol=self.atol)
def test_Q2V_single(self):
desired_V = np.load('./test_data/test_gw_4x4_V_single_iter.npy')
Q = np.load('./test_data/test_gw_4x4_Q_single_iter.npy')
actual_V = self.gw.Q2V(Q)
self.assertEqual(actual_V.shape, (self.gw.n_states + 1,), msg='Q2V should return array V of'
' shape {} but has returned V with shape {}.'.format(
self.gw.n_states + 1,
actual_V.shape))
actual_V = self.gw.Q2V(Q)
nptest.assert_allclose(actual_V, desired_V, rtol=self.rtol, atol=self.atol)
def test_Q2V(self):
desired_V = np.load('./test_data/test_gw_4x4_V.npy')
Q = np.load('./test_data/test_gw_4x4_Q.npy')
actual_V = self.gw.Q2V(Q)
self.assertEqual(actual_V.shape, (self.gw.n_states + 1,), msg='Q2V should return array V of'
' shape {} but has returned V with shape {}.'.format(
self.gw.n_states + 1,
actual_V.shape))
actual_V = self.gw.Q2V(Q)
nptest.assert_allclose(actual_V, desired_V, rtol=self.rtol, atol=self.atol)
def test_Q2Vbypolicy(self):
desired_V = np.load('./test_data/test_gw_4x4_V.npy')
Q = np.load('./test_data/test_gw_4x4_Q.npy')
policy = np.load('./test_data/test_gw_4x4_policy.npy')
actual_V = self.gw.Q2Vbypolicy(Q, policy)
self.assertEqual(actual_V.shape, (self.gw.n_states + 1,), msg='Q2Vbypolicy should return array V of'
' shape {} but has returned V with shape {}.'.format(
self.gw.n_states + 1,
actual_V.shape))
nptest.assert_allclose(actual_V, desired_V, rtol=self.rtol, atol=self.atol)
def test_Q2policy(self):
Q = np.load('./test_data/test_gw_4x4_Q.npy')
desired_policy = np.load('./test_data/test_gw_4x4_policy.npy')
actual_policy = self.gw.Q2policy(Q)
self.assertEqual(actual_policy.shape, (self.gw.n_states + 1,), msg='Q2policy should return array policy of'
' shape {} but has returned V with shape {}.'.format(
self.gw.n_states + 1,
actual_policy.shape))
nptest.assert_allclose(actual_policy, desired_policy, rtol=self.rtol)
@ignore_warnings
def test_value_iteration_single_iter(self):
actual_Q = self.gw.value_iteration(max_iter=1)
desired_Q = np.load('./test_data/test_gw_4x4_Q_single_iter.npy')
desired_Q_shape = (self.gw.n_states + 1,self.gw.n_actions)
self.assertEqual(actual_Q.shape, desired_Q_shape,
msg='Value_iteration should return array Q of'
' shape {} but has returned V with shape {}.'.format(
desired_Q_shape,
actual_Q.shape))
nptest.assert_allclose(actual_Q, desired_Q, rtol=self.rtol, atol=self.atol)
def test_value_iteration(self):
desired_Q = np.load('./test_data/test_gw_4x4_Q.npy')
desired_Q_shape = (self.gw.n_states + 1, self.gw.n_actions)
actual_Q = self.gw.value_iteration()
nptest.assert_allclose(actual_Q, desired_Q, rtol=self.rtol, atol=self.atol)
def test_policy_iteration_policy_only(self):
actual_policy = self.gw.Q2policy(self.gw.policy_iteration())
desired_Q = np.load('./test_data/test_gw_4x4_Q.npy')
desired_policy = self.gw.Q2policy(desired_Q)
#actual_policy = self.gw.Q2policy(actual_Q)
nptest.assert_allclose(actual_policy, desired_policy, rtol=self.rtol, atol=self.atol)
def test_policy_iteration(self):
actual_Q = self.gw.policy_iteration()
desired_Q = np.load('./test_data/test_gw_4x4_Q.npy')
desired_Q_shape = (self.gw.n_states + 1, self.gw.n_actions)
self.assertEqual(actual_Q.shape, desired_Q_shape,
msg='Policy_iteration should return array Q of'
' shape {} but has returned V with shape {}.'.format(
desired_Q_shape,
actual_Q.shape))
nptest.assert_allclose(actual_Q, desired_Q, rtol=self.rtol, atol=self.atol)
class TestGridWorld5x5(TestCase):
rtol = 1e-4 # relative tolerance for comparing two floats
atol = 1e-08 # absolute tolerance for comparing two floats
def setUp(self):
self.gw = GridWorld.get_world('5x5')
def test_is_obstacle_at(self):
for i,j in it.product(range(self.gw.n_rows),range(self.gw.n_columns)):
if (i,j) in [(1,0), (1,1), (2,2)]:
continue
self.assertFalse(self.gw._is_obstacle([i, j]), msg='No obstacle should be at [{},{}].'.format(i,j))
self.assertTrue(self.gw._is_obstacle([1, 1]), msg='An obstacle should be at [{},{}].'.format(1, 1))
def test_is_on_grid_true(self):
for i,j in it.product(range(self.gw.n_rows),range(self.gw.n_columns)):
self.assertTrue(self.gw._is_on_grid([i, j]),msg='The point [{},{}] should be on the grid.'.format(i, j))
def test_is_on_grid_false(self):
for point in ([-1,0], [-2,-2], [5,0], [0,5], [5,5], [0,-1]):
self.assertFalse(self.gw._is_on_grid(point),msg='The point [{}] should not be on the grid.'.format(point))
def test_transition_proba(self):
true_transition_proba = np.load('./test_data/test_gw_5x5_transition_proba.npy')
nptest.assert_allclose(self.gw.transition_proba,true_transition_proba,rtol=self.rtol, atol=self.atol)
def test_Q2V_single(self):
desired_V = np.load('./test_data/test_gw_5x5_V_single_iter.npy')
Q = np.load('./test_data/test_gw_5x5_Q_single_iter.npy')
actual_V = self.gw.Q2V(Q)
self.assertEqual(actual_V.shape, (self.gw.n_states + 1,), msg='Q2V should return array V of'
' shape {} but has returned V with shape {}.'.format(
self.gw.n_states + 1,
actual_V.shape))
actual_V = self.gw.Q2V(Q)
nptest.assert_allclose(actual_V, desired_V, rtol=self.rtol, atol=self.atol)
def test_Q2V(self):
desired_V = np.load('./test_data/test_gw_5x5_V.npy')
Q = np.load('./test_data/test_gw_5x5_Q.npy')
actual_V = self.gw.Q2V(Q)
self.assertEqual(actual_V.shape, (self.gw.n_states + 1,), msg='Q2V should return array V of'
' shape {} but has returned V with shape {}.'.format(
self.gw.n_states + 1,
actual_V.shape))
actual_V = self.gw.Q2V(Q)
| nptest.assert_allclose(actual_V, desired_V, rtol=self.rtol, atol=self.atol) | numpy.testing.assert_allclose |
import scipy
import numpy as np
import scipy.interpolate as interp
import scipy.ndimage.filters as filt
import matplotlib.pyplot as plt
def flag_outliers(signal,
thresh_stdv=4,
buffer=10,
visualize=False):
""" Flag outliers based on median abs deviation.
Returns two arrays of indices.
The first gives the indices to be deleted.
The second gives the indices of locations in the new signal which
will potentially have discontinuities due to fluroescence reset.
Parameter:
signal:
thresh_stdv: threshold standard deviation
buffer:
visualize: whether to visualize flagged outliers
Return:
del_idx:
disc_idx:
"""
# z-score to locate outliers
keep_idx = abs(signal - np.median(signal)) < thresh_stdv * np.std(signal)
# minimum filter removes pixels within buffer distance of outliers
keep_idx = filt.minimum_filter(keep_idx, size=2 * buffer + 1)
# Plot flagged outliers -- hacky so may break if params unreasonable
if visualize:
fig = plt.figure(figsize=(16, 4))
trans_idx = np.argwhere(filt.convolve1d(keep_idx, np.array([1, -1])))
for idx in range(len(trans_idx)):
if idx == 0:
plt_idx = np.arange(0, trans_idx[idx])
else:
plt_idx = np.arange(trans_idx[idx - 1], trans_idx[idx])
color = 'b' if keep_idx[trans_idx[idx] - 1] else 'r'
plt.plot(plt_idx, signal[plt_idx], color)
if trans_idx[-1] < len(signal):
plt_idx = np.arange(trans_idx[idx], len(signal))
color = 'b' if keep_idx[len(signal) - 1] else 'r'
plt.plot(plt_idx, signal[plt_idx], color)
plt.plot(np.arange(len(signal)),
(np.ones(len(signal)) * np.median(signal)) -
(thresh_stdv * np.std(signal)), 'g')
plt.plot(np.arange(len(signal)),
(np.ones(len(signal)) * np.median(signal)) +
(thresh_stdv * np.std(signal)), 'g')
plt.title('Outliers Flagged For Removal & Threshold')
plt.show()
# List of indices to be deleted
del_idx = np.argwhere(~keep_idx)
# list of indices where samples were cutout (possible discontinuities)
disc_idx = np.argwhere(filt.convolve1d(
keep_idx, np.array([1, -1]))[keep_idx])
return del_idx, disc_idx
def _get_knots(stim,
k=3,
followup=100,
spacing=250):
"""
Parameter:
stim:
k:
followup:
spacing:
Return:
"""
# Locate transition indices
trans_idx = np.argwhere(filt.convolve1d(stim > 0, np.array([1, -1])))
# Repeat knots and add transition extras
knots = np.append(np.append(np.zeros(k + 1),
np.sort(np.append(np.repeat(trans_idx, k),
trans_idx + followup))),
np.ones(k + 1) * len(stim)).astype('int')
# add regularly spaced extra knots between transitions
extras = | np.empty(0) | numpy.empty |
import numpy as np
EPS = 1e-8
def create_initrho(K):
''' Make vector rho that implies E[beta] is nearly uniform.
Returns
--------
rho : 1D array, size K
Each entry rho[k] >= 0.
Post Condition
-------
E[leftover mass] = r
E[beta_k] \approx (1-r)/K
where r is a small amount of remaining/leftover mass
'''
remMass = np.minimum(0.1, 1.0 / (K * K))
# delta = 0, -1 + r, -2 + 2r, ...
delta = (-1 + remMass) * np.arange(0, K, 1, dtype=np.float)
rho = (1 - remMass) / (K + delta)
return rho
def create_initomega(K, nDoc, gamma):
''' Make initial guess for omega.
'''
return (nDoc / K + gamma) * np.ones(K)
def forceRhoInBounds(rho, EPS=EPS):
''' Verify every entry of rho (and beta) are within [EPS, 1-EPS]
Leads to numerical stability.
Returns
-------
rho : 1D array, size K
Each entry satisfies: EPS <= rho[k] <= 1-EPS.
'''
rho = np.maximum(np.minimum(rho, 1.0 - EPS), EPS)
beta = rho2beta_active(rho)
didFix = 0
badMask = beta < EPS
if np.any(beta < EPS):
beta[badMask] = 1.01 * EPS
addedMass = np.sum(badMask) * 1.01 * EPS
beta[np.logical_not(badMask)] *= (1 - addedMass)
didFix = 1
if (1.0 - | np.sum(beta) | numpy.sum |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jul 29 18:33:36 2021
@author: peter
"""
from pathlib import Path
import datetime
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from vsd_cancer.functions import stats_functions as statsf
import f.plotting_functions as pf
import matplotlib.cm
import matplotlib.gridspec as gridspec
import matplotlib as mpl
import scipy.ndimage as ndimage
def make_figures(initial_df, save_dir, figure_dir, filetype=".png", redo_stats=False):
figsave = Path(figure_dir, "ttx_figure")
if not figsave.is_dir():
figsave.mkdir()
plot_TTX_pre_post(save_dir, figsave, filetype, redo_stats)
plot_TTX_washout(save_dir, figsave, filetype, redo_stats)
plot_pre_post_ttx_traces(initial_df, save_dir, figsave, filetype)
def plot_pre_post_ttx_traces(initial_df, save_dir, figsave, filetype):
def get_most_active_traces(num_traces, df, trial_save, trial_string):
tcs = np.load(Path(trial_save, f"{trial_string}_all_tcs.npy"))
event_dict = np.load(
Path(trial_save, f"{trial_string}_event_properties.npy"), allow_pickle=True
).item()
idx = 0
events = event_dict["events"][idx]
keep = [x for x in np.arange(tcs.shape[0])]
# sort by event amounts
sort_order = np.array(
[
np.sum(np.abs(events["event_props"][x][:, -1]))
if x in events.keys()
else 0
for x in range(tcs.shape[0])
]
)
tcs = tcs[keep, :]
sort_order = np.argsort(sort_order[keep])[::-1]
tcs = tcs[sort_order, :]
so = np.array(keep)[sort_order]
tcs = ndimage.gaussian_filter(tcs[:num_traces, ...], (0, 3))
so = so[:num_traces]
return tcs, so
df = pd.read_csv(initial_df)
ncells = 10
T = 0.2
trial_strings = [
"cancer_20201216_slip1_area2_long_acq_long_acq_blue_0.0296_green_0.0765_heated_to_37_1",
"cancer_20201216_slip1_area3_long_acq_long_acq_blue_0.0296_green_0.0765_heated_to_37_with_TTX_1",
]
tcs = []
for t in trial_strings:
print(df[df.trial_string == t].stage)
tcs.append(
get_most_active_traces(ncells, df, Path(save_dir, "ratio_stacks", t), t)[0]
)
fig, ax = plt.subplots(ncols=2)
ax[0].plot(np.arange(tcs[0].shape[1]) * T, tcs[0].T + np.arange(ncells) / 20, "k")
ax[1].sharey(ax[0])
ax[1].plot(np.arange(tcs[1].shape[1]) * T, tcs[1].T + np.arange(ncells) / 20, "k")
pf.plot_scalebar(ax[0], 0, 0.95, 100, 0.02)
ax[0].axis("off")
ax[1].axis("off")
fig.savefig(
Path(figsave, "example_traces", f"example_traces{filetype}"),
bbox_inches="tight",
dpi=300,
transparent=True,
)
def plot_TTX_pre_post(save_dir, figsave, filetype, redo_stats):
df = pd.read_csv(Path(save_dir, "all_events_df.csv"))
df["exp_stage"] = df.expt + "_" + df.stage
use = [
x
for x in np.unique(df["exp_stage"])
if "TTX" in x and "washout_washout" not in x
]
ttx = [1, 10]
log = [True, False]
only_neg = [True, False]
histtype = ["bar", "step"]
ttx = [1, 10]
log = [True]
only_neg = [False]
histtype = ["bar"]
for t in ttx:
for l in log:
for n in only_neg:
for h in histtype:
fig = plot_events_TTX(
df, use, TTX_level=t, log=l, only_neg=n, histtype=h
)
fig.savefig(
Path(
figsave,
"pre_post",
str(t),
f"TTX_{t}um_histograms_{h}_log_{l}_onlyneg_{n}{filetype}",
),
bbox_inches="tight",
dpi=300,
transparent=True,
)
df2 = pd.read_csv(Path(save_dir, "TTX_active_df_by_cell.csv"))
T = 0.2
df2["exp_stage"] = df2.expt + "_" + df2.stage
df2["day_slip"] = df2.day.astype(str) + "_" + df2.slip.astype(str)
df2["neg_event_rate"] = (df2["n_neg_events"]) / (df2["obs_length"] * T)
df2["neg_integ_rate"] = (
-1 * (df2["neg_integrated_events"]) / (df2["obs_length"] * T)
)
use2 = [x for x in np.unique(df2["exp_stage"]) if "washout" not in x]
plot_TTX_summary(
df2,
use2,
figsave,
filetype,
redo_stats=redo_stats,
key="neg_event_rate",
function=np.mean,
function_name="np.mean",
scale=3,
density=True,
)
plot_TTX_summary(
df2,
use2,
figsave,
filetype,
redo_stats=False,
key="neg_event_rate",
function=np.mean,
function_name="np.mean",
scale=3,
density=False,
)
# plot_TTX_summary(df2,use2,figsave,filetype,redo_stats = redo_stats,key = 'neg_integ_rate', function = np.mean,function_name = 'np.mean',scale = 3, density = True)
# plot_TTX_summary(df2,use2,figsave,filetype,redo_stats = False,key = 'neg_integ_rate', function = np.mean,function_name = 'np.mean',scale = 3, density = False)
def plot_TTX_washout(save_dir, figsave, filetype, redo_stats):
df = pd.read_csv(Path(save_dir, "all_events_df.csv"))
df["exp_stage"] = df.expt + "_" + df.stage
use = [x for x in np.unique(df["exp_stage"]) if "TTX" in x and "washout" in x]
log = [True, False]
only_neg = [True, False]
histtype = ["bar", "step"]
log = [True]
only_neg = [False]
histtype = ["bar"]
for l in log:
for n in only_neg:
for h in histtype:
fig = plot_events_TTX_washout(df, use, log=l, only_neg=n, histtype=h)
fig.savefig(
Path(
figsave,
"washout",
f"TTX_washout_histograms_{h}_log_{l}_onlyneg_{n}{filetype}",
),
bbox_inches="tight",
dpi=300,
transparent=True,
)
# now plot the mean and bootstrapped cis
df2 = pd.read_csv(Path(save_dir, "TTX_active_df_by_cell.csv"))
T = 0.2
df2["exp_stage"] = df2.expt + "_" + df2.stage
df2["neg_event_rate"] = (df2["n_neg_events"]) / (df2["obs_length"] * T)
df2["day_slip"] = df2.day.astype(str) + "_" + df2.slip.astype(str)
df2["neg_integ_rate"] = (
-1 * (df2["neg_integrated_events"]) / (df2["obs_length"] * T)
)
use2 = [x for x in np.unique(df2["exp_stage"]) if "washout" in x]
plot_washout_summary(
df2,
use2,
figsave,
filetype,
redo_stats=redo_stats,
key="neg_event_rate",
function=np.mean,
function_name="np.mean",
scale=3,
density=True,
)
plot_washout_summary(
df2,
use2,
figsave,
filetype,
redo_stats=False,
key="neg_event_rate",
function=np.mean,
function_name="np.mean",
scale=3,
density=False,
)
# plot_washout_summary(df2,use2,figsave,filetype,redo_stats = redo_stats,key = 'neg_integ_rate', function = np.mean,function_name = 'np.mean',scale = 3, density = True)
# plot_washout_summary(df2,use2,figsave,filetype,redo_stats = False,key = 'neg_integ_rate', function = np.mean,function_name = 'np.mean',scale = 3, density = False)
def plot_washout_summary(
df,
use,
figsave,
filetype,
redo_stats=True,
num_resamplings=10**6,
key="neg_event_rate",
function=np.mean,
function_name="np.mean",
scale=3,
density=True,
):
dfn = df.copy()
use_bool = np.array([np.any(x in use) for x in dfn.exp_stage])
dfn = dfn[use_bool]
pre = dfn[dfn.stage == "pre"][key].to_numpy()
post = dfn[dfn.stage == "post"][key].to_numpy()
wash = dfn[dfn.stage == "washout"][key].to_numpy()
ppre = dfn[dfn.stage == "pre"][[key, "day_slip"]]
ppost = dfn[dfn.stage == "post"][[key, "day_slip"]]
wwash = dfn[dfn.stage == "washout"][[key, "day_slip"]]
bins = np.histogram(np.concatenate((pre, post, wash)) * 10**3, bins=10)[1]
fig, axarr = plt.subplots(nrows=3)
c = 0.05
axarr[0].hist(
pre * 10**scale,
bins=bins,
log=True,
density=density,
label="pre TTX",
color=(c, c, c),
)
axarr[1].hist(
post * 10**scale,
bins=bins,
log=True,
density=density,
label="post 10 uM TTX",
color=(c, c, c),
)
axarr[2].hist(
wash * 10**scale,
bins=bins,
log=True,
density=density,
label="washout",
color=(c, c, c),
)
axarr[0].sharey(axarr[1])
axarr[2].sharey(axarr[1])
for idx, a in enumerate(axarr):
if not density:
a.set_ylim([0.6, 10**4.5])
a.set_yticks(10 ** np.arange(0, 4, 3))
a.legend(frameon=False, loc=(0.4, 0.4), fontsize=16)
pf.set_all_fontsize(a, 16)
if idx != 2:
a.set_xticklabels([])
if not density:
axarr[1].set_ylabel("Number of cells")
else:
axarr[1].set_ylabel("Proportion of cells")
if key == "neg_event_rate":
axarr[-1].set_xlabel("Negative event rate " + "(1000 cells$^{-1}$ s$^{-1}$)")
elif key == "neg_integ_rate":
axarr[-1].set_xlabel(
f"Integrated event rate per {10**scale} cells " + "(%$\cdot$s / s)"
)
else:
raise ValueError("wrong key")
fig.savefig(
Path(
figsave, "summary", f"TTX_washout_compare_density_{density}_{key}{filetype}"
),
bbox_inches="tight",
dpi=300,
transparent=True,
)
if redo_stats:
p_pre_post, _, f1 = statsf.bootstrap_test(
pre,
post,
function=function,
plot=True,
num_resamplings=num_resamplings,
names=["Pre TTX", "Post TTX"],
)
p_pre_wash, _, f2 = statsf.bootstrap_test_2sided(
wash,
pre,
function=function,
plot=True,
num_resamplings=num_resamplings,
names=["Pre TTX", "washout"],
)
p_wash_post, _, f3 = statsf.bootstrap_test(
wash,
post,
function=function,
plot=True,
num_resamplings=num_resamplings,
names=["Washout", "Post TTX"],
)
f1.savefig(
Path(
figsave, "summary", "bootstrap", f"bootstrap_pre_post_{key}{filetype}"
),
bbox_inches="tight",
dpi=300,
transparent=True,
)
f2.savefig(
Path(
figsave, "summary", "bootstrap", f"bootstrap_wash_pre_{key}{filetype}"
),
bbox_inches="tight",
dpi=300,
transparent=True,
)
f3.savefig(
Path(
figsave, "summary", "bootstrap", f"bootstrap_wash_post_{key}{filetype}"
),
bbox_inches="tight",
dpi=300,
transparent=True,
)
with open(
Path(figsave, "summary", f"statistical_test_results_washout_{key}.txt"), "w"
) as f:
f.write(f"{datetime.datetime.now()}\n")
f.write(
f"Testing significance of second less than first for function {function_name}\n"
)
f.write(f"N cells pre: {len(pre)}\n")
f.write(f"N cells post: {len(post)}\n")
f.write(f"N cells wash: {len(wash)}\n")
f.write(f'N slips pre: {len(np.unique(ppre["day_slip"]))}\n')
f.write(f'N slips post: {len(np.unique(ppost["day_slip"]))}\n')
f.write(f'N slips wash: {len(np.unique(wwash["day_slip"]))}\n')
f.write(f"Pre mean rate: {np.mean(pre)}\n")
f.write(f"Post mean rate: {np.mean(post)}\n")
f.write(f"Wash mean rate: {np.mean(wash)}\n")
f.write(f"Num resamples: {num_resamplings}\n")
f.write(f"p pre-post {p_pre_post}\n")
f.write(f"p pre-wash (2 sided) {p_pre_wash}\n")
f.write(f"p wash-post {p_wash_post}\n")
def plot_TTX_summary(
df,
use,
figsave,
filetype,
redo_stats=True,
num_resamplings=10**6,
key="neg_event_rate",
function=np.mean,
function_name="np.mean",
scale=3,
density=True,
):
dfn = df.copy()
use_bool = np.array([np.any(x in use) for x in dfn.exp_stage])
dfn = dfn[use_bool]
pre_10 = dfn[dfn.exp_stage == "TTX_10um_pre"][key].to_numpy()
post_10 = dfn[dfn.exp_stage == "TTX_10um_post"][key].to_numpy()
pre_1 = dfn[dfn.exp_stage == "TTX_1um_pre"][key].to_numpy()
post_1 = dfn[dfn.exp_stage == "TTX_1um_post"][key].to_numpy()
ppre_10 = dfn[dfn.exp_stage == "TTX_10um_pre"][[key, "day_slip"]]
ppost_10 = dfn[dfn.exp_stage == "TTX_10um_post"][[key, "day_slip"]]
ppre_1 = dfn[dfn.exp_stage == "TTX_1um_pre"][[key, "day_slip"]]
ppost_1 = dfn[dfn.exp_stage == "TTX_1um_post"][[key, "day_slip"]]
bins_10 = np.histogram(np.concatenate((pre_10, post_10)) * 10**3, bins=10)[1]
bins_1 = np.histogram(np.concatenate((pre_1, post_1)) * 10**3, bins=10)[1]
fig_10, axarr_10 = plt.subplots(nrows=2)
c = 0.05
axarr_10[0].hist(
pre_10 * 10**scale,
bins=bins_10,
log=True,
density=density,
label="pre TTX",
color=(c, c, c),
)
axarr_10[1].hist(
post_10 * 10**scale,
bins=bins_10,
log=True,
density=density,
label="post 10 uM TTX",
color=(c, c, c),
)
axarr_10[0].sharey(axarr_10[1])
for idx, a in enumerate(axarr_10):
if not density:
a.set_ylim([0.6, 10**4.5])
a.set_yticks(10 ** np.arange(0, 4, 3))
a.legend(frameon=False, loc=(0.4, 0.4), fontsize=16)
pf.set_all_fontsize(a, 16)
if idx != 1:
a.set_xticklabels([])
if not density:
axarr_10[1].set_ylabel("Number of cells")
else:
axarr_10[1].set_ylabel("Proportion of cells")
if key == "neg_event_rate":
axarr_10[-1].set_xlabel("Negative event rate " + "(1000 cells$^{-1}$ s$^{-1}$)")
elif key == "neg_integ_rate":
axarr_10[-1].set_xlabel(
f"Integrated event rate per {10**scale} cells " + "(%$\cdot$s / s)"
)
else:
raise ValueError("wrong key")
fig_10.savefig(
Path(figsave, "summary", f"TTX_10um_compare_density_{density}_{key}{filetype}"),
bbox_inches="tight",
dpi=300,
transparent=True,
)
if redo_stats:
p_pre_post_10, _, f1 = statsf.bootstrap_test(
pre_10,
post_10,
function=function,
plot=True,
num_resamplings=num_resamplings,
names=["Pre TTX", "Post 10 uM TTX"],
)
f1.savefig(
Path(figsave, "summary", "bootstrap", f"bootstrap_pre_10_{key}{filetype}"),
bbox_inches="tight",
dpi=300,
transparent=True,
)
with open(
Path(figsave, "summary", f"statistical_test_results_10uM_{key}.txt"), "w"
) as f:
f.write(f"{datetime.datetime.now()}\n")
f.write(
f"Testing significance of second less than first for function {function_name}\n"
)
f.write(f"N cells pre: {len(pre_10)}\n")
f.write(f"N cells post: {len(post_10)}\n")
f.write(f'N slips pre: {len(np.unique(ppre_10["day_slip"]))}\n')
f.write(f'N slips post: {len(np.unique(ppost_10["day_slip"]))}\n')
f.write(f"Pre mean rate: {np.mean(pre_10)}\n")
f.write(f"Post mean rate: {np.mean(post_10)}\n")
print("Hello")
f.write(f"Num resamples: {num_resamplings}\n")
f.write(f"p pre-post {p_pre_post_10}\n")
fig_1, axarr_1 = plt.subplots(nrows=2)
c = 0.05
axarr_1[0].hist(
pre_1 * 10**scale,
bins=bins_1,
log=True,
density=density,
label="pre TTX",
color=(c, c, c),
)
axarr_1[1].hist(
post_1 * 10**scale,
bins=bins_1,
log=True,
density=density,
label="post 1 uM TTX",
color=(c, c, c),
)
axarr_1[0].sharey(axarr_1[1])
for idx, a in enumerate(axarr_1):
if not density:
a.set_ylim([0.6, 10**4.5])
a.set_yticks(10 ** np.arange(0, 4, 3))
a.legend(frameon=False, loc=(0.4, 0.4), fontsize=16)
pf.set_all_fontsize(a, 16)
if idx != 1:
a.set_xticklabels([])
if not density:
axarr_1[1].set_ylabel("Number of cells")
else:
axarr_1[1].set_ylabel("Proportion of cells")
if key == "neg_event_rate":
axarr_1[-1].set_xlabel("Negative event rate " + "(1000 cells$^{-1}$ s$^{-1}$)")
elif key == "neg_integ_rate":
axarr_1[-1].set_xlabel(
f"Integrated event rate per {10**scale} cells " + "(%$\cdot$s / s)"
)
else:
raise ValueError("wrong key")
fig_1.savefig(
Path(figsave, "summary", f"TTX_1um_compare_density_{density}_{key}{filetype}"),
bbox_inches="tight",
dpi=300,
transparent=True,
)
if redo_stats:
p_pre_post_1, _, f1 = statsf.bootstrap_test(
pre_1,
post_1,
function=function,
plot=True,
num_resamplings=num_resamplings,
names=["Pre TTX", "Post 1 uM TTX"],
)
f1.savefig(
Path(figsave, "summary", "bootstrap", f"bootstrap_pre_1_{key}{filetype}"),
bbox_inches="tight",
dpi=300,
transparent=True,
)
with open(
Path(figsave, "summary", f"statistical_test_results_1uM_{key}.txt"), "w"
) as f:
f.write(f"{datetime.datetime.now()}\n")
f.write(
f"Testing significance of second less than first for function {function_name}\n"
)
f.write(f"N cells pre: {len(pre_1)}\n")
f.write(f"N cells post: {len(post_1)}\n")
f.write(f'N slips pre: {len(np.unique(ppre_1["day_slip"]))}\n')
f.write(f'N slips post: {len(np.unique(ppost_1["day_slip"]))}\n')
f.write(f"Pre mean rate: {np.mean(pre_1)}\n")
f.write(f"Post mean rate: {np.mean(post_1)}\n")
f.write(f"Num resamples: {num_resamplings}\n")
f.write(f"p pre-post {p_pre_post_1}\n")
def plot_events_TTX(
df,
use,
TTX_level=1,
log=True,
upper_lim=6.6,
lower_lim=0,
T=0.2,
nbins=20,
only_neg=True,
histtype="bar",
):
dfn = df.copy()
use = [x for x in use if f"{TTX_level}um" in x]
use_bool = np.array([np.any(x in use) for x in dfn.exp_stage])
dfn = dfn[use_bool]
too_big = np.abs(dfn.event_amplitude) > upper_lim / 100
too_small = np.abs(dfn.event_amplitude) < lower_lim / 100
dfn = dfn[np.logical_not(np.logical_or(too_big, too_small))]
if only_neg:
dfn = dfn[dfn["event_amplitude"] < 0]
length_bins = np.histogram(dfn["event_length"] * T, bins=nbins)[1]
if only_neg:
amp_bins = np.histogram(np.abs(dfn["event_amplitude"]) * 100, bins=nbins)[1]
else:
amp_bins = | np.histogram(dfn["event_amplitude"] * 100, bins=nbins) | numpy.histogram |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Dec 16 17:34:28 2020
@author: pmbpanther
"""
import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import quad, nquad
from numpy.testing import assert_almost_equal
from inspect import signature
π = np.pi
oo = np.inf
class Wavefunction(object):
"""
Class for 6.S079 Quantum Circuits, designed to work with and perform simple manipulations
of wavefunctions, e.g. add, subtract, divide, multiply.
"""
def __init__(self, wfunc, ndim = None):
"""
Initializes an instance of the Wavefunction class, given a function object.
wfunc must return a complex NumPy value.
FIXME, slight concern what if someone calls Wavefunction(lambda *x: foobar(*x))
"""
self.ψ = wfunc
self.ndim = ndim
if not ndim:
self.ndim = len(signature(wfunc).parameters)
def __call__(self, *args):
"""
This code permits the wavefunction class to be callable
>>> ψ = Wavefunction(lambda x: np.exp(-x**2))
>>> print(ψ(0))
1.0
>>> print(ψ.ψ(0))
1.0
"""
return self.ψ(*args)
@classmethod
def init_gaussian(cls, *args) -> "Wavefunction object based on Gaussian":
"""
Factory method that initializes a properly normalized Gaussian wavefunction.
*args is a list of tuples. Each tuple contains (Xo, σ) for one of the
dimensions along which the gaussian is to be defined
>>> wf1 = Wavefunction.init_gaussian((0,1))
>>> print(wf1(0))
(0.6316187777460647+0j)
>>> wf1 = Wavefunction.init_gaussian((0,1), (1,2))
>>> print(wf1(0,1))
(0.28209479177387814+0j)
"""
def result(*xs):
return_val = 1
for x, arg in zip(xs,args):
Xo, σ = arg
return_val *= np.exp(-(x - Xo)**2/(4*σ**2))/(2*π*σ**2)**0.25
return return_val + 0j
return cls(result, len(args))
@classmethod
def init_plane_wave(cls, *args) -> "Wavefunction object based on plane wave":
"""
Factory method that initializes a plane wave
"""
def result(*x):
return_val = 1
for i, arg in enumerate(args):
Xo, λ = arg
return_val *= np.exp(1j*(x[i]-Xo)*2*π/λ)
return return_val
return cls(result, len(args))
@classmethod
def init_interp(cls, vec):
raise NotImplementedError
def __add__(self, wf2):
"""
Note, the result is in general not normalized.
>>> wf1 = Wavefunction.init_gaussian((0,1))
>>> wf2 = Wavefunction.init_gaussian((1,2))
>>> wf3 = wf1 + wf2
>>> wf3(0)
(1.0511812443492508+0j)
>>> wf1(0) + wf2(0)
(1.0511812443492508+0j)
"""
return self.__class__(lambda *x: self(*x) + wf2(*x))
def __sub__(self, wf2):
return self.__class__(lambda *x: self(*x) - wf2(*x))
def __mul__(self, arg2):
"""
Multiply wavefunction by a complex value coefficient
"""
# FIXME, I think the first case should never happen
if isinstance(arg2, self.__class__):
return self.__class__(lambda *x: self(*x) * arg2(*x))
else:
return self.__class__(lambda *x: arg2 * self(*x))
def __rmul__(self, arg2):
"""
Multiply wavefunction by another wavefunction or a complex value
"""
return self.__class__(lambda *x: arg2 * self(*x))
def __truediv__(self, arg2):
"""
Divide wavefunction by another wavefunction or a complex value
"""
if not isinstance(arg2, self.__class__):
return self.__class__(lambda *x: self(*x) / arg2)
else:
return self.__class__(lambda *x: self(*x) / arg2(*x))
def __abs__(self):
""" Calculate absolute value of wavefunction
>>> abs(Wavefunction.init_gaussian((0,1)))
0.9999999999999997
If for some reason the user wishes to normalize over a finite
region (E.g. because the function is not integrable, or
periodic boundary conditions are in effect over a finite range,
the limits can be provided as a tuple.
"""
func = lambda *x: np.real(self(*x))**2 - np.imag(self(*x))**2
limits = [(-oo, oo) for _ in range(self.ndim)]
return nquad(func, limits)[0]
def normalize(self): # FIXME
"""
Function returns a normalized wavefunction given an input of a non-normalized
wavefunction. It is needed whenever wavefunctions are added.
>>> wf = Wavefunction.init_gaussian((0,1)) + Wavefunction.init_gaussian((0,1))
>>> abs(wf.normalize())
0.9999999999999999
"""
return self.__class__(self.ψ, self.ndim)/np.sqrt(abs(self))
def vectorize(self, *args):
"""
Assigns the internal variable vec to be equal to the Wavefunction's ψ, broadcasted over an array,
startingat x_min and ending at x_max, with N total points.
Each dimension is spec'd in an (xmin, xmax, N) tuple
"""
# make arrays
array_list = []
for x_min, x_max, N in args:
array_list.append(np.linspace(x_min, x_max, N))
X = np.meshgrid(*array_list)
self.mat = self(*X)
self.ranges = args
self.vec = self.mat.copy().flatten()
return self.vec
def visualize1D(self, **kwargs):
"""
plot_wavefunction:: plot a one-dimensional wavefunction.
This is intended to be a utility function, so that, for example, one can quickly plot
something as part of another routine. It can also be used to simply plot a static
wavefunction.
Not implemented: use it to update artists for an animation or another graphic setting
that is already constructed.
self: wavefunction to be plotted, can be a func or a vector
range: tuple with min-max to be plotted
N: number of plotpoints
method: cartesian, polar, pdf, or 3d
"""
x_min, x_max = kwargs["x_range"]
xs = np.linspace(x_min, x_max, kwargs["N"])
x_label = kwargs["x_label"]
method = kwargs["method"]
# be flexible about accepting self either as a function or a vector
try:
ψs = self(xs)
except:
raise NotImplementedError
if method == "cartesian":
plt.plot(xs, np.abs(ψs), label="|ψ|")
plt.plot(xs, np.real(ψs), label="real part")
plt.plot(xs, np.imag(ψs), label="imaginary part")
plt.legend(loc='upper right')
plt.xlabel(x_label)
plt.ylabel("Amplitude")
plt.title("Wavefunction")
return plt.gcf()
if method == "polar":
# or equivalently, one can look at magnitude and phase
fig, (ax1, ax2) = plt.subplots(2)
fig.suptitle('Polar plot')
ax1.plot(xs, np.abs(ψs), label="magnitude")
ax1.set(ylabel="|ψ|")
ax2.plot(xs, np.angle(ψs), label="phase")
ax2.set(xlabel=x_label, ylabel="∠ψ")
return plt.gcf()
if method == "pdf":
plt.plot(xs, | np.abs(ψs) | numpy.abs |
import os
import time
import math
import random
import numpy as np
import h5py
import matplotlib.pyplot as plt
import torch
import torch.backends.cudnn as cudnn
import torch.nn as nn
import torch.nn.functional as F
from torch import optim
from torch.autograd import Variable
from pytorch3d.io import save_ply, save_obj, load_objs_as_meshes, load_obj, load_ply
from pytorch3d.structures import Meshes
from pytorch3d.renderer import (
look_at_view_transform,
FoVPerspectiveCameras,
PointLights,
DirectionalLights,
Materials,
RasterizationSettings,
MeshRenderer,
MeshRasterizer,
SoftPhongShader,
TexturesUV,
Textures,
TexturesVertex
)
import cv2
import mcubes
from typing import List
from ..preprocessing.utils import shapenet_cam_params
from .ShapeNetRendering import ShapeNetRendering
from .utils import *
from .modelSVR import IM_SVR
class IM_SVR_DD(IM_SVR):
def __init__(self, config):
super().__init__(config)
self.shapenet_cam_params = shapenet_cam_params
def load_data(self, config):
'''
Overrides base class method in order to only load data required for deep dreaming.
:param config:
:return:
'''
# get config values
z_base = int(config.interpol_z1)
z_target = int(config.interpol_z2)
self.crop_edge = self.view_size - self.crop_size
data_hdf5_name = self.data_dir + '/' + self.dataset_load + '.hdf5'
if os.path.exists(data_hdf5_name):
data_dict = h5py.File(data_hdf5_name, 'r')
offset_x = int(self.crop_edge / 2)
offset_y = int(self.crop_edge / 2)
# reshape to NCHW
# get the shape of the first two cropped pictures
cropped_shape = np.reshape(
data_dict['pixels'][0:2, :, offset_y:offset_y + self.crop_size, offset_x:offset_x + self.crop_size],
[-1, self.view_num, 1, self.crop_size, self.crop_size]).shape
self.data_pixels = np.empty(shape=cropped_shape)
# now grab only the data that is needed. This must be done iteratively or hdf5 can throw and error
# (selection indices must be of increasing order only)
for ind, z in enumerate([z_base, z_target]):
self.data_pixels[ind, ...] = np.reshape(
data_dict['pixels'][z, :, offset_y:offset_y + self.crop_size, offset_x:offset_x + self.crop_size],
[self.view_num, 1, self.crop_size, self.crop_size])
else:
print("error: cannot load " + data_hdf5_name)
exit(0)
def get_activation(self, output_list):
'''
A wrapper function to establish the forward hook
:param out:
:return:
'''
def hook(model, input, output):
output_list[0] = output
return hook
def get_zvec(self, z_num):
if z_num < len(self.data_pixels):
batch_view = self.data_pixels[z_num:z_num + 1, self.test_idx].astype(np.float32) / 255.0
batch_view = torch.from_numpy(batch_view)
batch_view = batch_view.to(self.device)
z_vec_, _ = self.im_network(batch_view, None, None, is_training=False)
z_vec = z_vec_.detach().cpu().numpy()
return (z_vec)
else:
print("z_num not a valid number")
def interpolate_z(self, config):
'''
A method to create the meshes from latent z vectors linearly interpolated between two vectors.
:param config:
:return:
'''
# TODO: uncomment load data
super().load_data(config=config)
# TODO: load previous checkpoint
self.load_checkpoint()
z1 = int(config.interpol_z1)
z2 = int(config.interpol_z2)
interpol_steps = int(config.interpol_steps)
result_base_directory = config.interpol_directory
self.result_dir_name = 'interpol_' + str(z1) + '_' + str(z2)
self.result_dir = result_base_directory + '/' + self.result_dir_name
print(self.result_dir)
# Create output directory
if not os.path.isdir(self.result_dir):
os.mkdir(self.result_dir)
print('creating directory ' + self.result_dir)
# get the z vectors via forward pass through encoder
z1_vec = self.get_zvec(z1)
print(z1_vec)
z2_vec = self.get_zvec(z2)
print(z2_vec)
# compute linear interpolation between vectors
fraction = np.linspace(0, 1, interpol_steps)
interpolated_z = np.multiply.outer(np.ones_like(fraction), z1_vec) + np.multiply.outer(fraction,
z2_vec - z1_vec)
interpolated_z = interpolated_z.astype(np.float64)
self.out_filenames = []
for z_index in np.arange(interpol_steps):
self.out_filenames.append(self.result_dir + "/" + "out_{:.2f}.ply".format(fraction[z_index]))
for z_index in np.arange(interpol_steps):
start_time = time.time()
model_z = interpolated_z[z_index:z_index + 1].astype(np.float64)
# print('current latent vector:')
# print(model_z.shape)
model_z = torch.from_numpy(model_z).float()
model_z = model_z.to(self.device)
self.im_network.eval()
model_float = self.z2voxel(model_z)
vertices, triangles = mcubes.marching_cubes(model_float, self.sampling_threshold)
vertices = (vertices.astype(np.float32) - 0.5) / self.real_size - 0.5
# vertices = self.optimize_mesh(vertices,model_z)
write_ply_triangle(self.result_dir + "/" + "out_{:.2f}.ply".format(fraction[z_index]), vertices, triangles)
end_time = time.time() - start_time
print("computed interpolation {} in {} seconds".format(z_index, end_time))
def create_saved_images(self, images, name):
num_images = int(images.shape[0])
cols = 3
rows = -int(-num_images // cols)
# convert back to grayscale
rescale_images = images
print(images.max())
print(images.min())
fig, axs = plt.subplots(nrows=rows,
ncols=cols,
sharex='all',
sharey='all',
figsize=(cols * 2, rows * 2),
gridspec_kw={'wspace': 0, 'hspace': 0}
)
for ax, im in zip(axs.flatten(), range(num_images)):
ax.imshow(rescale_images[im, 0, :, :], cmap='gray', vmin=0, vmax=1)
ax.axis('off')
plt.savefig(self.result_dir + '/' + name)
# output shape as ply
def create_model_mesh(self, batch_view, num, config):
# TODO: uncomment load checkpoint
# load previous checkpoint
self.load_checkpoint()
self.im_network.eval()
model_z, _ = self.im_network(batch_view, None, None, is_training=False)
model_float = self.z2voxel(model_z)
print('model_float shape')
print(model_float.shape)
# This transform nescessary to accomodate coordinate transform induced in marching cubes
model_float = np.flip(np.transpose(model_float, (2, 1, 0)), 0)
vertices, triangles = mcubes.marching_cubes(model_float, self.sampling_threshold)
vertices = (vertices.astype(np.float32) - 0.5) / self.real_size - 0.5
# vertices = self.optimize_mesh(vertices,model_z)
full_path = self.result_dir + "/" + str(num) + "_vox.ply"
write_ply_triangle(full_path, vertices, triangles)
print("created .ply for image {}".format(num))
return full_path
def cv2_image_transform(self, img):
'''
Basic image transform used as input to IM_SVR
:param img:
:return:
'''
'''
imgo = img[:, :, :3] * 255
imgo = cv2.cvtColor(imgo, cv2.COLOR_BGR2GRAY)
imga = (img[:, :, 3])
img_out = imgo * imga + 255.0 * (1 - imga)
img_out = np.round(img_out).astype(np.uint8)
'''
img[:, :, :3] = img[:, :, :3] * 255
img_out = cv2.cvtColor(img[:, :, :], cv2.COLOR_BGRA2GRAY) / 255
# img_out = np.round(img_out).astype(np.uint8)
# print(img_out.shape)
img_out = cv2.resize(img_out, dsize=(128, 128))
img_out = img_out[np.newaxis, :, :].astype(np.float32)
return img_out
def annealing_view(self, ply_path):
# param_num = self.test_idx
param_num = 7
# get image transform
R, T = look_at_view_transform(
dist=shapenet_cam_params["distance"][param_num] * 3,
elev=shapenet_cam_params["elevation"][param_num],
azim=shapenet_cam_params["azimuth"][param_num])
cameras = FoVPerspectiveCameras(device=self.device,
R=R,
T=T,
fov=shapenet_cam_params["field_of_view"][param_num]
)
raster_settings = RasterizationSettings(
image_size=128,
blur_radius=0.0,
faces_per_pixel=1,
)
lights = PointLights(device=self.device, location=[[0.0, 0.0, -3.0]])
renderer = MeshRenderer(
rasterizer=MeshRasterizer(
cameras=cameras,
raster_settings=raster_settings
),
shader=SoftPhongShader(
device=self.device,
cameras=cameras,
lights=lights
)
)
verts = []
faces = []
verts_rgb = []
titles = []
vert, face = load_ply(ply_path)
verts.append(vert.to(self.device))
faces.append(face.to(self.device))
verts_rgb.append(torch.ones_like(vert).to(self.device))
textures = Textures(verts_rgb=verts_rgb)
interpol_mesh = Meshes(verts, faces, textures)
image = renderer(interpol_mesh).cpu().numpy()
print(image.shape)
reformatted_image = self.cv2_image_transform(image[0])
print(reformatted_image.min())
out = torch.from_numpy(reformatted_image).unsqueeze(0).type(torch.float32).to(self.device)
# print(out)
return out
def annealing_view_pytorch3d(self, ply_paths: List[str]):
verts = []
faces = []
verts_rgb = []
for ply_path in ply_paths:
vert, face = load_ply(ply_path)
verts.append(vert.to(self.device))
faces.append(face.to(self.device))
verts_rgb.append(torch.ones_like(vert).to(self.device))
# verts_rgb.append(torch.rand(size=vert.size()).to(self.device))
textures = Textures(verts_rgb=verts_rgb)
interpol_mesh = Meshes(verts, faces, textures)
# print(interpol_mesh.isempty())
# print(interpol_mesh.num_verts_per_mesh())
image = self.shapenet_render.render(model_ids=[0],
meshes=interpol_mesh,
device=self.device
).cpu().numpy()
# print(image.shape)
reformatted_image = self.cv2_image_transform(image[0])
out = torch.from_numpy(reformatted_image).unsqueeze(0).type(torch.float32).to(self.device)
return out
def latent_gradient(self, base_batch_view, target_batch_view, step, config):
style_activation = self.style_activation.clone()
# zero gradients
self.im_network.zero_grad()
# re-register forward hook on each forward pass.
# self.target_layer.register_forward_hook(self.get_activation(self.target_activation))
z_vec_, _ = self.im_network(base_batch_view, None, None, is_training=False)
base_activation = self.target_activation[0]
# compute best feature maps
features, width, height = style_activation.shape
style_activation = style_activation.view(features, -1)
comp_base_activation = base_activation.squeeze().view(features, -1)
# Matrix of best matching feature maps.
A = torch.matmul(torch.transpose(comp_base_activation, 0, 1), style_activation)
# A = comp_base_activation.T.dot(style_activation)
loss = comp_base_activation[:, torch.argmax(A, 1)].view(features, width, height).detach()
# run the graph in reverse
base_activation.backward(loss.unsqueeze(0))
return base_batch_view.grad
def deep_dream(self, config):
# TODO: uncomment load data
super().load_data(config)
# TODO: uncomment checkpoint load
# load previous checkpoint
self.load_checkpoint()
# get config values
z_base = int(config.interpol_z1)
base_im_num = int(config.z1_im_view)
z_target = int(config.interpol_z2)
target_im_num = int(config.z1_im_view)
# instantiate camera rendering class
self.shapenet_render = ShapeNetRendering(model_nums=[z_base, z_target],
R2N2_dir=config.R2N2_dir,
model_views=[[base_im_num], [target_im_num]],
splitfile=config.splitfile
)
# set the dreaming rate and boundary size
self.dream_rate = config.dream_rate
annealing_step = config.annealing_rate
# Set up forward hook to pull values
self.layer_num = config.layer_num
# list index includes as zero entry the generator module itself.
# 2 layers up front should not be used
num_model_layers = len(list(self.im_network.img_encoder.named_children())) - 2
if self.layer_num < 2 or self.layer_num >= num_model_layers:
print('Layer number is too large: select layer numbers from 2 to {}'.format(num_model_layers))
exit(0)
# Get target layer
# self.target_layer = list(list(self.im_network.img_encoder.children())[self.layer_num].children())[-1]
self.target_layer = list(self.im_network.img_encoder.children())[self.layer_num]
self.target_activation = [None]
# register forward hook
self.target_layer.register_forward_hook(self.get_activation(self.target_activation))
interpol_steps = int(config.interpol_steps)
result_base_directory = config.interpol_directory
result_dir_name = 'DeepDream_SVR' + str(z_base) + '_' + str(z_target) + '_layer_' + str(self.layer_num)
self.result_dir = result_base_directory + '/' + result_dir_name
# Create output directory
# TODO: re-create directory
if not os.path.isdir(self.result_dir):
os.mkdir(self.result_dir)
print('creating directory ' + self.result_dir)
# store images
num_images = interpol_steps // annealing_step
annealing_images = | np.empty(shape=(num_images + 2, 1, 128, 128)) | numpy.empty |
from __future__ import print_function
import numpy as np
import math
import random
import time
import sys
import operator
import os
from numpy import zeros, newaxis
import re
#import matplotlib.pyplot as plt
import glob
#import skimage
#import skimage.io
#import scipy.io as scp
from sklearn.utils import shuffle
from util.Generate_pm_pa import *
from util.UAV_subfunctions import *
from util.Extract_Patch import *
from util.Detect_Patch import *
from sklearn.ensemble import AdaBoostClassifier
from sklearn.tree import DecisionTreeClassifier
from sklearn.externals import joblib
#import pandas
import keras
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten
from keras.layers import Conv2D, MaxPooling2D
from keras import backend as K
from keras.models import load_model
from keras.callbacks import ReduceLROnPlateau,EarlyStopping, ModelCheckpoint
from keras.models import load_model
videoPath = './Data/'
app_model_path = './models/max500_1_10_threelayers/'
app_model_path_track = './models/Appearance_OriImage/'
mvmodel_path = './models/motion/'
bimodel_path = './models/Adaboost/'
bimodel_path_track = './models/Adaboost_track/'
#defult is 15, 2
trackwinS =15
video_savePath_features = './Experiment_Results/Final/Video/'
if not os.path.exists(video_savePath_features):
print ("path doesn't exist. trying to make")
os.makedirs(video_savePath_features)
video_savePath_Detection = './Experiment_Results/Final/txt/'
if not os.path.exists(video_savePath_Detection):
print ("path doesn't exist. trying to make")
os.makedirs(video_savePath_Detection)
par = []
par.append([0.001,40])
index= list(range(50))
print(index)
from sklearn.utils import shuffle
index = shuffle(index, random_state=42)
print("complete shuffling")
print(index)
maxD=4
for ind in range(1,2):
appmodel=load_model(app_model_path+str(ind)+'.h5')
appmodel.summary()
appmodel_track=load_model(app_model_path_track+str(ind)+'.h5')
appmodel_track.summary()
mvmodel = load_model(mvmodel_path+str(ind)+'.h5')
mvmodel.summary()
combinemodel = joblib.load(bimodel_path+'fold'+str(ind)+'.pkl')
combinemodel_track = joblib.load(bimodel_path_track+'fold'+str(ind)+'.pkl')
a = 0.001
b = 50
#test_ind = index[10*(ind-1):10*(ind-1)+10]
test_ind = index[10*(ind-1):10*(ind-1)+1]
objNo = 0
dtNo = 0
htNo = 0
allFA = 0
for i in test_ind:
all_params = dict(videoName = str(i+1),
downrightx = 350,
upleftx = 0,
downrighty = 780,
uplefty = 510,
fileName = 'supervised_SVM_'+str(i),
debug = 1,
qualityini = 0.005,#np.float32(sys.argv[4]),#1.5#,
K = 1,# number of previous frames before Xt-1
MaxCorns = 600,#np.int16(sys.argv[5]),#200,#600/(resizeFactor*resizeFactor),
mindist1 = 25,#np.int16(sys.argv[6]),#15,
quality = a,#np.float32(sys.argv[7]),#0.001 #,
maxcorners = 1000,#np.int16(sys.argv[8]),#100,#/(resizeFactor*resizeFactor),
mindist = b,#15,#np.int16(sys.argv[9]),#1,
use_ransac = True,
track_len = 10,# track_len: maximum number of points recorded in the track
lamda = 0,#taking average if bidirectional error
detect_interval = 6,
)
print ('Video:',all_params['videoName'])
videoName = all_params['videoName']
uplefty = all_params['uplefty']
downrighty = all_params['downrighty']
upleftx = all_params['upleftx']
downrightx = all_params['downrightx']
fileName = all_params['fileName']
debug = all_params['debug']
K = all_params['K']
qualityini = all_params['qualityini']
MaxCorns = all_params['MaxCorns']
mindist1 = all_params['mindist1']
use_ransac = all_params['use_ransac']
track_len = all_params['track_len']
lamda = all_params['lamda']
quality = all_params['quality']
maxcorners = all_params['maxcorners']
mindist = all_params['mindist']
detect_interval = all_params['detect_interval']
## parameter for feature detection(original image) and tracking[for background subtraction]
feature_params = dict( maxCorners = MaxCorns,
qualityLevel = qualityini,
minDistance = mindist1,
blockSize = 5 )
## parameter for feature tracking(original image)
lk_params = dict( winSize = (19, 19),
maxLevel = 2,
criteria = (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 20, 0.03))
## parameter for feature detection(error image) and tracking[for feature extraction and tracking]
print (maxcorners, quality, mindist)
feature_params_track = dict( maxCorners = 500,
qualityLevel = quality/20.0,
minDistance = mindist,
blockSize = 9 )
feature_params_track_oriImg = feature_params_track
lk_params_track = dict( winSize = (19, 19),
maxLevel = 2,
criteria = (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 30, 0.03),
minEigThreshold=1e-4)
lk_params_track_ori = dict( winSize = (25, 25),
maxLevel = 3,
flags = cv2.OPTFLOW_USE_INITIAL_FLOW,
criteria = (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 30, 0.03),
minEigThreshold=1e-4)
feature_params_Detect = dict( maxCorners = 10,
qualityLevel = 0.00000015,
minDistance = 0,
blockSize = 3 )
#cam_gt=cv2.VideoCapture(videoPath+ 'shor_clip_gtVideo/uav_Video_'+videoName+'_gt.mov')
print(videoName)
cam=cv2.VideoCapture(videoPath+ 'Videos/Clip_'+videoName+'.mov')
gt_text = open(videoPath+ 'Annotation_update_180925/Video_'+videoName+'_gt.txt',"r")
f_txt = open(video_savePath_Detection+ videoName+'_dt.txt','w')
# read in one frame in order to obtain the video size
frameidx = 1
color=cam.read()[1]
color_gt=color.copy()#cam_gt.read()[1]
prepreFrame = np.float32(cv2.cvtColor(color, cv2.COLOR_RGB2GRAY))
h,w,channel = color.shape
groundtruth = gt_text.readline()
outputFeature = "time_layer: "+ str(frameidx)+" detections: "
f_txt.write(outputFeature+"\n")
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
FPS = cam.get(cv2.CAP_PROP_FPS)
video_PosPatch = cv2.VideoWriter(video_savePath_features+videoName+'.mov', fourcc,FPS,(w,h))
# initialize feature points
pImg = None
#initialize H_back
H_back = None
# read in Xt-1
color=cam.read()[1]
color_gt =color.copy()#cam_gt.read()[1]
groundtruth = gt_text.readline()
frameidx+=1
outputFeature = "time_layer: "+ str(frameidx)+" detections: "
#f_txt.write(outputFeature+"\n")
Xtminus1 = np.float32(cv2.cvtColor(color, cv2.COLOR_RGB2GRAY))
# blocks is 1 except for the pitot tube region(0)
blocks = np.ones((h,w), dtype='float32')
#blocks[uplefty:downrighty,upleftx:downrightx ] = 0
# parameter for groundtruth dilation
dt_d = 4
radius = 10
Dotft = []
Patchft=[]
maxPatchId = 0
while True:
#print(frameidx)
##############Start Detection Part############
######Background Subtraction #################
print('frameID:', frameidx)
gray = Xtminus1.copy()
# read in current frame Xt
future_color = cam.read()[1]
if future_color is None:
frameidx+=1
outputFeature = "time_layer: "+ str(frameidx)+" detections: "
f_txt.write(outputFeature)
break
frameidx+=1
Xt = np.float32(cv2.cvtColor(future_color, cv2.COLOR_RGB2GRAY))
## generate groundtruth mask
gt_split = groundtruth.split()
length = len(gt_split)
gt_index = 3
gt_mask = np.zeros_like(Xt)
gt_ft_maske = np.zeros_like(Xt)
bbox_index = 0
centers = []
color_gt = color.copy()
while gt_index< length:
bbox_index+=1
uplefty = gt_split[gt_index]
uplefty = int(uplefty[1:-1])
upleftx = gt_split[gt_index+1]
upleftx = int(upleftx[0:-1])
downrighty = gt_split[gt_index+2]
downrighty = int(downrighty[0:-1])
downrightx = gt_split[gt_index+3]
downrightx = int(downrightx[0:-2])
downrighty = np.min([downrighty+dt_d, h-1])
downrightx = np.min([downrightx+dt_d, w-1])
uplefty = np.max([uplefty-dt_d,0])
upleftx = np.max([upleftx-dt_d,0])
cv2.rectangle(color_gt,(np.int16(upleftx),np.int16(uplefty)),(np.int16(downrightx),np.int16(downrighty)), (255,0,0),1)
gt_mask[uplefty:downrighty, upleftx:downrightx] = bbox_index#255
gt_ft_maske[uplefty:downrighty, upleftx:downrightx] = 255
centers.append([(upleftx+downrightx)/2,(uplefty+downrighty)/2])
gt_index += 4
oriImage = color_gt.copy()
oriImage_1 = color_gt.copy()
# extract feature points for previous frame gray = Xt-1. By using maskOut function, only keep features outside the pitot tube area
if pImg is None or frameidx % track_len == 0:
pImg = cv2.goodFeaturesToTrack( | np.uint8(gray) | numpy.uint8 |
# -*- coding:utf-8 -*-
import json
import os
import numpy as np
import random
import config
import re
import functools
# from bert_serving.client import BertClient
class file_data_loader:
def __next__(self):
raise NotImplementedError
def next(self):
return self.__next__()
def next_batch(self, batch_size):
raise NotImplementedError
class cmp():
def __init__(self, x):
self.x = x
def __lt__(self, other):
a_key = self.x['head']['id'] + '#' + self.x['tail']['id'] + '#' + self.x['relation']
b_key = other.x['head']['id'] + '#' + other.x['tail']['id'] + '#' + other.x['relation']
if (a_key > b_key):
return False
elif (a_key == b_key):
return False
else:
return True
class json_file_data_loader(file_data_loader):
# 以instance作为最小单位
MODE_INSTANCE = 0
# 以bag为最小单位,每个bag中实体对相同,一般用于test(因为不知道relation)
MODE_ENTPAIR_BAG = 1
# 以bag为最小单位,每个bag中实体对和关系相同,一般用于train
MODE_RELFACT_BAG = 2
def _load_processed_file(self, dataset):
# train or test
name_prefix = '.'.join(self.file_name.split('/')[-1].split('.')[:-1])
word_vec_name_prefix = '.'.join(self.word_vec_file_name.split('/')[-1].split('.')[:-1])
processed_data_dir = '_processed_data'
if not os.path.isdir(processed_data_dir):
return False
word_npy_file_name = os.path.join(processed_data_dir, dataset + "_" + name_prefix + '_word.npy')
pos1_npy_file_name = os.path.join(processed_data_dir, dataset + "_" + name_prefix + '_pos1.npy')
pos2_npy_file_name = os.path.join(processed_data_dir, dataset + "_" + name_prefix + '_pos2.npy')
rel_npy_file_name = os.path.join(processed_data_dir, dataset + "_" + name_prefix + '_rel.npy')
rel_npy_file_name2 = os.path.join(processed_data_dir, dataset + "_" + name_prefix + '_rel2.npy')
rel_npy_file_name3 = os.path.join(processed_data_dir, dataset + "_" + name_prefix + '_rel3.npy')
mask_npy_file_name = os.path.join(processed_data_dir, dataset + "_" + name_prefix + '_mask.npy')
length_npy_file_name = os.path.join(processed_data_dir, dataset + "_" + name_prefix + '_length.npy')
entpair2scope_file_name = os.path.join(processed_data_dir, dataset + "_" + name_prefix + '_entpair2scope.json')
relfact2scope_file_name = os.path.join(processed_data_dir, dataset + "_" + name_prefix + '_relfact2scope.json')
word_vec_mat_file_name = os.path.join(processed_data_dir, dataset + "_" + word_vec_name_prefix + '_mat.npy')
word2id_file_name = os.path.join(processed_data_dir, dataset + "_" + word_vec_name_prefix + '_word2id.json')
id2word_file_name = os.path.join(processed_data_dir, dataset + "_" + word_vec_name_prefix + '_id2word.json')
entity1_file_name = os.path.join(processed_data_dir, dataset + "_" + name_prefix + '_entity1.npy')
entity2_file_name = os.path.join(processed_data_dir, dataset + "_" + name_prefix + '_entity2.npy')
sentence_file_name = os.path.join(processed_data_dir, dataset + "_" + name_prefix + '_sentence.txt')
if not os.path.exists(word_npy_file_name) or \
not os.path.exists(pos1_npy_file_name) or \
not os.path.exists(pos2_npy_file_name) or \
not os.path.exists(rel_npy_file_name) or \
not os.path.exists(mask_npy_file_name) or \
not os.path.exists(length_npy_file_name) or \
not os.path.exists(entpair2scope_file_name) or \
not os.path.exists(relfact2scope_file_name) or \
not os.path.exists(word_vec_mat_file_name) or \
not os.path.exists(word2id_file_name) or \
not os.path.exists(entity1_file_name) or \
not os.path.exists(entity2_file_name) or \
not os.path.exists(sentence_file_name) or \
not os.path.exists(id2word_file_name):
return False
print("Loading pre-processing files...")
self.data_word = np.load(word_npy_file_name)
self.data_pos1 = np.load(pos1_npy_file_name)
self.data_pos2 = np.load(pos2_npy_file_name)
self.data_rel = np.load(rel_npy_file_name)
self.data_rel2 = np.load(rel_npy_file_name2)
self.data_rel3 = np.load(rel_npy_file_name3)
self.data_mask = np.load(mask_npy_file_name)
self.data_length = np.load(length_npy_file_name)
with open(entpair2scope_file_name, 'r', encoding='utf8') as fr:
self.entpair2scope = json.load(fr)
with open(relfact2scope_file_name, 'r', encoding='utf8') as fr:
self.relfact2scope = json.load(fr)
self.word_vec_mat = np.load(word_vec_mat_file_name)
print("word vec" + str(len(self.word_vec_mat)))
with open(word2id_file_name, 'r', encoding='utf8') as fr:
self.word2id = json.load(fr)
with open(id2word_file_name, 'r', encoding='utf8') as fr:
self.id2word = json.load(fr)
self.data_entity1 = np.load(entity1_file_name)
self.data_entity2 = np.load(entity2_file_name)
if (self.data_word.shape[1] != config.model.max_length):
print("Pre-processing ata is expired, Reprocessing")
return False
with open(sentence_file_name, 'r', encoding='utf8') as fr:
self.data_sentence = []
for line in fr:
self.data_sentence.append(line)
print('Finish loading')
return True
def __init__(self, file_name, word_vec_file_name, rel2id_file_name, rel2id_file_name2, rel2id_file_name3,
deepwalk_file_name, rel_rel2_filename, rel_rel3_filename, entity2id_file_name, mid_file_name,
entity_type_file_name, mode, shuffle, sen_num_bag='all', max_length=config.model.max_length,
case_sensitive=False, batch_size=config.model.batch_size):
'''
:param file_name: 数据路径
:param word_vec_file_name: 词向量路径
:param rel2id_file_name: relation to id 路径
:param mode: 组织数据的模式,有3种方式:MODE_INSTANCE , MODE_ENTPAIR_BAG,MODE_RELFACT_BAG
:param shuffle: 是否shuffle数据
:param max_length: 规定句子的最长长度
:param batch_size: 定义batch_size
'''
# self.bc = BertClient(check_length=False)
self.sen_num_bag = sen_num_bag
self.file_name = file_name
self.word_vec_file_name = word_vec_file_name
self.rel2id_file_name = rel2id_file_name
self.mode = mode
self.shuffle = shuffle
self.max_length = max_length
self.batch_size = batch_size
with open(rel2id_file_name, 'r') as fr:
self.rel2id = json.load(fr)
if rel2id_file_name2 is not None:
with open(rel2id_file_name2, 'r') as fr:
self.rel2id2 = json.load(fr)
if rel2id_file_name3 is not None:
with open(rel2id_file_name3, 'r') as fr:
self.rel2id3 = json.load(fr)
dataset = file_name.split("/")[-2]
print("dataset: " + dataset)
deepwalk_dict = {}
max_num = 0
with open(deepwalk_file_name, 'r', encoding='utf8') as fr:
num, dim = fr.readline().split()
print("%s entities, %s dim" % (num, dim))
while (True):
line = fr.readline()
if (not line):
break
index = line.find(' ')
e_id = line[0:index]
vec = line[index:-1].strip().split()
deepwalk_dict[int(e_id)] = list(vec)
max_num = max(int(e_id), max_num)
# self.deepwalk_mat = np.ones((max_num+1,int(dim)),dtype=np.float32)
self.deepwalk_mat = np.random.rand(max_num + 1, int(dim)).astype(np.float32)
with open(rel_rel2_filename, 'r', encoding='utf8') as fr:
self.rel_rel2 = json.load(fr)
with open(rel_rel3_filename, 'r', encoding='utf8') as fr:
self.rel_rel3 = json.load(fr)
for id, e_id in enumerate(deepwalk_dict):
vec = deepwalk_dict[e_id]
self.deepwalk_mat[int(e_id), :] = vec
with open(entity2id_file_name, 'r', encoding='utf8') as fr:
self.entity2id = json.load(fr)
with open(entity_type_file_name, 'r', encoding='utf8') as fr:
self.entity_type = json.load(fr)
with open(mid_file_name, 'r', encoding='utf8') as fr:
self.mid2id = json.load(fr)
self.entity_type_id = {}
for mid in self.entity_type:
type_list = self.entity_type[mid]
for type in type_list:
if self.entity_type_id.get(type) is None:
self.entity_type_id[type] = len(self.entity_type_id)
print(self.entity_type_id)
print(len(self.entity_type_id))
self.entityid_type = {}
for mid in self.entity_type:
for type in self.entity_type[mid]:
if self.mid2id.get(mid) is not None:
if self.entityid_type.get(self.mid2id[mid]) is None:
self.entityid_type[self.mid2id[mid]] = [self.entity_type_id[type]]
else:
self.entityid_type[self.mid2id[mid]].append(self.entity_type_id[type])
if (not self._load_processed_file(dataset)):
if file_name is None or not os.path.isfile(file_name):
raise Exception("[ERROR] Data file doesn't exist")
if word_vec_file_name is None or not os.path.isfile(word_vec_file_name):
raise Exception("[ERROR] word2vec file doesn't exist")
if rel2id_file_name is None or not os.path.isfile(rel2id_file_name):
raise Exception("[ERROR] word2vec file doesn't exist")
# load file
print("log4 Hierarchical att fine-tune dropout 0.1")
print("Loading data file...")
with open(self.file_name, 'r', encoding='utf8') as fr:
self.ori_data = json.load(fr)
print("Finish loading")
# Eliminate case sensitive
if not case_sensitive:
print("Elimiating case sensitive problem...")
for i in range(len(self.ori_data)):
self.ori_data[i]['sentence'] = self.ori_data[i]['sentence'].lower()
self.ori_data[i]['head']['word'] = self.ori_data[i]['head']['word'].lower()
self.ori_data[i]['tail']['word'] = self.ori_data[i]['tail']['word'].lower()
print("Finish eliminating")
print("Loading word vector file...")
with open(self.word_vec_file_name, 'r', encoding='utf8') as fr:
self.ori_word_vec = json.load(fr)
print("Finish loading")
# sort data by entities and relations
print("sort data")
# self.ori_data.sort(key = cmp)
def compare_by_entities_and_relations(a, b):
a_key = a['head']['id'] + '#' + a['tail']['id'] + '#' + a['relation']
b_key = b['head']['id'] + '#' + b['tail']['id'] + '#' + b['relation']
if a_key > b_key:
return 1
elif a_key == b_key:
return 0
else:
return -1
self.ori_data.sort(key=functools.cmp_to_key(compare_by_entities_and_relations))
print('Finish sorting')
# pre-processing word vec
self.word2id = {}
self.id2word = {}
self.word_vec_tot = len(self.ori_word_vec)
UNK = self.word_vec_tot
BLANK = self.word_vec_tot + 1
self.word2id['UNK'] = UNK
self.word2id['BLANK'] = BLANK
self.word_vec_dim = len(self.ori_word_vec[0]['vec'])
print("Got {} words of {} dims".format(self.word_vec_tot, self.word_vec_dim))
print("Building word vector matrix and mapping...")
self.word_vec_mat = np.zeros((self.word_vec_tot, self.word_vec_dim), dtype=np.float32)
for cur_id, word in enumerate(self.ori_word_vec):
w = word['word']
if not case_sensitive:
w = w.lower()
self.word2id[w] = cur_id
self.id2word[cur_id] = w
self.word_vec_mat[cur_id, :] = word['vec']
self.word2id['UNK'] = UNK
self.id2word[UNK] = 'UNK'
self.word2id['BLANK'] = BLANK
self.id2word[BLANK] = 'BLANK'
print("Finish building")
# Pre-processing
print("Pre-processing data...")
self.instance_tot = len(self.ori_data)
self.entpair2scope = {} # (head,tail) -> scope
self.relfact2scope = {} # (head,tail,rel) -> scope
self.data_word = np.zeros((self.instance_tot, self.max_length), dtype=np.int32)
self.data_pos1 = np.zeros((self.instance_tot, self.max_length), dtype=np.int32)
self.data_pos2 = np.zeros((self.instance_tot, self.max_length), dtype=np.int32)
self.data_rel = np.zeros((self.instance_tot), dtype=np.int32)
self.data_rel2 = np.zeros((self.instance_tot), dtype=np.int32)
self.data_rel3 = np.zeros((self.instance_tot), dtype=np.int32)
self.data_mask = np.zeros((self.instance_tot, self.max_length), dtype=np.int32)
self.data_length = np.zeros((self.instance_tot), dtype=np.int32)
self.data_entity1 = np.zeros((self.instance_tot), dtype=np.int32)
self.data_entity2 = np.zeros((self.instance_tot), dtype=np.int32)
# bc = BertClient()
last_entpair = ''
last_entpair_pos = -1
last_relfact = ''
last_relfact_pos = -1
dirty_data_number = 0
self.data_sentence = []
pattern = re.compile(r'\s')
for i in range(self.instance_tot):
ins = self.ori_data[i]
dataset = file_name.split("/")[-2]
self.data_sentence.append(ins['sentence'].strip())
if (ins['relation'] in self.rel2id):
self.data_rel[i] = self.rel2id[ins['relation']]
items = ins['relation'].split('/')
if len(items) == 1:
rel_layer2 = ins['relation']
rel_layer3 = ins['relation']
else:
rel_layer2 = '/' + items[1] + '/' + items[2]
rel_layer3 = '/' + items[1]
self.data_rel2[i] = self.rel2id2[rel_layer2]
self.data_rel3[i] = self.rel2id3[rel_layer3]
else:
self.data_rel[i] = self.rel2id['NA']
self.data_rel2[i] = self.rel2id2['NA']
self.data_rel3[i] = self.rel2id3['NA']
sentence = ' '.join(ins['sentence'].split())
head = ins['head']['word']
tail = ins['tail']['word']
cur_entpair = ins['head']['id'] + '#' + ins['tail']['id']
cur_relfact = ins['head']['id'] + '#' + ins['tail']['id'] + '#' + ins['relation']
if (cur_entpair != last_entpair):
if (last_entpair != ''):
self.entpair2scope[last_entpair] = [last_entpair_pos, i]
last_entpair = cur_entpair
last_entpair_pos = i
if (cur_relfact != last_relfact):
if (last_relfact != ''):
self.relfact2scope[last_relfact] = [last_relfact_pos, i]
last_relfact = cur_relfact
last_relfact_pos = i
# position
p1 = None
p2 = None
p1 = sentence.find(' ' + head + ' ')
p2 = sentence.find(' ' + tail + ' ')
# 如果是首 尾
if (p1 == -1):
if (sentence[:len(head) + 1] == head + " "):
p1 = 0
elif (sentence[-len(head) - 1:] == " " + head):
p1 = len(sentence) - len(head)
else:
p1 = 0
else:
p1 += 1
if (p2 == -1):
if (sentence[:len(tail) + 1] == tail + " "):
p2 = 0
elif (sentence[-len(tail) - 1:] == " " + tail):
p2 = len(sentence) - len(tail)
else:
p2 = 0
else:
p2 += 1
words = sentence.split()
cur_ref_data_word = self.data_word[i]
cur_pos = 0
pos1 = -1
pos2 = -1
for j, word in enumerate(words):
# print(cur_pos,ins['sentence'][cur_pos])
if (j < max_length):
if word in self.word2id:
cur_ref_data_word[j] = self.word2id[word]
else:
cur_ref_data_word[j] = UNK
if cur_pos == p1:
pos1 = j
p1 = -1
if cur_pos == p2:
pos2 = j
p2 = -1
cur_pos += len(word) + 1
for k in range(len(words), max_length):
cur_ref_data_word[k] = BLANK
self.data_length[i] = min(len(words), max_length)
if (pos1 == -1 or pos2 == -1):
raise Exception(
"[ERROR] Position error, index = {}, sentence = {}, head = {}, tail = {}".format(i, sentence,
head, tail))
pos1 = min(pos1, max_length - 1)
pos2 = min(pos2, max_length - 1)
pos_min = min(pos1, pos2)
pos_max = max(pos1, pos2)
for j in range(max_length):
self.data_pos1[i][j] = j - pos1 + max_length
self.data_pos2[i][j] = j - pos2 + max_length
if (j >= self.data_length[i]):
self.data_mask[i][j] = 0
elif j <= pos_min:
self.data_mask[i][j] = 1
elif j <= pos_max:
self.data_mask[i][j] = 2
else:
self.data_mask[i][j] = 3
entity1 = ins['head']['word'].strip().lower()
entity2 = ins['tail']['word'].strip().lower()
self.data_entity1[i] = len(self.entity2id)
if self.entity2id.get(entity1) is not None:
self.data_entity1[i] = self.entity2id[entity1]
self.data_entity2[i] = len(self.entity2id)
if self.entity2id.get(entity2) is not None:
self.data_entity2[i] = self.entity2id[entity2]
if last_entpair != '':
self.entpair2scope[last_entpair] = [last_entpair_pos, self.instance_tot]
if last_relfact != '':
self.relfact2scope[last_relfact] = [last_relfact_pos, self.instance_tot]
print("Finish pre-processing")
print("Storing preprocessing file...")
# train or test
name_prefix = '.'.join(self.file_name.split('/')[-1].split('.')[:-1])
word_vec_name_prefix = '.'.join(self.word_vec_file_name.split('/')[-1].split('.')[:-1])
processed_data_dir = '_processed_data'
if not os.path.isdir(processed_data_dir):
os.mkdir(processed_data_dir)
print("discards data number ", dirty_data_number)
np.save(os.path.join(processed_data_dir, dataset + "_" + name_prefix + '_word.npy'), self.data_word)
np.save(os.path.join(processed_data_dir, dataset + "_" + name_prefix + '_pos1.npy'), self.data_pos1)
np.save(os.path.join(processed_data_dir, dataset + "_" + name_prefix + '_pos2.npy'), self.data_pos2)
np.save(os.path.join(processed_data_dir, dataset + "_" + name_prefix + '_rel.npy'), self.data_rel)
np.save(os.path.join(processed_data_dir, dataset + "_" + name_prefix + '_rel2.npy'), self.data_rel2)
np.save(os.path.join(processed_data_dir, dataset + "_" + name_prefix + '_rel3.npy'), self.data_rel3)
np.save(os.path.join(processed_data_dir, dataset + "_" + name_prefix + '_mask.npy'), self.data_mask)
np.save(os.path.join(processed_data_dir, dataset + "_" + name_prefix + '_length.npy'), self.data_length)
np.save(os.path.join(processed_data_dir, dataset + "_" + name_prefix + '_entity1.npy'), self.data_entity1)
np.save(os.path.join(processed_data_dir, dataset + "_" + name_prefix + '_entity2.npy'), self.data_entity2)
with open(os.path.join(processed_data_dir, dataset + "_" + name_prefix + '_entpair2scope.json'), 'w',
encoding='utf8') as fw:
json.dump(self.entpair2scope, fw, ensure_ascii=False)
with open(os.path.join(processed_data_dir, dataset + "_" + name_prefix + '_relfact2scope.json'), 'w',
encoding='utf8') as fw:
json.dump(self.relfact2scope, fw, ensure_ascii=False)
np.save(os.path.join(processed_data_dir, dataset + "_" + word_vec_name_prefix + '_mat.npy'),
self.word_vec_mat)
with open(os.path.join(processed_data_dir, dataset + "_" + word_vec_name_prefix + '_word2id.json'), 'w',
encoding='utf8') as fw:
json.dump(self.word2id, fw, ensure_ascii=False)
with open(os.path.join(processed_data_dir, dataset + "_" + word_vec_name_prefix + '_id2word.json'), 'w',
encoding='utf8') as fw:
json.dump(self.id2word, fw, ensure_ascii=False)
with open(os.path.join(processed_data_dir, dataset + "_" + name_prefix + '_sentence.txt'), 'w',
encoding='utf8') as fw:
for line in self.data_sentence:
fw.write(line + '\n')
print("Finish storing")
self.instance_tot = self.data_word.shape[0]
self.entpair_tot = len(self.entpair2scope)
self.relfact_tot = 0 # relfact数, 除了 relation 关系
relation_fact = {}
for key in self.relfact2scope:
if (key[-2:] != 'NA'):
self.relfact_tot += 1
rel = key.strip().split('#')[-1]
if relation_fact.get(rel) is not None:
relation_fact[rel] += 1
else:
relation_fact[rel] = 1
with open('relation_fact.json', 'w', encoding='utf8') as fw:
json.dump(relation_fact, fw)
self.rel_tot = len(self.rel2id)
self.rel_tot2 = len(self.rel2id2)
self.rel_tot3 = len(self.rel2id3)
if self.mode == self.MODE_INSTANCE:
self.order = list(range(self.instance_tot))
elif self.mode == self.MODE_ENTPAIR_BAG:
self.order = list(range(len(self.entpair2scope)))
self.scope_name = []
self.scope = []
for key, value in self.entpair2scope.items():
self.scope_name.append(key)
self.scope.append(value)
elif self.mode == self.MODE_RELFACT_BAG:
self.order = list(range(len(self.relfact2scope)))
self.scope_name = []
self.scope = []
for key, value in self.relfact2scope.items():
self.scope_name.append(key)
self.scope.append(value)
else:
raise Exception("[ERROR] Invalid mode")
print("len order", len(self.order))
self.idx = 0
if (self.shuffle):
random.shuffle(self.order)
print("Total entity pair:%d" % (len(self.entpair2scope)))
print("Total relation fact:%d" % (len(self.relfact2scope)))
print("Total instance:%d" % (self.instance_tot))
def __iter__(self):
return self
def __next__(self):
return self.next_batch(self.batch_size)
def next_batch(self, batch_size):
if self.mode != self.MODE_INSTANCE:
if self.idx >= len(self.order):
self.idx = 0
if self.shuffle:
random.shuffle(self.order)
raise StopIteration
else:
if self.idx >= self.instance_tot:
self.idx = 0
if self.shuffle:
random.shuffle(self.order)
raise StopIteration
batch_data = {}
if self.mode == self.MODE_INSTANCE:
idx0 = self.idx
idx1 = min(self.instance_tot, self.idx + batch_size)
self.idx = idx1
batch_data['word'] = self.data_word[idx0:idx1]
batch_data['pos1'] = self.data_pos1[idx0:idx1]
batch_data['pos2'] = self.data_pos2[idx0:idx1]
batch_data['rel'] = self.data_rel[idx0:idx1]
batch_data['rel2'] = self.data_rel2[idx0:idx1]
batch_data['rel3'] = self.data_rel3[idx0:idx1]
batch_data['mask'] = self.data_mask[idx0:idx1]
batch_data['length'] = self.data_length[idx0:idx1]
batch_data['scope'] = np.stack([list(range(batch_size)), list(range(1, batch_size + 1))], axis=1)
batch_data['entity1'] = self.data_entity1[idx0:idx1]
batch_data['entity2'] = self.data_entity2[idx0:idx1]
batch_data['idx'] = [(i, i) for i in range(idx0, idx1)]
batch_data['ins_rel'] = self.data_rel[idx0:idx1]
batch_data['ins_rel2'] = self.data_rel2[idx0:idx1]
batch_data['ins_rel3'] = self.data_rel3[idx0:idx1]
if idx1 - idx0 < batch_size:
padding = batch_size - (idx1 - idx0)
batch_data['word'] = np.concatenate(
[batch_data['word'], np.zeros((padding, self.data_word.shape[-1]), dtype=np.int32)])
batch_data['pos1'] = np.concatenate(
[batch_data['pos1'], np.zeros((padding, self.data_pos1.shape[-1]), dtype=np.int32)])
batch_data['pos2'] = np.concatenate(
[batch_data['pos2'], np.zeros((padding, self.data_pos2.shape[-1]), dtype=np.int32)])
batch_data['mask'] = np.concatenate(
[batch_data['mask'], np.zeros((padding, self.data_mask.shape[-1]), dtype=np.int32)])
batch_data['rel'] = np.concatenate([batch_data['rel'], np.zeros((padding), dtype=np.int32)])
batch_data['rel2'] = np.concatenate([batch_data['rel2'], np.zeros((padding), dtype=np.int32)])
batch_data['rel3'] = np.concatenate([batch_data['rel3'], np.zeros((padding), dtype=np.int32)])
batch_data['length'] = np.concatenate([batch_data['length'], np.zeros((padding), dtype=np.int32)])
batch_data['entity1'] = np.concatenate([batch_data['entity1'], np.zeros((padding), dtype=np.int32)])
batch_data['entity2'] = np.concatenate([batch_data['entity2'], np.zeros((padding), dtype=np.int32)])
batch_data['idx'] = batch_data['idx'] + [(1, -1) for i in range(padding)]
batch_data['ins_rel'] = np.concatenate([batch_data['ins_rel'], np.zeros((padding), dtype=np.int32)])
batch_data['ins_rel2'] = np.concatenate([batch_data['ins_rel2'], np.zeros((padding), dtype=np.int32)])
batch_data['ins_rel3'] = np.concatenate([batch_data['ins_rel3'], np.zeros((padding), dtype=np.int32)])
elif self.mode == self.MODE_ENTPAIR_BAG or self.mode == self.MODE_RELFACT_BAG:
least_bag_sentence_num = None
if self.sen_num_bag == 'all':
least_bag_sentence_num = 0
else:
least_bag_sentence_num = 2
idx0 = self.idx
idx1 = self.idx + batch_size
if idx1 > len(self.order):
idx1 = len(self.order)
_word = []
_pos1 = []
_pos2 = []
_mask = []
_rel = []
_rel2 = []
_rel3 = []
_ins_rel = []
_ins_rel2 = []
_ins_rel3 = []
_multi_rel = []
_multi_rel2 = []
_multi_rel3 = []
_entpair = []
_length = []
_scope = []
_entity1 = []
_entity2 = []
_idx = []
_sentence = []
_bc_embedding = []
cur_pos = 0
cnt = 0
true_index = idx0
for i in range(idx0, len(self.order)):
if self.scope[self.order[i]][1] - self.scope[self.order[i]][0] < least_bag_sentence_num:
continue
indx = [j for j in range(self.scope[self.order[i]][0], self.scope[self.order[i]][1])]
random.shuffle(indx)
_word.append(self.data_word[self.scope[self.order[i]][0]:self.scope[self.order[i]][1]])
_pos1.append(self.data_pos1[self.scope[self.order[i]][0]:self.scope[self.order[i]][1]])
_pos2.append(self.data_pos2[self.scope[self.order[i]][0]:self.scope[self.order[i]][1]])
_mask.append(self.data_mask[self.scope[self.order[i]][0]:self.scope[self.order[i]][1]])
_rel.append(self.data_rel[self.scope[self.order[i]][0]])
_rel2.append(self.data_rel2[self.scope[self.order[i]][0]])
_rel3.append(self.data_rel3[self.scope[self.order[i]][0]])
_ins_rel.append(self.data_rel[self.scope[self.order[i]][0]:self.scope[self.order[i]][1]])
_ins_rel2.append(self.data_rel2[self.scope[self.order[i]][0]:self.scope[self.order[i]][1]])
_ins_rel3.append(self.data_rel3[self.scope[self.order[i]][0]:self.scope[self.order[i]][1]])
_length.append(self.data_length[self.scope[self.order[i]][0]:self.scope[self.order[i]][1]])
bag_size = self.scope[self.order[i]][1] - self.scope[self.order[i]][0]
_scope.append([cur_pos, cur_pos + bag_size])
_entity1.append(self.data_entity1[self.scope[self.order[i]][0]:self.scope[self.order[i]][1]])
_entity2.append(self.data_entity2[self.scope[self.order[i]][0]:self.scope[self.order[i]][1]])
_idx.append((self.scope[self.order[i]][0], self.scope[self.order[i]][1]))
_sentence = _sentence + self.data_sentence[self.scope[self.order[i]][0]:self.scope[self.order[i]][1]]
cur_pos = cur_pos + bag_size
if self.mode == self.MODE_ENTPAIR_BAG:
_one_multi_rel = np.zeros((self.rel_tot), dtype=np.int32)
_one_multi_rel2 = np.zeros((self.rel_tot2), dtype=np.int32)
_one_multi_rel3 = np.zeros((self.rel_tot3), dtype=np.int32)
for j in range(self.scope[self.order[i]][0], self.scope[self.order[i]][1]):
_one_multi_rel[self.data_rel[j]] = 1
_one_multi_rel2[self.data_rel2[j]] = 1
_one_multi_rel3[self.data_rel3[j]] = 1
_multi_rel.append(_one_multi_rel)
_multi_rel2.append(_one_multi_rel2)
_multi_rel3.append(_one_multi_rel3)
_entpair.append(self.scope_name[self.order[i]])
cnt += 1
true_index = i
if cnt == batch_size:
break
for i in range(batch_size - cnt):
_word.append(np.zeros((1, self.data_word.shape[-1]), dtype=np.int32))
_pos1.append(np.zeros((1, self.data_pos1.shape[-1]), dtype=np.int32))
_pos2.append(np.zeros((1, self.data_pos2.shape[-1]), dtype=np.int32))
_mask.append(np.zeros((1, self.data_mask.shape[-1]), dtype=np.int32))
_rel.append(0)
_rel2.append(0)
_rel3.append(0)
_ins_rel.append(np.zeros((1), dtype=np.int32))
_ins_rel2.append(np.zeros((1), dtype=np.int32))
_ins_rel3.append(np.zeros((1), dtype=np.int32))
_length.append(np.zeros((1), dtype=np.int32))
_scope.append([cur_pos, cur_pos + 1])
_entity1.append(np.zeros((1), dtype=np.int32))
_entity2.append(np.zeros((1), dtype=np.int32))
_sentence.append(["None"])
_idx.append((1, -1))
cur_pos += 1
if self.mode == self.MODE_ENTPAIR_BAG:
_multi_rel.append(np.zeros((self.rel_tot), dtype=np.int32))
_multi_rel2.append(np.zeros((self.rel_tot2), dtype=np.int32))
_multi_rel3.append(np.zeros((self.rel_tot3), dtype=np.int32))
_entpair.append('None#None')
self.idx = true_index + 1
batch_data['word'] = np.concatenate(_word)
batch_data['pos1'] = np.concatenate(_pos1)
batch_data['pos2'] = np.concatenate(_pos2)
batch_data['mask'] = np.concatenate(_mask)
batch_data['rel'] = np.stack(_rel)
batch_data['rel2'] = np.stack(_rel2)
batch_data['rel3'] = np.stack(_rel3)
batch_data['ins_rel'] = np.concatenate(_ins_rel)
batch_data['ins_rel2'] = np.concatenate(_ins_rel2)
batch_data['ins_rel3'] = np.concatenate(_ins_rel3)
if self.mode == self.MODE_ENTPAIR_BAG:
batch_data['multi_rel'] = | np.stack(_multi_rel) | numpy.stack |
# Copyright (c) 2014, <NAME>.
# Licensed under the BSD 3-clause license (see LICENSE.txt)
import numpy as np
from scipy.special import wofz
from .kern import Kern
from ...core.parameterization import Param
from ...core.parameterization.transformations import Logexp
from ...util.caching import Cache_this
class EQ_ODE2(Kern):
"""
Covariance function for second order differential equation driven by an exponentiated quadratic covariance.
This outputs of this kernel have the form
.. math::
\frac{\text{d}^2y_j(t)}{\text{d}^2t} + C_j\frac{\text{d}y_j(t)}{\text{d}t} + B_jy_j(t) = \sum_{i=1}^R w_{j,i} u_i(t)
where :math:`R` is the rank of the system, :math:`w_{j,i}` is the sensitivity of the :math:`j`th output to the :math:`i`th latent function, :math:`d_j` is the decay rate of the :math:`j`th output and :math:`f_i(t)` and :math:`g_i(t)` are independent latent Gaussian processes goverened by an exponentiated quadratic covariance.
:param output_dim: number of outputs driven by latent function.
:type output_dim: int
:param W: sensitivities of each output to the latent driving function.
:type W: ndarray (output_dim x rank).
:param rank: If rank is greater than 1 then there are assumed to be a total of rank latent forces independently driving the system, each with identical covariance.
:type rank: int
:param C: damper constant for the second order system.
:type C: array of length output_dim.
:param B: spring constant for the second order system.
:type B: array of length output_dim.
"""
#This code will only work for the sparseGP model, due to limitations in models for this kernel
def __init__(self, input_dim=2, output_dim=1, rank=1, W=None, lengthscale=None, C=None, B=None, active_dims=None, name='eq_ode2'):
#input_dim should be 1, but kern._slice_X is not returning index information required to evaluate kernels
assert input_dim == 2, "only defined for 1 input dims"
super(EQ_ODE2, self).__init__(input_dim=input_dim, active_dims=active_dims, name=name)
self.rank = rank
self.output_dim = output_dim
if lengthscale is None:
lengthscale = .5+np.random.rand(self.rank)
else:
lengthscale = np.asarray(lengthscale)
assert lengthscale.size in [1, self.rank], "Bad number of lengthscales"
if lengthscale.size != self.rank:
lengthscale = np.ones(self.input_dim)*lengthscale
if W is None:
#W = 0.5*np.random.randn(self.output_dim, self.rank)/np.sqrt(self.rank)
W = np.ones((self.output_dim, self.rank))
else:
assert W.shape == (self.output_dim, self.rank)
if C is None:
C = np.ones(self.output_dim)
if B is None:
B = np.ones(self.output_dim)
self.C = Param('C', C, Logexp())
self.B = Param('B', B, Logexp())
self.lengthscale = Param('lengthscale', lengthscale, Logexp())
self.W = Param('W', W)
self.link_parameters(self.lengthscale, self.C, self.B, self.W)
@Cache_this(limit=2)
def K(self, X, X2=None):
#This way is not working, indexes are lost after using k._slice_X
#index = np.asarray(X, dtype=np.int)
#index = index.reshape(index.size,)
if hasattr(X, 'values'):
X = X.values
index = np.int_(X[:, 1])
index = index.reshape(index.size,)
X_flag = index[0] >= self.output_dim
if X2 is None:
if X_flag:
#Calculate covariance function for the latent functions
index -= self.output_dim
return self._Kuu(X, index)
else:
raise NotImplementedError
else:
#This way is not working, indexes are lost after using k._slice_X
#index2 = np.asarray(X2, dtype=np.int)
#index2 = index2.reshape(index2.size,)
if hasattr(X2, 'values'):
X2 = X2.values
index2 = np.int_(X2[:, 1])
index2 = index2.reshape(index2.size,)
X2_flag = index2[0] >= self.output_dim
#Calculate cross-covariance function
if not X_flag and X2_flag:
index2 -= self.output_dim
return self._Kfu(X, index, X2, index2) #Kfu
else:
index -= self.output_dim
return self._Kfu(X2, index2, X, index).T #Kuf
#Calculate the covariance function for diag(Kff(X,X))
def Kdiag(self, X):
#This way is not working, indexes are lost after using k._slice_X
#index = np.asarray(X, dtype=np.int)
#index = index.reshape(index.size,)
if hasattr(X, 'values'):
X = X.values
index = np.int_(X[:, 1])
index = index.reshape(index.size,)
#terms that move along t
t = X[:, 0].reshape(X.shape[0], 1)
d = np.unique(index) #Output Indexes
B = self.B.values[d]
C = self.C.values[d]
S = self.W.values[d, :]
#Index transformation
indd = np.arange(self.output_dim)
indd[d] = np.arange(d.size)
index = indd[index]
#Check where wd becomes complex
wbool = C*C >= 4.*B
B = B.reshape(B.size, 1)
C = C.reshape(C.size, 1)
alpha = .5*C
C2 = C*C
wbool2 = wbool[index]
ind2t = np.where(wbool2)
ind3t = np.where(np.logical_not(wbool2))
#Terms that move along q
lq = self.lengthscale.values.reshape(1, self.lengthscale.size)
S2 = S*S
kdiag = np.empty((t.size, ))
indD = np.arange(B.size)
#(1) When wd is real
if np.any(np.logical_not(wbool)):
#Indexes of index and t related to (2)
t1 = t[ind3t]
ind = index[ind3t]
d = np.asarray(np.where(np.logical_not(wbool))[0]) #Selection of outputs
indd = indD.copy()
indd[d] = np.arange(d.size)
ind = indd[ind]
#Dx1 terms
S2lq = S2[d]*(.5*lq)
c0 = S2lq*np.sqrt(np.pi)
w = .5*np.sqrt(4.*B[d] - C2[d])
alphad = alpha[d]
w2 = w*w
gam = alphad + 1j*w
gamc = alphad - 1j*w
c1 = .5/(alphad*w2)
c2 = .5/(gam*w2)
c = c1 - c2
#DxQ terms
nu = lq*(gam*.5)
K01 = c0*c
#Nx1 terms
gamt = -gam[ind]*t1
gamct = -gamc[ind]*t1
egamt = np.exp(gamt)
ec = egamt*c2[ind] - np.exp(gamct)*c1[ind]
#NxQ terms
t_lq = t1/lq
# Upsilon Calculations
# Using wofz
wnu = wofz(1j*nu)
lwnu = np.log(wnu)
t2_lq2 = -t_lq*t_lq
upm = wnu[ind] - np.exp(t2_lq2 + gamt + np.log(wofz(1j*(t_lq + nu[ind]))))
upm[t1[:, 0] == 0, :] = 0.
nu2 = nu*nu
z1 = nu[ind] - t_lq
indv1 = np.where(z1.real >= 0.)
indv2 = np.where(z1.real < 0.)
upv = -np.exp(lwnu[ind] + gamt)
if indv1[0].shape > 0:
upv[indv1] += np.exp(t2_lq2[indv1] + np.log(wofz(1j*z1[indv1])))
if indv2[0].shape > 0:
upv[indv2] += np.exp(nu2[ind[indv2[0]], indv2[1]] + gamt[indv2[0], 0] + np.log(2.))\
- np.exp(t2_lq2[indv2] + np.log(wofz(-1j*z1[indv2])))
upv[t1[:, 0] == 0, :] = 0.
#Covariance calculation
kdiag[ind3t] = np.sum(np.real(K01[ind]*upm), axis=1)
kdiag[ind3t] += np.sum(np.real((c0[ind]*ec)*upv), axis=1)
#(2) When w_d is complex
if np.any(wbool):
t1 = t[ind2t]
ind = index[ind2t]
#Index transformation
d = np.asarray(np.where(wbool)[0])
indd = indD.copy()
indd[d] = np.arange(d.size)
ind = indd[ind]
#Dx1 terms
S2lq = S2[d]*(lq*.25)
c0 = S2lq*np.sqrt(np.pi)
w = .5*np.sqrt(C2[d] - 4.*B[d])
alphad = alpha[d]
gam = alphad - w
gamc = alphad + w
w2 = -w*w
c1 = .5/(alphad*w2)
c21 = .5/(gam*w2)
c22 = .5/(gamc*w2)
c = c1 - c21
c2 = c1 - c22
#DxQ terms
K011 = c0*c
K012 = c0*c2
nu = lq*(.5*gam)
nuc = lq*(.5*gamc)
#Nx1 terms
gamt = -gam[ind]*t1
gamct = -gamc[ind]*t1
egamt = np.exp(gamt)
egamct = np.exp(gamct)
ec = egamt*c21[ind] - egamct*c1[ind]
ec2 = egamct*c22[ind] - egamt*c1[ind]
#NxQ terms
t_lq = t1/lq
#Upsilon Calculations using wofz
t2_lq2 = -t_lq*t_lq #Required when using wofz
wnu = wofz(1j*nu).real
lwnu = np.log(wnu)
upm = wnu[ind] - np.exp(t2_lq2 + gamt + np.log(wofz(1j*(t_lq + nu[ind])).real))
upm[t1[:, 0] == 0., :] = 0.
nu2 = nu*nu
z1 = nu[ind] - t_lq
indv1 = np.where(z1 >= 0.)
indv2 = np.where(z1 < 0.)
upv = -np.exp(lwnu[ind] + gamt)
if indv1[0].shape > 0:
upv[indv1] += np.exp(t2_lq2[indv1] + np.log(wofz(1j*z1[indv1]).real))
if indv2[0].shape > 0:
upv[indv2] += np.exp(nu2[ind[indv2[0]], indv2[1]] + gamt[indv2[0], 0] + np.log(2.))\
- np.exp(t2_lq2[indv2] + np.log(wofz(-1j*z1[indv2]).real))
upv[t1[:, 0] == 0, :] = 0.
wnuc = wofz(1j*nuc).real
lwnuc = np.log(wnuc)
upmc = wnuc[ind] - np.exp(t2_lq2 + gamct + np.log(wofz(1j*(t_lq + nuc[ind])).real))
upmc[t1[:, 0] == 0., :] = 0.
nuc2 = nuc*nuc
z1 = nuc[ind] - t_lq
indv1 = np.where(z1 >= 0.)
indv2 = np.where(z1 < 0.)
upvc = - np.exp(lwnuc[ind] + gamct)
if indv1[0].shape > 0:
upvc[indv1] += np.exp(t2_lq2[indv1] + np.log(wofz(1j*z1[indv1]).real))
if indv2[0].shape > 0:
upvc[indv2] += np.exp(nuc2[ind[indv2[0]], indv2[1]] + gamct[indv2[0], 0] + np.log(2.))\
- np.exp(t2_lq2[indv2] + np.log(wofz(-1j*z1[indv2]).real))
upvc[t1[:, 0] == 0, :] = 0.
#Covariance calculation
kdiag[ind2t] = np.sum(K011[ind]*upm + K012[ind]*upmc + (c0[ind]*ec)*upv + (c0[ind]*ec2)*upvc, axis=1)
return kdiag
def update_gradients_full(self, dL_dK, X, X2 = None):
#index = np.asarray(X, dtype=np.int)
#index = index.reshape(index.size,)
if hasattr(X, 'values'):
X = X.values
self.B.gradient = np.zeros(self.B.shape)
self.C.gradient = np.zeros(self.C.shape)
self.W.gradient = np.zeros(self.W.shape)
self.lengthscale.gradient = np.zeros(self.lengthscale.shape)
index = np.int_(X[:, 1])
index = index.reshape(index.size,)
X_flag = index[0] >= self.output_dim
if X2 is None:
if X_flag: #Kuu or Kmm
index -= self.output_dim
tmp = dL_dK*self._gkuu_lq(X, index)
for q in np.unique(index):
ind = np.where(index == q)
self.lengthscale.gradient[q] = tmp[np.ix_(ind[0], ind[0])].sum()
else:
raise NotImplementedError
else: #Kfu or Knm
#index2 = np.asarray(X2, dtype=np.int)
#index2 = index2.reshape(index2.size,)
if hasattr(X2, 'values'):
X2 = X2.values
index2 = np.int_(X2[:, 1])
index2 = index2.reshape(index2.size,)
X2_flag = index2[0] >= self.output_dim
if not X_flag and X2_flag:
index2 -= self.output_dim
else:
dL_dK = dL_dK.T #so we obtaing dL_Kfu
indtemp = index - self.output_dim
Xtemp = X
X = X2
X2 = Xtemp
index = index2
index2 = indtemp
glq, gSdq, gB, gC = self._gkfu(X, index, X2, index2)
tmp = dL_dK*glq
for q in np.unique(index2):
ind = np.where(index2 == q)
self.lengthscale.gradient[q] = tmp[:, ind].sum()
tmpB = dL_dK*gB
tmpC = dL_dK*gC
tmp = dL_dK*gSdq
for d in np.unique(index):
ind = np.where(index == d)
self.B.gradient[d] = tmpB[ind, :].sum()
self.C.gradient[d] = tmpC[ind, :].sum()
for q in np.unique(index2):
ind2 = np.where(index2 == q)
self.W.gradient[d, q] = tmp[np.ix_(ind[0], ind2[0])].sum()
def update_gradients_diag(self, dL_dKdiag, X):
#index = np.asarray(X, dtype=np.int)
#index = index.reshape(index.size,)
if hasattr(X, 'values'):
X = X.values
self.B.gradient = np.zeros(self.B.shape)
self.C.gradient = np.zeros(self.C.shape)
self.W.gradient = np.zeros(self.W.shape)
self.lengthscale.gradient = np.zeros(self.lengthscale.shape)
index = np.int_(X[:, 1])
index = index.reshape(index.size,)
glq, gS, gB, gC = self._gkdiag(X, index)
tmp = dL_dKdiag.reshape(index.size, 1)*glq
self.lengthscale.gradient = tmp.sum(0)
#TODO: Avoid the reshape by a priori knowing the shape of dL_dKdiag
tmpB = dL_dKdiag*gB.reshape(dL_dKdiag.shape)
tmpC = dL_dKdiag*gC.reshape(dL_dKdiag.shape)
tmp = dL_dKdiag.reshape(index.size, 1)*gS
for d in np.unique(index):
ind = np.where(index == d)
self.B.gradient[d] = tmpB[ind].sum()
self.C.gradient[d] = tmpC[ind].sum()
self.W.gradient[d, :] = tmp[ind].sum(0)
def gradients_X(self, dL_dK, X, X2=None):
#index = np.asarray(X, dtype=np.int)
#index = index.reshape(index.size,)
if hasattr(X, 'values'):
X = X.values
index = np.int_(X[:, 1])
index = index.reshape(index.size,)
X_flag = index[0] >= self.output_dim
#If input_dim == 1, use this
#gX = np.zeros((X.shape[0], 1))
#Cheat to allow gradient for input_dim==2
gX = np.zeros(X.shape)
if X2 is None: #Kuu or Kmm
if X_flag:
index -= self.output_dim
gX[:, 0] = 2.*(dL_dK*self._gkuu_X(X, index)).sum(0)
return gX
else:
raise NotImplementedError
else: #Kuf or Kmn
#index2 = np.asarray(X2, dtype=np.int)
#index2 = index2.reshape(index2.size,)
if hasattr(X2, 'values'):
X2 = X2.values
index2 = np.int_(X2[:, 1])
index2 = index2.reshape(index2.size,)
X2_flag = index2[0] >= self.output_dim
if X_flag and not X2_flag: #gradient of Kuf(Z, X) wrt Z
index -= self.output_dim
gX[:, 0] = (dL_dK*self._gkfu_z(X2, index2, X, index).T).sum(1)
return gX
else:
raise NotImplementedError
#---------------------------------------#
# Helper functions #
#---------------------------------------#
#Evaluation of squared exponential for LFM
def _Kuu(self, X, index):
index = index.reshape(index.size,)
t = X[:, 0].reshape(X.shape[0],)
lq = self.lengthscale.values.reshape(self.rank,)
lq2 = lq*lq
#Covariance matrix initialization
kuu = np.zeros((t.size, t.size))
#Assign 1. to diagonal terms
kuu[np.diag_indices(t.size)] = 1.
#Upper triangular indices
indtri1, indtri2 = np.triu_indices(t.size, 1)
#Block Diagonal indices among Upper Triangular indices
ind = np.where(index[indtri1] == index[indtri2])
indr = indtri1[ind]
indc = indtri2[ind]
r = t[indr] - t[indc]
r2 = r*r
#Calculation of covariance function
kuu[indr, indc] = np.exp(-r2/lq2[index[indr]])
#Completation of lower triangular part
kuu[indc, indr] = kuu[indr, indc]
return kuu
#Evaluation of cross-covariance function
def _Kfu(self, X, index, X2, index2):
#terms that move along t
t = X[:, 0].reshape(X.shape[0], 1)
d = np.unique(index) #Output Indexes
B = self.B.values[d]
C = self.C.values[d]
S = self.W.values[d, :]
#Index transformation
indd = np.arange(self.output_dim)
indd[d] = np.arange(d.size)
index = indd[index]
#Check where wd becomes complex
wbool = C*C >= 4.*B
#Output related variables must be column-wise
C = C.reshape(C.size, 1)
B = B.reshape(B.size, 1)
C2 = C*C
#Input related variables must be row-wise
z = X2[:, 0].reshape(1, X2.shape[0])
lq = self.lengthscale.values.reshape((1, self.rank))
#print np.max(z), np.max(z/lq[0, index2])
alpha = .5*C
wbool2 = wbool[index]
ind2t = np.where(wbool2)
ind3t = np.where(np.logical_not(wbool2))
kfu = np.empty((t.size, z.size))
indD = np.arange(B.size)
#(1) when wd is real
if np.any(np.logical_not(wbool)):
#Indexes of index and t related to (2)
t1 = t[ind3t]
ind = index[ind3t]
#Index transformation
d = np.asarray(np.where(np.logical_not(wbool))[0])
indd = indD.copy()
indd[d] = np.arange(d.size)
ind = indd[ind]
#Dx1 terms
w = .5*np.sqrt(4.*B[d] - C2[d])
alphad = alpha[d]
gam = alphad - 1j*w
#DxQ terms
Slq = (S[d]/w)*(.5*lq)
c0 = Slq*np.sqrt(np.pi)
nu = gam*(.5*lq)
#1xM terms
z_lq = z/lq[0, index2]
#NxQ terms
t_lq = t1/lq
#NxM terms
zt_lq = z_lq - t_lq[:, index2]
# Upsilon Calculations
#Using wofz
tz = t1-z
fullind = np.ix_(ind, index2)
zt_lq2 = -zt_lq*zt_lq
z_lq2 = -z_lq*z_lq
gamt = -gam[ind]*t1
upsi = - np.exp(z_lq2 + gamt + np.log(wofz(1j*(z_lq + nu[fullind]))))
z1 = zt_lq + nu[fullind]
indv1 = np.where(z1.real >= 0.)
indv2 = np.where(z1.real < 0.)
if indv1[0].shape > 0:
upsi[indv1] += np.exp(zt_lq2[indv1] + np.log(wofz(1j*z1[indv1])))
if indv2[0].shape > 0:
nua2 = nu[ind[indv2[0]], index2[indv2[1]]]**2
upsi[indv2] += np.exp(nua2 - gam[ind[indv2[0]], 0]*tz[indv2] + np.log(2.))\
- np.exp(zt_lq2[indv2] + np.log(wofz(-1j*z1[indv2])))
upsi[t1[:, 0] == 0., :] = 0.
#Covariance calculation
kfu[ind3t] = c0[fullind]*upsi.imag
#(2) when wd is complex
if np.any(wbool):
#Indexes of index and t related to (2)
t1 = t[ind2t]
ind = index[ind2t]
#Index transformation
d = np.asarray(np.where(wbool)[0])
indd = indD.copy()
indd[d] = np.arange(d.size)
ind = indd[ind]
#Dx1 terms
w = .5*np.sqrt(C2[d] - 4.*B[d])
alphad = alpha[d]
gam = alphad - w
gamc = alphad + w
#DxQ terms
Slq = S[d]*(lq*.25)
c0 = -Slq*(np.sqrt(np.pi)/w)
nu = gam*(lq*.5)
nuc = gamc*(lq*.5)
#1xM terms
z_lq = z/lq[0, index2]
#NxQ terms
t_lq = t1/lq[0, index2]
#NxM terms
zt_lq = z_lq - t_lq
# Upsilon Calculations
tz = t1-z
z_lq2 = -z_lq*z_lq
zt_lq2 = -zt_lq*zt_lq
gamt = -gam[ind]*t1
gamct = -gamc[ind]*t1
fullind = np.ix_(ind, index2)
upsi = np.exp(z_lq2 + gamt + np.log(wofz(1j*(z_lq + nu[fullind])).real))\
- np.exp(z_lq2 + gamct + np.log(wofz(1j*(z_lq + nuc[fullind])).real))
z1 = zt_lq + nu[fullind]
indv1 = np.where(z1 >= 0.)
indv2 = np.where(z1 < 0.)
if indv1[0].shape > 0:
upsi[indv1] -= np.exp(zt_lq2[indv1] + np.log(wofz(1j*z1[indv1]).real))
if indv2[0].shape > 0:
nua2 = nu[ind[indv2[0]], index2[indv2[1]]]**2
upsi[indv2] -= np.exp(nua2 - gam[ind[indv2[0]], 0]*tz[indv2] + np.log(2.))\
- np.exp(zt_lq2[indv2] + np.log(wofz(-1j*z1[indv2]).real))
z1 = zt_lq + nuc[fullind]
indv1 = np.where(z1 >= 0.)
indv2 = np.where(z1 < 0.)
if indv1[0].shape > 0:
upsi[indv1] += np.exp(zt_lq2[indv1] + np.log(wofz(1j*z1[indv1]).real))
if indv2[0].shape > 0:
nuac2 = nuc[ind[indv2[0]], index2[indv2[1]]]**2
upsi[indv2] += np.exp(nuac2 - gamc[ind[indv2[0]], 0]*tz[indv2] + np.log(2.))\
- np.exp(zt_lq2[indv2] + np.log(wofz(-1j*z1[indv2]).real))
upsi[t1[:, 0] == 0., :] = 0.
kfu[ind2t] = c0[np.ix_(ind, index2)]*upsi
return kfu
#Gradient of Kuu wrt lengthscale
def _gkuu_lq(self, X, index):
t = X[:, 0].reshape(X.shape[0],)
index = index.reshape(X.shape[0],)
lq = self.lengthscale.values.reshape(self.rank,)
lq2 = lq*lq
#Covariance matrix initialization
glq = np.zeros((t.size, t.size))
#Upper triangular indices
indtri1, indtri2 = np.triu_indices(t.size, 1)
#Block Diagonal indices among Upper Triangular indices
ind = np.where(index[indtri1] == index[indtri2])
indr = indtri1[ind]
indc = indtri2[ind]
r = t[indr] - t[indc]
r2 = r*r
r2_lq2 = r2/lq2[index[indr]]
#Calculation of covariance function
er2_lq2 = np.exp(-r2_lq2)
#Gradient wrt lq
c = 2.*r2_lq2/lq[index[indr]]
glq[indr, indc] = er2_lq2*c
#Complete the lower triangular
glq[indc, indr] = glq[indr, indc]
return glq
#Be careful this derivative should be transpose it
def _gkuu_X(self, X, index): #Diagonal terms are always zero
t = X[:, 0].reshape(X.shape[0],)
index = index.reshape(index.size,)
lq = self.lengthscale.values.reshape(self.rank,)
lq2 = lq*lq
#Covariance matrix initialization
gt = np.zeros((t.size, t.size))
#Upper triangular indices
indtri1, indtri2 = np.triu_indices(t.size, 1) #Offset of 1 from the diagonal
#Block Diagonal indices among Upper Triangular indices
ind = np.where(index[indtri1] == index[indtri2])
indr = indtri1[ind]
indc = indtri2[ind]
r = t[indr] - t[indc]
r2 = r*r
r2_lq2 = r2/(-lq2[index[indr]])
#Calculation of covariance function
er2_lq2 = np.exp(r2_lq2)
#Gradient wrt t
c = 2.*r/lq2[index[indr]]
gt[indr, indc] = er2_lq2*c
#Complete the lower triangular
gt[indc, indr] = -gt[indr, indc]
return gt
#Gradients for Diagonal Kff
def _gkdiag(self, X, index):
index = index.reshape(index.size,)
#terms that move along t
d = np.unique(index)
B = self.B[d].values
C = self.C[d].values
S = self.W[d, :].values
#Index transformation
indd = np.arange(self.output_dim)
indd[d] = np.arange(d.size)
index = indd[index]
#Check where wd becomes complex
wbool = C*C >= 4.*B
#Output related variables must be column-wise
t = X[:, 0].reshape(X.shape[0], 1)
B = B.reshape(B.size, 1)
C = C.reshape(C.size, 1)
alpha = .5*C
C2 = C*C
S2 = S*S
wbool2 = wbool[index]
ind2t = np.where(wbool2)
ind3t = np.where(np.logical_not(wbool2))
#Input related variables must be row-wise
lq = self.lengthscale.values.reshape(1, self.rank)
lq2 = lq*lq
gB = np.empty((t.size,))
gC = np.empty((t.size,))
glq = np.empty((t.size, lq.size))
gS = np.empty((t.size, lq.size))
indD = np.arange(B.size)
#(1) When wd is real
if np.any(np.logical_not(wbool)):
#Indexes of index and t related to (1)
t1 = t[ind3t]
ind = index[ind3t]
#Index transformation
d = np.asarray(np.where(np.logical_not(wbool))[0])
indd = indD.copy()
indd[d] = np.arange(d.size)
ind = indd[ind]
#Dx1 terms
S2lq = S2[d]*(.5*lq)
c0 = S2lq*np.sqrt(np.pi)
w = .5*np.sqrt(4.*B[d] - C2[d])
alphad = alpha[d]
alpha2 = alphad*alphad
w2 = w*w
gam = alphad + 1j*w
gam2 = gam*gam
gamc = alphad - 1j*w
c1 = 0.5/alphad
c2 = 0.5/gam
c = c1 - c2
#DxQ terms
c0 = c0/w2
nu = (.5*lq)*gam
#Nx1 terms
gamt = -gam[ind]*t1
gamct = -gamc[ind]*t1
egamt = np.exp(gamt)
egamct = np.exp(gamct)
ec = egamt*c2[ind] - egamct*c1[ind]
#NxQ terms
t_lq = t1/lq
t2_lq2 = -t_lq*t_lq
t_lq2 = t_lq/lq
et2_lq2 = np.exp(t2_lq2)
etlq2gamt = np.exp(t2_lq2 + gamt)
##Upsilon calculations
#Using wofz
wnu = wofz(1j*nu)
lwnu = np.log(wnu)
t2_lq2 = -t_lq*t_lq
upm = wnu[ind] - np.exp(t2_lq2 + gamt + np.log(wofz(1j*(t_lq + nu[ind]))))
upm[t1[:, 0] == 0, :] = 0.
nu2 = nu*nu
z1 = nu[ind] - t_lq
indv1 = np.where(z1.real >= 0.)
indv2 = np.where(z1.real < 0.)
upv = -np.exp(lwnu[ind] + gamt)
if indv1[0].shape > 0:
upv[indv1] += np.exp(t2_lq2[indv1] + np.log(wofz(1j*z1[indv1])))
if indv2[0].shape > 0:
upv[indv2] += np.exp(nu2[ind[indv2[0]], indv2[1]] + gamt[indv2[0], 0] + np.log(2.))\
- np.exp(t2_lq2[indv2] + np.log(wofz(-1j*z1[indv2])))
upv[t1[:, 0] == 0, :] = 0.
#Gradient wrt S
Slq = S[d]*lq #For grad wrt S
c0_S = Slq*np.sqrt(np.pi)/w2
K01 = c0_S*c
gS[ind3t] = np.real(K01[ind]*upm) + np.real((c0_S[ind]*ec)*upv)
#For B and C
upmd = etlq2gamt - 1.
upvd = egamt - et2_lq2
# gradient wrt B
dw_dB = 0.5/w
dgam_dB = 1j*dw_dB
Ba1 = c0*(0.5*dgam_dB/gam2 + (0.5*lq2*gam*dgam_dB - 2.*dw_dB/w)*c)
Ba2_1 = c0*(dgam_dB*(0.5/gam2 - 0.25*lq2) + dw_dB/(w*gam))
Ba2_2 = c0*dgam_dB/gam
Ba3 = c0*(-0.25*lq2*gam*dgam_dB/alphad + dw_dB/(w*alphad))
Ba4_1 = (S2lq*lq)*dgam_dB/w2
Ba4 = Ba4_1*c
gB[ind3t] = np.sum(np.real(Ba1[ind]*upm) - np.real(((Ba2_1[ind] + Ba2_2[ind]*t1)*egamt - Ba3[ind]*egamct)*upv)\
+ np.real(Ba4[ind]*upmd) + np.real((Ba4_1[ind]*ec)*upvd), axis=1)
# gradient wrt C
dw_dC = - alphad*dw_dB
dgam_dC = 0.5 + 1j*dw_dC
Ca1 = c0*(-0.25/alpha2 + 0.5*dgam_dC/gam2 + (0.5*lq2*gam*dgam_dC - 2.*dw_dC/w)*c)
Ca2_1 = c0*(dgam_dC*(0.5/gam2 - 0.25*lq2) + dw_dC/(w*gam))
Ca2_2 = c0*dgam_dC/gam
Ca3_1 = c0*(0.25/alpha2 - 0.25*lq2*gam*dgam_dC/alphad + dw_dC/(w*alphad))
Ca3_2 = 0.5*c0/alphad
Ca4_1 = (S2lq*lq)*dgam_dC/w2
Ca4 = Ca4_1*c
gC[ind3t] = np.sum(np.real(Ca1[ind]*upm) - np.real(((Ca2_1[ind] + Ca2_2[ind]*t1)*egamt - (Ca3_1[ind] + Ca3_2[ind]*t1)*egamct)*upv)\
+ np.real(Ca4[ind]*upmd) + np.real((Ca4_1[ind]*ec)*upvd), axis=1)
#Gradient wrt lengthscale
#DxQ terms
la = (1./lq + nu*gam)*c0
la1 = la*c
c0l = (S2[d]/w2)*lq
la3 = c0l*c
gam_2 = .5*gam
glq[ind3t] = (la1[ind]*upm).real + ((la[ind]*ec)*upv).real\
+ (la3[ind]*(-gam_2[ind] + etlq2gamt*(-t_lq2 + gam_2[ind]))).real\
+ ((c0l[ind]*ec)*(-et2_lq2*(t_lq2 + gam_2[ind]) + egamt*gam_2[ind])).real
#(2) When w_d is complex
if np.any(wbool):
t1 = t[ind2t]
ind = index[ind2t]
#Index transformation
d = np.asarray(np.where(wbool)[0])
indd = indD.copy()
indd[d] = np.arange(d.size)
ind = indd[ind]
#Dx1 terms
S2lq = S2[d]*(.25*lq)
c0 = S2lq*np.sqrt(np.pi)
w = .5*np.sqrt(C2[d]-4.*B[d])
w2 = -w*w
alphad = alpha[d]
alpha2 = alphad*alphad
gam = alphad - w
gamc = alphad + w
gam2 = gam*gam
gamc2 = gamc*gamc
c1 = .5/alphad
c21 = .5/gam
c22 = .5/gamc
c = c1 - c21
c2 = c1 - c22
#DxQ terms
c0 = c0/w2
nu = .5*lq*gam
nuc = .5*lq*gamc
#Nx1 terms
gamt = -gam[ind]*t1
gamct = -gamc[ind]*t1
egamt = np.exp(gamt)
egamct = np.exp(gamct)
ec = egamt*c21[ind] - egamct*c1[ind]
ec2 = egamct*c22[ind] - egamt*c1[ind]
#NxQ terms
t_lq = t1/lq
t2_lq2 = -t_lq*t_lq
et2_lq2 = np.exp(t2_lq2)
etlq2gamct = np.exp(t2_lq2 + gamct)
etlq2gamt = np.exp(t2_lq2 + gamt)
#Upsilon Calculations using wofz
t2_lq2 = -t_lq*t_lq #Required when using wofz
wnu = np.real(wofz(1j*nu))
lwnu = np.log(wnu)
upm = wnu[ind] - np.exp(t2_lq2 + gamt + np.log(wofz(1j*(t_lq + nu[ind])).real))
upm[t1[:, 0] == 0., :] = 0.
nu2 = nu*nu
z1 = nu[ind] - t_lq
indv1 = np.where(z1 >= 0.)
indv2 = np.where(z1 < 0.)
upv = -np.exp(lwnu[ind] + gamt)
if indv1[0].shape > 0:
upv[indv1] += np.exp(t2_lq2[indv1] + np.log(wofz(1j*z1[indv1]).real))
if indv2[0].shape > 0:
upv[indv2] += np.exp(nu2[ind[indv2[0]], indv2[1]] + gamt[indv2[0], 0] + np.log(2.)) - np.exp(t2_lq2[indv2]\
+ np.log(wofz(-1j*z1[indv2]).real))
upv[t1[:, 0] == 0, :] = 0.
wnuc = wofz(1j*nuc).real
upmc = wnuc[ind] - np.exp(t2_lq2 + gamct + np.log(wofz(1j*(t_lq + nuc[ind])).real))
upmc[t1[:, 0] == 0., :] = 0.
lwnuc = np.log(wnuc)
nuc2 = nuc*nuc
z1 = nuc[ind] - t_lq
indv1 = np.where(z1 >= 0.)
indv2 = np.where(z1 < 0.)
upvc = -np.exp(lwnuc[ind] + gamct)
if indv1[0].shape > 0:
upvc[indv1] += np.exp(t2_lq2[indv1] + np.log(wofz(1j*z1[indv1]).real))
if indv2[0].shape > 0:
upvc[indv2] += np.exp(nuc2[ind[indv2[0]], indv2[1]] + gamct[indv2[0], 0] + np.log(2.)) - np.exp(t2_lq2[indv2]\
+ np.log(wofz(-1j*z1[indv2]).real))
upvc[t1[:, 0] == 0, :] = 0.
#Gradient wrt S
#NxQ terms
c0_S = (S[d]/w2)*(lq*(np.sqrt(np.pi)*.5))
K011 = c0_S*c
K012 = c0_S*c2
gS[ind2t] = K011[ind]*upm + K012[ind]*upmc + (c0_S[ind]*ec)*upv + (c0_S[ind]*ec2)*upvc
#Is required to cache this, C gradient also required them
upmd = -1. + etlq2gamt
upvd = -et2_lq2 + egamt
upmdc = -1. + etlq2gamct
upvdc = -et2_lq2 + egamct
# Gradient wrt B
dgam_dB = 0.5/w
dgamc_dB = -dgam_dB
Ba1 = c0*(0.5*dgam_dB/gam2 + (0.5*lq2*gam*dgam_dB - 1./w2)*c)
Ba3 = c0*(-0.25*lq2*gam*dgam_dB/alphad + 0.5/(w2*alphad))
Ba4_1 = (S2lq*lq)*dgam_dB/w2
Ba4 = Ba4_1*c
Ba2_1 = c0*(dgam_dB*(0.5/gam2 - 0.25*lq2) + 0.5/(w2*gam))
Ba2_2 = c0*dgam_dB/gam
Ba1c = c0*(0.5*dgamc_dB/gamc2 + (0.5*lq2*gamc*dgamc_dB - 1./w2)*c2)
Ba3c = c0*(-0.25*lq2*gamc*dgamc_dB/alphad + 0.5/(w2*alphad))
Ba4_1c = (S2lq*lq)*dgamc_dB/w2
Ba4c = Ba4_1c*c2
Ba2_1c = c0*(dgamc_dB*(0.5/gamc2 - 0.25*lq2) + 0.5/(w2*gamc))
Ba2_2c = c0*dgamc_dB/gamc
gB[ind2t] = np.sum(Ba1[ind]*upm - ((Ba2_1[ind] + Ba2_2[ind]*t1)*egamt - Ba3[ind]*egamct)*upv\
+ Ba4[ind]*upmd + (Ba4_1[ind]*ec)*upvd\
+ Ba1c[ind]*upmc - ((Ba2_1c[ind] + Ba2_2c[ind]*t1)*egamct - Ba3c[ind]*egamt)*upvc\
+ Ba4c[ind]*upmdc + (Ba4_1c[ind]*ec2)*upvdc, axis=1)
##Gradient wrt C
dw_dC = 0.5*alphad/w
dgam_dC = 0.5 - dw_dC
dgamc_dC = 0.5 + dw_dC
S2lq2 = S2lq*lq
Ca1 = c0*(-0.25/alpha2 + 0.5*dgam_dC/gam2 + (0.5*lq2*gam*dgam_dC + alphad/w2)*c)
Ca2_1 = c0*(dgam_dC*(0.5/gam2 - 0.25*lq2) - 0.5*alphad/(w2*gam))
Ca2_2 = c0*dgam_dC/gam
Ca3_1 = c0*(0.25/alpha2 - 0.25*lq2*gam*dgam_dC/alphad - 0.5/w2)
Ca3_2 = 0.5*c0/alphad
Ca4_1 = S2lq2*(dgam_dC/w2)
Ca4 = Ca4_1*c
Ca1c = c0*(-0.25/alpha2 + 0.5*dgamc_dC/gamc2 + (0.5*lq2*gamc*dgamc_dC + alphad/w2)*c2)
Ca2_1c = c0*(dgamc_dC*(0.5/gamc2 - 0.25*lq2) - 0.5*alphad/(w2*gamc))
Ca2_2c = c0*dgamc_dC/gamc
Ca3_1c = c0*(0.25/alpha2 - 0.25*lq2*gamc*dgamc_dC/alphad - 0.5/w2)
Ca3_2c = 0.5*c0/alphad
Ca4_1c = S2lq2*(dgamc_dC/w2)
Ca4c = Ca4_1c*c2
gC[ind2t] = np.sum(Ca1[ind]*upm - ((Ca2_1[ind] + Ca2_2[ind]*t1)*egamt - (Ca3_1[ind] + Ca3_2[ind]*t1)*egamct)*upv\
+ Ca4[ind]*upmd + (Ca4_1[ind]*ec)*upvd\
+ Ca1c[ind]*upmc - ((Ca2_1c[ind] + Ca2_2c[ind]*t1)*egamct - (Ca3_1c[ind] + Ca3_2c[ind]*t1)*egamt)*upvc\
+ Ca4c[ind]*upmdc + (Ca4_1c[ind]*ec2)*upvdc, axis=1)
#Gradient wrt lengthscale
#DxQ terms
la = (1./lq + nu*gam)*c0
lac = (1./lq + nuc*gamc)*c0
la1 = la*c
la1c = lac*c2
t_lq2 = t_lq/lq
c0l = (S2[d]/w2)*(.5*lq)
la3 = c0l*c
la3c = c0l*c2
gam_2 = .5*gam
gamc_2 = .5*gamc
glq[ind2t] = la1c[ind]*upmc + (lac[ind]*ec2)*upvc\
+ la3c[ind]*(-gamc_2[ind] + etlq2gamct*(-t_lq2 + gamc_2[ind]))\
+ (c0l[ind]*ec2)*(-et2_lq2*(t_lq2 + gamc_2[ind]) + egamct*gamc_2[ind])\
+ la1[ind]*upm + (la[ind]*ec)*upv\
+ la3[ind]*(-gam_2[ind] + etlq2gamt*(-t_lq2 + gam_2[ind]))\
+ (c0l[ind]*ec)*(-et2_lq2*(t_lq2 + gam_2[ind]) + egamt*gam_2[ind])
return glq, gS, gB, gC
def _gkfu(self, X, index, Z, index2):
index = index.reshape(index.size,)
#TODO: reduce memory usage
#terms that move along t
d = np.unique(index)
B = self.B[d].values
C = self.C[d].values
S = self.W[d, :].values
#Index transformation
indd = np.arange(self.output_dim)
indd[d] = np.arange(d.size)
index = indd[index]
#Check where wd becomes complex
wbool = C*C >= 4.*B
#t column
t = X[:, 0].reshape(X.shape[0], 1)
C = C.reshape(C.size, 1)
B = B.reshape(B.size, 1)
C2 = C*C
#z row
z = Z[:, 0].reshape(1, Z.shape[0])
index2 = index2.reshape(index2.size,)
lq = self.lengthscale.values.reshape((1, self.rank))
lq2 = lq*lq
alpha = .5*C
wbool2 = wbool[index]
ind2t = np.where(wbool2)
ind3t = np.where(np.logical_not(wbool2))
#kfu = np.empty((t.size, z.size))
glq = np.empty((t.size, z.size))
gSdq = np.empty((t.size, z.size))
gB = np.empty((t.size, z.size))
gC = np.empty((t.size, z.size))
indD = np.arange(B.size)
#(1) when wd is real
if np.any(np.logical_not(wbool)):
#Indexes of index and t related to (2)
t1 = t[ind3t]
ind = index[ind3t]
#Index transformation
d = np.asarray(np.where(np.logical_not(wbool))[0])
indd = indD.copy()
indd[d] = np.arange(d.size)
ind = indd[ind]
#Dx1 terms
w = .5*np.sqrt(4.*B[d] - C2[d])
alphad = alpha[d]
gam = alphad - 1j*w
gam_2 = .5*gam
S_w = S[d]/w
S_wpi = S_w*(.5*np.sqrt(np.pi))
#DxQ terms
c0 = S_wpi*lq #lq*Sdq*sqrt(pi)/(2w)
nu = gam*lq
nu2 = 1.+.5*(nu*nu)
nu *= .5
#1xM terms
z_lq = z/lq[0, index2]
z_lq2 = -z_lq*z_lq
#NxQ terms
t_lq = t1/lq
#DxM terms
gamt = -gam[ind]*t1
#NxM terms
zt_lq = z_lq - t_lq[:, index2]
zt_lq2 = -zt_lq*zt_lq
ezt_lq2 = -np.exp(zt_lq2)
ezgamt = np.exp(z_lq2 + gamt)
# Upsilon calculations
fullind = np.ix_(ind, index2)
upsi = - np.exp(z_lq2 + gamt + np.log(wofz(1j*(z_lq + nu[fullind]))))
tz = t1-z
z1 = zt_lq + nu[fullind]
indv1 = np.where(z1.real >= 0.)
indv2 = np.where(z1.real < 0.)
if indv1[0].shape > 0:
upsi[indv1] += np.exp(zt_lq2[indv1] + np.log(wofz(1j*z1[indv1])))
if indv2[0].shape > 0:
nua2 = nu[ind[indv2[0]], index2[indv2[1]]]**2
upsi[indv2] += np.exp(nua2 - gam[ind[indv2[0]], 0]*tz[indv2] + np.log(2.))\
- np.exp(zt_lq2[indv2] + np.log(wofz(-1j*z1[indv2])))
upsi[t1[:, 0] == 0., :] = 0.
#Gradient wrt S
#DxQ term
Sa1 = lq*(.5*np.sqrt(np.pi))/w
gSdq[ind3t] = Sa1[np.ix_(ind, index2)]*upsi.imag
#Gradient wrt lq
la1 = S_wpi*nu2
la2 = S_w*lq
uplq = ezt_lq2*(gam_2[ind])
uplq += ezgamt*(-z_lq/lq[0, index2] + gam_2[ind])
glq[ind3t] = (la1[np.ix_(ind, index2)]*upsi).imag
glq[ind3t] += la2[np.ix_(ind, index2)]*uplq.imag
#Gradient wrt B
#Dx1 terms
dw_dB = .5/w
dgam_dB = -1j*dw_dB
#DxQ terms
Ba1 = -c0*dw_dB/w #DXQ
Ba2 = c0*dgam_dB #DxQ
Ba3 = lq2*gam_2 #DxQ
Ba4 = (dgam_dB*S_w)*(.5*lq2) #DxQ
gB[ind3t] = ((Ba1[np.ix_(ind, index2)] + Ba2[np.ix_(ind, index2)]*(Ba3[np.ix_(ind, index2)] - (t1-z)))*upsi).imag\
+ (Ba4[np.ix_(ind, index2)]*(ezt_lq2 + ezgamt)).imag
#Gradient wrt C (it uses some calculations performed in B)
#Dx1 terms
dw_dC = -.5*alphad/w
dgam_dC = 0.5 - 1j*dw_dC
#DxQ terms
Ca1 = -c0*dw_dC/w #DXQ
Ca2 = c0*dgam_dC #DxQ
Ca4 = (dgam_dC*S_w)*(.5*lq2) #DxQ
gC[ind3t] = ((Ca1[np.ix_(ind, index2)] + Ca2[np.ix_(ind, index2)]*(Ba3[np.ix_(ind, index2)] - (t1-z)))*upsi).imag\
+ (Ca4[np.ix_(ind, index2)]*(ezt_lq2 + ezgamt)).imag
#(2) when wd is complex
if np.any(wbool):
#Indexes of index and t related to (2)
t1 = t[ind2t]
ind = index[ind2t]
#Index transformation
d = np.asarray(np.where(wbool)[0])
indd = indD.copy()
indd[d] = np.arange(d.size)
ind = indd[ind]
#Dx1 terms
w = .5*np.sqrt(C2[d] - 4.*B[d])
w2 = w*w
alphad = alpha[d]
gam = alphad - w
gamc = alphad + w
#DxQ terms
S_w= -S[d]/w #minus is given by j*j
S_wpi = S_w*(.25*np.sqrt(np.pi))
c0 = S_wpi*lq
gam_2 = .5*gam
gamc_2 = .5*gamc
nu = gam*lq
nuc = gamc*lq
nu2 = 1.+.5*(nu*nu)
nuc2 = 1.+.5*(nuc*nuc)
nu *= .5
nuc *= .5
#1xM terms
z_lq = z/lq[0, index2]
z_lq2 = -z_lq*z_lq
#Nx1
gamt = -gam[ind]*t1
gamct = -gamc[ind]*t1
#NxQ terms
t_lq = t1/lq[0, index2]
#NxM terms
zt_lq = z_lq - t_lq
zt_lq2 = -zt_lq*zt_lq
ezt_lq2 = -np.exp(zt_lq2)
ezgamt = np.exp(z_lq2 + gamt)
ezgamct = np.exp(z_lq2 + gamct)
# Upsilon calculations
fullind = np.ix_(ind, index2)
upsi1 = - np.exp(z_lq2 + gamct + np.log(wofz(1j*(z_lq + nuc[fullind])).real))
tz = t1-z
z1 = zt_lq + nuc[fullind]
indv1 = np.where(z1 >= 0.)
indv2 = np.where(z1 < 0.)
if indv1[0].shape > 0:
upsi1[indv1] += np.exp(zt_lq2[indv1] + np.log(wofz(1j*z1[indv1]).real))
if indv2[0].shape > 0:
nuac2 = nuc[ind[indv2[0]], index2[indv2[1]]]**2
upsi1[indv2] += np.exp(nuac2 - gamc[ind[indv2[0]], 0]*tz[indv2] + np.log(2.))\
- np.exp(zt_lq2[indv2] + np.log(wofz(-1j*z1[indv2]).real))
upsi1[t1[:, 0] == 0., :] = 0.
upsi2 = - np.exp(z_lq2 + gamt + np.log(wofz(1j*(z_lq + nu[fullind])).real))
z1 = zt_lq + nu[fullind]
indv1 = np.where(z1 >= 0.)
indv2 = np.where(z1 < 0.)
if indv1[0].shape > 0:
upsi2[indv1] += np.exp(zt_lq2[indv1] + np.log(wofz(1j*z1[indv1]).real))
if indv2[0].shape > 0:
nua2 = nu[ind[indv2[0]], index2[indv2[1]]]**2
upsi2[indv2] += np.exp(nua2 - gam[ind[indv2[0]], 0]*tz[indv2] + np.log(2.))\
- np.exp(zt_lq2[indv2] + np.log(wofz(-1j*z1[indv2]).real))
upsi2[t1[:, 0] == 0., :] = 0.
#Gradient wrt lq
la1 = S_wpi*nu2
la1c = S_wpi*nuc2
la2 = S_w*(.5*lq)
uplq = ezt_lq2*(gamc_2[ind]) + ezgamct*(-z_lq/lq[0, index2] + gamc_2[ind])\
- ezt_lq2*(gam_2[ind]) - ezgamt*(-z_lq/lq[0, index2] + gam_2[ind])
glq[ind2t] = la1c[np.ix_(ind, index2)]*upsi1 - la1[np.ix_(ind, index2)]*upsi2\
+ la2[np.ix_(ind, index2)]*uplq
#Gradient wrt S
Sa1 = (lq*(-.25*np.sqrt(np.pi)))/w
gSdq[ind2t] = Sa1[np.ix_(ind, index2)]*(upsi1 - upsi2)
#Gradient wrt B
#Dx1 terms
dgam_dB = .5/w
dgamc_dB = -dgam_dB
#DxQ terms
Ba1 = .5*(c0/w2)
Ba2 = c0*dgam_dB
Ba3 = lq2*gam_2
Ba4 = (dgam_dB*S_w)*(.25*lq2)
Ba2c = c0*dgamc_dB
Ba3c = lq2*gamc_2
Ba4c = (dgamc_dB*S_w)*(.25*lq2)
gB[ind2t] = (Ba1[np.ix_(ind, index2)] + Ba2c[np.ix_(ind, index2)]*(Ba3c[np.ix_(ind, index2)] - (t1-z)))*upsi1\
+ Ba4c[np.ix_(ind, index2)]*(ezt_lq2 + ezgamct)\
- (Ba1[np.ix_(ind, index2)] + Ba2[np.ix_(ind, index2)]*(Ba3[np.ix_(ind, index2)] - (t1-z)))*upsi2\
- Ba4[np.ix_(ind, index2)]*(ezt_lq2 + ezgamt)
#Gradient wrt C
#Dx1 terms
dgam_dC = 0.5 - .5*(alphad/w)
dgamc_dC = 0.5 + .5*(alphad/w)
#DxQ terms
Ca1 = -c0*(.5*alphad/w2)
Ca2 = c0*dgam_dC
Ca4 = (dgam_dC*S_w)*(.25*lq2)
Ca2c = c0*dgamc_dC
Ca4c = (dgamc_dC*S_w)*(.25*lq2)
gC[ind2t] = (Ca1[np.ix_(ind, index2)] + Ca2c[np.ix_(ind, index2)]*(Ba3c[np.ix_(ind, index2)] - (t1-z)))*upsi1\
+ Ca4c[np.ix_(ind, index2)]*(ezt_lq2 + ezgamct)\
- (Ca1[np.ix_(ind, index2)] + Ca2[np.ix_(ind, index2)]*(Ba3[np.ix_(ind, index2)] - (t1-z)))*upsi2\
- Ca4[np.ix_(ind, index2)]*(ezt_lq2 + ezgamt)
return glq, gSdq, gB, gC
#TODO: reduce memory usage
def _gkfu_z(self, X, index, Z, index2): #Kfu(t,z)
index = index.reshape(index.size,)
#terms that move along t
d = np.unique(index)
B = self.B[d].values
C = self.C[d].values
S = self.W[d, :].values
#Index transformation
indd = np.arange(self.output_dim)
indd[d] = np.arange(d.size)
index = indd[index]
#Check where wd becomes complex
wbool = C*C >= 4.*B
wbool2 = wbool[index]
ind2t = np.where(wbool2)
ind3t = np.where(np.logical_not(wbool2))
#t column
t = X[:, 0].reshape(X.shape[0], 1)
C = C.reshape(C.size, 1)
B = B.reshape(B.size, 1)
C2 = C*C
alpha = .5*C
#z row
z = Z[:, 0].reshape(1, Z.shape[0])
index2 = index2.reshape(index2.size,)
lq = self.lengthscale.values.reshape((1, self.rank))
#kfu = np.empty((t.size, z.size))
gz = np.empty((t.size, z.size))
indD = np.arange(B.size)
#(1) when wd is real
if np.any(np.logical_not(wbool)):
#Indexes of index and t related to (2)
t1 = t[ind3t]
ind = index[ind3t]
#TODO: Find a better way of doing this
#Index transformation
d = np.asarray(np.where(np.logical_not(wbool))[0])
indd = indD.copy()
indd[d] = np.arange(d.size)
ind = indd[ind]
#Dx1 terms
w = .5*np.sqrt(4.*B[d] - C2[d])
alphad = alpha[d]
gam = alphad - 1j*w
S_w = S[d]/w
S_wpi =S_w*(.5*np.sqrt(np.pi))
#DxQ terms
c0 = S_wpi*lq #lq*Sdq*sqrt(pi)/(2w)
nu = (.5*gam)*lq
#1xM terms
z_lq = z/lq[0, index2]
z_lq2 = -z_lq*z_lq
#NxQ terms
t_lq = t1/lq
#DxM terms
gamt = -gam[ind]*t1
#NxM terms
zt_lq = z_lq - t_lq[:, index2]
zt_lq2 = -zt_lq*zt_lq
#ezt_lq2 = -np.exp(zt_lq2)
ezgamt = np.exp(z_lq2 + gamt)
# Upsilon calculations
fullind = np.ix_(ind, index2)
upsi = - np.exp(z_lq2 + gamt + np.log(wofz(1j*(z_lq + nu[fullind]))))
tz = t1-z
z1 = zt_lq + nu[fullind]
indv1 = np.where(z1.real >= 0.)
indv2 = np.where(z1.real < 0.)
if indv1[0].shape > 0:
upsi[indv1] += np.exp(zt_lq2[indv1] + np.log(wofz(1j*z1[indv1])))
if indv2[0].shape > 0:
nua2 = nu[ind[indv2[0]], index2[indv2[1]]]**2
upsi[indv2] += np.exp(nua2 - gam[ind[indv2[0]], 0]*tz[indv2] + np.log(2.))\
- np.exp(zt_lq2[indv2] + np.log(wofz(-1j*z1[indv2])))
upsi[t1[:, 0] == 0., :] = 0.
#Gradient wrt z
za1 = c0*gam
#za2 = S_w
gz[ind3t] = (za1[np.ix_(ind, index2)]*upsi).imag + S_w[ | np.ix_(ind, index2) | numpy.ix_ |
import numpy as np
from numpy import linalg
import time
import sys
import math
import cmath
global pi
pi = np.pi
global sin
sin = np.sin
global cos
cos = np.cos
global asin
asin = np.arcsin
global acos
acos = np.arccos
global atan2
atan2 = np.arctan2
def asind(x):
temp_theta = asin(x.real)
return np.multiply(temp_theta,180.0/pi)
def acosd(x):
temp_theta = acos(x.real)
return np.multiply(temp_theta,180.0/pi)
def sind(x):
tempx = np.multiply(x,pi/180.0)
return sin(tempx)
def cosd(x):
tempx = np.multiply(x,pi/180.0)
return cos(tempx)
def tand(x):
tempx = np.multiply(x,pi/180.0)
return tan(tempx)
def atan2d(x,y):
try:
temp_theta = atan2(x.real,y.real)
return np.multiply(temp_theta,180.0/pi)
except:
pdb.set_trace()
def blockPrint():
sys.stdout = open(os.devnull, 'w')
def enablePrint():
sys.stdout = sys.__stdout__
def wait_till(TIME_STAMP):
tDiff = TIME_STAMP-time.time()
while(time.time()<TIME_STAMP):
wait_time = TIME_STAMP - time.time()
#sys.stdout.write("Wait time: %d seconds \r" % (wait_time))
#sys.stdout.flush()
return tDiff
def read_file(file_name):
f = open(file_name, "r")
s = f.read()
f.close()
return s
def rotx(x):
c = cosd(x)
s = sind(x)
R = np.matrix([[1,0,0], [0,c,-s], [0, s, c]])
return R
def roty(x):
c = cosd(x)
s = sind(x)
R = | np.matrix([[c, 0, s], [0, 1, 0], [-s, 0, c]]) | numpy.matrix |
'''
Created on Dec 15, 2015
@author: <NAME>
'''
import unittest
import os
import numpy as np
from scipy.spatial.distance import euclidean
from smac.configspace import pcs
from smac.optimizer.local_search import LocalSearch
from smac.configspace import ConfigurationSpace
from ConfigSpace.hyperparameters import CategoricalHyperparameter, \
UniformFloatHyperparameter, UniformIntegerHyperparameter
def rosenbrock_4d(cfg):
x1 = cfg["x1"]
x2 = cfg["x2"]
x3 = cfg["x3"]
x4 = cfg["x4"]
val = (100 * (x2 - x1 ** 2) ** 2 + (x1 - 1) ** 2 +
100 * (x3 - x2 ** 2) ** 2 + (x2 - 1) ** 2 +
100 * (x4 - x3 ** 2) ** 2 + (x3 - 1) ** 2)
return(val)
class TestLocalSearch(unittest.TestCase):
def setUp(self):
current_dir = os.path.dirname(__file__)
self.test_files_dir = os.path.join(current_dir, '..', 'test_files')
seed = np.random.randint(1, 100000)
self.cs = ConfigurationSpace(seed=seed)
x1 = UniformFloatHyperparameter("x1", -5, 5, default=5)
self.cs.add_hyperparameter(x1)
x2 = UniformIntegerHyperparameter("x2", -5, 5, default=5)
self.cs.add_hyperparameter(x2)
x3 = CategoricalHyperparameter(
"x3", [5, 2, 0, 1, -1, -2, 4, -3, 3, -5, -4], default=5)
self.cs.add_hyperparameter(x3)
x4 = UniformIntegerHyperparameter("x4", -5, 5, default=5)
self.cs.add_hyperparameter(x4)
def test_local_search(self):
def acquisition_function(point):
opt = np.array([1, 1, 1, 1])
dist = [euclidean(point, opt)]
return -np.min(dist)
l = LocalSearch(acquisition_function, self.cs, epsilon=1e-10,
max_iterations=100000)
start_point = self.cs.sample_configuration()
acq_val_start_point = acquisition_function(start_point.get_array())
_, acq_val_incumbent = l.maximize(start_point)
# Local search needs to find something that is as least as good as the
# start point
self.assertLessEqual(acq_val_start_point, acq_val_incumbent)
def test_local_search_2(self):
pcs_file = os.path.join(self.test_files_dir, "test_local_search.pcs")
seed = | np.random.randint(1, 100000) | numpy.random.randint |
#!/usr/bin/env python3.8
import cv2
import numpy as np
import rospy
from geometry_msgs.msg import Twist
from sensor_msgs.msg import Image, LaserScan
from std_msgs.msg import String
class ScanTest:
def __init__(self):
# self.scan = LaserScan()
self.sub_scan = rospy.Subscriber("scan", LaserScan, self.scan_callback)
self.pub_test = rospy.Publisher("test", String, queue_size=10)
# self.vel_pub = rospy.Publisher('cmd_vel', Twist, queue_size=1)
# self.image_pub = rospy.Publisher("cv_image", Image, queue_size=1)
def scan_callback(self, scan: LaserScan):
self.scan = scan
rospy.loginfo( | np.array(self.scan.ranges) | numpy.array |
import numpy as np
import matplotlib.pyplot as plt
func_axis = np.arange(-100,100)
u = np.heaviside(func_axis,1)
u_p_4 = np.roll(u,-4) #the end wont be plotted so dont care
u_m_5 = np.roll(u,5)
#starting function
x = func_axis*(u_p_4-u_m_5)
x_graph = x[90:111]
plot_axis = np.arange(-10,11)
plt.figure(1)
plt.stem(plot_axis,x_graph,use_line_collection=True)
plt.savefig('test.png')#just for reference
#1a
g1 = np.roll(x_graph,3)
plt.figure(2)
plt.stem(plot_axis,g1,use_line_collection=True)
plt.xlabel("n")
plt.ylabel("g1[n]")
plt.savefig("hw1_1a.png")
#1b
g2 = np.zeros(21,dtype=int)
for i, point in enumerate(g2):
index = i-10
g2[i] = x[(2*index-3)+100]
plt.figure(3)
plt.stem(plot_axis,g2,use_line_collection=True)
plt.xlabel("n")
plt.ylabel("g2[n]")
plt.savefig("hw1_1b.png")
#1c
plt.figure(4)
g3 = np.flip(x_graph)
g3 = np.roll(g3,1)
plt.stem(plot_axis,g3,use_line_collection=True)
plt.xlabel("n")
plt.ylabel("g3[n]")
plt.savefig("hw1_1c.png")
#1d
plt.figure(5)
g4 =np.roll(g3,2)
plt.stem(plot_axis,g4,use_line_collection=True)
plt.xlabel("n")
plt.ylabel("g4[n]")
plt.savefig("hw1_1d.png")
#1e
g5 = np.zeros(21, dtype=int)
for i, point in enumerate(g5):
index = i-10
if (int(index/2) == float(index)/2):
g5[i] = x[int(index/2)+100]
plt.figure(6)
plt.stem(plot_axis,g5,use_line_collection=True)
plt.xlabel("n")
plt.ylabel("g5[n]")
plt.savefig("hw1_1e.png")
#1f
delta = np.zeros(21, dtype=int)
delta[10] =1
g6 = x_graph*delta
plt.figure(7)
plt.stem(plot_axis,g6,use_line_collection=True)
plt.xlabel("n")
plt.ylabel("g6[n]")
plt.savefig("hw1_1f.png")
#---------------------------------------------#
#Problem 2A
#---------------------------------------------#
#generate x
x_n = | np.zeros(21) | numpy.zeros |
#!/usr/bin/env python
"""
Tests some aspect of ia_utilities.
"""
import numpy
import tifffile
import storm_analysis.sa_library.dao_fit_c as daoFitC
import storm_analysis.sa_library.ia_utilities_c as iaUtilsC
import storm_analysis.simulator.draw_gaussians_c as dg
def imagesCopy(images):
images_copy = []
for image in images:
images_copy.append(numpy.copy(image))
return images_copy
def test_ia_util_1():
"""
Test finding peaks in an empty image.
"""
x_size = 100
y_size = 80
images = [numpy.zeros((x_size,y_size), dtype = numpy.float64)]
z_values = [0.1]
mxf = iaUtilsC.MaximaFinder(margin = 1,
radius = 2,
threshold = 1,
z_values = z_values)
[x, y, z] = mxf.findMaxima(images)
assert(x.size == 0)
def test_ia_util_2():
"""
Test finding peaks in an image.
"""
x_size = 100
y_size = 80
images = [numpy.zeros((x_size,y_size), dtype = numpy.float64)]
z_values = [0.1]
# Above threshold, unequal height.
images[0][10,11] = 1.1
images[0][10,12] = 1.5
# Above threshold, equal height.
images[0][15,8] = 1.5
images[0][15,9] = 1.5
# Below threshold.
images[0][20,11] = 0.5
mxf = iaUtilsC.MaximaFinder(margin = 1,
radius = 2,
threshold = 1,
z_values = z_values)
[x, y, z, h] = mxf.findMaxima(images, want_height = True)
assert(x.size == 2)
for i in range(z.size):
assert (abs(z[i] - z_values[0]) < 1.0e-6)
assert (abs(h[i] - 1.5) < 1.0e-6)
def test_ia_util_3():
"""
Test agreement with fitting regarding orientation.
"""
height = 20.0
sigma = 1.5
x_size = 100
y_size = 120
background = numpy.zeros((x_size, y_size)) + 10.0
image = dg.drawGaussians((x_size, y_size),
numpy.array([[20.0, 40.0, height, sigma, sigma]]))
image += background
# Configure fitter.
mfit = daoFitC.MultiFitter2D()
mfit.initializeC(image)
mfit.newImage(image)
mfit.newBackground(background)
# Configure finder.
z_values = [0.0]
mxf = iaUtilsC.MaximaFinder(margin = 1,
radius = 2 * sigma,
threshold = background[0,0] + 0.5*height,
z_values = z_values)
# Find peaks.
[x, y, z] = mxf.findMaxima([image])
sigma = numpy.ones(x.size) * sigma
peaks = {"x" : x,
"y" : y,
"z" : z,
"sigma" : sigma}
# Pass peaks to fitter.
mfit.newPeaks(peaks, "finder")
# Check height.
h = mfit.getPeakProperty("height")
for i in range(h.size):
assert (abs(h[i] - height)/height < 0.1)
# Check background.
bg = mfit.getPeakProperty("background")
for i in range(bg.size):
assert (abs(bg[i] - 10.0) < 1.0e-6)
mfit.cleanup(verbose = False)
def test_ia_util_4():
"""
Multiple z planes test.
"""
x_size = 100
y_size = 80
images = [numpy.zeros((x_size,y_size), dtype = numpy.float64),
numpy.zeros((x_size,y_size), dtype = numpy.float64),
numpy.zeros((x_size,y_size), dtype = numpy.float64)]
z_values = [1.0,2.0,3.0]
images[0][20,10] = 1.3
images[1][20,10] = 1.2
images[2][20,10] = 1.5
# Default z range (the entire stack).
mxf = iaUtilsC.MaximaFinder(margin = 1,
radius = 2,
threshold = 1,
z_values = z_values)
[x, y, z] = mxf.findMaxima(imagesCopy(images))
assert(x.size == 1)
assert(abs(z[0] - z_values[2]) < 1.0e-6)
# z range is limited to adjacent slices.
#
mxf = iaUtilsC.MaximaFinder(margin = 1,
radius = 2,
threshold = 1,
z_range = 1,
z_values = z_values)
[x, y, z] = mxf.findMaxima(imagesCopy(images))
assert(x.size == 2)
assert(abs(z[0] - z_values[0]) < 1.0e-6)
assert(abs(z[1] - z_values[2]) < 1.0e-6)
# z range is limited to current slice.
#
mxf = iaUtilsC.MaximaFinder(margin = 1,
radius = 2,
threshold = 1,
z_range = 0,
z_values = z_values)
[x, y, z] = mxf.findMaxima(imagesCopy(images))
assert(x.size == 3)
for i in range(z.size):
assert(abs(z[i] - z_values[i]) < 1.0e-6)
def test_ia_util_5():
"""
Test that limits on the number of peak duplicates are working.
"""
x_size = 100
y_size = 80
images = [numpy.zeros((x_size,y_size), dtype = numpy.float64)]
z_values = [0.1]
# Single peak.
images[0][10,21] = 1.1
images[0][10,20] = 1.2
mxf = iaUtilsC.MaximaFinder(margin = 1,
radius = 2,
threshold = 1,
z_values = z_values)
# Find the peak.
[x, y, z] = mxf.findMaxima(imagesCopy(images))
assert (x.size == 1)
# This should not find anything, since the peak was
# already found above.
[x, y, z] = mxf.findMaxima(imagesCopy(images))
assert (x.size == 0)
# Reset and now we should find it again.
mxf.resetTaken()
[x, y, z] = mxf.findMaxima(imagesCopy(images))
assert (x.size == 1)
def test_ia_util_6():
"""
Test radius.
"""
x_size = 100
y_size = 80
images = [numpy.zeros((x_size,y_size), dtype = numpy.float64)]
z_values = [0.1]
images[0][10,23] = 1.2
images[0][10,22] = 1.1
images[0][10,21] = 1.1
images[0][10,20] = 1.2
# Should only find 1 peak.
mxf = iaUtilsC.MaximaFinder(margin = 1,
radius = 3,
threshold = 1,
z_values = z_values)
[x, y, z] = mxf.findMaxima(imagesCopy(images))
assert (x.size == 1)
# Should find two peaks.
mxf = iaUtilsC.MaximaFinder(margin = 1,
radius = 2,
threshold = 1,
z_values = z_values)
[x, y, z] = mxf.findMaxima(imagesCopy(images))
assert (x.size == 2)
def test_ia_util_7():
"""
Test margin.
"""
x_size = 100
y_size = 80
images = [numpy.zeros((x_size,y_size), dtype = numpy.float64)]
z_values = [0.1]
images[0][10,5] = 1.2
images[0][10,6] = 1.1
images[0][10,7] = 1.1
images[0][20,10] = 1.1
images[0][20,11] = 1.2
# Should only find 1 peak.
mxf = iaUtilsC.MaximaFinder(margin = 6,
radius = 3,
threshold = 1,
z_values = z_values)
[x, y, z] = mxf.findMaxima(imagesCopy(images))
assert (x.size == 1)
# Should find two peaks.
mxf = iaUtilsC.MaximaFinder(margin = 4,
radius = 3,
threshold = 1,
z_values = z_values)
[x, y, z] = mxf.findMaxima(imagesCopy(images))
assert (x.size == 2)
def test_ia_util_8():
"""
Test allowing multiple duplicates.
"""
x_size = 100
y_size = 80
images = [numpy.zeros((x_size,y_size), dtype = numpy.float64)]
z_values = [0.1]
# Single peak.
images[0][10,21] = 1.1
images[0][10,20] = 1.2
mxf = iaUtilsC.MaximaFinder(margin = 1,
n_duplicates = 2,
radius = 2,
threshold = 1,
z_values = z_values)
# Find the peak.
np = [1, 1, 0]
for elt in np:
[x, y, z] = mxf.findMaxima(imagesCopy(images))
assert (x.size == elt)
# Reset.
mxf.resetTaken()
# Test again.
np = [1, 1, 0]
for elt in np:
[x, y, z] = mxf.findMaxima(imagesCopy(images))
assert (x.size == elt)
def test_ia_util_9():
"""
Test runningIfHasNeighbors() function.
"""
# Test 4 of 5 with new neighbors, one in error state.
c_x = numpy.array([1.0, 2.0, 3.0, 4.0, 5.0])
c_y = numpy.array([1.0, 1.0, 1.0, 1.0, 1.0])
n_x = numpy.array([1.1, 2.1, 3.1, 4.1])
n_y = numpy.array([1.1, 1.1, 1.1, 1.1])
status = numpy.array([0, 1, 2, 1, 1], dtype = numpy.int32)
new_status = iaUtilsC.runningIfHasNeighbors(status, c_x, c_y, n_x, n_y, 0.5)
correct = [0, 0, 2, 0, 1]
for i in range(new_status.size):
assert(new_status[i] == correct[i])
# Test 2 of 5 with new neighbors, one in error state.
n_x = numpy.array([1.9, 2.1])
n_y = numpy.array([1.1, 1.1])
status = numpy.array([0, 1, 2, 1, 1], dtype = numpy.int32)
new_status = iaUtilsC.runningIfHasNeighbors(status, c_x, c_y, n_x, n_y, 0.5)
correct = [0, 0, 2, 1, 1]
for i in range(new_status.size):
assert(new_status[i] == correct[i])
# Test 1 of 2 with new neighbors, but both with radius of each other.
c_x = numpy.array([2.0, 3.0])
c_y = numpy.array([2.0, 2.0])
n_x = numpy.array([1.0])
n_y = numpy.array([2.0])
status = numpy.array([1, 1], dtype = numpy.int32)
new_status = iaUtilsC.runningIfHasNeighbors(status, c_x, c_y, n_x, n_y, 1.5)
correct = [0, 1]
for i in range(new_status.size):
assert(new_status[i] == correct[i])
def test_ia_util_10():
"""
Test markDimmerPeaks() function.
"""
n_peaks = 25
x = numpy.random.uniform(size = n_peaks)
y = numpy.random.uniform(size = n_peaks)
h = numpy.random.uniform(size = n_peaks) + 1.0
status = numpy.ones(n_peaks, dtype = numpy.int32)*iaUtilsC.CONVERGED
# Make first peak the tallest.
h[0] = 4.0
# Move last peak outside of the removal radius.
x[-1] = 4.0
# Move second to last peak away from everything.
x[-2] = 40.0
assert (iaUtilsC.markDimmerPeaks(x, y, h, status, 2.0, 5.0) == (n_peaks - 3))
for i in range(1,n_peaks-2):
assert(status[i] == iaUtilsC.ERROR)
assert(status[0] == iaUtilsC.RUNNING)
assert(status[-1] == iaUtilsC.RUNNING)
assert(status[-2] == iaUtilsC.CONVERGED)
def test_ia_util_11():
"""
Test finding peaks in an image.
"""
x_size = 100
y_size = 80
images = [numpy.zeros((x_size,y_size), dtype = numpy.float64)]
z_values = [0.1]
# A row of peaks greater than radius with decreasing heights, there
# should still only be a single maxima.
images[0][10,11] = 1.6
images[0][10,12] = 1.5
images[0][10,13] = 1.4
images[0][10,14] = 1.3
images[0][10,15] = 1.2
images[0][10,16] = 1.1
mxf = iaUtilsC.MaximaFinder(margin = 1,
radius = 2,
threshold = 1,
z_values = z_values)
[x, y, z] = mxf.findMaxima(images)
assert(x.size == 1)
assert(abs(x[0] - 11.0) < 1.0e-6)
assert(abs(y[0] - 10.0) < 1.0e-6)
def test_ia_util_12():
"""
Test removeNeighbors().
"""
x = numpy.array([1.0, 2.0, 4.0])
y = numpy.ones(x.size)
[px, py] = iaUtilsC.removeNeighbors(x, y, 0.5)
assert(px.size == 3)
assert(py.size == 3)
[px, py] = iaUtilsC.removeNeighbors(x, y, 1.5)
assert(px.size == 1)
assert(py.size == 1)
def test_ia_util_13():
"""
Test marking peak status (and neighbors status) based on significance.
"""
px = numpy.array([30.0,35.0,40.0])
py = numpy.array([30.0,30.0,30.0])
sig = numpy.array([1.0,2.0,3.0])
# This should not update anything.
status = numpy.ones(3, dtype = numpy.int32)*iaUtilsC.CONVERGED
n_marked = iaUtilsC.markLowSignificancePeaks(px,
py,
sig,
status,
0.0,
7.0)
assert(n_marked == 0)
for i in range(3):
assert(status[i] == iaUtilsC.CONVERGED)
# This should only mark the first peak for removal.
status = numpy.ones(3, dtype = numpy.int32)*iaUtilsC.CONVERGED
n_marked = iaUtilsC.markLowSignificancePeaks(px,
py,
sig,
status,
sig[0] + 0.1,
3.0)
assert(n_marked == 1)
assert(status[0] == iaUtilsC.ERROR)
assert(status[1] == iaUtilsC.CONVERGED)
assert(status[2] == iaUtilsC.CONVERGED)
# This should the first peak for removal and the second as RUNNING.
status = numpy.ones(3, dtype = numpy.int32)*iaUtilsC.CONVERGED
n_marked = iaUtilsC.markLowSignificancePeaks(px,
py,
sig,
status,
sig[0] + 0.1,
7.0)
assert(n_marked == 1)
assert(status[0] == iaUtilsC.ERROR)
assert(status[1] == iaUtilsC.RUNNING)
assert(status[2] == iaUtilsC.CONVERGED)
# This should the first peak for removal and both others as RUNNING.
status = numpy.ones(3, dtype = numpy.int32)*iaUtilsC.CONVERGED
n_marked = iaUtilsC.markLowSignificancePeaks(px,
py,
sig,
status,
sig[0] + 0.1,
11.0)
assert(n_marked == 1)
assert(status[0] == iaUtilsC.ERROR)
assert(status[1] == iaUtilsC.RUNNING)
assert(status[2] == iaUtilsC.RUNNING)
# This should the first peak & second for removal and the last as RUNNING.
status = numpy.ones(3, dtype = numpy.int32)*iaUtilsC.CONVERGED
n_marked = iaUtilsC.markLowSignificancePeaks(px,
py,
sig,
status,
sig[1] + 0.1,
7.0)
assert(n_marked == 2)
assert(status[0] == iaUtilsC.ERROR)
assert(status[1] == iaUtilsC.ERROR)
assert(status[2] == iaUtilsC.RUNNING)
def test_ia_util_14():
"""
Some tests of our KDTree.
"""
x1 = numpy.array([1.0, 2.0, 3.0])
y1 = numpy.array([1.0, 1.0, 1.0])
kd = iaUtilsC.KDTree(x = x1, y = y1)
x2 = numpy.array([1.1, 4.0])
y2 = | numpy.array([1.0, 1.0]) | numpy.array |
from collections import OrderedDict
import numpy as np
from skimage import measure
# TODO: Refactoring
def eval_synthetic(it, gen, data, tag='', batch_size = 128, sampler=None):
metrics = OrderedDict()
if sampler is not None:
z = sampler(batch_size * 8) # TODO: Originally 1024
samples = gen(z) # Feed z
else:
samples = gen(batch_size * 8) # Generate n images TODO: Originally 1024
# Simple metric for MoG (VEEGAN, https://arxiv.org/abs/1705.07761)
if 'get_hq_ratio' in dir(data) and 'get_n_modes' in dir(data):
metrics['hq_ratio'] = data.get_hq_ratio(samples) * 100.0
metrics['modes_ratio'] = data.get_n_modes(samples) / float(data.n_modes) * 100.0
print( "{}({}) ".format(tag, it), ', '.join(['{}={:.2f}'.format(k, v) for k, v in metrics.iteritems()]))
return metrics
# TODO: Refactoring
# Simple & naive evaluation function
def eval_images_naive(it, gen, data, tag='', sampler=None):
metrics = OrderedDict()
if sampler is not None:
z = sampler(128)
samples = gen(z) # Feed z
else:
samples = gen(128) # Generate n images
true_samples = data.validation.images
true_labels = data.validation.labels if 'labels' in dir(data.validation) else None
# Compute dist.
dist_func = lambda a, b: np.linalg.norm((a - b).reshape((-1)), ord=2)
# Distance: (generated samples) x (true samples)
dist = np.array([[dist_func(x, x_true) for x_true in true_samples] for x in samples])
best_matching_i_true = np.argmin(dist, axis=1)
metrics['n_modes'] = len(np.unique(best_matching_i_true))
metrics['ave_dist'] = np.average(np.min(dist, axis=1))
# Check the labels (if exist)
if true_labels is not None:
label_cnts = np.sum(true_labels[best_matching_i_true], axis=0)
metrics['n_labels'] = np.sum(label_cnts > 0)
# Compute SSIM among top-k candidates (XXX: No supporting evidence for this approx.)
k = 10
top_k_matching_samples = np.argpartition(dist, k, axis=1)[:, :k]
# Please refer to https://en.wikipedia.org/wiki/Structural_similarity
# compare_ssim assumes (W, H, C) ordering
sim_func = lambda a, b: measure.compare_ssim(a, b, multichannel=True, data_range=2.0)
# Similarity: (generated samples) x (top-k candidates)
sim = [[sim_func(samples[i], true_samples[i_true]) for i_true in i_topk] \
for i, i_topk in enumerate(top_k_matching_samples)]
sim = np.array(sim)
metrics['ave_sim'] = np.average( | np.max(sim, axis=1) | numpy.max |
#!/usr/bin/python3
# -*- coding=utf-8 -*-
import numpy as np
from scipy.special import expit
from common.yolo_postprocess_np import yolo_handle_predictions, yolo_correct_boxes, yolo_adjust_boxes
def yolo5_decode_single_head(prediction, anchors, num_classes, input_dims, scale_x_y):
'''Decode final layer features to bounding box parameters.'''
batch_size = np.shape(prediction)[0]
num_anchors = len(anchors)
grid_size = np.shape(prediction)[1:3]
#check if stride on height & width are same
assert input_dims[0]//grid_size[0] == input_dims[1]//grid_size[1], 'model stride mismatch.'
stride = input_dims[0] // grid_size[0]
prediction = np.reshape(prediction,
(batch_size, grid_size[0] * grid_size[1] * num_anchors, num_classes + 5))
################################
# generate x_y_offset grid map
grid_y = np.arange(grid_size[0])
grid_x = np.arange(grid_size[1])
x_offset, y_offset = np.meshgrid(grid_x, grid_y)
x_offset = np.reshape(x_offset, (-1, 1))
y_offset = np.reshape(y_offset, (-1, 1))
x_y_offset = np.concatenate((x_offset, y_offset), axis=1)
x_y_offset = np.tile(x_y_offset, (1, num_anchors))
x_y_offset = np.reshape(x_y_offset, (-1, 2))
x_y_offset = np.expand_dims(x_y_offset, 0)
################################
# Log space transform of the height and width
anchors = np.tile(anchors, (grid_size[0] * grid_size[1], 1))
anchors = np.expand_dims(anchors, 0)
assert scale_x_y, 'YOLOv5 decode should have scale_x_y.'
# YOLOv5 box decode
#
# Now all the prediction part (x,y,w,h,obj,cls) use
# sigmoid(expit) for decode, so we do it together
#
# Reference:
# https://github.com/ultralytics/yolov5/blob/master/models/yolo.py#L56
# https://alexeyab84.medium.com/scaled-yolo-v4-is-the-best-neural-network-for-object-detection-on-ms-coco-dataset-39dfa22fa982
prediction = expit(prediction)
box_xy_tmp = prediction[..., :2] * scale_x_y - (scale_x_y - 1) / 2
box_xy = (box_xy_tmp + x_y_offset) / np.array(grid_size)[::-1]
box_wh = ((prediction[..., 2:4]*2)**2 * anchors) / np.array(input_dims)[::-1]
# Sigmoid objectness scores
objectness = prediction[..., 4] # p_o (objectness score)
objectness = np.expand_dims(objectness, -1) # To make the same number of values for axis 0 and 1
# Sigmoid class scores
class_scores = prediction[..., 5:]
return | np.concatenate([box_xy, box_wh, objectness, class_scores], axis=2) | numpy.concatenate |
from unittest import TestCase
import numpy as np
from kmeans import iou, avg_iou, kmeans
class TestBasic(TestCase):
def test_iou_100(self):
self.assertEqual(iou([200, 200], np.array([[200, 200]])), 1.)
def test_iou_50(self):
self.assertEqual(iou([200, 200], np.array([[100, 200]])), .5)
self.assertEqual(iou([200, 200], np.array([[200, 100]])), .5)
def test_iou_75(self):
self.assertEqual(iou([200, 200], np.array([[150, 200]])), .75)
self.assertEqual(iou([200, 200], np.array([[200, 150]])), .75)
def test_iou_20(self):
self.assertEqual(iou([183, 73], np.array([[73, 36.6]])), .2)
self.assertEqual(iou([183, 73], | np.array([[36.6, 73]]) | numpy.array |
import numpy as np
from load_screens import load_screens
from scipy.special import stdtr
# Load batch-corrected screens
screens = load_screens()
# Remove cell lines with any missing genes
# (not required for DepMap 18Q3, but is for more recent releases)
# You can use other strategies to remove NaNs instead, like imputing,
# removing genes with any missing cell lines
screens.dropna(axis=1, inplace=True)
# Warp screen data and intercept based on covariance of screens
cholsigmainv = np.linalg.cholesky(np.linalg.inv( | np.cov(screens.T) | numpy.cov |
# -*- coding:utf-8 -*-
# !/usr/bin/python3.6
import numpy as np
import operator
import file2Matrix as f2m
import KNN
def classifyPerson():
#输出结果
resultList = {'C': '讨厌', 'B': '有些喜欢', 'A': '非常喜欢'}
#三维特征用户输入
precentTats = float(input("玩视频游戏所耗时间百分比:"))
ffMiles = float(input("每年获得的飞行常客里程数:"))
iceCream = float(input("每周消费的冰激淋公升数:"))
#打开并处理数据
datingDataMat, datingLabels = f2m.file2Matrix("testSet.txt")
#训练集归一化
normDataSet, ranges, minVals = f2m.autoNorm(datingDataMat)
#生成NumPy数组,测试集
inArr = | np.array([ffMiles, precentTats, iceCream]) | numpy.array |
from typing import Text
import matplotlib.pyplot as plt
import numpy as np
import random
import TuneUp_functions as maths
import csv
import pygame
import time as t
from time import sleep
import pygame.freetype
pygame.freetype.init()
#thrust curves courtesy of https://www.thrustcurve.org/
e12_thrust = [
[0.052, 5.045],
[0.096, 9.910],
[0.196, 24.144],
[0.251, 31.351],
[0.287, 32.973],
[0.300, 29.910],
[0.344, 17.117],
[0.370, 14.414],
[0.400, 12.973],
[0.500, 11.712],
[0.600, 11.171],
[0.700, 10.631],
[0.800, 10.09],
[0.900, 9.73],
[1.000, 9.55],
[1.101, 9.91],
[1.200, 9.55],
[1.300, 9.73],
[1.400, 9.73],
[1.500, 9.73],
[1.600, 9.73],
[1.700, 9.55],
[1.800, 9.73],
[1.900, 9.73],
[2.000, 9.55],
[2.100, 9.55],
[2.200, 9.73],
[2.300, 9.19],
[2.375, 9.37],
[2.400, 5.95],
[2.440, 0.0]
]
f15_thrust = [
[0.063, 2.127],
[0.118, 4.407],
[0.158, 8.359],
[0.228, 13.68],
[0.340, 20.82],
[0.386, 26.75],
[0.425, 25.38],
[0.481, 22.19],
[0.583, 17.93],
[0.883, 16.11],
[1.191, 14.59],
[1.364, 15.35],
[1.569, 15.65],
[1.727, 14.74],
[2.00, 14.28],
[2.39, 13.68],
[2.68, 13.08],
[2.96, 13.07],
[3.25, 13.05],
[3.35, 13.0],
[3.39, 7.30],
[3.40, 0.00]
]
e6_thrust = [
[0.056, 18.59],
[0.112, 20.12],
[0.168, 17.575],
[0.307, 14.38],
[0.531, 10.45],
[0.894, 7.696],
[1.146, 6.244],
[1.691, 5.808],
[2.836, 5.663],
[3.898, 5.517],
[4.275, 5.227],
[4.415, 4.937],
[5.058, 5.082],
[5.519, 5.227],
[5.603, 6.679],
[5.729, 3.921],
[5.882, 2.323],
[5.966, 1.016],
[6.06, 0]
]
f10_thrust = [
[0.015, 28.22],
[0.077, 26.082],
[0.201, 24.934],
[0.31 ,22.806],
[0.464, 20.183],
[0.573, 17.886],
[0.789, 16.075],
[1.068, 13.946],
[1.393, 12.63],
[1.718, 11.155],
[2.166, 9.844],
[2.677, 9.515],
[3.311, 9.187],
[3.683, 8.859],
[3.791, 9.679],
[4.101, 9.679],
[4.658, 9.515],
[5.168, 9.023],
[5.725, 9.023],
[6.112, 8.531],
[6.329, 8.859],
[6.499, 7.546],
[6.685, 5.742],
[6.778, 4.921],
[6.917, 2.625],
[7.025, 1.312],
[7.13, 0]
]
g12_RCT_thrust = [
[0.03, 18.549],
[0.117, 19.96],
[0.239, 20.64],
[0.362, 20.111],
[0.519, 18.982],
[0.694, 17.138],
[0.886, 15.02],
[1.131, 13.186],
[1.375, 11.915],
[1.689, 11.069],
[2.021, 10.363],
[2.422, 10.232],
[3.172, 9.677],
[4.114, 9.267],
[5.039, 8.857],
[6.137, 8.733],
[7.132, 8.607],
[7.795, 8.335],
[7.952, 8.196],
[8.074, 8.055],
[8.179, 6.924],
[8.319, 4.661],
[8.476, 1.973],
[8.55, 0]
]
g12st_thrust = [
[0.042, 33.827],
[0.104, 30.173],
[0.23, 28.009],
[0.543, 22.326],
[0.836, 16.102],
[1.024, 12.448],
[1.379, 10.96],
[2.006, 10.148],
[4.054, 9.742],
[6.269, 10.148],
[6.415, 10.148],
[6.582, 10.148],
[11.973, 9.742],
[12.475, 9.742],
[12.663, 9.607],
[12.83, 9.066],
[12.913, 7.713],
[12.934, 5.412],
[13.018, 2.03],
[13.06, 0.0]
]
g11_thrust = [
[0.084, 30.444],
[0.105, 28.414],
[0.209, 27.738],
[0.419, 24.085],
[0.753, 18.402],
[0.9, 14.748],
[1.046, 11.907],
[1.444, 10.013],
[2.051, 9.742],
[3.034, 9.201],
[4.018, 9.471],
[5.483, 9.201],
[5.713, 8.93],
[9.375, 9.742],
[9.501, 8.93],
[11.049, 9.742],
[12.263, 9.336],
[13.288, 8.66],
[13.456, 7.307],
[13.602, 4.6],
[13.77, 1.624],
[13.937, 0.0]
]
g8st_thrust = [
[0.038, 5.121],
[0.039, 8.069],
[0.188, 9.828],
[0.414, 10.397],
[0.715, 10.19],
[1.354, 9.517],
[2.069, 9.155],
[3.424, 8.793],
[4.552, 8.431],
[6.057, 8.276],
[6.81, 8.069],
[7.713, 8.121],
[9.03, 8.017],
[9.97, 7.966],
[10.76, 7.914],
[14.222, 7.397],
[14.335, 7.19],
[15.764, 7.138],
[16.404, 6.983],
[16.554, 7.5],
[16.63 ,6.724],
[16.818, 5.69],
[16.968, 3.414],
[17.119, 1.655],
[17.269, 0.0]
]
h13st_thrust = [
[0.005, 0.107],
[0.024, 2.636],
[0.035, 18.978],
[0.081, 32.724],
[0.147, 36.421],
[0.379, 44.529],
[0.452, 23.851],
[0.566, 18.890],
[0.818, 16.728],
[1.286, 15.676],
[2.114, 14.753],
[3.230, 14.032],
[4.382, 13.926],
[5.786, 13.469],
[7.082, 13.119],
[8.666, 12.916],
[10.286, 12.820],
[12.086, 12.612],
[13.598, 12.333],
[14.750, 11.908],
[15.230, 11.078],
[15.302, 6.048],
[15.432, 0]
]
#------------------------------------------------------------------------------------------------------------------
#time settings
timeStep = 300 #HZ
csv_log_frequency = 50 #HZ
# quick note about simTime - the simulation will automatically stop once your rocket touches the ground after liftoff,
# so I would reccomend setting it so something high if youre using an engine file instead of constant thrust
simTime = 60 #Seconds
PIDLoopTime = 50 #HZ
#------------------------------------------------------------------------------------------------------------------
#PID gains initializers, tweak these and see how your rocket performs!
usePID = True
P_gain = 1.8
I_gain = 0.2
D_gain = 0.3
#a cap on the integral to prevent windup
I_max = 3
use_proportional_on_measurement = False
#position control PID gains
position_control = False
P_gain_pos = 3
I_gain_pos = 3
D_gain_pos = 5
I_max_pos = 15
use_proportional_on_measurement_pos = True
#if you dont want to use PID, you can use full state feedback instead
#to use FSF, you need to do 2 things:
#acheive full activation of your frontal lobe
#and set usePID to false
fsf_gains = np.matrix([20,0.1,1,0.5])
#ori, ori rate, pos, pos rate
fsf_setpoint = np.array([0,1,0,0.2])
#------------------------------------------------------------------------------------------------------------------
#simulation settings
constant_thrust = 12 #Newtons
setPoint = 0 # degrees
setPoint_position = 0 # meters
ori_start = 0 #degrees
rotational_vel_start = 0 #degrees per second
use_thrust_curve = True
thrust_curve = e12_thrust
windForceMultiplier = 5
log_sim_to_CSV = True
read_flight_path_file = False
maxRotationalVel = 100
playback_speed = 1 # 1 = real time
position_lateral_start = 0
#------------------------------------------------------------------------------------------------------------------
#physical characteristics of your rocket
massMomentOfInertia = 0.0404203354 # kg * m^2
leverArm = 0.44 # meters
rocketMass = 0.614 # kg
Cp_moment_arm = 0.45 # meters from center of mass
actuator_angle = 0
maxActuatorDeflection = 30 # degrees
maxActuatorSpeed = 50 # degrees per second
linkageRatio = 3 # ratio between servo position and actuator position
actuatorNoise = 1 #multiplier for actuator noise
sensor_noise = 0.5 # multiplier for sensor noise
sensor_bias = 0.2 # bias in one direction
accumulative_noise = True # if true then sensor_noise will be an accumulative error instead of slight randomization
#-- dont edit after this point! --
#- but if you dare to dig deeper -
#- you will find the glorious -
#- simulation code! -
#-- you have been warned --
class PID:
def __init__(self, kP, kI, kD, setpoint, iMax, usePONM):
#assigning gains to user inputs
self.kP = kP
self.kI = kI
self.kD = kD
#the value that the PID controller wants the input to become
self.setPoint = setpoint
# you might not see this in your run-of-the-mill PID library, this is just a limit on how bit the integral can get
self.iMax = iMax
#you are even less likely to see this in your run-of-the-mill PID library
#this is basically a different implementation of the proportional gain, where instead of looking at the error
#the proportional part of the controller looks at the change between the initial sensed value and the current sensed value
self.usePONM = usePONM
if usePONM == True:
self.proportional = 0
#this variable stores the most recent process variable, so that when update is called the PID controller can
#know not only the current error, but also the speed at which it is approaching or departing from the setpoint!
#this helps with reducing overshoot by feeding it into the derivitive value, which basically functions as a break on a car
self.lastProcess = 0
#this is the integral, which helps combat steady state error. Eg. your rocket is stable, and has canceled all rotation on
#it's body, but its 10 degrees off target! the integral is crucial here as it increases over time with the error
self.integral = 0
self.error = 0
def setSetpoint(self, setpoint):
self.setPoint = setpoint
def zeroIntegral(self):
self.integral = 0
def compute(self, process, dt):
change = process - self.lastProcess
self.lastProcess = process
self.error = self.setPoint - process
if self.usePONM == True:
#whats happening here is the proportional changing with the process variable
self.proportional -= change * self.kP
else:
proportional = self.error * self.kP
#checking that the integral will not exceed the maximum value allowed by the user
if abs(self.integral + self.error * self.kI * dt) < self.iMax:
self.integral += self.error * self.kI * dt
derivitive = change * self.kD / dt
if self.usePONM == True:
return self.proportional + self.integral - derivitive
else:
return proportional + self.integral - derivitive
class full_state_feedback:
#gains
fsf_gains = np.matrix([0,0,0,0])
#setpoints (ori, rotational speed, position, velocity)
fsf_setpoint = np.array([0,0,0,0])
lastOri = 0
lastPos = 0
I = 0
output = 0
def __init__(self, _gains, _setpoint):
self.fsf_gains = _gains
self.fsf_setpoint = _setpoint
def compute(self, position, orientation, dt):
x = np.matrix([[ori - self.fsf_setpoint[0]],
[((ori - self.lastOri) * dt) - self.fsf_setpoint[1]],
[position - self.fsf_setpoint[2]],
[((position - self.lastPos) * dt) - self.fsf_setpoint[3]]])
out = -self.fsf_gains * x
self.output = np.sum(out)
self.I += self.output * 0.01
self.lastOri = ori
self.lastPos = position
self.output += self.I
global RAD_TO_DEG
global DEG_TO_RAD
#conversions from degrees (more human readable) to radians (for the maths)
DEG_TO_RAD = np.pi / 180
RAD_TO_DEG = 180 / np.pi
last_actuator_angle = 0
velocity_lateral = 0
velocity_vertical = 0
position_lateral = position_lateral_start
position_vertical = 0
rotationalVel = 0
sensorError = 0
lastPIDCalc = 0
PIDCalcDelay = 1 / PIDLoopTime
lastCSVLog = 0
CSVLogDelay = 1 / csv_log_frequency
ori = ori_start * DEG_TO_RAD
sensed_ori = ori
flightPlan = []
time = 0
Dt = 1 / timeStep
counter = 0
timeSteps = simTime * timeStep
def parse_flightPath():
with open('flightPath.csv', newline='\n') as pathFile:
reader = csv.reader(pathFile, delimiter=',', quotechar='"')
for row in reader:
flightPlan.append([float(row[0]), float(row[1])])
global l_setpoint
l_setpoint = [0,0]
oriList = []
def interpolate_flightpath():
global l_setpoint
for instruction in flightPlan:
if instruction[0] > 0:
timeDiff = instruction[0] - l_setpoint[0]
setPointDiff = instruction[1] - l_setpoint[1]
stepsNeeded = timeDiff * timeStep
adder = setPointDiff / stepsNeeded
i = 0
ori_change = l_setpoint[1]
while i < stepsNeeded:
i += 1
ori_change += adder
oriList.append(float(ori_change))
l_setpoint = instruction
i = 0
finalOriSetpoint = oriList[-1]
if len(oriList) / timeStep < timeSteps:
while i <= timeSteps + 1 - len(oriList):
oriList.append(float(finalOriSetpoint))
if read_flight_path_file == True:
parse_flightPath()
interpolate_flightpath()
#control system object initializers
pid_ori = PID(P_gain, I_gain, D_gain, setPoint, I_max, use_proportional_on_measurement)
pid_pos = PID(P_gain_pos, I_gain_pos, D_gain_pos, setPoint_position, I_max_pos, use_proportional_on_measurement_pos)
fsf_controller = full_state_feedback(fsf_gains, fsf_setpoint)
ascent = False
apogee = False
thrustList = []
global lPoint
lPoint = [0, 0]
#making a better thrust curve by averaging the thrust curve data
def interpolateThrust():
global lPoint
for point in thrust_curve:
if point[0] > 0:
thrustDiff = point[1] - lPoint[1]
timeDiff = point[0] - lPoint[0]
stepsNeeded = timeDiff * timeStep
adder = thrustDiff / stepsNeeded
i = 0
thrustToAdd = lPoint[1]
while i < stepsNeeded:
i += 1
thrustToAdd += adder
thrustList.append(thrustToAdd)
lPoint = point
interpolateThrust()
i = 0
if len(thrustList) / timeStep < timeSteps:
while i <= timeSteps + 1 - len(thrustList):
thrustList.append(0)
#making a list for the wind forces
i = 0
windForce = []
constWind = random.randint(-100, 100) / 50 * windForceMultiplier
while i <= timeSteps + 1:
i += 1
windForce.append(np.sin((i / timeStep / 2) * windForceMultiplier) + constWind)
area = 0.00456
def getDrag(vel):
return 0.65 * area * 1.225 * np.power(vel, 2)
#initializing csv
f = open("data_out.csv", "w")
f.write("time,ori,sensed_ori,actuator_angle,velocity_lateral,velocity_vertical,position_lateral,position_vertical,windForce,thrust,setpoint\n")
f.close()
#colors for pygame
white = (255, 255, 255)
yellow = (255, 255, 102)
black = (0, 0, 0)
red = (255, 0, 0)
green = (0, 255, 0)
blue = (50, 153, 213)
dis_width = 1280
dis_height = 720
dis = pygame.display.set_mode((dis_width, dis_height))
#custom rectangle object for making a rotatable rectangle
class rectangle():
def __init__(self, center_x, center_y, width, height):
self.cx = center_x
self.cy = center_y
self.width = width
self.height = height
self.half_width = width / 2
self.half_height = height / 2
self.hypotenuse = np.sqrt((self.half_height * self.half_height) + (self.half_width * self.half_width))
self.standard_angle = | np.arcsin(self.half_width / self.hypotenuse) | numpy.arcsin |
#!/usr/bin/env python
# MIT License
#
# Copyright (c) 2019 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#
# This file is a part of the CIRN Interaction Language.
from __future__ import print_function, division
import logging
from os import path
import math
import numpy as np
from .reservation_reader import ReservationReader
from .observer_reader import ObserverReader
from .spectrum_grid import SpectrumGrid
from .usage_reader import UsageReader
from .geodata_reader import GeodataReader
class SpecEval(object):
"""
Creates statistics on spectrum usage.
"""
def __init__(self):
self.log = logging.getLogger('spec_eval')
# for the observer data
self.observer_dir = None
self.observer_config = None
self.observer_grid = None
self.observer_threshold = None
# for the CIL reports
self.gateway_pcap = None
self.gateway_stats = None
self.measured_voxels = []
self.forecast_voxels = []
# for the spec-val tool
self.gdf_file_name = None
self.gdf_file_report = None
self.gdf_file_shapes = None
# bounds of the spectrum region
self.time_start = None
self.time_stop = None
self.time_bins = None
self.freq_start = None
self.freq_stop = None
self.freq_bins = None
# numpy matrixes with duty cycles for each bin
self.observer_duty = None # from observer passband data
self.observer_quantized = None # from observer passband data, quantized to be true or false
self.measured_duty = None # from CIL past measurements
self.measured_quantized = None # from CIL past measurements, quantized to be true or false
self.forecast_duty = None # from CIL future forecasts
self.gdf_file_duty = None # from the spec-val tool
self.forecast_quantized = None # from CIL future forecasts, quantized to be true or false
# numpy matrices with quantized errors for each bin
self.measured_v_observer = None
self.forecast_v_observer = None
def read_observer_data(self, observer_dir):
self.log.info('Reading observer data from %s',
path.basename(observer_dir))
reader = ObserverReader(observer_dir)
reader.read_state_change()
reader.read_configs()
reader.read_pass_band_rf()
self.observer_dir = observer_dir
self.observer_config = reader.config
self.observer_grid = reader.grid
def read_usage_data(self, gateway_pcap, gateway_srn=None, incumbent_srn=None):
self.log.info('Reading usage data from %s',
path.basename(gateway_pcap))
reader = UsageReader(gateway_pcap, gateway_srn, incumbent_srn)
reader.read_messages()
self.gateway_pcap = gateway_pcap
self.gateway_stats = reader.stats
self.measured_voxels = reader.measured_past_voxels
self.forecast_voxels = reader.forecast_future_voxels
def read_gdf_data(self, gdf_file_name, rf_start_time):
self.log.info('Reading geodata frames from %s', gdf_file_name)
reader = GeodataReader(gdf_file_name, rf_start_time)
self.gdf_file_name = gdf_file_name
self.gdf_file_report = {
'filename': reader.stats['filename'],
'bbox': reader.stats['bbox'],
'geometry_types': reader.stats['geometry_types'],
}
self.gdf_file_shapes = reader.select_shapes()
def set_bounds(self, time_start, time_stop, time_bins, time_step,
freq_start, freq_stop, freq_bins, freq_step):
# use the bounds from the observer if not specified
time_start = time_start or self.observer_grid.time_start
time_stop = time_stop or self.observer_grid.time_stop
freq_start = freq_start or self.observer_grid.freq_start
freq_stop = freq_stop or self.observer_grid.freq_stop
# make sure that we have proper ranges
time_start = min(max(time_start, self.observer_grid.time_start),
self.observer_grid.time_stop)
time_stop = min(max(time_stop, self.observer_grid.time_start),
self.observer_grid.time_stop)
freq_start = min(max(freq_start, self.observer_grid.freq_start),
self.observer_grid.freq_stop)
freq_stop = min(max(freq_stop, self.observer_grid.freq_start),
self.observer_grid.freq_stop)
# override bins if step is specified
if time_step and (time_stop - time_start) > time_step > 0:
time_stop = time_start + \
math.floor((time_stop - time_start) / time_step) * time_step
time_bins = int(round((time_stop - time_start) / time_step))
if freq_step and (freq_stop - freq_start) > freq_step > 0:
freq_stop = freq_start + \
math.floor((freq_stop - freq_start) / freq_step) * freq_step
freq_bins = int(round((freq_stop - freq_start) / freq_step))
# save everything
self.time_start = time_start
self.time_stop = time_stop
self.time_bins = time_bins
self.freq_start = freq_start
self.freq_stop = freq_stop
self.freq_bins = freq_bins
self.log.info('Selected times: start %s stop %s',
time_start, time_stop)
self.log.info('Selected bins: time %s freq %s', time_bins, freq_bins)
def calculate_observer_duty_cylces(self, threshold):
self.log.info('Calculating observer duty cycles')
grid = self.observer_grid.threshold(threshold)
grid = grid.resample(
self.time_start, self.time_stop, self.time_bins,
self.freq_start, self.freq_stop, self.freq_bins)
self.observer_threshold = threshold
self.observer_duty = grid.data
self.observer_quantized = self.observer_grid.resample( self.time_start, self.time_stop, self.time_bins, self.freq_start, self.freq_stop, self.freq_bins, take_max=True ).data
self.observer_quantized[self.observer_quantized >= threshold] = 1
self.observer_quantized[self.observer_quantized < 1] = 0
def calculate_spectrum_usage_duty_cycles(self):
self.log.info('Calculating measured spectrum duty cycles')
grid = SpectrumGrid(
self.time_start, self.time_stop, self.time_bins,
self.freq_start, self.freq_stop, self.freq_bins)
for voxel in self.measured_voxels:
grid.add_voxel(voxel)
self.measured_duty = grid.data
self.measured_quantized = grid.data
self.measured_quantized[self.measured_quantized>0] = 1
self.log.info('Calculating forecast spectrum duty cycles')
grid = SpectrumGrid(
self.time_start, self.time_stop, self.time_bins,
self.freq_start, self.freq_stop, self.freq_bins)
for voxel in self.forecast_voxels:
grid.add_voxel(voxel)
self.forecast_duty = grid.data
self.forecast_quantized = grid.data ;
self.forecast_quantized[self.forecast_quantized>0] = 1
def calculate_gdf_file_duty_cycles(self):
self.log.info('Calculating geodata spectrum duty cycles')
grid = SpectrumGrid(
self.time_start, self.time_stop, self.time_bins,
self.freq_start, self.freq_stop, self.freq_bins)
for shape in self.gdf_file_shapes:
grid.add_shape(shape)
self.gdf_file_duty = grid.data
def get_diff_stat(self, diff):
return {
'above': float(np.average(np.maximum(diff, 0))),
'below': float(np.average(np.maximum(-diff, 0))),
'total': float(np.average(np.abs(diff)))
}
def get_diff_quant_stat(self, a, b):
above = a-b ;
below = -above ;
total = np.abs(a-b) ;
above[above<0] = 0 ;
below[below<0] = 0 ;
return {
'above': float(np.sum(above)/np.sum(b)),
'below': float(np.sum(below)/np.sum(b)),
'total': float(np.sum(total)/ | np.sum(b) | numpy.sum |
from __future__ import print_function, division
import os
import sys
import pytest
import warnings
import numpy
from galpy.util import galpyWarning
from test_actionAngle import reset_warning_registry
_TRAVIS= bool(os.getenv('TRAVIS'))
PY2= sys.version < '3'
# Print all galpyWarnings always for tests of warnings
warnings.simplefilter("always",galpyWarning)
#Basic sanity checking: circular orbit should have constant R, zero vR, vT=vc
def test_actionAngleTorus_basic():
from galpy.actionAngle import actionAngleTorus
from galpy.potential import MWPotential, rl, vcirc, \
FlattenedPowerPotential, PlummerPotential
tol= -4.
jr= 10.**-10.
jz= 10.**-10.
aAT= actionAngleTorus(pot=MWPotential)
# at R=1, Lz=1
jphi= 1.
angler= numpy.linspace(0.,2.*numpy.pi,101)
anglephi= numpy.linspace(0.,2.*numpy.pi,101)+1.
anglez= numpy.linspace(0.,2.*numpy.pi,101)+2.
RvR= aAT(jr,jphi,jz,angler,anglephi,anglez).T
assert numpy.all(numpy.fabs(RvR[0]-rl(MWPotential,jphi)) < 10.**tol), \
'circular orbit does not have constant radius for actionAngleTorus'
assert numpy.all(numpy.fabs(RvR[1]) < 10.**tol), \
'circular orbit does not have zero radial velocity for actionAngleTorus'
assert numpy.all(numpy.fabs(RvR[2]-vcirc(MWPotential,rl(MWPotential,jphi))) < 10.**tol), \
'circular orbit does not have constant vT=vc for actionAngleTorus'
assert numpy.all(numpy.fabs(RvR[3]) < 10.**tol), \
'circular orbit does not have zero vertical height for actionAngleTorus'
assert numpy.all(numpy.fabs(RvR[4]) < 10.**tol), \
'circular orbit does not have zero vertical velocity for actionAngleTorus'
# at Lz=1.5, using Plummer
tol= -3.25
pp= PlummerPotential(normalize=1.)
aAT= actionAngleTorus(pot=pp)
jphi= 1.5
RvR= aAT(jr,jphi,jz,angler,anglephi,anglez).T
assert numpy.all(numpy.fabs(RvR[0]-rl(pp,jphi)) < 10.**tol), \
'circular orbit does not have constant radius for actionAngleTorus'
assert numpy.all(numpy.fabs(RvR[1]) < 10.**tol), \
'circular orbit does not have zero radial velocity for actionAngleTorus'
assert numpy.all(numpy.fabs(RvR[2]-vcirc(pp,rl(pp,jphi))) < 10.**tol), \
'circular orbit does not have constant vT=vc for actionAngleTorus'
assert numpy.all(numpy.fabs(RvR[3]) < 10.**tol), \
'circular orbit does not have zero vertical height for actionAngleTorus'
assert numpy.all(numpy.fabs(RvR[4]) < 10.**tol), \
'circular orbit does not have zero vertical velocity for actionAngleTorus'
# at Lz=0.5, using FlattenedPowerPotential
tol= -4.
fp= FlattenedPowerPotential(normalize=1.)
aAT= actionAngleTorus(pot=fp)
jphi= 0.5
RvR= aAT(jr,jphi,jz,angler,anglephi,anglez).T
assert numpy.all(numpy.fabs(RvR[0]-rl(fp,jphi)) < 10.**tol), \
'circular orbit does not have constant radius for actionAngleTorus'
assert numpy.all(numpy.fabs(RvR[1]) < 10.**tol), \
'circular orbit does not have zero radial velocity for actionAngleTorus'
assert numpy.all(numpy.fabs(RvR[2]-vcirc(fp,rl(fp,jphi))) < 10.**tol), \
'circular orbit does not have constant vT=vc for actionAngleTorus'
assert numpy.all(numpy.fabs(RvR[3]) < 10.**tol), \
'circular orbit does not have zero vertical height for actionAngleTorus'
assert numpy.all(numpy.fabs(RvR[4]) < 10.**tol), \
'circular orbit does not have zero vertical velocity for actionAngleTorus'
return None
#Basic sanity checking: close-to-circular orbit should have freq. = epicycle freq.
def test_actionAngleTorus_basic_freqs():
from galpy.actionAngle import actionAngleTorus
from galpy.potential import epifreq, omegac, verticalfreq, rl, \
JaffePotential, PowerSphericalPotential, HernquistPotential
tol= -3.
jr= 10.**-6.
jz= 10.**-6.
jp= JaffePotential(normalize=1.)
aAT= actionAngleTorus(pot=jp)
# at Lz=1
jphi= 1.
om= aAT.Freqs(jr,jphi,jz)
assert numpy.fabs((om[0]-epifreq(jp,rl(jp,jphi)))/om[0]) < 10.**tol, \
'Close-to-circular orbit does not have Or=kappa for actionAngleTorus'
assert numpy.fabs((om[1]-omegac(jp,rl(jp,jphi)))/om[1]) < 10.**tol, \
'Close-to-circular orbit does not have Ophi=omega for actionAngleTorus'
assert numpy.fabs((om[2]-verticalfreq(jp,rl(jp,jphi)))/om[2]) < 10.**tol, \
'Close-to-circular orbit does not have Oz=nu for actionAngleTorus'
# at Lz=1.5, w/ different potential
pp= PowerSphericalPotential(normalize=1.)
aAT= actionAngleTorus(pot=pp)
jphi= 1.5
om= aAT.Freqs(jr,jphi,jz)
assert numpy.fabs((om[0]-epifreq(pp,rl(pp,jphi)))/om[0]) < 10.**tol, \
'Close-to-circular orbit does not have Or=kappa for actionAngleTorus'
assert numpy.fabs((om[1]-omegac(pp,rl(pp,jphi)))/om[1]) < 10.**tol, \
'Close-to-circular orbit does not have Ophi=omega for actionAngleTorus'
assert numpy.fabs((om[2]-verticalfreq(pp,rl(pp,jphi)))/om[2]) < 10.**tol, \
'Close-to-circular orbit does not have Oz=nu for actionAngleTorus'
# at Lz=0.5, w/ different potential
tol= -2.5 # appears more difficult
hp= HernquistPotential(normalize=1.)
aAT= actionAngleTorus(pot=hp)
jphi= 0.5
om= aAT.Freqs(jr,jphi,jz)
assert numpy.fabs((om[0]-epifreq(hp,rl(hp,jphi)))/om[0]) < 10.**tol, \
'Close-to-circular orbit does not have Or=kappa for actionAngleTorus'
assert numpy.fabs((om[1]-omegac(hp,rl(hp,jphi)))/om[1]) < 10.**tol, \
'Close-to-circular orbit does not have Ophi=omega for actionAngleTorus'
assert numpy.fabs((om[2]-verticalfreq(hp,rl(hp,jphi)))/om[2]) < 10.**tol, \
'Close-to-circular orbit does not have Oz=nu for actionAngleTorus'
return None
#Test that orbit from actionAngleTorus is the same as an integrated orbit
def test_actionAngleTorus_orbit():
from galpy.actionAngle import actionAngleTorus
from galpy.potential import MWPotential2014
from galpy.orbit import Orbit
# Set up instance
aAT= actionAngleTorus(pot=MWPotential2014,tol=10.**-5.)
jr,jphi,jz= 0.05,1.1,0.025
# First calculate frequencies and the initial RvR
RvRom= aAT.xvFreqs(jr,jphi,jz,
numpy.array([0.]),
numpy.array([1.]),
numpy.array([2.]))
om= RvRom[1:]
# Angles along an orbit
ts= numpy.linspace(0.,100.,1001)
angler= ts*om[0]
anglephi= 1.+ts*om[1]
anglez= 2.+ts*om[2]
# Calculate the orbit using actionAngleTorus
RvR= aAT(jr,jphi,jz,angler,anglephi,anglez).T
# Calculate the orbit using orbit integration
orb= Orbit([RvRom[0][0,0],RvRom[0][0,1],RvRom[0][0,2],
RvRom[0][0,3],RvRom[0][0,4],RvRom[0][0,5]])
orb.integrate(ts,MWPotential2014)
# Compare
tol= -3.
assert numpy.all(numpy.fabs(orb.R(ts)-RvR[0]) < 10.**tol), \
'Integrated orbit does not agree with torus orbit in R'
assert numpy.all(numpy.fabs(orb.vR(ts)-RvR[1]) < 10.**tol), \
'Integrated orbit does not agree with torus orbit in vR'
assert numpy.all(numpy.fabs(orb.vT(ts)-RvR[2]) < 10.**tol), \
'Integrated orbit does not agree with torus orbit in vT'
assert numpy.all(numpy.fabs(orb.z(ts)-RvR[3]) < 10.**tol), \
'Integrated orbit does not agree with torus orbit in z'
assert numpy.all(numpy.fabs(orb.vz(ts)-RvR[4]) < 10.**tol), \
'Integrated orbit does not agree with torus orbit in vz'
assert numpy.all(numpy.fabs((orb.phi(ts)-RvR[5]+numpy.pi) % (2.*numpy.pi) -numpy.pi) < 10.**tol), \
'Integrated orbit does not agree with torus orbit in phi'
return None
# Test that actionAngleTorus w/ interp pot gives same freqs as regular pot
# Doesn't work well: TM aborts because our interpolated forces aren't
# consistent enough with the potential for TM's taste, but we test that it at
# at least works somewhat
def test_actionAngleTorus_interppot_freqs():
from galpy.actionAngle import actionAngleTorus
from galpy.potential import LogarithmicHaloPotential, interpRZPotential
lp= LogarithmicHaloPotential(normalize=1.)
ip= interpRZPotential(RZPot=lp,
interpPot=True,
interpDens=True,interpRforce=True,interpzforce=True,
enable_c=True)
aAT= actionAngleTorus(pot=lp)
aATi= actionAngleTorus(pot=ip)
jr,jphi,jz= 0.05,1.1,0.02
om= aAT.Freqs(jr,jphi,jz)
omi= aATi.Freqs(jr,jphi,jz)
assert numpy.fabs((om[0]-omi[0])/om[0]) < 0.2, 'Radial frequency computed using the torus machine does not agree between potential and interpolated potential'
assert numpy.fabs((om[1]-omi[1])/om[1]) < 0.2, 'Azimuthal frequency computed using the torus machine does not agree between potential and interpolated potential'
assert numpy.fabs((om[2]-omi[2])/om[2]) < 0.8, 'Vertical frequency computed using the torus machine does not agree between potential and interpolated potential'
return None
#Test the actionAngleTorus against an isochrone potential: actions
def test_actionAngleTorus_Isochrone_actions():
from galpy.potential import IsochronePotential
from galpy.actionAngle import actionAngleTorus, \
actionAngleIsochrone
ip= IsochronePotential(normalize=1.,b=1.2)
aAI= actionAngleIsochrone(ip=ip)
tol= -6.
aAT= actionAngleTorus(pot=ip,tol=tol)
jr,jphi,jz= 0.075,1.1,0.05
angler= numpy.array([0.])
anglephi= numpy.array([numpy.pi])
anglez= numpy.array([numpy.pi/2.])
# Calculate position from aAT
RvR= aAT(jr,jphi,jz,angler,anglephi,anglez).T
# Calculate actions from aAI
ji= aAI(*RvR)
djr= numpy.fabs((ji[0]-jr)/jr)
dlz= numpy.fabs((ji[1]-jphi)/jphi)
djz= numpy.fabs((ji[2]-jz)/jz)
assert djr < 10.**tol, 'actionAngleTorus and actionAngleIsochrone applied to isochrone potential disagree for Jr at %f%%' % (djr*100.)
assert dlz < 10.**tol, 'actionAngleTorus and actionAngleIsochrone applied to isochrone potential disagree for Jr at %f%%' % (dlz*100.)
assert djz < 10.**tol, 'actionAngleTorus and actionAngleIsochrone applied to isochrone potential disagree for Jr at %f%%' % (djz*100.)
return None
#Test the actionAngleTorus against an isochrone potential: frequencies and angles
def test_actionAngleTorus_Isochrone_freqsAngles():
from galpy.potential import IsochronePotential
from galpy.actionAngle import actionAngleTorus, \
actionAngleIsochrone
ip= IsochronePotential(normalize=1.,b=1.2)
aAI= actionAngleIsochrone(ip=ip)
tol= -6.
aAT= actionAngleTorus(pot=ip,tol=tol)
jr,jphi,jz= 0.075,1.1,0.05
angler= numpy.array([0.1])+numpy.linspace(0.,numpy.pi,101)
angler= angler % (2.*numpy.pi)
anglephi= numpy.array([numpy.pi])+numpy.linspace(0.,numpy.pi,101)
anglephi= anglephi % (2.*numpy.pi)
anglez= numpy.array([numpy.pi/2.])+numpy.linspace(0.,numpy.pi,101)
anglez= anglez % (2.*numpy.pi)
# Calculate position from aAT
RvRom= aAT.xvFreqs(jr,jphi,jz,angler,anglephi,anglez)
# Calculate actions, frequencies, and angles from aAI
ws= aAI.actionsFreqsAngles(*RvRom[0].T)
dOr= numpy.fabs((ws[3]-RvRom[1]))
dOp= numpy.fabs((ws[4]-RvRom[2]))
dOz= numpy.fabs((ws[5]-RvRom[3]))
dar= numpy.fabs((ws[6]-angler))
dap= numpy.fabs((ws[7]-anglephi))
daz= numpy.fabs((ws[8]-anglez))
dar[dar > numpy.pi]-= 2.*numpy.pi
dar[dar < -numpy.pi]+= 2.*numpy.pi
dap[dap > numpy.pi]-= 2.*numpy.pi
dap[dap < -numpy.pi]+= 2.*numpy.pi
daz[daz > numpy.pi]-= 2.*numpy.pi
daz[daz < -numpy.pi]+= 2.*numpy.pi
assert numpy.all(dOr < 10.**tol), 'actionAngleTorus and actionAngleIsochrone applied to isochrone potential disagree for Or at %f%%' % (numpy.nanmax(dOr)*100.)
assert numpy.all(dOp < 10.**tol), 'actionAngleTorus and actionAngleIsochrone applied to isochrone potential disagree for Ophi at %f%%' % (numpy.nanmax(dOp)*100.)
assert numpy.all(dOz < 10.**tol), 'actionAngleTorus and actionAngleIsochrone applied to isochrone potential disagree for Oz at %f%%' % (numpy.nanmax(dOz)*100.)
assert numpy.all(dar < 10.**tol), 'actionAngleTorus and actionAngleIsochrone applied to isochrone potential disagree for ar at %f' % (numpy.nanmax(dar))
assert numpy.all(dap < 10.**tol), 'actionAngleTorus and actionAngleIsochrone applied to isochrone potential disagree for aphi at %f' % (numpy.nanmax(dap))
assert numpy.all(daz < 10.**tol), 'actionAngleTorus and actionAngleIsochrone applied to isochrone potential disagree for az at %f' % (numpy.nanmax(daz))
return None
#Test the actionAngleTorus against a Staeckel potential: actions
def test_actionAngleTorus_Staeckel_actions():
from galpy.potential import KuzminKutuzovStaeckelPotential
from galpy.actionAngle import actionAngleTorus, \
actionAngleStaeckel
delta= 1.2
kp= KuzminKutuzovStaeckelPotential(normalize=1.,Delta=delta)
aAS= actionAngleStaeckel(pot=kp,delta=delta,c=True)
tol= -3.
aAT= actionAngleTorus(pot=kp,tol=tol)
jr,jphi,jz= 0.075,1.1,0.05
angler= numpy.array([0.])
anglephi= numpy.array([numpy.pi])
anglez= numpy.array([numpy.pi/2.])
# Calculate position from aAT
RvR= aAT(jr,jphi,jz,angler,anglephi,anglez).T
# Calculate actions from aAI
ji= aAS(*RvR)
djr= numpy.fabs((ji[0]-jr)/jr)
dlz= numpy.fabs((ji[1]-jphi)/jphi)
djz= numpy.fabs((ji[2]-jz)/jz)
assert djr < 10.**tol, 'actionAngleTorus and actionAngleStaeckel applied to Staeckel potential disagree for Jr at %f%%' % (djr*100.)
assert dlz < 10.**tol, 'actionAngleTorus and actionAngleStaeckel applied to Staeckel potential disagree for Jr at %f%%' % (dlz*100.)
assert djz < 10.**tol, 'actionAngleTorus and actionAngleStaeckel applied to Staeckel potential disagree for Jr at %f%%' % (djz*100.)
return None
#Test the actionAngleTorus against an isochrone potential: frequencies and angles
def test_actionAngleTorus_Staeckel_freqsAngles():
from galpy.potential import KuzminKutuzovStaeckelPotential
from galpy.actionAngle import actionAngleTorus, \
actionAngleStaeckel
delta= 1.2
kp= KuzminKutuzovStaeckelPotential(normalize=1.,Delta=delta)
aAS= actionAngleStaeckel(pot=kp,delta=delta,c=True)
tol= -3.
aAT= actionAngleTorus(pot=kp,tol=tol)
jr,jphi,jz= 0.075,1.1,0.05
angler= numpy.array([0.1])+numpy.linspace(0.,numpy.pi,101)
angler= angler % (2.*numpy.pi)
anglephi= numpy.array([numpy.pi])+numpy.linspace(0.,numpy.pi,101)
anglephi= anglephi % (2.*numpy.pi)
anglez= numpy.array([numpy.pi/2.])+numpy.linspace(0.,numpy.pi,101)
anglez= anglez % (2.*numpy.pi)
# Calculate position from aAT
RvRom= aAT.xvFreqs(jr,jphi,jz,angler,anglephi,anglez)
# Calculate actions, frequencies, and angles from aAI
ws= aAS.actionsFreqsAngles(*RvRom[0].T)
dOr= numpy.fabs((ws[3]-RvRom[1]))
dOp= numpy.fabs((ws[4]-RvRom[2]))
dOz= numpy.fabs((ws[5]-RvRom[3]))
dar= numpy.fabs((ws[6]-angler))
dap= numpy.fabs((ws[7]-anglephi))
daz= numpy.fabs((ws[8]-anglez))
dar[dar > numpy.pi]-= 2.*numpy.pi
dar[dar < -numpy.pi]+= 2.*numpy.pi
dap[dap > numpy.pi]-= 2.*numpy.pi
dap[dap < -numpy.pi]+= 2.*numpy.pi
daz[daz > numpy.pi]-= 2.*numpy.pi
daz[daz < -numpy.pi]+= 2.*numpy.pi
assert numpy.all(dOr < 10.**tol), 'actionAngleTorus and actionAngleStaeckel applied to Staeckel potential disagree for Or at %f%%' % (numpy.nanmax(dOr)*100.)
assert numpy.all(dOp < 10.**tol), 'actionAngleTorus and actionAngleStaeckel applied to Staeckel potential disagree for Ophi at %f%%' % (numpy.nanmax(dOp)*100.)
assert numpy.all(dOz < 10.**tol), 'actionAngleTorus and actionAngleStaeckel applied to Staeckel potential disagree for Oz at %f%%' % (numpy.nanmax(dOz)*100.)
assert numpy.all(dar < 10.**tol), 'actionAngleTorus and actionAngleStaeckel applied to Staeckel potential disagree for ar at %f' % (numpy.nanmax(dar))
assert numpy.all(dap < 10.**tol), 'actionAngleTorus and actionAngleStaeckel applied to Staeckel potential disagree for aphi at %f' % (numpy.nanmax(dap))
assert numpy.all(daz < 10.**tol), 'actionAngleTorus and actionAngleStaeckel applied to Staeckel potential disagree for az at %f' % (numpy.nanmax(daz))
return None
#Test the actionAngleTorus against a general potential w/ actionAngleIsochroneApprox: actions
def test_actionAngleTorus_isochroneApprox_actions():
from galpy.potential import MWPotential2014
from galpy.actionAngle import actionAngleTorus, \
actionAngleIsochroneApprox
aAIA= actionAngleIsochroneApprox(pot=MWPotential2014,b=0.8)
tol= -2.5
aAT= actionAngleTorus(pot=MWPotential2014,tol=tol)
jr,jphi,jz= 0.075,1.1,0.05
angler= numpy.array([0.])
anglephi= numpy.array([numpy.pi])
anglez= numpy.array([numpy.pi/2.])
# Calculate position from aAT
RvR= aAT(jr,jphi,jz,angler,anglephi,anglez).T
# Calculate actions from aAIA
ji= aAIA(*RvR)
djr= numpy.fabs((ji[0]-jr)/jr)
dlz= numpy.fabs((ji[1]-jphi)/jphi)
djz= numpy.fabs((ji[2]-jz)/jz)
assert djr < 10.**tol, 'actionAngleTorus and actionAngleIsochroneApprox applied to MWPotential2014 potential disagree for Jr at %f%%' % (djr*100.)
assert dlz < 10.**tol, 'actionAngleTorus and actionAngleIsochroneApprox applied to MWPotential2014 potential disagree for Jr at %f%%' % (dlz*100.)
assert djz < 10.**tol, 'actionAngleTorus and actionAngleMWPotential2014 applied to MWPotential2014 potential disagree for Jr at %f%%' % (djz*100.)
return None
#Test the actionAngleTorus against a general potential w/ actionAngleIsochrone: frequencies and angles
def test_actionAngleTorus_isochroneApprox_freqsAngles():
from galpy.potential import MWPotential2014
from galpy.actionAngle import actionAngleTorus, \
actionAngleIsochroneApprox
aAIA= actionAngleIsochroneApprox(pot=MWPotential2014,b=0.8)
tol= -3.5
aAT= actionAngleTorus(pot=MWPotential2014,tol=tol)
jr,jphi,jz= 0.075,1.1,0.05
angler= numpy.array([0.1])+numpy.linspace(0.,numpy.pi,21)
angler= angler % (2.*numpy.pi)
anglephi= numpy.array([numpy.pi])+numpy.linspace(0.,numpy.pi,21)
anglephi= anglephi % (2.*numpy.pi)
anglez= numpy.array([numpy.pi/2.])+numpy.linspace(0.,numpy.pi,21)
anglez= anglez % (2.*numpy.pi)
# Calculate position from aAT
RvRom= aAT.xvFreqs(jr,jphi,jz,angler,anglephi,anglez)
# Calculate actions, frequencies, and angles from aAI
ws= aAIA.actionsFreqsAngles(*RvRom[0].T)
dOr= numpy.fabs((ws[3]-RvRom[1]))
dOp= numpy.fabs((ws[4]-RvRom[2]))
dOz= numpy.fabs((ws[5]-RvRom[3]))
dar= numpy.fabs((ws[6]-angler))
dap= numpy.fabs((ws[7]-anglephi))
daz= numpy.fabs((ws[8]-anglez))
dar[dar > numpy.pi]-= 2.*numpy.pi
dar[dar < -numpy.pi]+= 2.*numpy.pi
dap[dap > numpy.pi]-= 2.*numpy.pi
dap[dap < -numpy.pi]+= 2.*numpy.pi
daz[daz > numpy.pi]-= 2.*numpy.pi
daz[daz < -numpy.pi]+= 2.*numpy.pi
assert numpy.all(dOr < 10.**tol), 'actionAngleTorus and actionAngleIsochroneApprox applied to MWPotential2014 potential disagree for Or at %f%%' % (numpy.nanmax(dOr)*100.)
assert numpy.all(dOp < 10.**tol), 'actionAngleTorus and actionAngleIsochroneApprox applied to MWPotential2014 potential disagree for Ophi at %f%%' % (numpy.nanmax(dOp)*100.)
assert numpy.all(dOz < 10.**tol), 'actionAngleTorus and actionAngleIsochroneApprox applied to MWPotential2014 potential disagree for Oz at %f%%' % (numpy.nanmax(dOz)*100.)
assert numpy.all(dar < 10.**tol), 'actionAngleTorus and actionAngleIsochroneApprox applied to MWPotential2014 potential disagree for ar at %f' % (numpy.nanmax(dar))
assert numpy.all(dap < 10.**tol), 'actionAngleTorus and actionAngleIsochroneApprox applied to MWPotential2014 potential disagree for aphi at %f' % (numpy.nanmax(dap))
assert numpy.all(daz < 10.**tol), 'actionAngleTorus and actionAngleIsochroneApprox applied to MWPotential2014 potential disagree for az at %f' % (numpy.nanmax(daz))
return None
# Test that the frequencies returned by hessianFreqs are the same as those returned by Freqs
def test_actionAngleTorus_hessian_freqs():
from galpy.potential import MWPotential2014
from galpy.actionAngle import actionAngleTorus
aAT= actionAngleTorus(pot=MWPotential2014)
jr,jphi,jz= 0.075,1.1,0.05
fO= aAT.Freqs(jr,jphi,jz)[:3]
hO= aAT.hessianFreqs(jr,jphi,jz)[1:4]
assert numpy.all(numpy.fabs(numpy.array(fO)- | numpy.array(hO) | numpy.array |
# This module has been generated automatically from space group information
# obtained from the Computational Crystallography Toolbox
#
"""
Space groups
This module contains a list of all the 230 space groups that can occur in
a crystal. The variable space_groups contains a dictionary that maps
space group numbers and space group names to the corresponding space
group objects.
.. moduleauthor:: <NAME> <<EMAIL>>
"""
#-----------------------------------------------------------------------------
# Copyright (C) 2013 The Mosaic Development Team
#
# Distributed under the terms of the BSD License. The full license is in
# the file LICENSE.txt, distributed as part of this software.
#-----------------------------------------------------------------------------
import numpy as N
class SpaceGroup(object):
"""
Space group
All possible space group objects are created in this module. Other
modules should access these objects through the dictionary
space_groups rather than create their own space group objects.
"""
def __init__(self, number, symbol, transformations):
"""
:param number: the number assigned to the space group by
international convention
:type number: int
:param symbol: the Hermann-Mauguin space-group symbol as used
in PDB and mmCIF files
:type symbol: str
:param transformations: a list of space group transformations,
each consisting of a tuple of three
integer arrays (rot, tn, td), where
rot is the rotation matrix and tn/td
are the numerator and denominator of the
translation vector. The transformations
are defined in fractional coordinates.
:type transformations: list
"""
self.number = number
self.symbol = symbol
self.transformations = transformations
self.transposed_rotations = N.array([N.transpose(t[0])
for t in transformations])
self.phase_factors = N.exp(N.array([(-2j*N.pi*t[1])/t[2]
for t in transformations]))
def __repr__(self):
return "SpaceGroup(%d, %s)" % (self.number, repr(self.symbol))
def __len__(self):
"""
:return: the number of space group transformations
:rtype: int
"""
return len(self.transformations)
def symmetryEquivalentMillerIndices(self, hkl):
"""
:param hkl: a set of Miller indices
:type hkl: Scientific.N.array_type
:return: a tuple (miller_indices, phase_factor) of two arrays
of length equal to the number of space group
transformations. miller_indices contains the Miller
indices of each reflection equivalent by symmetry to the
reflection hkl (including hkl itself as the first element).
phase_factor contains the phase factors that must be applied
to the structure factor of reflection hkl to obtain the
structure factor of the symmetry equivalent reflection.
:rtype: tuple
"""
hkls = N.dot(self.transposed_rotations, hkl)
p = N.multiply.reduce(self.phase_factors**hkl, -1)
return hkls, p
space_groups = {}
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(1, 'P 1', transformations)
space_groups[1] = sg
space_groups['P 1'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(2, 'P -1', transformations)
space_groups[2] = sg
space_groups['P -1'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(3, 'P 1 2 1', transformations)
space_groups[3] = sg
space_groups['P 1 2 1'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(4, 'P 1 21 1', transformations)
space_groups[4] = sg
space_groups['P 1 21 1'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(5, 'C 1 2 1', transformations)
space_groups[5] = sg
space_groups['C 1 2 1'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(6, 'P 1 m 1', transformations)
space_groups[6] = sg
space_groups['P 1 m 1'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(7, 'P 1 c 1', transformations)
space_groups[7] = sg
space_groups['P 1 c 1'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(8, 'C 1 m 1', transformations)
space_groups[8] = sg
space_groups['C 1 m 1'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(9, 'C 1 c 1', transformations)
space_groups[9] = sg
space_groups['C 1 c 1'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(10, 'P 1 2/m 1', transformations)
space_groups[10] = sg
space_groups['P 1 2/m 1'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(11, 'P 1 21/m 1', transformations)
space_groups[11] = sg
space_groups['P 1 21/m 1'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(12, 'C 1 2/m 1', transformations)
space_groups[12] = sg
space_groups['C 1 2/m 1'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(13, 'P 1 2/c 1', transformations)
space_groups[13] = sg
space_groups['P 1 2/c 1'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(14, 'P 1 21/c 1', transformations)
space_groups[14] = sg
space_groups['P 1 21/c 1'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(15, 'C 1 2/c 1', transformations)
space_groups[15] = sg
space_groups['C 1 2/c 1'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(16, 'P 2 2 2', transformations)
space_groups[16] = sg
space_groups['P 2 2 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(17, 'P 2 2 21', transformations)
space_groups[17] = sg
space_groups['P 2 2 21'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(18, 'P 21 21 2', transformations)
space_groups[18] = sg
space_groups['P 21 21 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(19, 'P 21 21 21', transformations)
space_groups[19] = sg
space_groups['P 21 21 21'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(20, 'C 2 2 21', transformations)
space_groups[20] = sg
space_groups['C 2 2 21'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(21, 'C 2 2 2', transformations)
space_groups[21] = sg
space_groups['C 2 2 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(22, 'F 2 2 2', transformations)
space_groups[22] = sg
space_groups['F 2 2 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(23, 'I 2 2 2', transformations)
space_groups[23] = sg
space_groups['I 2 2 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(24, 'I 21 21 21', transformations)
space_groups[24] = sg
space_groups['I 21 21 21'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(25, 'P m m 2', transformations)
space_groups[25] = sg
space_groups['P m m 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(26, 'P m c 21', transformations)
space_groups[26] = sg
space_groups['P m c 21'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(27, 'P c c 2', transformations)
space_groups[27] = sg
space_groups['P c c 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(28, 'P m a 2', transformations)
space_groups[28] = sg
space_groups['P m a 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(29, 'P c a 21', transformations)
space_groups[29] = sg
space_groups['P c a 21'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(30, 'P n c 2', transformations)
space_groups[30] = sg
space_groups['P n c 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(31, 'P m n 21', transformations)
space_groups[31] = sg
space_groups['P m n 21'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(32, 'P b a 2', transformations)
space_groups[32] = sg
space_groups['P b a 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(33, 'P n a 21', transformations)
space_groups[33] = sg
space_groups['P n a 21'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(34, 'P n n 2', transformations)
space_groups[34] = sg
space_groups['P n n 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(35, 'C m m 2', transformations)
space_groups[35] = sg
space_groups['C m m 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(36, 'C m c 21', transformations)
space_groups[36] = sg
space_groups['C m c 21'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(37, 'C c c 2', transformations)
space_groups[37] = sg
space_groups['C c c 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(38, 'A m m 2', transformations)
space_groups[38] = sg
space_groups['A m m 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(39, 'A b m 2', transformations)
space_groups[39] = sg
space_groups['A b m 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(40, 'A m a 2', transformations)
space_groups[40] = sg
space_groups['A m a 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(41, 'A b a 2', transformations)
space_groups[41] = sg
space_groups['A b a 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(42, 'F m m 2', transformations)
space_groups[42] = sg
space_groups['F m m 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([3,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([3,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([3,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([3,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(43, 'F d d 2', transformations)
space_groups[43] = sg
space_groups['F d d 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(44, 'I m m 2', transformations)
space_groups[44] = sg
space_groups['I m m 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(45, 'I b a 2', transformations)
space_groups[45] = sg
space_groups['I b a 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(46, 'I m a 2', transformations)
space_groups[46] = sg
space_groups['I m a 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(47, 'P m m m', transformations)
space_groups[47] = sg
space_groups['P m m m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(48, 'P n n n :2', transformations)
space_groups[48] = sg
space_groups['P n n n :2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(49, 'P c c m', transformations)
space_groups[49] = sg
space_groups['P c c m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(50, 'P b a n :2', transformations)
space_groups[50] = sg
space_groups['P b a n :2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(51, 'P m m a', transformations)
space_groups[51] = sg
space_groups['P m m a'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(52, 'P n n a', transformations)
space_groups[52] = sg
space_groups['P n n a'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(53, 'P m n a', transformations)
space_groups[53] = sg
space_groups['P m n a'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(54, 'P c c a', transformations)
space_groups[54] = sg
space_groups['P c c a'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(55, 'P b a m', transformations)
space_groups[55] = sg
space_groups['P b a m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(56, 'P c c n', transformations)
space_groups[56] = sg
space_groups['P c c n'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(57, 'P b c m', transformations)
space_groups[57] = sg
space_groups['P b c m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(58, 'P n n m', transformations)
space_groups[58] = sg
space_groups['P n n m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(59, 'P m m n :2', transformations)
space_groups[59] = sg
space_groups['P m m n :2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(60, 'P b c n', transformations)
space_groups[60] = sg
space_groups['P b c n'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(61, 'P b c a', transformations)
space_groups[61] = sg
space_groups['P b c a'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(62, 'P n m a', transformations)
space_groups[62] = sg
space_groups['P n m a'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(63, 'C m c m', transformations)
space_groups[63] = sg
space_groups['C m c m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(64, 'C m c a', transformations)
space_groups[64] = sg
space_groups['C m c a'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(65, 'C m m m', transformations)
space_groups[65] = sg
space_groups['C m m m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(66, 'C c c m', transformations)
space_groups[66] = sg
space_groups['C c c m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(67, 'C m m a', transformations)
space_groups[67] = sg
space_groups['C m m a'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(68, 'C c c a :2', transformations)
space_groups[68] = sg
space_groups['C c c a :2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(69, 'F m m m', transformations)
space_groups[69] = sg
space_groups['F m m m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([4,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([4,4,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([4,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([4,4,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,3,3])
trans_den = N.array([1,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([4,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,3,1])
trans_den = N.array([4,4,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,1,1])
trans_den = N.array([4,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,1,1])
trans_den = N.array([4,4,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([2,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([3,0,3])
trans_den = N.array([4,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([3,1,1])
trans_den = N.array([4,4,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,-1,1])
trans_den = N.array([2,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([4,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,-1,1])
trans_den = N.array([4,4,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,3,1])
trans_den = N.array([2,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([3,1,1])
trans_den = N.array([4,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([3,3,0])
trans_den = N.array([4,4,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,-1])
trans_den = N.array([2,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,-1])
trans_den = N.array([4,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([4,4,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(70, 'F d d d :2', transformations)
space_groups[70] = sg
space_groups['F d d d :2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(71, 'I m m m', transformations)
space_groups[71] = sg
space_groups['I m m m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(72, 'I b a m', transformations)
space_groups[72] = sg
space_groups['I b a m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(73, 'I b c a', transformations)
space_groups[73] = sg
space_groups['I b c a'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(74, 'I m m a', transformations)
space_groups[74] = sg
space_groups['I m m a'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(75, 'P 4', transformations)
space_groups[75] = sg
space_groups['P 4'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,3])
trans_den = N.array([1,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(76, 'P 41', transformations)
space_groups[76] = sg
space_groups['P 41'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(77, 'P 42', transformations)
space_groups[77] = sg
space_groups['P 42'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,3])
trans_den = N.array([1,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(78, 'P 43', transformations)
space_groups[78] = sg
space_groups['P 43'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(79, 'I 4', transformations)
space_groups[79] = sg
space_groups['I 4'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,3])
trans_den = N.array([2,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,3])
trans_den = N.array([2,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,5])
trans_den = N.array([1,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,5])
trans_den = N.array([1,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(80, 'I 41', transformations)
space_groups[80] = sg
space_groups['I 41'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(81, 'P -4', transformations)
space_groups[81] = sg
space_groups['P -4'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(82, 'I -4', transformations)
space_groups[82] = sg
space_groups['I -4'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(83, 'P 4/m', transformations)
space_groups[83] = sg
space_groups['P 4/m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(84, 'P 42/m', transformations)
space_groups[84] = sg
space_groups['P 42/m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(85, 'P 4/n :2', transformations)
space_groups[85] = sg
space_groups['P 4/n :2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(86, 'P 42/n :2', transformations)
space_groups[86] = sg
space_groups['P 42/n :2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(87, 'I 4/m', transformations)
space_groups[87] = sg
space_groups['I 4/m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-3,-3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([3,5,5])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([3,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,-1,-1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(88, 'I 41/a :2', transformations)
space_groups[88] = sg
space_groups['I 41/a :2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(89, 'P 4 2 2', transformations)
space_groups[89] = sg
space_groups['P 4 2 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(90, 'P 4 21 2', transformations)
space_groups[90] = sg
space_groups['P 4 21 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,3])
trans_den = N.array([1,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,3])
trans_den = N.array([1,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,4])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(91, 'P 41 2 2', transformations)
space_groups[91] = sg
space_groups['P 41 2 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([2,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([2,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(92, 'P 41 21 2', transformations)
space_groups[92] = sg
space_groups['P 41 21 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(93, 'P 42 2 2', transformations)
space_groups[93] = sg
space_groups['P 42 2 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(94, 'P 42 21 2', transformations)
space_groups[94] = sg
space_groups['P 42 21 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,3])
trans_den = N.array([1,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,3])
trans_den = N.array([1,1,4])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(95, 'P 43 2 2', transformations)
space_groups[95] = sg
space_groups['P 43 2 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([2,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([2,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(96, 'P 43 21 2', transformations)
space_groups[96] = sg
space_groups['P 43 21 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(97, 'I 4 2 2', transformations)
space_groups[97] = sg
space_groups['I 4 2 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,3])
trans_den = N.array([2,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,3])
trans_den = N.array([2,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,3])
trans_den = N.array([2,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,3])
trans_den = N.array([2,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,5])
trans_den = N.array([1,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,5])
trans_den = N.array([1,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,5])
trans_den = N.array([1,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,5])
trans_den = N.array([1,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(98, 'I 41 2 2', transformations)
space_groups[98] = sg
space_groups['I 41 2 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(99, 'P 4 m m', transformations)
space_groups[99] = sg
space_groups['P 4 m m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(100, 'P 4 b m', transformations)
space_groups[100] = sg
space_groups['P 4 b m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(101, 'P 42 c m', transformations)
space_groups[101] = sg
space_groups['P 42 c m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(102, 'P 42 n m', transformations)
space_groups[102] = sg
space_groups['P 42 n m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(103, 'P 4 c c', transformations)
space_groups[103] = sg
space_groups['P 4 c c'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(104, 'P 4 n c', transformations)
space_groups[104] = sg
space_groups['P 4 n c'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(105, 'P 42 m c', transformations)
space_groups[105] = sg
space_groups['P 42 m c'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(106, 'P 42 b c', transformations)
space_groups[106] = sg
space_groups['P 42 b c'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(107, 'I 4 m m', transformations)
space_groups[107] = sg
space_groups['I 4 m m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(108, 'I 4 c m', transformations)
space_groups[108] = sg
space_groups['I 4 c m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,3])
trans_den = N.array([2,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,3])
trans_den = N.array([2,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,3])
trans_den = N.array([2,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,3])
trans_den = N.array([2,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,5])
trans_den = N.array([1,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,5])
trans_den = N.array([1,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,5])
trans_den = N.array([1,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,5])
trans_den = N.array([1,2,4])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(109, 'I 41 m d', transformations)
space_groups[109] = sg
space_groups['I 41 m d'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,3])
trans_den = N.array([2,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,3])
trans_den = N.array([2,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,5])
trans_den = N.array([1,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,5])
trans_den = N.array([1,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([1,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([1,2,4])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(110, 'I 41 c d', transformations)
space_groups[110] = sg
space_groups['I 41 c d'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(111, 'P -4 2 m', transformations)
space_groups[111] = sg
space_groups['P -4 2 m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(112, 'P -4 2 c', transformations)
space_groups[112] = sg
space_groups['P -4 2 c'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(113, 'P -4 21 m', transformations)
space_groups[113] = sg
space_groups['P -4 21 m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(114, 'P -4 21 c', transformations)
space_groups[114] = sg
space_groups['P -4 21 c'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(115, 'P -4 m 2', transformations)
space_groups[115] = sg
space_groups['P -4 m 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(116, 'P -4 c 2', transformations)
space_groups[116] = sg
space_groups['P -4 c 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(117, 'P -4 b 2', transformations)
space_groups[117] = sg
space_groups['P -4 b 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(118, 'P -4 n 2', transformations)
space_groups[118] = sg
space_groups['P -4 n 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(119, 'I -4 m 2', transformations)
space_groups[119] = sg
space_groups['I -4 m 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(120, 'I -4 c 2', transformations)
space_groups[120] = sg
space_groups['I -4 c 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(121, 'I -4 2 m', transformations)
space_groups[121] = sg
space_groups['I -4 2 m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,3])
trans_den = N.array([2,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,3])
trans_den = N.array([2,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,3])
trans_den = N.array([2,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,3])
trans_den = N.array([2,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,5])
trans_den = N.array([1,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,5])
trans_den = N.array([1,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,5])
trans_den = N.array([1,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,5])
trans_den = N.array([1,2,4])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(122, 'I -4 2 d', transformations)
space_groups[122] = sg
space_groups['I -4 2 d'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(123, 'P 4/m m m', transformations)
space_groups[123] = sg
space_groups['P 4/m m m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(124, 'P 4/m c c', transformations)
space_groups[124] = sg
space_groups['P 4/m c c'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(125, 'P 4/n b m :2', transformations)
space_groups[125] = sg
space_groups['P 4/n b m :2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(126, 'P 4/n n c :2', transformations)
space_groups[126] = sg
space_groups['P 4/n n c :2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(127, 'P 4/m b m', transformations)
space_groups[127] = sg
space_groups['P 4/m b m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(128, 'P 4/m n c', transformations)
space_groups[128] = sg
space_groups['P 4/m n c'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(129, 'P 4/n m m :2', transformations)
space_groups[129] = sg
space_groups['P 4/n m m :2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(130, 'P 4/n c c :2', transformations)
space_groups[130] = sg
space_groups['P 4/n c c :2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(131, 'P 42/m m c', transformations)
space_groups[131] = sg
space_groups['P 42/m m c'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(132, 'P 42/m c m', transformations)
space_groups[132] = sg
space_groups['P 42/m c m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(133, 'P 42/n b c :2', transformations)
space_groups[133] = sg
space_groups['P 42/n b c :2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(134, 'P 42/n n m :2', transformations)
space_groups[134] = sg
space_groups['P 42/n n m :2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(135, 'P 42/m b c', transformations)
space_groups[135] = sg
space_groups['P 42/m b c'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(136, 'P 42/m n m', transformations)
space_groups[136] = sg
space_groups['P 42/m n m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(137, 'P 42/n m c :2', transformations)
space_groups[137] = sg
space_groups['P 42/n m c :2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(138, 'P 42/n c m :2', transformations)
space_groups[138] = sg
space_groups['P 42/n c m :2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(139, 'I 4/m m m', transformations)
space_groups[139] = sg
space_groups['I 4/m m m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(140, 'I 4/m c m', transformations)
space_groups[140] = sg
space_groups['I 4/m c m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-3,-1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-3,-1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([3,5,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([3,3,5])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([3,5,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([3,3,5])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,-1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,-1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,-1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,-1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(141, 'I 41/a m d :2', transformations)
space_groups[141] = sg
space_groups['I 41/a m d :2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-3,-1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-3,-3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([3,5,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([3,3,5])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([3,5,5])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([3,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,-1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,-1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,-1,-1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(142, 'I 41/a c d :2', transformations)
space_groups[142] = sg
space_groups['I 41/a c d :2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(143, 'P 3', transformations)
space_groups[143] = sg
space_groups['P 3'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(144, 'P 31', transformations)
space_groups[144] = sg
space_groups['P 31'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(145, 'P 32', transformations)
space_groups[145] = sg
space_groups['P 32'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(146, 'R 3 :H', transformations)
space_groups[146] = sg
space_groups['R 3 :H'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(147, 'P -3', transformations)
space_groups[147] = sg
space_groups['P -3'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(148, 'R -3 :H', transformations)
space_groups[148] = sg
space_groups['R -3 :H'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(149, 'P 3 1 2', transformations)
space_groups[149] = sg
space_groups['P 3 1 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(150, 'P 3 2 1', transformations)
space_groups[150] = sg
space_groups['P 3 2 1'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(151, 'P 31 1 2', transformations)
space_groups[151] = sg
space_groups['P 31 1 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(152, 'P 31 2 1', transformations)
space_groups[152] = sg
space_groups['P 31 2 1'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(153, 'P 32 1 2', transformations)
space_groups[153] = sg
space_groups['P 32 1 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(154, 'P 32 2 1', transformations)
space_groups[154] = sg
space_groups['P 32 2 1'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(155, 'R 3 2 :H', transformations)
space_groups[155] = sg
space_groups['R 3 2 :H'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(156, 'P 3 m 1', transformations)
space_groups[156] = sg
space_groups['P 3 m 1'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(157, 'P 3 1 m', transformations)
space_groups[157] = sg
space_groups['P 3 1 m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(158, 'P 3 c 1', transformations)
space_groups[158] = sg
space_groups['P 3 c 1'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(159, 'P 3 1 c', transformations)
space_groups[159] = sg
space_groups['P 3 1 c'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(160, 'R 3 m :H', transformations)
space_groups[160] = sg
space_groups['R 3 m :H'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,7])
trans_den = N.array([3,3,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,7])
trans_den = N.array([3,3,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,7])
trans_den = N.array([3,3,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,5])
trans_den = N.array([3,3,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,5])
trans_den = N.array([3,3,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,5])
trans_den = N.array([3,3,6])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(161, 'R 3 c :H', transformations)
space_groups[161] = sg
space_groups['R 3 c :H'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(162, 'P -3 1 m', transformations)
space_groups[162] = sg
space_groups['P -3 1 m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(163, 'P -3 1 c', transformations)
space_groups[163] = sg
space_groups['P -3 1 c'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(164, 'P -3 m 1', transformations)
space_groups[164] = sg
space_groups['P -3 m 1'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(165, 'P -3 c 1', transformations)
space_groups[165] = sg
space_groups['P -3 c 1'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(166, 'R -3 m :H', transformations)
space_groups[166] = sg
space_groups['R -3 m :H'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,2,7])
trans_den = N.array([3,3,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,2,7])
trans_den = N.array([3,3,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,2,7])
trans_den = N.array([3,3,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,1])
trans_den = N.array([3,3,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,1])
trans_den = N.array([3,3,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,1])
trans_den = N.array([3,3,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([2,1,5])
trans_den = N.array([3,3,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([2,1,5])
trans_den = N.array([3,3,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([2,1,5])
trans_den = N.array([3,3,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,-1])
trans_den = N.array([3,3,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,-1])
trans_den = N.array([3,3,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,-1])
trans_den = N.array([3,3,6])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(167, 'R -3 c :H', transformations)
space_groups[167] = sg
space_groups['R -3 c :H'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(168, 'P 6', transformations)
space_groups[168] = sg
space_groups['P 6'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,5])
trans_den = N.array([1,1,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(169, 'P 61', transformations)
space_groups[169] = sg
space_groups['P 61'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,5])
trans_den = N.array([1,1,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(170, 'P 65', transformations)
space_groups[170] = sg
space_groups['P 65'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(171, 'P 62', transformations)
space_groups[171] = sg
space_groups['P 62'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(172, 'P 64', transformations)
space_groups[172] = sg
space_groups['P 64'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(173, 'P 63', transformations)
space_groups[173] = sg
space_groups['P 63'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(174, 'P -6', transformations)
space_groups[174] = sg
space_groups['P -6'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(175, 'P 6/m', transformations)
space_groups[175] = sg
space_groups['P 6/m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(176, 'P 63/m', transformations)
space_groups[176] = sg
space_groups['P 63/m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(177, 'P 6 2 2', transformations)
space_groups[177] = sg
space_groups['P 6 2 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,5])
trans_den = N.array([1,1,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,5])
trans_den = N.array([1,1,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,6])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(178, 'P 61 2 2', transformations)
space_groups[178] = sg
space_groups['P 61 2 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,5])
trans_den = N.array([1,1,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,5])
trans_den = N.array([1,1,6])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(179, 'P 65 2 2', transformations)
space_groups[179] = sg
space_groups['P 65 2 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(180, 'P 62 2 2', transformations)
space_groups[180] = sg
space_groups['P 62 2 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(181, 'P 64 2 2', transformations)
space_groups[181] = sg
space_groups['P 64 2 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(182, 'P 63 2 2', transformations)
space_groups[182] = sg
space_groups['P 63 2 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(183, 'P 6 m m', transformations)
space_groups[183] = sg
space_groups['P 6 m m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(184, 'P 6 c c', transformations)
space_groups[184] = sg
space_groups['P 6 c c'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(185, 'P 63 c m', transformations)
space_groups[185] = sg
space_groups['P 63 c m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(186, 'P 63 m c', transformations)
space_groups[186] = sg
space_groups['P 63 m c'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(187, 'P -6 m 2', transformations)
space_groups[187] = sg
space_groups['P -6 m 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(188, 'P -6 c 2', transformations)
space_groups[188] = sg
space_groups['P -6 c 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(189, 'P -6 2 m', transformations)
space_groups[189] = sg
space_groups['P -6 2 m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(190, 'P -6 2 c', transformations)
space_groups[190] = sg
space_groups['P -6 2 c'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(191, 'P 6/m m m', transformations)
space_groups[191] = sg
space_groups['P 6/m m m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(192, 'P 6/m c c', transformations)
space_groups[192] = sg
space_groups['P 6/m c c'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(193, 'P 63/m c m', transformations)
space_groups[193] = sg
space_groups['P 63/m c m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(194, 'P 63/m m c', transformations)
space_groups[194] = sg
space_groups['P 63/m m c'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(195, 'P 2 3', transformations)
space_groups[195] = sg
space_groups['P 2 3'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(196, 'F 2 3', transformations)
space_groups[196] = sg
space_groups['F 2 3'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(197, 'I 2 3', transformations)
space_groups[197] = sg
space_groups['I 2 3'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(198, 'P 21 3', transformations)
space_groups[198] = sg
space_groups['P 21 3'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(199, 'I 21 3', transformations)
space_groups[199] = sg
space_groups['I 21 3'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(200, 'P m -3', transformations)
space_groups[200] = sg
space_groups['P m -3'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(201, 'P n -3 :2', transformations)
space_groups[201] = sg
space_groups['P n -3 :2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(202, 'F m -3', transformations)
space_groups[202] = sg
space_groups['F m -3'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([4,4,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([4,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([4,4,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([4,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([4,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([4,4,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([4,4,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([4,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([4,4,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([4,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([4,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([4,4,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,1])
trans_den = N.array([4,4,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,3,3])
trans_den = N.array([1,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([4,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,1])
trans_den = N.array([4,4,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([4,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,3,3])
trans_den = N.array([1,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,3,3])
trans_den = N.array([1,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([4,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,3,1])
trans_den = N.array([4,4,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([-1,1,1])
trans_den = N.array([4,4,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([-1,1,1])
trans_den = N.array([4,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([-1,1,1])
trans_den = N.array([4,4,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([-1,1,1])
trans_den = N.array([4,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,1,1])
trans_den = N.array([4,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,1,1])
trans_den = N.array([4,4,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([3,1,1])
trans_den = N.array([4,4,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([2,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([3,0,3])
trans_den = N.array([4,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([3,1,1])
trans_den = N.array([4,4,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([3,0,3])
trans_den = N.array([4,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([2,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([2,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([3,0,3])
trans_den = N.array([4,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([3,1,1])
trans_den = N.array([4,4,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,-1,1])
trans_den = N.array([4,4,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,-1,1])
trans_den = N.array([2,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([4,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,-1,1])
trans_den = N.array([4,4,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([4,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,-1,1])
trans_den = N.array([2,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,-1,1])
trans_den = N.array([2,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([4,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,-1,1])
trans_den = N.array([4,4,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([3,3,0])
trans_den = N.array([4,4,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,1])
trans_den = N.array([2,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([3,1,1])
trans_den = N.array([4,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([3,3,0])
trans_den = N.array([4,4,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([3,1,1])
trans_den = N.array([4,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,1])
trans_den = N.array([2,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,3,1])
trans_den = N.array([2,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([3,1,1])
trans_den = N.array([4,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([3,3,0])
trans_den = N.array([4,4,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([4,4,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,-1])
trans_den = N.array([2,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,-1])
trans_den = N.array([4,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([4,4,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,-1])
trans_den = N.array([4,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,-1])
trans_den = N.array([2,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,-1])
trans_den = N.array([2,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,-1])
trans_den = N.array([4,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([4,4,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(203, 'F d -3 :2', transformations)
space_groups[203] = sg
space_groups['F d -3 :2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(204, 'I m -3', transformations)
space_groups[204] = sg
space_groups['I m -3'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(205, 'P a -3', transformations)
space_groups[205] = sg
space_groups['P a -3'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(206, 'I a -3', transformations)
space_groups[206] = sg
space_groups['I a -3'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(207, 'P 4 3 2', transformations)
space_groups[207] = sg
space_groups['P 4 3 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(208, 'P 42 3 2', transformations)
space_groups[208] = sg
space_groups['P 42 3 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(209, 'F 4 3 2', transformations)
space_groups[209] = sg
space_groups['F 4 3 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([3,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([3,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([3,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([3,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([3,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([3,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([3,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([3,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([3,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([3,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([3,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([3,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([3,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([3,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([3,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([3,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([3,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([3,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([3,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([3,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([3,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([3,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([3,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([3,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(210, 'F 41 3 2', transformations)
space_groups[210] = sg
space_groups['F 41 3 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(211, 'I 4 3 2', transformations)
space_groups[211] = sg
space_groups['I 4 3 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([3,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([3,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([3,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([3,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([3,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([3,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(212, 'P 43 3 2', transformations)
space_groups[212] = sg
space_groups['P 43 3 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([3,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([3,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([3,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([3,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([3,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([3,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(213, 'P 41 3 2', transformations)
space_groups[213] = sg
space_groups['P 41 3 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([3,3,5])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([3,5,5])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([3,5,5])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([3,5,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([3,5,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([3,3,5])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([3,5,5])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([3,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([3,3,5])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([3,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([3,5,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([3,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(214, 'I 41 3 2', transformations)
space_groups[214] = sg
space_groups['I 41 3 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(215, 'P -4 3 m', transformations)
space_groups[215] = sg
space_groups['P -4 3 m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(216, 'F -4 3 m', transformations)
space_groups[216] = sg
space_groups['F -4 3 m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(217, 'I -4 3 m', transformations)
space_groups[217] = sg
space_groups['I -4 3 m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(218, 'P -4 3 n', transformations)
space_groups[218] = sg
space_groups['P -4 3 n'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(219, 'F -4 3 c', transformations)
space_groups[219] = sg
space_groups['F -4 3 c'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = | N.array([0,1,0]) | numpy.array |
import json
import multiprocessing
import warnings
from pathlib import PurePosixPath, Path
from typing import Optional, List, Tuple, Dict, Union
import numpy as np
import pandas as pd
from joblib._multiprocessing_helpers import mp
from rdkit import Chem
from rdkit.Chem import AllChem, Mol, MACCSkeys
from sklearn.feature_extraction import DictVectorizer
from sklearn.metrics import roc_auc_score
from tqdm import tqdm
from datasets.utils import process_map
def _init_molecule(molecule: Union[str, Mol, bytes]) -> Mol:
if isinstance(molecule, bytes):
mol = Mol(molecule)
elif isinstance(molecule, Mol):
mol = molecule
else:
mol = Chem.MolFromSmiles(molecule)
return mol
class ECFC_featurizer():
"""based on the implemenation provided by <NAME>"""
def __init__(self, radius=6, min_fragm_occur=50, useChirality=True, useFeatures=False):
self.v = DictVectorizer(sparse=True, dtype=np.uint16)
self.min_fragm_occur = min_fragm_occur
self.idx_col = None
self.radius = radius
self.useChirality = useChirality
self.useFeatures = useFeatures
def compute_fp_list(self, smiles_list):
fp_list = []
for smiles in smiles_list:
try:
if isinstance(smiles, list):
smiles = smiles[0]
mol = Chem.MolFromSmiles(smiles) # TODO small hack only applicable here!!!
fp_list.append(AllChem.GetMorganFingerprint(mol, self.radius, useChirality=self.useChirality,
useFeatures=self.useFeatures).GetNonzeroElements()) # returns a dict
except:
fp_list.append({})
return fp_list
def fit(self, x_train):
fp_list = self.compute_fp_list(x_train)
Xraw = self.v.fit_transform(fp_list)
idx_col = np.array((Xraw > 0).sum(axis=0) >= self.min_fragm_occur).flatten()
self.idx_col = idx_col
return Xraw[:, self.idx_col].toarray()
def transform(self, x_test):
fp_list = self.compute_fp_list(x_test)
X_raw = self.v.transform(fp_list)
return X_raw[:, self.idx_col].toarray()
class ECFPFeaturizer():
def __init__(self,
radius: int = 2,
fold: Optional[int] = None,
use_chirality: bool = True,
use_features: bool = True,
return_count: bool = True,
map_dict: Optional[dict] = None,
n_jobs: int = multiprocessing.cpu_count(),
mp_context: str = "spawn",
chunksize: int = None,
):
self.radius = radius
self.fold = fold
self.use_chirality = use_chirality
self.use_features = use_features
self.map_dict = map_dict
self.return_count = return_count
self.n_jobs = n_jobs
self.mp_context = mp_context
self.chunksize = chunksize
@property
def n_features(self) -> int:
if self.fold is None:
return len(self.map_dict) if self.map_dict else -1
else:
return self.fold
def _ecfp(self, smile: str) -> Union[Tuple[Dict, Dict, Mol], Tuple[None, None, None]]:
mol = Chem.MolFromSmiles(smile)
if mol is None:
warnings.warn(f"could not parse smile: {smile}")
return None, None, None
else:
bit_info = {}
fingerprint = AllChem.GetMorganFingerprint(mol, radius=self.radius, useChirality=self.use_chirality,
useFeatures=self.use_features, bitInfo=bit_info).GetNonzeroElements()
return fingerprint, bit_info, mol
def ecfp(self, smiles: List[str]) -> Tuple[List[dict], List[dict], List[Mol]]:
if self.n_jobs > 1:
fingerprints, bit_infos, mols = zip(
*process_map(
self._ecfp, smiles,
chunksize=(len(smiles) // self.n_jobs) + 1 if self.chunksize is None else self.chunksize,
# chunksize=1,
max_workers=self.n_jobs, desc="_ecfp",
mp_context=mp.get_context(self.mp_context)
)
)
else:
fingerprints, bit_infos, mols = zip(*list(map(self._ecfp, tqdm(smiles, total=len(smiles), desc="_ecfp"))))
return fingerprints, bit_infos, mols
def _fit(self, fingerprints: List[dict]):
if self.map_dict is None:
features = sorted(list(set.union(*[set(s.keys()) for s in fingerprints])))
if self.fold is None:
self.map_dict = dict(zip(features, range(len(features))))
else:
self.map_dict = {f: f % self.fold for f in features}
def fit_transform(self, smiles: List[str]) -> np.ndarray:
fingerprints, *_ = self.ecfp(smiles)
self._fit(fingerprints)
desc_mat = np.zeros((len(fingerprints), self.n_features), dtype=np.uint8)
for i, fp in enumerate(fingerprints):
for f, cnt in fp.items():
if f in self.map_dict:
desc_mat[i, self.map_dict[f]] = cnt
else:
warnings.warn(f"feature {f} not in map")
return desc_mat
def __call__(self, smiles: List[str]) -> np.ndarray:
features = self.fit_transform(smiles)
return features if self.return_count else np.where(features > 0, 1, 0).astype(features.dtype)
def _atomic_mapping(self,
molecule: Union[str, Mol, bytes],
num_atoms: Optional[int] = None,
bit_info: Optional[dict] = None
) -> List[List[Tuple[int, int]]]:
"""
gets the individual atomic mapping for one molecule - mapping indicates the feature idx + factor which contributes
"""
mol = _init_molecule(molecule)
num_atoms = mol.GetNumAtoms() if not num_atoms else num_atoms
if bit_info is None:
bit_info = {}
AllChem.GetMorganFingerprint(mol, radius=self.radius, useChirality=self.use_chirality, useFeatures=self.use_features,
bitInfo=bit_info)
atomic_mapping = [[] for _ in range(num_atoms)]
for feature, value in bit_info.items():
# feature mapping to account for e.g. folding
feature_idx = self.map_dict[feature]
for center_atom, radius in value:
mapping_submol = [[] for _ in range(num_atoms)]
count_atoms = 0
if radius > 0:
env_mol = Chem.FindAtomEnvironmentOfRadiusN(mol, radius, center_atom)
atom_map = {}
Chem.PathToSubmol(mol, env_mol, atomMap=atom_map)
for atom_k in atom_map.keys():
mapping_submol[atom_k].append(feature_idx)
count_atoms += 1
else:
mapping_submol[center_atom].append(feature_idx)
count_atoms = 1
for i in range(num_atoms):
if len(mapping_submol[i]) > 0:
for _feature_idx in mapping_submol[i]:
atomic_mapping[i].append((_feature_idx, count_atoms))
return atomic_mapping
def _atomic_attribution(self,
mol: Mol,
feature_attribution: np.ndarray,
num_atoms: Optional[int] = None,
bit_info: Optional[dict] = None) -> np.ndarray:
"""
gets the individual atomic contribution for one molecule based on the feature attribution
based and adapted from the implementation provided by <NAME>
"""
num_atoms = mol.GetNumAtoms() if not num_atoms else num_atoms
if bit_info is None:
bit_info = {}
AllChem.GetMorganFingerprint(mol, radius=self.radius, useChirality=self.use_chirality, useFeatures=self.use_features,
bitInfo=bit_info)
atomic_attribution = np.zeros(num_atoms)
for f, value in bit_info.items():
# feature mapping to account for e.g. folding
f = self.map_dict[f]
attribution_value = feature_attribution[f]
for center_atom, radius in value:
attribution_submol = np.zeros(num_atoms)
count_atoms = 0
if radius > 0:
env_mol = Chem.FindAtomEnvironmentOfRadiusN(mol, radius, center_atom)
atom_map = {}
Chem.PathToSubmol(mol, env_mol, atomMap=atom_map)
for atom_k in atom_map.keys():
attribution_submol[atom_k] += attribution_value
count_atoms += 1
else:
attribution_submol[center_atom] += attribution_value
count_atoms = 1
attribution_submol /= count_atoms
atomic_attribution += attribution_submol
return atomic_attribution
def atomic_attributions(self, smiles: List[str], feature_attributions: np.ndarray) -> List[np.ndarray]:
assert len(smiles) == len(
feature_attributions), f"provided number of smiles {len(smiles)} does not match number of features {len(feature_attributions)}"
fingerprints, bit_infos, mols = self.ecfp(smiles)
if self.map_dict is None:
self._fit(fingerprints)
atomic_attributions = []
for i, (smile, fingerprint, bit_info, mol) in tqdm(enumerate(zip(smiles, fingerprints, bit_infos, mols)), total=len(smiles),
desc="_ecfp_atomic_attributions"):
if mol is None:
raise ValueError(f"could not process smile/molecule {i}: {smile}")
atomic_attribution = self._atomic_attribution(mol, feature_attributions[i], bit_info=bit_info)
atomic_attributions.append(atomic_attribution)
return atomic_attributions
def atomic_mappings(self, smiles: List[str]) -> List[List[List[Tuple[int, int]]]]:
fingerprints, bit_infos, mols = self.ecfp(smiles)
if self.map_dict is None:
self._fit(fingerprints)
atomic_mappings = []
for i, (smile, fingerprint, bit_info, mol) in tqdm(enumerate(zip(smiles, fingerprints, bit_infos, mols)), total=len(smiles),
desc="_ecfp_atomic_mappings"):
if mol is None:
raise ValueError(f"could not process smile/molecule {i}: {smile}")
atomic_mapping = self._atomic_mapping(mol, bit_info=bit_info)
atomic_mappings.append(atomic_mapping)
return atomic_mappings
def _smarts_substr() -> Dict[int, Mol]:
with open(Path(PurePosixPath(__file__)).parent / "resources/maccs_smarts_substr.json") as file:
data = json.load(file)
return {int(k): Chem.MolFromSmarts(smile) for k, smile in data.items()}
class MACCSFeaturizer():
SMARTS_ATOMIC_NUMBER = {
2: [104], # atomic num >103 Not complete, RDKit only accepts up to #104
3: [32, 33, 34, 50, 51, 52, 82, 83, 84], # Group IVa,Va,VIa Rows 4-6
4: [89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103], # actinide
5: [21, 22, 39, 40, 72], # Group IIIB,IVB
6: [57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71], # Lanthanide
7: [23, 24, 25, 41, 42, 43, 73, 74, 75], # Group VB,VIB,VIIB
9: [26, 27, 28, 44, 45, 46, 76, 77, 78], # Group VIII
10: [4, 12, 20, 38, 56, 88], # Group II
12: [29, 30, 47, 48, 79, 80], # Group IB,IIB
18: [5, 13, 31, 49, 81], # Group III
27: [53], # I
29: [15], # P
35: [3, 11, 19, 37, 55, 87], # Group I
42: [9], # Fluor
46: [35], # Br
88: [16], # S
103: [17], # Cl
134: [9, 17, 35, 53] # Halogen: F,Cl,Br,I
}
SMARTS_SUBSTR = _smarts_substr()
def __init__(self, n_jobs: int = multiprocessing.cpu_count(), mp_context: str = "spawn", chunksize: int = None, ):
super(MACCSFeaturizer).__init__()
self.n_jobs = n_jobs
self.mp_context = mp_context
self.chunksize = chunksize
@property
def n_features(self) -> int:
return 167
def _macc(self, molecule: Union[str, Mol, bytes]) -> np.ndarray:
mol = _init_molecule(molecule)
_maccs = MACCSkeys.GenMACCSKeys(mol)
return np.array(_maccs)
def _maccs(self, smiles: List[str]) -> Tuple[np.ndarray, List[Mol]]:
maccs, mols = [], []
for i, smile in enumerate(tqdm(smiles, desc="_mol_maccs")):
mol = Chem.MolFromSmiles(smile)
mols.append(mol)
if mol is None:
warnings.warn(f"could not parse smile {i}: {smile}")
_mols = [m.ToBinary() for m in mols if m]
if self.n_jobs > 1:
maccs = process_map(self._macc, _mols,
chunksize=(len(smiles) // self.n_jobs) + 1 if self.chunksize is None else self.chunksize,
# chunksize=1,
max_workers=self.n_jobs,
desc="_maccs",
mp_context=mp.get_context(self.mp_context))
else:
maccs = list(map(self._macc, _mols))
return np.stack(maccs), mols
def __call__(self, smiles: List[str]) -> np.ndarray:
return self._maccs(smiles)[0]
def _atomic_mapping(self, molecule: Union[str, Mol, bytes],
num_atoms: Optional[int] = None) -> List[List[Tuple[int, int]]]:
mol = _init_molecule(molecule)
num_atoms = mol.GetNumAtoms() if not num_atoms else num_atoms
idx_maccs = list(MACCSFeaturizer.SMARTS_SUBSTR.keys())
idx_maccs_atomnumbs = list(MACCSFeaturizer.SMARTS_ATOMIC_NUMBER.keys())
atomic_attribution = np.zeros(num_atoms)
atomic_mapping = [[] for _ in range(num_atoms)]
for maccs_idx in idx_maccs:
# Substructure features
pattern = MACCSFeaturizer.SMARTS_SUBSTR[maccs_idx]
feature_idx = maccs_idx
substructures = mol.GetSubstructMatches(pattern)
mapping_submol = [[] for _ in range(num_atoms)]
count_atoms = 0
for atom_idx in range(num_atoms):
for structure in substructures:
if atom_idx in structure:
mapping_submol[atom_idx].append(feature_idx)
count_atoms += 1
count_atoms = 1 if count_atoms == 0 else count_atoms
for i in range(num_atoms):
if len(mapping_submol[i]) > 0:
for _feature_idx in mapping_submol[i]:
atomic_mapping[i].append((_feature_idx, count_atoms))
# Count features
# MACCS feature: 130
atomic_mapping = MACCSFeaturizer.maccs_count_features_mapping(maccs_idx, substructures, num_atoms,
atomic_mapping, feature_idx1=124,
feature_idx2=130)
# MACCS feature: 127
atomic_mapping = MACCSFeaturizer.maccs_count_features_mapping(maccs_idx, substructures, num_atoms,
atomic_mapping, feature_idx1=143,
feature_idx2=127)
# MACCS feature: 138:
atomic_mapping = MACCSFeaturizer.maccs_count_features_mapping(maccs_idx, substructures, num_atoms,
atomic_mapping, feature_idx1=153,
feature_idx2=138)
# MACCS features: 140, 146, 159
## 159
if maccs_idx == 164 and len(substructures) > 1:
mapping_submol = [[] for _ in range(num_atoms)]
count_atoms = 0
for atom_idx in range(num_atoms):
for structure in substructures:
if atom_idx in structure:
mapping_submol[atom_idx].append(159)
count_atoms += 1
count_atoms = 1 if count_atoms == 0 else count_atoms
for i in range(num_atoms):
if len(mapping_submol[i]) > 0:
for _feature_idx in mapping_submol[i]:
atomic_mapping[i].append((_feature_idx, count_atoms))
## 146
if len(substructures) > 2:
mapping_submol = [[] for _ in range(num_atoms)]
count_atoms = 0
for atom_idx in range(num_atoms):
for structure in substructures:
if atom_idx in structure:
mapping_submol[atom_idx].append(146)
count_atoms += 1
count_atoms = 1 if count_atoms == 0 else count_atoms
for i in range(num_atoms):
if len(mapping_submol[i]) > 0:
for _feature_idx in mapping_submol[i]:
atomic_mapping[i].append((_feature_idx, count_atoms))
## 140
if len(substructures) > 3:
mapping_submol = [[] for _ in range(num_atoms)]
count_atoms = 0
for atom_idx in range(num_atoms):
for structure in substructures:
if atom_idx in structure:
mapping_submol[atom_idx].append(140)
count_atoms += 1
count_atoms = 1 if count_atoms == 0 else count_atoms
for i in range(num_atoms):
if len(mapping_submol[i]) > 0:
for _feature_idx in mapping_submol[i]:
atomic_mapping[i].append((_feature_idx, count_atoms))
# MACCS feature 142
atomic_mapping = MACCSFeaturizer.maccs_count_features_mapping(maccs_idx, substructures, num_atoms,
atomic_mapping, feature_idx1=161,
feature_idx2=142)
# MACCS feature 145
atomic_mapping = MACCSFeaturizer.maccs_count_features_mapping(maccs_idx, substructures, num_atoms,
atomic_mapping, feature_idx1=163,
feature_idx2=145)
# MACCS feature 149
atomic_mapping = MACCSFeaturizer.maccs_count_features_mapping(maccs_idx, substructures, num_atoms,
atomic_mapping, feature_idx1=160,
feature_idx2=149)
# Atomic number features
for idx_maccs_atomnumb in idx_maccs_atomnumbs:
maccs_feature = MACCSFeaturizer.SMARTS_ATOMIC_NUMBER[idx_maccs_atomnumb]
feature_idx = idx_maccs_atomnumb
mapping_submol = [[] for _ in range(num_atoms)]
count_atoms = 0
for atom_idx in range(num_atoms):
if atom_idx in maccs_feature:
mapping_submol[atom_idx].append(feature_idx)
count_atoms += 1
count_atoms = 1 if count_atoms == 0 else count_atoms
for i in range(num_atoms):
if len(mapping_submol[i]) > 0:
for _feature_idx in mapping_submol[i]:
atomic_mapping[i].append((_feature_idx, count_atoms))
# MACCS 125: Aromatic rings
atomic_mapping = MACCSFeaturizer.maccs_125_aromaticrings_mapping(mol, num_atoms, atomic_mapping)
# MACCS 166: Fragments
atomic_mapping = MACCSFeaturizer.maccs_166_fragments_mapping(mol, num_atoms, atomic_mapping)
return atomic_mapping
def _atomic_attribution(self, molecule: Union[str, Mol, bytes], feature_attribution: np.ndarray,
num_atoms: Optional[int] = None) -> np.ndarray:
"""adapted/based on the implementation by <NAME>"""
mol = _init_molecule(molecule)
num_atoms = mol.GetNumAtoms() if not num_atoms else num_atoms
idx_maccs = list(MACCSFeaturizer.SMARTS_SUBSTR.keys())
idx_maccs_atomnumbs = list(MACCSFeaturizer.SMARTS_ATOMIC_NUMBER.keys())
atomic_attribution = np.zeros(num_atoms)
for maccs_idx in idx_maccs:
# Substructure features
pattern = MACCSFeaturizer.SMARTS_SUBSTR[maccs_idx]
attribution_value = feature_attribution[maccs_idx]
substructures = mol.GetSubstructMatches(pattern)
attribution_submol = np.zeros(num_atoms)
count_atoms = 0
for atom_idx in range(num_atoms):
for structure in substructures:
if atom_idx in structure:
attribution_submol[atom_idx] += attribution_value
count_atoms += 1
if count_atoms != 0:
attribution_submol = attribution_submol / count_atoms
atomic_attribution += attribution_submol
# Count features
# MACCS feature: 130
atomic_attribution = MACCSFeaturizer.maccs_count_features(maccs_idx, substructures, feature_attribution, num_atoms,
atomic_attribution,
feature_idx1=124, feature_idx2=130)
# MACCS feature: 127
atomic_attribution = MACCSFeaturizer.maccs_count_features(maccs_idx, substructures, feature_attribution, num_atoms,
atomic_attribution,
feature_idx1=143, feature_idx2=127)
# MACCS feature: 138:
atomic_attribution = MACCSFeaturizer.maccs_count_features(maccs_idx, substructures, feature_attribution, num_atoms,
atomic_attribution,
feature_idx1=153, feature_idx2=138)
# MACCS features: 140, 146, 159
## 159
if maccs_idx == 164 and len(substructures) > 1:
attribution_value = feature_attribution[159]
attribution_submol = np.zeros(num_atoms)
count_atoms = 0
for atom_idx in range(num_atoms):
for structure in substructures:
if atom_idx in structure:
attribution_submol[atom_idx] += attribution_value
count_atoms += 1
if count_atoms != 0:
attribution_submol = attribution_submol / count_atoms
atomic_attribution += attribution_submol
## 146
if len(substructures) > 2:
attribution_value = feature_attribution[146]
attribution_submol = np.zeros(num_atoms)
count_atoms = 0
for atom_idx in range(num_atoms):
for structure in substructures:
if atom_idx in structure:
attribution_submol[atom_idx] += attribution_value
count_atoms += 1
if count_atoms != 0:
attribution_submol = attribution_submol / count_atoms
atomic_attribution += attribution_submol
## 140
if len(substructures) > 3:
attribution_value = feature_attribution[140]
attribution_submol = np.zeros(num_atoms)
count_atoms = 0
for atom_idx in range(num_atoms):
for structure in substructures:
if atom_idx in structure:
attribution_submol[atom_idx] += attribution_value
count_atoms += 1
if count_atoms != 0:
attribution_submol = attribution_submol / count_atoms
atomic_attribution += attribution_submol
# MACCS feature 142
atomic_attribution = MACCSFeaturizer.maccs_count_features(maccs_idx, substructures, feature_attribution, num_atoms,
atomic_attribution,
feature_idx1=161, feature_idx2=142)
# MACCS feature 145
atomic_attribution = MACCSFeaturizer.maccs_count_features(maccs_idx, substructures, feature_attribution, num_atoms,
atomic_attribution,
feature_idx1=163, feature_idx2=145)
# MACCS feature 149
atomic_attribution = MACCSFeaturizer.maccs_count_features(maccs_idx, substructures, feature_attribution, num_atoms,
atomic_attribution,
feature_idx1=160, feature_idx2=149)
# Atomic number features
for idx_maccs_atomnumb in idx_maccs_atomnumbs:
maccs_feature = MACCSFeaturizer.SMARTS_ATOMIC_NUMBER[idx_maccs_atomnumb]
attribution_value = feature_attribution[idx_maccs_atomnumb]
attribution_submol = np.zeros(num_atoms)
count_atoms = 0
for atom_idx in range(num_atoms):
if atom_idx in maccs_feature:
attribution_submol[atom_idx] += attribution_value
count_atoms += 1
if count_atoms != 0:
attribution_submol = attribution_submol / count_atoms
atomic_attribution += attribution_submol
# MACCS 125: Aromatic rings
atomic_attribution = MACCSFeaturizer.maccs_125_aromaticrings(mol, feature_attribution, num_atoms, atomic_attribution)
# MACCS 166: Fragments
atomic_attribution = MACCSFeaturizer.maccs_166_fragments(mol, feature_attribution, num_atoms, atomic_attribution)
return atomic_attribution
def atomic_mappings(self, smiles: List[str]) -> List[List[List[Tuple[int, int]]]]:
_, mols = self._maccs(smiles)
_mols = [m.ToBinary() for m in mols if m]
if self.n_jobs > 1:
atomic_mappings = process_map(self._atomic_mapping, _mols,
chunksize=(len(smiles) // self.n_jobs) + 1 if self.chunksize is None else self.chunksize,
# chunksize=1,
max_workers=self.n_jobs,
desc="_maccs_atomic_mappings",
mp_context=mp.get_context(self.mp_context))
else:
atomic_mappings = list(
map(self._atomic_mapping, tqdm(_mols, total=len(smiles), desc="_maccs_atomic_mappings")))
return atomic_mappings
def atomic_attributions(self, smiles: List[str], feature_attributions: np.ndarray) -> List[np.ndarray]:
assert len(smiles) == len(
feature_attributions), f"provided number of smiles {len(smiles)} does not match number of features {len(feature_attributions)}"
_, mols = self._maccs(smiles)
_mols = [m.ToBinary() for m in mols if m]
if self.n_jobs > 1:
atomic_attributions = process_map(self._atomic_attribution, _mols, feature_attributions,
chunksize=(len(smiles) // self.n_jobs) + 1 if self.chunksize is None else self.chunksize,
# chunksize=1,
max_workers=self.n_jobs,
desc="_maccs_atomic_attributions",
mp_context=mp.get_context(self.mp_context))
else:
atomic_attributions = list(
map(self._atomic_attribution, tqdm(_mols, total=len(smiles), desc="_maccs_atomic_attributions"), feature_attributions))
return atomic_attributions
@staticmethod
def maccs_count_features_mapping(maccs_idx: int, substructures, num_atoms: int,
atomic_mapping: List[List[Tuple[int, int]]], feature_idx1: int, feature_idx2: int
) -> List[List[Tuple[int, int]]]:
if maccs_idx == feature_idx1 and len(substructures) > 1:
mapping_submol = [[] for _ in range(num_atoms)]
count_atoms = 0
for atom_idx in range(num_atoms):
for structure in substructures:
if atom_idx in structure:
mapping_submol[atom_idx].append(feature_idx2)
count_atoms += 1
count_atoms = 1 if count_atoms == 0 else count_atoms
for i in range(num_atoms):
if len(mapping_submol[i]) > 0:
for _feature_idx in mapping_submol[i]:
atomic_mapping[i].append((_feature_idx, count_atoms))
return atomic_mapping
@staticmethod
def maccs_count_features(maccs_idx: int, substructures, feature_attribution: np.ndarray, num_atoms: int, atomic_attribution: np.ndarray,
feature_idx1: int, feature_idx2: int) -> np.ndarray:
"""based on the implementation by <NAME>"""
if maccs_idx == feature_idx1 and len(substructures) > 1:
attribution_value = feature_attribution[feature_idx2]
weights_submol = np.zeros(num_atoms)
count_atoms = 0
for atom_idx in range(num_atoms):
for structure in substructures:
if atom_idx in structure:
weights_submol[atom_idx] += attribution_value
count_atoms += 1
if count_atoms != 0:
weights_submol = weights_submol / count_atoms
atomic_attribution += weights_submol
return atomic_attribution
@staticmethod
def isRingAromatic(mol: Mol, ringbond: Tuple[int, ...]) -> bool:
"""based on the implementation by <NAME>"""
for id in ringbond:
if not mol.GetBondWithIdx(id).GetIsAromatic():
return False
return True
@staticmethod
def maccs_125_aromaticrings_mapping(mol: Mol,
num_atoms: int, atomic_mapping: List[List[Tuple[int, int]]]):
substructure = list()
ri = mol.GetRingInfo()
ringcount = ri.NumRings()
rings = ri.AtomRings()
ringbonds = ri.BondRings()
if ringcount > 1:
for ring_idx in range(ringcount):
ring = rings[ring_idx]
ringbond = ringbonds[ring_idx]
is_aromatic = MACCSFeaturizer.isRingAromatic(mol, ringbond)
if is_aromatic == True:
substructure.append(ring)
mapping_submol = [[] for _ in range(num_atoms)]
count_atoms = 0
for atom_idx in range(num_atoms):
for structure in substructure:
if atom_idx in structure:
mapping_submol[atom_idx].append(125)
count_atoms += 1
count_atoms = 1 if count_atoms == 0 else count_atoms
for i in range(num_atoms):
if len(mapping_submol[i]) > 0:
for _feature_idx in mapping_submol[i]:
atomic_mapping[i].append((_feature_idx, count_atoms))
return atomic_mapping
@staticmethod
def maccs_125_aromaticrings(mol: Mol, feature_attribution: np.ndarray, num_atoms: int, atomic_attribution: np.ndarray) -> np.ndarray:
"""based on the implementation by <NAME>"""
attribution_value = feature_attribution[125]
substructure = list()
ri = mol.GetRingInfo()
ringcount = ri.NumRings()
rings = ri.AtomRings()
ringbonds = ri.BondRings()
if ringcount > 1:
for ring_idx in range(ringcount):
ring = rings[ring_idx]
ringbond = ringbonds[ring_idx]
is_aromatic = MACCSFeaturizer.isRingAromatic(mol, ringbond)
if is_aromatic == True:
substructure.append(ring)
weights_submol = np.zeros(num_atoms)
count_atoms = 0
for atom_idx in range(num_atoms):
for structure in substructure:
if atom_idx in structure:
weights_submol[atom_idx] += attribution_value
count_atoms += 1
if count_atoms != 0:
weights_submol = weights_submol / count_atoms
atomic_attribution += weights_submol
return atomic_attribution
@staticmethod
def maccs_166_fragments_mapping(mol: Mol, num_atoms: int, atomic_mapping: List[List[Tuple[int, int]]]) -> List[
List[Tuple[int, int]]]:
frags = Chem.GetMolFrags(mol)
if len(frags) > 1:
mapping_submol = [[] for _ in range(num_atoms)]
count_atoms = 0
for atom_idx in range(num_atoms):
for structure in frags:
if atom_idx in structure:
mapping_submol[atom_idx].append(166)
count_atoms += 1
count_atoms = 1 if count_atoms == 0 else count_atoms
for i in range(num_atoms):
if len(mapping_submol[i]) > 0:
for _feature_idx in mapping_submol[i]:
atomic_mapping[i].append((_feature_idx, count_atoms))
return atomic_mapping
@staticmethod
def maccs_166_fragments(mol: Mol, feature_attribution: np.ndarray, num_atoms: int, atomic_attribution: np.ndarray) -> np.ndarray:
"""based on the implementation by <NAME>"""
attribution_value = feature_attribution[166]
frags = Chem.GetMolFrags(mol)
if len(frags) > 1:
weights_submol = np.zeros(num_atoms)
count_atoms = 0
for atom_idx in range(num_atoms):
for structure in frags:
if atom_idx in structure:
weights_submol[atom_idx] += attribution_value
count_atoms += 1
if count_atoms != 0:
weights_submol = weights_submol / count_atoms
atomic_attribution += weights_submol
return atomic_attribution
def _all_patterns():
"""based/adapted on the implementation by <NAME>"""
with open(Path(PurePosixPath(__file__)).parent / "resources/tox_smarts.json") as file:
smarts_list = [s[1] for s in json.load(file)]
# Code does not work for this case
assert len([s for s in smarts_list if ("AND" in s) and ("OR" in s)]) == 0
# Chem.MolFromSmarts takes a long time so it pays of to parse all the smarts first
# and then use them for all molecules. This gives a huge speedup over existing code.
# a list of patterns, whether to negate the match result and how to join them to obtain one boolean value
all_patterns = []
for smarts in smarts_list:
patterns = [] # list of smarts-patterns
# value for each of the patterns above. Negates the values of the above later.
negations = []
if " AND " in smarts:
smarts = smarts.split(" AND ")
merge_any = False # If an " AND " is found all "subsmarts" have to match
else:
# If there is an " OR " present it"s enough is any of the "subsmarts" match.
# This also accumulates smarts where neither " OR " nor " AND " occur
smarts = smarts.split(" OR ")
merge_any = True
# for all subsmarts check if they are preceded by "NOT "
for s in smarts:
neg = s.startswith("NOT ")
if neg:
s = s[4:]
patterns.append(Chem.MolFromSmarts(s))
negations.append(neg)
all_patterns.append((patterns, negations, merge_any))
return all_patterns
class ToxFeaturizer():
ALL_PATTERNS = _all_patterns()
def __init__(self, n_jobs: int = multiprocessing.cpu_count(), mp_context: str = "spawn", chunksize: int = None, ):
super(ToxFeaturizer, self).__init__()
self.n_jobs = n_jobs
self.mp_context = mp_context
self.chunksize = chunksize
@property
def n_features(self) -> int:
return 826
def _tox(self, molecule: Union[str, Mol, bytes]) -> np.ndarray:
"""
based/adapted on the implementation by <NAME>
Matches the tox patterns against a molecule. Returns a boolean array
"""
mol = _init_molecule(molecule)
mol_features = []
for patts, negations, merge_any in ToxFeaturizer.ALL_PATTERNS:
matches = [mol.HasSubstructMatch(p) for p in patts]
matches = [m != n for m, n in zip(matches, negations)]
if merge_any:
pres = any(matches)
else:
pres = all(matches)
mol_features.append(pres)
return np.array(mol_features)
def _toxs(self, smiles: List[str]) -> Tuple[np.ndarray, List[Mol]]:
toxs, mols = [], []
for i, smile in enumerate(tqdm(smiles, desc="_mols_toxs")):
mol = Chem.MolFromSmiles(smile)
mols.append(mol)
if mol is None:
warnings.warn(f"could not parse smile {i}: {smile}")
_mols = [m.ToBinary() for m in mols if m]
if self.n_jobs > 1:
toxs = process_map(self._tox, _mols,
chunksize=(len(smiles) // self.n_jobs) + 1 if self.chunksize is None else self.chunksize,
# chunksize=1,
max_workers=self.n_jobs,
desc="_toxs",
mp_context=mp.get_context(self.mp_context))
else:
toxs = list(map(self._tox, _mols))
return np.stack([t for t in toxs if not None]), mols
def __call__(self, smiles: List[str]) -> np.ndarray:
"""returns a binary numpy array"""
return self._toxs(smiles)[0]
def _atomic_mapping(self,
molecule: Union[str, Mol, bytes],
num_atoms: Optional[int] = None,
) -> List[List[Tuple[int, int]]]:
"""
gets the individual atomic mapping for one molecule - mapping indicates the feature idx + factor which contributes
"""
mol = _init_molecule(molecule)
num_atoms = mol.GetNumAtoms() if not num_atoms else num_atoms
atomic_mapping = [[] for _ in range(num_atoms)]
for feature_idx, (patts, negations, merge_any) in enumerate(ToxFeaturizer.ALL_PATTERNS):
mapping_submol = [[] for _ in range(num_atoms)]
count_atoms = 0
for atom_idx in range(num_atoms):
for i in range(len(negations)):
neg = negations[i]
pattern = patts[i]
substructures = mol.GetSubstructMatches(pattern)
for structure in substructures:
atom_in_sub = list()
if str(neg) == "False":
if atom_idx in structure:
atom_in_sub.append("y")
elif str(neg) == "True":
if atom_idx not in structure:
atom_in_sub.append("y")
if "y" in str(atom_in_sub):
mapping_submol[atom_idx].append(feature_idx)
count_atoms += 1
if count_atoms != 0:
for i in range(num_atoms):
if len(mapping_submol[i]) > 0:
for _feature_idx in mapping_submol[i]:
atomic_mapping[i].append((_feature_idx, count_atoms))
return atomic_mapping
def _atomic_attribution(self, molecule: Union[str, Mol, bytes], feature_attribution: np.ndarray,
num_atoms: Optional[int] = None) -> np.ndarray:
"""adapted/based on the implementation by <NAME>"""
mol = _init_molecule(molecule)
num_atoms = mol.GetNumAtoms() if not num_atoms else num_atoms
atomic_attribution = np.zeros(num_atoms)
tox_idx = 0
for patts, negations, merge_any in ToxFeaturizer.ALL_PATTERNS:
attribution_value = feature_attribution[tox_idx]
attribution_submol = np.zeros(num_atoms)
count_atoms = 0
for atom_idx in range(num_atoms):
for i in range(len(negations)):
neg = negations[i]
pattern = patts[i]
substructures = mol.GetSubstructMatches(pattern)
for structure in substructures:
atom_in_sub = list()
if str(neg) == "False":
if atom_idx in structure:
atom_in_sub.append("y")
elif str(neg) == "True":
if atom_idx not in structure:
atom_in_sub.append("y")
if "y" in str(atom_in_sub):
attribution_submol[atom_idx] += attribution_value
count_atoms += 1
if count_atoms != 0:
attribution_submol = attribution_submol / count_atoms
atomic_attribution += attribution_submol
tox_idx += 1
return atomic_attribution
def atomic_attributions(self, smiles: List[str], feature_attributions: np.ndarray) -> List[np.ndarray]:
assert len(smiles) == len(
feature_attributions), f"provided number of smiles {len(smiles)} does not match number of features {len(feature_attributions)}"
_, mols = self._toxs(smiles)
_mols = [m.ToBinary() for m in mols if m]
if self.n_jobs > 1:
atomic_attributions = process_map(self._atomic_attribution, _mols, feature_attributions,
chunksize=(len(smiles) // self.n_jobs) + 1 if self.chunksize is None else self.chunksize,
# chunksize=1,
max_workers=self.n_jobs,
desc="_tox_atomic_attributions",
mp_context=mp.get_context(self.mp_context))
else:
atomic_attributions = list(
map(self._atomic_attribution, tqdm(_mols, total=len(smiles), desc="_tox_atomic_attributions"), feature_attributions))
return atomic_attributions
def atomic_mappings(self, smiles: List[str]) -> List[List[List[Tuple[int, int]]]]:
_, mols = self._toxs(smiles)
_mols = [m.ToBinary() for m in mols if m]
if self.n_jobs > 1:
atomic_mappings = process_map(self._atomic_mapping, _mols,
chunksize=(len(smiles) // self.n_jobs) + 1 if self.chunksize is None else self.chunksize,
# chunksize=1,
max_workers=self.n_jobs,
desc="_tox_atomic_mappings",
mp_context=mp.get_context(self.mp_context))
else:
atomic_mappings = list(
map(self._atomic_mapping, tqdm(_mols, total=len(smiles), desc="_tox_atomic_mappings")))
return atomic_mappings
def _atomic_attribution_from_mapping(atomic_mapping: List[List[Tuple[int, int]]], feature_attribution: np.ndarray) -> np.ndarray:
"""calculate atomic attribution for single molecule based on provided mapping and features attributions"""
num_atoms = len(atomic_mapping)
atomic_attribution = np.zeros(num_atoms)
for atom_idx, atom_map in enumerate(atomic_mapping):
for feature_idx, count_atoms in atom_map:
atomic_attribution[atom_idx] += feature_attribution[feature_idx] * 1 / count_atoms
return atomic_attribution
def atomic_attributions_from_mappings(atomic_mappings: List[List[List[Tuple[int, int]]]],
feature_attributions: np.ndarray,
n_jobs: int = multiprocessing.cpu_count(),
mp_context: str = "fork",
chunksize: int = None) -> List[np.ndarray]:
"""calculate atomic attributions for multiple molecules based on provided mappings and features attributions"""
if n_jobs > 1:
atomic_attributions = process_map(_atomic_attribution_from_mapping, atomic_mappings, feature_attributions,
chunksize=(len(atomic_mappings) // n_jobs) + 1 if chunksize is None else chunksize,
max_workers=n_jobs,
desc="_attributions_from_atomic_mappings",
mp_context=mp.get_context(mp_context))
else:
atomic_attributions = list(
map(_atomic_attribution_from_mapping,
tqdm(atomic_mappings, total=len(atomic_mappings), desc="_attributions_from_atomic_mappings"), feature_attributions))
return atomic_attributions
def calculate_ranking_scores(smiles: List[str],
references: Union[List[str], List[Tuple[str, int]]],
atomic_attributions: List[np.ndarray],
labels: Optional[np.ndarray] = None,
preds: Optional[np.ndarray] = None,
) -> Tuple[Dict, List[Dict], pd.DataFrame]:
"""
Function calculates the score to rank atoms of reference smiles/atomic substructures according to the provided atomic attribution/weights
Args:
smiles (): List of smile strings
references (): List of tuples of provided reference smiles and if they are supposed to be active or not
Scores are calculated per reference smile
atomic_attributions (): List of atomic attributions/weights
labels (): Optional provide binary true labels
preds (): Optional provide binary predictions
Returns:
Tuple containing
- Dictionary of mean calculated scores for all provided reference smiles
- List of dictionaries per reference score with mean scores per reference smile
- Dataframe containing table with full details per smile and per reference smile with all matches, scores, etc.
"""
assert len(smiles) == len(
atomic_attributions), f"length of provided smiles {len(smiles)} must match length of provided attributions {len(atomic_attributions)}"
if labels is not None:
assert labels.ndim == 1, f"nr of dimensions of provided labels must be 1 but is {labels.ndim}"
assert len(labels) == len(smiles), f"nr of labels {len(labels)} must match number of smiles {len(smiles)}"
if preds is not None:
assert preds.ndim == 1, f"nr of dimensions of provided predictions must be 1 but is {preds.ndim}"
assert len(preds) == len(smiles), f"nr of predictions {len(preds)} must match number of smiles {len(smiles)}"
df = pd.DataFrame()
df["smile"] = smiles
if labels is not None:
df["label"] = labels
if preds is not None:
df["pred"] = preds
# TODO rewrite loops for performance + add multiprocessing
reference_results = []
for reference in tqdm(references):
if isinstance(reference, tuple):
reference_smile, reference_active = reference
reference_active = "active" if reference_active == 1 else "inactive"
else:
reference_smile = reference
reference_active = None
reference_mol = Chem.MolFromSmiles(reference_smile)
atom_matches, reference_attributions = [], []
scores = []
for i, smile in enumerate(smiles):
mol = Chem.MolFromSmiles(smile)
num_atoms = mol.GetNumAtoms()
match = mol.GetSubstructMatch(reference_mol)
if match:
reference_atoms = [1 if i in match else 0 for i in range(num_atoms)]
if not np.isnan(atomic_attributions[i]).any(): # failsafe check
# score to rank atoms according to reference atom using the corresponding attributions
score = roc_auc_score(reference_atoms, atomic_attributions[i])
scores.append(score)
else:
warnings.warn(f"encountered nan atomic attribution for smile {smile}")
scores.append(float("nan"))
atom_matches.append(str(reference_atoms))
else:
scores.append(float("nan"))
atom_matches.append("n/a")
reference_attributions.append(str(atomic_attributions[i]))
scores = np.array(scores)
matches = np.array([0 if m == "n/a" else 1 for m in atom_matches])
reference_result = {
"avg_score": | np.nanmean(scores) | numpy.nanmean |
# -*- coding: utf8 -*-
import numpy as np
from tensorflow.examples.tutorials.mnist import input_data
import csv
from sklearn.preprocessing import normalize
def load_data(path,shuffle=False):
mnist = input_data.read_data_sets(path, one_hot=True)
trainX = mnist.train.images # ndarray
trainY = mnist.train.labels
trainY = trainY.astype('float32')
valX = mnist.validation.images
valY = mnist.validation.labels
valY = valY.astype('float32')
testX = mnist.test.images
testY = mnist.test.labels
testY = testY.astype('float32')
if shuffle:
r = np.random.permutation(len(trainY))
trainX = trainX[r,:]
trainY = trainY[r,:]
r = np.random.permutation(len(valY))
valX = valX[r,:]
valY = valY[r,:]
r = np.random.permutation(len(testY))
testX = testX[r,:]
testY = testY[r,:]
return trainX, trainY, valX, valY, testX, testY
def load_data_batch(path,start=0,batch_size=None,shuffle=False):
if batch_size == None:
X = np.load("./" + path).astype(np.float32)[:, :, :, None]
else:
X = np.load("./" + path).astype(np.float32)[start:start+batch_size, :]
X = X/255
if len(X.shape)>2:
X = np.reshape(X,[X.shape[0],X.shape[1]*X.shape[2]])
if shuffle:
r = np.random.permutation(X.shape[0])
X = X[r,:]
trainX = X
return trainX
def load_data_zi(path,shuffle=False,val_ratio=0.8):
X = np.load("./" + path + "/jg.npy").astype(np.float32)[:, :, :, None] # 2994*80*80,没有归一化
# X = np.load("./"+path+"/simsun80.npy").astype(np.float32)[:,:,:,None] # 2994*80*80,没有归一化
X = X/255
X = np.reshape(X,[X.shape[0],X.shape[1]*X.shape[2]])
trainX = X[:np.round(val_ratio*X.shape[0])]
valX = X[np.round(val_ratio * X.shape[0]):]
return trainX, valX
def load_goods_data(train_ratio = 0.9, shuffle=True, use_cat = True):
X=np.loadtxt(open("./data/goods_vectors_new.csv","rb"),delimiter=",",skiprows=0)
if use_cat:
X = X[:,3:] # 前3列是id,后15列是one-hot的分类信息
else:
Y = X[:, -15:]
X = X[:, 3:-15]
nan_loc = np.argwhere(np.isnan(X))
if len(nan_loc)>0:
X = np.delete(X,nan_loc[0],axis=0)
X = normalize(X,axis=1)
if shuffle:
idx = np.random.permutation(X.shape[0])
X = X[idx,:]
Y = Y[idx,:]
else :
idx = range(len(X))
trainX = X[:np.round(train_ratio * X.shape[0])]
trainidx = idx[:np.round(train_ratio * X.shape[0])]
trainY = Y[: | np.round(train_ratio * X.shape[0]) | numpy.round |
import numpy as np
import numpy.linalg as npl
import numpy.random as npr
import scipy.linalg as spl
import scipy.optimize as spo
import scipy.sparse as sps
from time import time
from geom import Geom
from bc import BC
from darcy import DarcyExp
from dasa import DASAExpLM
from se_kernel import SEKernel
def compute_Lreg(geom):
Nc = geom.cells.num
Nfint = np.sum(geom.faces.is_interior)
neighbors = geom.faces.neighbors[:,geom.faces.is_interior]
rows = np.concatenate((np.arange(Nfint), np.arange(Nfint)))
cols = | np.concatenate((neighbors[0], neighbors[1])) | numpy.concatenate |
import h5py
import numpy as np
class FileProvider:
"""Helper class to read hdf5 files."""
def __init__(self,
file_path:str,
modality:str,
seq_length:int = None):
""" Initialize class object.
Args:
file_path (str): Path to `hdf5` file to read.
modality (str): Modality to read data.
seq_length (int): Number of consecutive frames to provide.
"""
self.modality = modality
self.file_path = file_path
self.num_calls = 0
self.num_samples = self._get_num_samples()
self.num_seqs = self._get_num_sequences()
self.seq_length = self.num_seqs if seq_length == None else seq_length
self.total_num_calls = np.ceil(self.num_seqs / self.seq_length).astype(int)
def _get_num_samples(self, key:str = 'num_samples'):
""" Returns the number of samples in the file.
Stored in file as attribute with name `num_samples`.
"""
with h5py.File(self.file_path, 'r') as dataset:
num_samples = dataset.attrs[key]
print(num_samples)
return num_samples
def h5py_dataset_iterator(self, g, prefix=''):
for key in g.keys():
item = g[key]
path = '{}/{}'.format(prefix, key)
if isinstance(item, h5py.Dataset): # test for dataset
yield (path, item)
elif isinstance(item, h5py.Group): # test for group (go down)
yield from h5py_dataset_iterator(item, path)
def _get_num_sequences(self, key:str = 'seq_num'):
""" Returns the number of sequences in the file.
Stored in file as attribute with name `seq_num`.
"""
with h5py.File(self.file_path, 'r') as dataset:
num_samples = dataset.attrs[key]
print(num_samples)
with h5py.File(self.file_path, 'r') as f:
for (path, dset) in self.h5py_dataset_iterator(f):
print(path, dset)
return num_samples
def _get_label_names(self, key:str = 'label_names'):
""" Returns the names of the labels.
Stored in file as attribute with name `label_names`.
"""
with h5py.File(self.file_path, 'r') as dataset:
label_names = dataset.attrs[key]
return label_names
def reset(self):
""" Reset the parameter needed to re-read the data.
Performed Uusually after each epoch.
"""
self.num_calls = 0
def total_calls_reached(self):
""" Checks whether all data were read."""
return self.total_num_calls == self.num_calls
def __get_data(self, dataset:h5py.File, start:int, end:int):
""" Reads and returns the requested data.
Args:
dataset (h5py.File): File to get data from.
start (int): Start frame of sequence.
end (int): End frame of sequence.
"""
if isinstance(self.modality, list):
return [np.array(dataset[x][start:end]) for x in self.modality]
else:
return | np.array(dataset[self.modality][start:end]) | numpy.array |
'''
episodestats.py
implements statistic that are used in producing employment statistics for the
lifecycle model
'''
import h5py
import numpy as np
import numpy_financial as npf
import matplotlib.pyplot as plt
import matplotlib as mpl
import seaborn as sns
from scipy.stats import norm
#import locale
from tabulate import tabulate
import pandas as pd
import scipy.optimize
from tqdm import tqdm_notebook as tqdm
from . empstats import Empstats
from scipy.stats import gaussian_kde
#locale.setlocale(locale.LC_ALL, 'fi_FI')
def modify_offsettext(ax,text):
'''
For y axis
'''
x_pos = 0.0
y_pos = 1.0
horizontalalignment='left'
verticalalignment='bottom'
offset = ax.yaxis.get_offset_text()
#value=offset.get_text()
# value=float(value)
# if value>=1e12:
# text='biljoonaa'
# elif value>1e9:
# text=str(value/1e9)+' miljardia'
# elif value==1e9:
# text=' miljardia'
# elif value>1e6:
# text=str(value/1e6)+' miljoonaa'
# elif value==1e6:
# text='miljoonaa'
# elif value>1e3:
# text=str(value/1e3)+' tuhatta'
# elif value==1e3:
# text='tuhatta'
offset.set_visible(False)
ax.text(x_pos, y_pos, text, transform=ax.transAxes,
horizontalalignment=horizontalalignment,
verticalalignment=verticalalignment)
class Labels():
def get_labels(self,language='English'):
labels={}
if language=='English':
labels['osuus tilassa x']='Proportion in state {} [%]'
labels['age']='Age [y]'
labels['ratio']='Proportion [%]'
labels['unemp duration']='Length of unemployment [y]'
labels['scaled freq']='Scaled frequency'
labels['probability']='probability'
labels['telp']='Employee pension premium'
labels['sairausvakuutus']='Health insurance'
labels['työttömyysvakuutusmaksu']='Unemployment insurance'
labels['puolison verot']='Partners taxes'
labels['taxes']='Taxes'
labels['asumistuki']='Housing benefit'
labels['toimeentulotuki']='Supplementary benefit'
labels['tyottomyysturva']='Unemployment benefit'
labels['paivahoito']='Daycare'
labels['elake']='Pension'
labels['tyollisyysaste']='Employment rate'
labels['tyottomien osuus']='Proportion of unemployed'
labels['havainto']='Observation'
labels['tyottomyysaste']='Unemployment rate [%]'
labels['tyottomien osuus']='Proportion of unemployed [%]'
labels['tyollisyysaste %']='Employment rate [%]'
labels['ero osuuksissa']='Difference in proportions [%]'
labels['osuus']='proportion'
labels['havainto, naiset']='data, women'
labels['havainto, miehet']='data, men'
labels['palkkasumma']='Palkkasumma [euroa]'
labels['Verokiila %']='Verokiila [%]'
labels['Työnteko [hlö/htv]']='Työnteko [hlö/htv]'
labels['Työnteko [htv]']='Työnteko [htv]'
labels['Työnteko [hlö]']='Työnteko [hlö]'
labels['Työnteko [miljoonaa hlö/htv]']='Työnteko [miljoonaa hlö/htv]'
labels['Työnteko [miljoonaa htv]']='Työnteko [miljoonaa htv]'
labels['Työnteko [miljoonaa hlö]']='Työnteko [miljoonaa hlö]'
labels['Osatyönteko [%-yks]']='Osa-aikatyössä [%-yks]'
labels['Muut tulot [euroa]']='Muut tulot [euroa]'
labels['Henkilöitä']='Henkilöitä'
labels['Verot [euroa]']='Verot [euroa]'
labels['Verot [[miljardia euroa]']='Verot [[miljardia euroa]'
labels['Verokertymä [euroa]']='Verokertymä [euroa]'
labels['Verokertymä [miljardia euroa]']='Verokertymä [miljardia euroa]'
labels['Muut tarvittavat tulot [euroa]']='Muut tarvittavat tulot [euroa]'
labels['Muut tarvittavat tulot [miljardia euroa]']='Muut tarvittavat tulot [miljardia euroa]'
labels['malli']='Life cycle model'
else:
labels['osuus tilassa x']='Osuus tilassa {} [%]'
labels['age']='Ikä [v]'
labels['ratio']='Osuus tilassa [%]'
labels['unemp duration']='työttömyysjakson pituus [v]'
labels['scaled freq']='skaalattu taajuus'
labels['probability']='todennäköisyys'
labels['telp']='TEL-P'
labels['sairausvakuutus']='Sairausvakuutus'
labels['työttömyysvakuutusmaksu']='Työttömyysvakuutusmaksu'
labels['puolison verot']='puolison verot'
labels['taxes']='Verot'
labels['asumistuki']='Asumistuki'
labels['toimeentulotuki']='Toimeentulotuki'
labels['tyottomyysturva']='Työttömyysturva'
labels['paivahoito']='Päivähoito'
labels['elake']='Eläke'
labels['tyollisyysaste']='työllisyysaste'
labels['tyottomien osuus']='työttömien osuus'
labels['havainto']='havainto'
labels['tyottomyysaste']='Työttömyysaste [%]'
labels['tyottomien osuus']='Työttömien osuus väestöstö [%]'
labels['tyollisyysaste %']='Työllisyysaste [%]'
labels['ero osuuksissa']='Ero osuuksissa [%]'
labels['osuus']='Osuus'
labels['havainto, naiset']='havainto, naiset'
labels['havainto, miehet']='havainto, miehet'
labels['palkkasumma']='Palkkasumma [euroa]'
labels['Verokiila %']='Verokiila [%]'
labels['Työnteko [hlö/htv]']='Työnteko [hlö/htv]'
labels['Työnteko [htv]']='Työnteko [htv]'
labels['Työnteko [hlö]']='Työnteko [hlö]'
labels['Työnteko [miljoonaa hlö/htv]']='Työnteko [miljoonaa hlö/htv]'
labels['Työnteko [miljoonaa htv]']='Työnteko [miljoonaa htv]'
labels['Työnteko [miljoonaa hlö]']='Työnteko [miljoonaa hlö]'
labels['Osatyönteko [%-yks]']='Osa-aikatyössä [%-yks]'
labels['Muut tulot [euroa]']='Muut tulot [euroa]'
labels['Henkilöitä']='Henkilöitä'
labels['Verot [euroa]']='Verot [euroa]'
labels['Verot [[miljardia euroa]']='Verot [[miljardia euroa]'
labels['Verokertymä [euroa]']='Verokertymä [euroa]'
labels['Verokertymä [miljardia euroa]']='Verokertymä [miljardia euroa]'
labels['Muut tarvittavat tulot [euroa]']='Muut tarvittavat tulot [euroa]'
labels['Muut tarvittavat tulot [miljardia euroa]']='Muut tarvittavat tulot [miljardia euroa]'
labels['malli']='elinkaarimalli'
return labels
class EpisodeStats():
def __init__(self,timestep,n_time,n_emps,n_pop,env,minimal,min_age,max_age,min_retirementage,year=2018,version=3,params=None,gamma=0.92,lang='English'):
self.version=version
self.gamma=gamma
self.params=params
self.lab=Labels()
self.reset(timestep,n_time,n_emps,n_pop,env,minimal,min_age,max_age,min_retirementage,year,params=params,lang=lang)
print('version',version)
def reset(self,timestep,n_time,n_emps,n_pop,env,minimal,min_age,max_age,min_retirementage,year,version=None,params=None,lang=None,dynprog=False):
self.min_age=min_age
self.max_age=max_age
self.min_retirementage=min_retirementage
self.minimal=minimal
if params is not None:
self.params=params
if lang is None:
self.language='English'
else:
self.language=lang
if version is not None:
self.version=version
self.setup_labels()
self.n_employment=n_emps
self.n_time=n_time
self.timestep=timestep # 0.25 = 3kk askel
self.inv_timestep=int(np.round(1/self.timestep)) # pitää olla kokonaisluku
self.n_pop=n_pop
self.year=year
self.env=env
self.reaalinen_palkkojenkasvu=0.016
self.palkkakerroin=(0.8*1+0.2*1.0/(1+self.reaalinen_palkkojenkasvu))**self.timestep
self.elakeindeksi=(0.2*1+0.8*1.0/(1+self.reaalinen_palkkojenkasvu))**self.timestep
self.dynprog=dynprog
if self.minimal:
self.version=0
if self.version in set([0,101]):
self.n_groups=1
else:
self.n_groups=6
self.empstats=Empstats(year=self.year,max_age=self.max_age,n_groups=self.n_groups,timestep=self.timestep,n_time=self.n_time,
min_age=self.min_age)
self.init_variables()
def init_variables(self):
n_emps=self.n_employment
self.empstate=np.zeros((self.n_time,n_emps))
self.gempstate=np.zeros((self.n_time,n_emps,self.n_groups))
self.deceiced=np.zeros((self.n_time,1))
self.alive=np.zeros((self.n_time,1))
self.galive=np.zeros((self.n_time,self.n_groups))
self.rewstate=np.zeros((self.n_time,n_emps))
self.poprewstate=np.zeros((self.n_time,self.n_pop))
self.salaries_emp=np.zeros((self.n_time,n_emps))
#self.salaries=np.zeros((self.n_time,self.n_pop))
self.actions=np.zeros((self.n_time,self.n_pop))
self.popempstate=np.zeros((self.n_time,self.n_pop))
self.popunemprightleft=np.zeros((self.n_time,self.n_pop))
self.popunemprightused=np.zeros((self.n_time,self.n_pop))
self.tyoll_distrib_bu=np.zeros((self.n_time,self.n_pop))
self.unemp_distrib_bu=np.zeros((self.n_time,self.n_pop))
self.siirtyneet=np.zeros((self.n_time,n_emps))
self.siirtyneet_det=np.zeros((self.n_time,n_emps,n_emps))
self.pysyneet=np.zeros((self.n_time,n_emps))
self.aveV=np.zeros((self.n_time,self.n_pop))
self.time_in_state=np.zeros((self.n_time,n_emps))
self.stat_tyoura=np.zeros((self.n_time,n_emps))
self.stat_toe=np.zeros((self.n_time,n_emps))
self.stat_pension=np.zeros((self.n_time,n_emps))
self.stat_paidpension=np.zeros((self.n_time,n_emps))
self.out_of_work=np.zeros((self.n_time,n_emps))
self.stat_unemp_len=np.zeros((self.n_time,self.n_pop))
self.stat_wage_reduction=np.zeros((self.n_time,n_emps))
self.stat_wage_reduction_g=np.zeros((self.n_time,n_emps,self.n_groups))
self.infostats_group=np.zeros((self.n_pop,1))
self.infostats_taxes=np.zeros((self.n_time,1))
self.infostats_wagetaxes=np.zeros((self.n_time,1))
self.infostats_taxes_distrib=np.zeros((self.n_time,n_emps))
self.infostats_etuustulo=np.zeros((self.n_time,1))
self.infostats_etuustulo_group=np.zeros((self.n_time,self.n_groups))
self.infostats_perustulo=np.zeros((self.n_time,1))
self.infostats_palkkatulo=np.zeros((self.n_time,1))
self.infostats_palkkatulo_eielakkeella=np.zeros((self.n_time,1))
self.infostats_palkkatulo_group=np.zeros((self.n_time,self.n_groups))
self.infostats_palkkatulo_eielakkeella_group=np.zeros((self.n_time,1))
self.infostats_ansiopvraha=np.zeros((self.n_time,1))
self.infostats_ansiopvraha_group=np.zeros((self.n_time,self.n_groups))
self.infostats_asumistuki=np.zeros((self.n_time,1))
self.infostats_asumistuki_group=np.zeros((self.n_time,self.n_groups))
self.infostats_valtionvero=np.zeros((self.n_time,1))
self.infostats_valtionvero_group=np.zeros((self.n_time,self.n_groups))
self.infostats_kunnallisvero=np.zeros((self.n_time,1))
self.infostats_kunnallisvero_group=np.zeros((self.n_time,self.n_groups))
self.infostats_valtionvero_distrib=np.zeros((self.n_time,n_emps))
self.infostats_kunnallisvero_distrib=np.zeros((self.n_time,n_emps))
self.infostats_ptel=np.zeros((self.n_time,1))
self.infostats_tyotvakmaksu=np.zeros((self.n_time,1))
self.infostats_tyoelake=np.zeros((self.n_time,1))
self.infostats_kokoelake=np.zeros((self.n_time,1))
self.infostats_opintotuki=np.zeros((self.n_time,1))
self.infostats_isyyspaivaraha=np.zeros((self.n_time,1))
self.infostats_aitiyspaivaraha=np.zeros((self.n_time,1))
self.infostats_kotihoidontuki=np.zeros((self.n_time,1))
self.infostats_sairauspaivaraha=np.zeros((self.n_time,1))
self.infostats_toimeentulotuki=np.zeros((self.n_time,1))
self.infostats_tulot_netto=np.zeros((self.n_time,1))
self.infostats_pinkslip=np.zeros((self.n_time,n_emps))
self.infostats_pop_pinkslip=np.zeros((self.n_time,self.n_pop))
self.infostats_chilren18_emp=np.zeros((self.n_time,n_emps))
self.infostats_chilren7_emp=np.zeros((self.n_time,n_emps))
self.infostats_chilren18=np.zeros((self.n_time,1))
self.infostats_chilren7=np.zeros((self.n_time,1))
self.infostats_tyelpremium=np.zeros((self.n_time,self.n_pop))
self.infostats_paid_tyel_pension=np.zeros((self.n_time,self.n_pop))
self.infostats_sairausvakuutus=np.zeros((self.n_time))
self.infostats_pvhoitomaksu=np.zeros((self.n_time,self.n_pop))
self.infostats_ylevero=np.zeros((self.n_time,1))
self.infostats_ylevero_distrib=np.zeros((self.n_time,n_emps))
self.infostats_irr=np.zeros((self.n_pop,1))
self.infostats_npv0=np.zeros((self.n_pop,1))
self.infostats_mother_in_workforce=np.zeros((self.n_time,1))
self.infostats_children_under3=np.zeros((self.n_time,self.n_pop))
self.infostats_children_under7=np.zeros((self.n_time,self.n_pop))
self.infostats_unempwagebasis=np.zeros((self.n_time,self.n_pop))
self.infostats_unempwagebasis_acc=np.zeros((self.n_time,self.n_pop))
self.infostats_toe=np.zeros((self.n_time,self.n_pop))
self.infostats_ove=np.zeros((self.n_time,n_emps))
self.infostats_kassanjasen=np.zeros((self.n_time))
self.infostats_poptulot_netto=np.zeros((self.n_time,self.n_pop))
self.infostats_pop_wage=np.zeros((self.n_time,self.n_pop))
self.infostats_pop_pension=np.zeros((self.n_time,self.n_pop))
self.infostats_equivalent_income=np.zeros(self.n_time)
self.infostats_alv=np.zeros(self.n_time)
self.infostats_puoliso=np.zeros(self.n_time)
self.pop_predrew=np.zeros((self.n_time,self.n_pop))
if self.version==101:
self.infostats_savings=np.zeros((self.n_time,self.n_pop))
self.sav_actions=np.zeros((self.n_time,self.n_pop))
def add(self,n,act,r,state,newstate,q=None,debug=False,plot=False,aveV=None,pred_r=None):
if self.version==0:
emp,_,_,a,_,_=self.env.state_decode(state) # current employment state
newemp,newpen,newsal,a2,tis,next_wage=self.env.state_decode(newstate)
g=0
bu=0
ove=0
jasen=0
puoliso=0
elif self.version==1:
# v1
emp,_,_,_,a,_,_,_,_,_,_,_,_,_=self.env.state_decode(state) # current employment state
newemp,g,newpen,newsal,a2,tis,paidpens,pink,toe,ura,oof,bu,wr,p=self.env.state_decode(newstate)
ove=0
jasen=0
puoliso=0
elif self.version==2:
# v2
emp,_,_,_,a,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_=self.env.state_decode(state) # current employment state
newemp,g,newpen,newsal,a2,tis,paidpens,pink,toe,ura,bu,wr,upr,uw,uwr,pr,c3,c7,c18,unemp_left,aa,toe58=self.env.state_decode(newstate)
ove=0
jasen=0
puoliso=0
elif self.version==3:
# v3
emp,_,_,_,a,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_=self.env.state_decode(state) # current employment state
newemp,g,newpen,newsal,a2,tis,paidpens,pink,toe,toek,ura,bu,wr,upr,uw,uwr,pr,c3,c7,c18,unemp_left,aa,toe58,ove,jasen=self.env.state_decode(newstate)
puoliso=0
elif self.version==4:
# v3
emp,_,_,_,a,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_=self.env.state_decode(state) # current employment state
newemp,g,newpen,newsal,a2,tis,paidpens,pink,toe,toek,ura,bu,wr,upr,uw,uwr,pr,\
c3,c7,c18,unemp_left,aa,toe58,ove,jasen,puoliso,puoliso_tyossa,puoliso_palkka=self.env.state_decode(newstate)
elif self.version==101:
emp,_,_,a,_,_,_=self.env.state_decode(state) # current employment state
newemp,newpen,newsal,a2,tis,next_wage,savings=self.env.state_decode(newstate)
g=0
bu=0
ove=0
jasen=0
t=int(np.round((a2-self.min_age)*self.inv_timestep))#-1
if a2>a and newemp>=0: # new state is not reset (age2>age)
if a2>self.min_retirementage and newemp==3 and self.version in set([1,2,3,4]):
newemp=2
if self.version in set([1,2,3,4]):
self.empstate[t,newemp]+=1
self.alive[t]+=1
self.rewstate[t,newemp]+=r
self.poprewstate[t,n]=r
self.actions[t,n]=act
self.popempstate[t,n]=newemp
#self.salaries[t,n]=newsal
self.salaries_emp[t,newemp]+=newsal
self.time_in_state[t,newemp]+=tis
if tis<=0.25 and newemp==5:
self.infostats_mother_in_workforce[t]+=1
self.infostats_pinkslip[t,newemp]+=pink
self.infostats_pop_pinkslip[t,n]=pink
self.gempstate[t,newemp,g]+=1
self.stat_wage_reduction[t,newemp]+=wr
self.stat_wage_reduction_g[t,newemp,g]+=wr
self.galive[t,g]+=1
self.stat_tyoura[t,newemp]+=ura
self.stat_toe[t,newemp]+=toe
self.stat_pension[t,newemp]+=newpen
self.stat_paidpension[t,newemp]+=paidpens
self.stat_unemp_len[t,n]=tis
self.popunemprightleft[t,n]=-self.env.unempright_left(newemp,tis,bu,a2,ura)
self.popunemprightused[t,n]=bu
self.infostats_group[n]=int(g)
self.infostats_unempwagebasis[t,n]=uw
self.infostats_unempwagebasis_acc[t,n]=uwr
self.infostats_toe[t,n]=toe
self.infostats_ove[t,newemp]+=ove
self.infostats_kassanjasen[t]+=jasen
self.infostats_pop_wage[t,n]=newsal
self.infostats_pop_pension[t,n]=newpen
self.infostats_puoliso[t]+=puoliso
if q is not None:
#print(newsal,q['palkkatulot'])
self.infostats_taxes[t]+=q['verot']*self.timestep*12
self.infostats_wagetaxes[t]+=q['verot_ilman_etuuksia']*self.timestep*12
self.infostats_taxes_distrib[t,newemp]+=q['verot']*self.timestep*12
self.infostats_etuustulo[t]+=q['etuustulo_brutto']*self.timestep*12
self.infostats_etuustulo_group[t,g]+=q['etuustulo_brutto']*self.timestep*12
self.infostats_perustulo[t]+=q['perustulo']*self.timestep*12
self.infostats_palkkatulo[t]+=q['palkkatulot']*self.timestep*12
self.infostats_palkkatulo_eielakkeella[t]+=q['palkkatulot_eielakkeella']*self.timestep*12
self.infostats_ansiopvraha[t]+=q['ansiopvraha']*self.timestep*12
self.infostats_asumistuki[t]+=q['asumistuki']*self.timestep*12
self.infostats_valtionvero[t]+=q['valtionvero']*self.timestep*12
self.infostats_valtionvero_distrib[t,newemp]+=q['valtionvero']*self.timestep*12
self.infostats_kunnallisvero[t]+=q['kunnallisvero']*self.timestep*12
self.infostats_kunnallisvero_distrib[t,newemp]+=q['kunnallisvero']*self.timestep*12
self.infostats_ptel[t]+=q['ptel']*self.timestep*12
self.infostats_tyotvakmaksu[t]+=q['tyotvakmaksu']*self.timestep*12
self.infostats_tyoelake[t]+=q['elake_maksussa']*self.timestep*12
self.infostats_kokoelake[t]+=q['kokoelake']*self.timestep*12
self.infostats_opintotuki[t]+=q['opintotuki']*self.timestep*12
self.infostats_isyyspaivaraha[t]+=q['isyyspaivaraha']*self.timestep*12
self.infostats_aitiyspaivaraha[t]+=q['aitiyspaivaraha']*self.timestep*12
self.infostats_kotihoidontuki[t]+=q['kotihoidontuki']*self.timestep*12
self.infostats_sairauspaivaraha[t]+=q['sairauspaivaraha']*self.timestep*12
self.infostats_toimeentulotuki[t]+=q['toimtuki']*self.timestep*12
self.infostats_tulot_netto[t]+=q['kateen']*self.timestep*12
self.infostats_tyelpremium[t,n]=q['tyel_kokomaksu']*self.timestep*12
self.infostats_paid_tyel_pension[t,n]=q['puhdas_tyoelake']*self.timestep*12
self.infostats_sairausvakuutus[t]+=q['sairausvakuutus']*self.timestep*12
self.infostats_pvhoitomaksu[t,n]=q['pvhoito']*self.timestep*12
self.infostats_ylevero[t]+=q['ylevero']*self.timestep*12
self.infostats_ylevero_distrib[t,newemp]=q['ylevero']*self.timestep*12
self.infostats_poptulot_netto[t,n]=q['kateen']*self.timestep*12
self.infostats_children_under3[t,n]=c3
self.infostats_children_under7[t,n]=c7
self.infostats_npv0[n]=q['multiplier']
self.infostats_equivalent_income[t]+=q['eq']
if 'alv' in q:
self.infostats_alv[t]+=q['alv']
#self.infostats_kassanjasen[t]+=1
elif self.version in set([0,101]):
self.empstate[t,newemp]+=1
self.alive[t]+=1
self.rewstate[t,newemp]+=r
self.infostats_tulot_netto[t]+=q['netto'] # already at annual level
self.infostats_poptulot_netto[t,n]=q['netto']
self.poprewstate[t,n]=r
self.popempstate[t,n]=newemp
#self.salaries[t,n]=newsal
self.salaries_emp[t,newemp]+=newsal
self.time_in_state[t,newemp]+=tis
self.infostats_equivalent_income[t]+=q['eq']
self.infostats_pop_wage[t,n]=newsal
self.infostats_pop_pension[t,n]=newpen
if self.dynprog and pred_r is not None:
self.pop_predrew[t,n]=pred_r
if self.version==101:
self.infostats_savings[t,n]=savings
self.actions[t,n]=act[0]
self.sav_actions[t,n]=act[1]
else:
self.actions[t,n]=act
# if self.version in set([1,2,3]):
# self.gempstate[t,newemp,g]+=1
# self.stat_wage_reduction[t,newemp]+=wr
# self.galive[t,g]+=1
# self.stat_tyoura[t,newemp]+=ura
# self.stat_toe[t,newemp]+=toe
# self.stat_pension[t,newemp]+=newpen
# self.stat_paidpension[t,newemp]+=paidpens
# self.stat_unemp_len[t,n]=tis
# self.popunemprightleft[t,n]=0
# self.popunemprightused[t,n]=0
if aveV is not None:
self.aveV[t,n]=aveV
if not emp==newemp:
self.siirtyneet[t,emp]+=1
self.siirtyneet_det[t,emp,newemp]+=1
else:
self.pysyneet[t,emp]+=1
elif newemp<0:
self.deceiced[t]+=1
def scale_error(self,x,target=None,averaged=False):
return (target-self.comp_scaled_consumption(x,averaged=averaged))
def comp_employed_ratio_by_age(self,emp=None,grouped=False,g=0):
if emp is None:
if grouped:
emp=np.squeeze(self.gempstate[:,:,g])
else:
emp=self.empstate
nn=np.sum(emp,1)
if self.minimal:
tyoll_osuus=(emp[:,1]+emp[:,3])/nn
htv_osuus=(emp[:,1]+0.5*emp[:,3])/nn
tyoll_osuus=np.reshape(tyoll_osuus,(tyoll_osuus.shape[0],1))
htv_osuus=np.reshape(htv_osuus,(htv_osuus.shape[0],1))
else:
# työllisiksi lasketaan kokoaikatyössä olevat, osa-aikaiset, ve+työ, ve+osatyö
# isyysvapaalla olevat jötetty pois, vaikka vapaa kestöö alle 3kk
tyoll_osuus=(emp[:,1]+emp[:,8]+emp[:,9]+emp[:,10])
htv_osuus=(emp[:,1]+0.5*emp[:,8]+emp[:,9]+0.5*emp[:,10])
tyoll_osuus=np.reshape(tyoll_osuus,(tyoll_osuus.shape[0],1))
htv_osuus=np.reshape(htv_osuus,(htv_osuus.shape[0],1))
return tyoll_osuus,htv_osuus
def comp_employed_aggregate(self,emp=None,start=20,end=63.5,grouped=False,g=0):
if emp is None:
if grouped:
emp=self.gempstate[:,:,g]
else:
emp=self.empstate
nn=np.sum(emp,1)
if self.minimal:
tyoll_osuus=(emp[:,1]+emp[:,3])/nn
htv_osuus=(emp[:,1]+0.5*emp[:,3])/nn
else:
# työllisiksi lasketaan kokoaikatyössä olevat, osa-aikaiset, ve+työ, ve+osatyö
# isyysvapaalla olevat jötetty pois, vaikka vapaa kestöö alle 3kk
tyoll_osuus=(emp[:,1]+emp[:,8]+emp[:,9]+emp[:,10])/nn
htv_osuus=(emp[:,1]+0.5*emp[:,8]+emp[:,9]+0.5*emp[:,10])/nn
htv_osuus=self.comp_state_stats(htv_osuus,start=start,end=end,ratio=True)
tyoll_osuus=self.comp_state_stats(tyoll_osuus,start=start,end=end,ratio=True)
return tyoll_osuus,htv_osuus
def comp_group_ps(self):
return self.comp_palkkasumma(grouped=True)
def comp_palkkasumma(self,start=19,end=68,grouped=False,scale_time=True):
demog2=self.empstats.get_demog()
if scale_time:
scale=self.timestep
else:
scale=1.0
min_cage=self.map_age(start)
max_cage=self.map_age(end)+1
if grouped:
scalex=demog2/self.n_pop*self.timestep
ps=np.zeros((self.n_time,6))
ps_norw=np.zeros((self.n_time,6))
a_ps=np.zeros(6)
a_ps_norw=np.zeros(6)
for k in range(self.n_pop):
g=int(self.infostats_group[k,0])
for t in range(min_cage,max_cage):
e=int(self.popempstate[t,k])
if e in set([1,10]):
ps[t,g]+=self.infostats_pop_wage[t,k]
ps_norw[t,g]+=self.infostats_pop_wage[t,k]
elif e in set([8,9]):
ps[t,g]+=self.infostats_pop_wage[t,k]*self.timestep
for g in range(6):
a_ps[g]=np.sum(scalex[min_cage:max_cage]*ps[min_cage:max_cage,g])
a_ps_norw[g]=np.sum(scalex[min_cage:max_cage]*ps_norw[min_cage:max_cage,g])
else:
scalex=demog2/self.n_pop*self.timestep
ps=np.zeros((self.n_time,1))
ps_norw=np.zeros((self.n_time,1))
for k in range(self.n_pop):
for t in range(min_cage,max_cage):
e=int(self.popempstate[t,k])
if e in set([1,10]):
ps[t,0]+=self.infostats_pop_wage[t,k]
ps_norw[t,0]+=self.infostats_pop_wage[t,k]
elif e in set([8,9]):
ps[t,0]+=self.infostats_pop_wage[t,k]
a_ps=np.sum(scalex[min_cage:max_cage]*ps[min_cage:max_cage])
a_ps_norw=np.sum(scalex[min_cage:max_cage]*ps_norw[min_cage:max_cage])
return a_ps,a_ps_norw
def comp_stats_agegroup(self,border=[19,35,50]):
n_groups=len(border)
low=border.copy()
high=border.copy()
high[0:n_groups-1]=border[1:n_groups]
high[-1]=65
employed=np.zeros(n_groups)
unemployed=np.zeros(n_groups)
ahtv=np.zeros(n_groups)
parttimeratio=np.zeros(n_groups)
unempratio=np.zeros(n_groups)
empratio=np.zeros(n_groups)
i_ps=np.zeros(n_groups)
i_ps_norw=np.zeros(n_groups)
for n in range(n_groups):
l=low[n]
h=high[n]
htv,tyollvaikutus,tyollaste,tyotosuus,tyottomat,osatyollaste=\
self.comp_tyollisyys_stats(self.empstate,scale_time=True,start=l,end=h,agegroups=True)
ps,ps_norw=self.comp_palkkasumma(start=l,end=h)
print(f'l {l} h {h}\nhtv {htv}\ntyollaste {tyollaste}\ntyotosuus {tyotosuus}\ntyottomat {tyottomat}\nosatyollaste {osatyollaste}\nps {ps}')
employed[n]=tyollvaikutus
ahtv[n]=htv
unemployed[n]=tyottomat
unempratio[n]=tyotosuus
empratio[n]=tyollaste
parttimeratio[n]=osatyollaste
i_ps[n]=ps
i_ps_norw[n]=ps_norw
return employed,ahtv,unemployed,parttimeratio,i_ps,i_ps_norw,unempratio,empratio
def comp_unemployed_ratio_by_age(self,emp=None,grouped=False,g=0):
if emp is None:
if grouped:
emp=self.gempstate[:,:,g]
else:
emp=self.empstate
nn=np.sum(emp,1)
if self.minimal:
tyot_osuus=emp[:,0]/nn
tyot_osuus=np.reshape(tyot_osuus,(tyot_osuus.shape[0],1))
else:
# työllisiksi lasketaan kokoaikatyössä olevat, osa-aikaiset, ve+työ, ve+osatyö
# isyysvapaalla olevat jötetty pois, vaikka vapaa kestöö alle 3kk
tyot_osuus=(emp[:,0]+emp[:,4]+emp[:,13])[:,None]
#tyot_osuus=np.reshape(tyot_osuus,(tyot_osuus.shape[0],1))
return tyot_osuus
def comp_unemployed_aggregate(self,emp=None,start=20,end=63.5,scale_time=True,grouped=False,g=0):
if emp is None:
if grouped:
emp=self.gempstate[:,:,g]
else:
emp=self.empstate
nn=np.sum(emp,1)
if self.minimal:
tyot_osuus=emp[:,0]/nn
else:
tyot_osuus=(emp[:,0]+emp[:,4]+emp[:,13])/nn
#print(f'tyot_osuus {tyot_osuus}')
unemp=self.comp_state_stats(tyot_osuus,start=start,end=end,ratio=True)
return unemp
def comp_parttime_aggregate(self,emp=None,start=20,end=63.5,scale_time=True,grouped=False,g=0):
'''
Lukumäärätiedot (EI HTV!)
'''
if emp is None:
if grouped:
emp=self.gempstate[:,:,g]
else:
emp=self.empstate
nn=np.sum(emp,1)
if not self.minimal:
tyossa=(emp[:,1]+emp[:,10]+emp[:,8]+emp[:,9])/nn
osatyossa=(emp[:,10]+emp[:,8])/nn
else:
tyossa=emp[:,1]/nn
osatyossa=0*tyossa
osatyo_osuus=osatyossa/tyossa
osatyo_osuus=self.comp_state_stats(osatyo_osuus,start=start,end=end,ratio=True)
kokotyo_osuus=1-osatyo_osuus
return kokotyo_osuus,osatyo_osuus
def comp_parttime_ratio_by_age(self,emp=None,grouped=False,g=0):
if emp is None:
if grouped:
emp=self.gempstate[:,:,g]
else:
emp=self.empstate
nn=np.sum(emp,1)
if self.minimal:
kokotyo_osuus=(emp[:,1])/nn
osatyo_osuus=(emp[:,3])/nn
else:
if grouped:
for g in range(6):
kokotyo_osuus=(emp[:,1,g]+emp[:,9,g])/nn
osatyo_osuus=(emp[:,8,g]+emp[:,10,g])/nn
else:
kokotyo_osuus=(emp[:,1]+emp[:,9])/nn
osatyo_osuus=(emp[:,8]+emp[:,10])/nn
osatyo_osuus=np.reshape(osatyo_osuus,(osatyo_osuus.shape[0],1))
kokotyo_osuus=np.reshape(kokotyo_osuus,(osatyo_osuus.shape[0],1))
return kokotyo_osuus,osatyo_osuus
def comp_employed_ratio(self,emp):
tyoll_osuus,htv_osuus=self.comp_employed_ratio_by_age(emp)
tyot_osuus=self.comp_unemployed_ratio_by_age(emp)
kokotyo_osuus,osatyo_osuus=self.comp_parttime_ratio_by_age(emp)
return tyoll_osuus,htv_osuus,tyot_osuus,kokotyo_osuus,osatyo_osuus
def comp_unemployed_detailed(self,emp):
if self.minimal:
ansiosid_osuus=emp[:,0]/np.sum(emp,1)
tm_osuus=ansiosid_osuus*0
else:
# työllisiksi lasketaan kokoaikatyössä olevat, osa-aikaiset, ve+työ, ve+osatyö
# isyysvapaalla olevat jötetty pois, vaikka vapaa kestöö alle 3kk
ansiosid_osuus=(emp[:,0]+emp[:,4])/np.sum(emp,1)
tm_osuus=(emp[:,13])/np.sum(emp,1)
return ansiosid_osuus,tm_osuus
def comp_tyollisyys_stats(self,emp,scale_time=True,start=19,end=68,full=False,tyot_stats=False,agg=False,shapes=False,only_groups=False,g=0,agegroups=False):
demog2=self.empstats.get_demog()
if scale_time:
scale=self.timestep
else:
scale=1.0
min_cage=self.map_age(start)
max_cage=self.map_age(end)+1
scalex=demog2[min_cage:max_cage]/self.n_pop*scale
if only_groups:
tyollosuus,htvosuus,tyot_osuus,kokotyo_osuus,osatyo_osuus=self.comp_employed_ratio(emp)
else:
tyollosuus,htvosuus,tyot_osuus,kokotyo_osuus,osatyo_osuus=self.comp_employed_ratio(emp)
htv=np.sum(scalex*htvosuus[min_cage:max_cage])
tyollvaikutus=np.sum(scalex*tyollosuus[min_cage:max_cage])
tyottomat=np.sum(scalex*tyot_osuus[min_cage:max_cage])
osatyollvaikutus=np.sum(scalex*osatyo_osuus[min_cage:max_cage])
kokotyollvaikutus=np.sum(scalex*kokotyo_osuus[min_cage:max_cage])
haj=np.mean(np.std(tyollosuus[min_cage:max_cage]))
tyollaste=tyollvaikutus/(np.sum(scalex)*self.n_pop)
osatyollaste=osatyollvaikutus/(kokotyollvaikutus+osatyollvaikutus)
kokotyollaste=kokotyollvaikutus/(kokotyollvaikutus+osatyollvaikutus)
if tyot_stats:
if agg:
#d2=np.squeeze(demog2)
tyolliset_osuus=np.squeeze(tyollosuus)
tyottomat_osuus=np.squeeze(tyot_osuus)
return tyolliset_ika,tyottomat_ika,htv_ika,tyolliset_osuus,tyottomat_osuus
else:
d2=np.squeeze(demog2)
tyolliset_ika=np.squeeze(scale*d2*np.squeeze(htvosuus))
tyottomat_ika=np.squeeze(scale*d2*np.squeeze(tyot_osuus))
htv_ika=np.squeeze(scale*d2*np.squeeze(htvosuus))
tyolliset_osuus=np.squeeze(tyollosuus)
tyottomat_osuus=np.squeeze(tyot_osuus)
return tyolliset_ika,tyottomat_ika,htv_ika,tyolliset_osuus,tyottomat_osuus
elif full:
return htv,tyollvaikutus,haj,tyollaste,tyollosuus,osatyollvaikutus,kokotyollvaikutus,osatyollaste,kokotyollaste
elif agegroups:
tyot_osuus=self.comp_unemployed_aggregate(start=start,end=end)
return htv,tyollvaikutus,tyollaste,tyot_osuus,tyottomat,osatyollaste
else:
return htv,tyollvaikutus,haj,tyollaste,tyollosuus
def comp_employment_stats(self,scale_time=True,returns=False):
demog2=self.empstats.get_demog()
if scale_time:
scale=self.timestep
else:
scale=1.0
min_cage=self.map_age(self.min_age)
max_cage=self.map_age(self.max_age)+1
scalex=np.squeeze(demog2/self.n_pop*self.timestep)
d=np.squeeze(demog2[min_cage:max_cage])
self.ratiostates=self.empstate/self.alive
self.demogstates=(self.empstate.T*scalex).T
if self.minimal>0:
self.stats_employed=self.demogstates[:,0]+self.demogstates[:,3]
self.stats_parttime=self.demogstates[:,3]
self.stats_unemployed=self.demogstates[:,0]
self.stats_all=np.sum(self.demogstates,1)
else:
self.stats_employed=self.demogstates[:,0]+self.demogstates[:,10]+self.demogstates[:,8]+self.demogstates[:,9]
self.stats_parttime=self.demogstates[:,10]+self.demogstates[:,8]
self.stats_unemployed=self.demogstates[:,0]+self.demogstates[:,4]+self.demogstates[:,13]
self.stats_all=np.sum(self.demogstates,1)
if returns:
return self.stats_employed,self.stats_parttime,self.stats_unemployed
# def test_emp(self):
# g_emp=0
# g_htv=0
# g_10=0
# g_1=0
# g_8=0
# g_9=0
# g_x=0
# scalex=1
#
# demog2=self.empstats.get_demog()
# scalex=np.squeeze(demog2/self.n_pop*self.timestep)
#
#
# for g in range(6):
# q=self.comp_participants(grouped=True,g=g)
# #g_1+=np.sum(self.gempstate[:,1,g])
# #g_10+=np.sum(self.gempstate[:,10,g])
# #g_8+=np.sum(self.gempstate[:,8,g])
# #g_9+=np.sum(self.gempstate[:,9,g])
# g_emp+=q['palkansaajia']
# g_htv+=q['htv']
# g_x+=np.sum((self.gempstate[:,1,g]+self.gempstate[:,10,g])*scalex)
#
# q=self.comp_participants()
# s_1=np.sum(self.empstate[:,1])
# s_10=np.sum(self.empstate[:,10])
# s_8=np.sum(self.empstate[:,8])
# s_9=np.sum(self.empstate[:,9])
# s_x=np.sum((self.empstate[:,1]+self.empstate[:,10])*scalex)
# emp=q['palkansaajia']
# htv=q['htv']
#
# print(f'htv {htv} vs g_htv {g_htv}')
# print(f'emp {emp} vs g_emp {g_emp}')
# print(f's_x {s_x} vs g_x {g_x}')
# #print(f's_1 {s_1} vs g_1 {g_1}')
# #print(f's_10 {s_10} vs g_10 {g_10}')
# #print(f's_8 {s_8} vs g_8 {g_8}')
# #print(f's_9 {s_9} vs g_9 {g_9}')
def comp_participants(self,scale=True,include_retwork=True,grouped=False,g=0):
'''
<NAME> lkm
scalex olettaa, että naisia & miehiä yhtä paljon. Tämän voisi tarkentaa.
'''
demog2=self.empstats.get_demog()
scalex=np.squeeze(demog2/self.n_pop*self.timestep)
#print('version',self.version)
q={}
if self.version in set([1,2,3,4]):
if grouped:
#print('group=',g)
emp=np.squeeze(self.gempstate[:,:,g])
q['yhteensä']=np.sum(np.sum(emp,axis=1)*scalex)
if include_retwork:
q['palkansaajia']=np.sum((emp[:,1]+emp[:,10]+emp[:,8]+emp[:,9])*scalex)
q['htv']=np.sum((emp[:,1]+0.5*emp[:,10]+0.5*emp[:,8]+emp[:,9])*scalex)
else:
q['palkansaajia']=np.sum((emp[:,1]+emp[:,10])*scalex)
q['htv']=np.sum((emp[:,1]+0.5*emp[:,10])*scalex)
q['ansiosidonnaisella']=np.sum((emp[:,0]+emp[:,4])*scalex)
q['tmtuella']=np.sum(emp[:,13]*scalex)
q['isyysvapaalla']=np.sum(emp[:,6]*scalex)
q['kotihoidontuella']=np.sum(emp[:,7]*scalex)
q['vanhempainvapaalla']=np.sum(emp[:,5]*scalex)
else:
q['yhteensä']=np.sum(np.sum(self.empstate[:,:],axis=1)*scalex)
if include_retwork:
q['palkansaajia']=np.sum((self.empstate[:,1]+self.empstate[:,10]+self.empstate[:,8]+self.empstate[:,9])*scalex)
q['htv']=np.sum((self.empstate[:,1]+0.5*self.empstate[:,10]+0.5*self.empstate[:,8]+self.empstate[:,9])*scalex)
else:
q['palkansaajia']=np.sum((self.empstate[:,1]+self.empstate[:,10])*scalex)
q['htv']=np.sum((self.empstate[:,1]+0.5*self.empstate[:,10])*scalex)
q['ansiosidonnaisella']=np.sum((self.empstate[:,0]+self.empstate[:,4])*scalex)
q['tmtuella']=np.sum(self.empstate[:,13]*scalex)
q['isyysvapaalla']=np.sum(self.empstate[:,6]*scalex)
q['kotihoidontuella']=np.sum(self.empstate[:,7]*scalex)
q['vanhempainvapaalla']=np.sum(self.empstate[:,5]*scalex)
else:
q['yhteensä']=np.sum(np.sum(self.empstate[:,:],1)*scalex)
q['palkansaajia']=np.sum((self.empstate[:,1])*scalex)
q['htv']=np.sum((self.empstate[:,1])*scalex)
q['ansiosidonnaisella']=np.sum((self.empstate[:,0])*scalex)
q['tmtuella']=np.sum(self.empstate[:,1]*0)
q['isyysvapaalla']=np.sum(self.empstate[:,1]*0)
q['kotihoidontuella']=np.sum(self.empstate[:,1]*0)
q['vanhempainvapaalla']=np.sum(self.empstate[:,1]*0)
return q
def comp_employment_groupstats(self,scale_time=True,g=0,include_retwork=True,grouped=True):
demog2=self.empstats.get_demog()
if scale_time:
scale=self.timestep
else:
scale=1.0
#min_cage=self.map_age(self.min_age)
#max_cage=self.map_age(self.max_age)+1
scalex=np.squeeze(demog2/self.n_pop*scale)
#d=np.squeeze(demog2[min_cage:max_cage])
if grouped:
ratiostates=np.squeeze(self.gempstate[:,:,g])/self.alive
demogstates=np.squeeze(self.gempstate[:,:,g])
else:
ratiostates=self.empstate[:,:]/self.alive
demogstates=self.empstate[:,:]
if self.version in set([1,2,3,4]):
if include_retwork:
stats_employed=np.sum((demogstates[:,1]+demogstates[:,9])*scalex)
stats_parttime=np.sum((demogstates[:,10]+demogstates[:,8])*scalex)
else:
stats_employed=np.sum((demogstates[:,1])*scalex)
stats_parttime=np.sum((demogstates[:,10])*scalex)
stats_unemployed=np.sum((demogstates[:,0]+demogstates[:,4]+demogstates[:,13])*scalex)
else:
stats_employed=np.sum((demogstates[:,0]+demogstates[:,3])*scalex)
stats_parttime=np.sum((demogstates[:,3])*scalex)
stats_unemployed=np.sum((demogstates[:,0])*scalex)
#stats_all=np.sum(demogstates,1)
return stats_employed,stats_parttime,stats_unemployed
def comp_state_stats(self,state,scale_time=True,start=20,end=63.5,ratio=False):
demog2=np.squeeze(self.empstats.get_demog())
#if scale_time:
# scale=self.timestep
#else:
# scale=1.0
min_cage=self.map_age(start)
max_cage=self.map_age(end)+1
#vaikutus=np.round(scale*np.sum(demog2[min_cage:max_cage]*state[min_cage:max_cage]))/np.sum(demog2[min_cage:max_cage])
vaikutus=np.sum(demog2[min_cage:max_cage]*state[min_cage:max_cage])/np.sum(demog2[min_cage:max_cage])
x=np.sum(demog2[min_cage:max_cage]*state[min_cage:max_cage])
y=np.sum(demog2[min_cage:max_cage])
#print(f'vaikutus {vaikutus} x {x} y {y}\n s {state[min_cage:max_cage]} mean {np.mean(state[min_cage:max_cage])}\n d {demog2[min_cage:max_cage]}')
return vaikutus
def get_vanhempainvapaat(self):
'''
Laskee vanhempainvapaalla olevien määrän outsider-mallia (Excel) varten, tila 6
'''
alive=np.zeros((self.galive.shape[0],1))
alive[:,0]=np.sum(self.galive[:,0:3],1)
ulkopuolella_m=np.sum(self.gempstate[:,7,0:3],axis=1)[:,None]/alive
alive[:,0]=np.sum(self.galive[:,3:6],1)
nn=np.sum(self.gempstate[:,5,3:6]+self.gempstate[:,7,3:6],axis=1)[:,None]-self.infostats_mother_in_workforce
ulkopuolella_n=nn/alive
return ulkopuolella_m[::4],ulkopuolella_n[::4]
def get_vanhempainvapaat_md(self):
'''
Laskee vanhempainvapaalla olevien määrän outsider-mallia (Excel) varten, tila 7
'''
alive=np.zeros((self.galive.shape[0],1))
alive[:,0]=np.sum(self.galive[:,0:3],1)
ulkopuolella_m=np.sum(self.gempstate[:,6,0:3],axis=1)[:,None]/alive
alive[:,0]=np.sum(self.galive[:,3:6],1)
nn=self.infostats_mother_in_workforce
ulkopuolella_n=nn/alive
return ulkopuolella_m[::4],ulkopuolella_n[::4]
def comp_L2error(self):
tyollisyysaste_m,osatyoaste_m,tyottomyysaste_m,ka_tyottomyysaste=self.comp_gempratios(gender='men',unempratio=False)
tyollisyysaste_w,osatyoaste_w,tyottomyysaste_w,ka_tyottomyysaste=self.comp_gempratios(gender='women',unempratio=False)
emp_statsratio_m=self.empstats.emp_stats(g=1)[:-1]*100
emp_statsratio_w=self.empstats.emp_stats(g=2)[:-1]*100
unemp_statsratio_m=self.empstats.unemp_stats(g=1)[:-1]*100
unemp_statsratio_w=self.empstats.unemp_stats(g=2)[:-1]*100
w1=1.0
w2=3.0
L2= w1*np.sum(np.abs(emp_statsratio_m-tyollisyysaste_m[:-1])**2)+\
w1*np.sum(np.abs(emp_statsratio_w-tyollisyysaste_w[:-1])**2)+\
w2*np.sum(np.abs(unemp_statsratio_m-tyottomyysaste_m[:-1])**2)+\
w2*np.sum(np.abs(unemp_statsratio_w-tyottomyysaste_w[:-1])**2)
L2=L2/self.n_pop
#print(L1,emp_statsratio_m,tyollisyysaste_m,tyollisyysaste_w,unemp_statsratio_m,tyottomyysaste_m,tyottomyysaste_w)
print('L2 error {}'.format(L2))
return L2
def comp_budgetL2error(self,ref_muut,scale=1):
q=self.comp_budget()
muut=q['muut tulot']
L2=-((ref_muut-muut)/scale)**2
print(f'L2 error {L2} (muut {muut} muut_ref {ref_muut})')
return L2
def optimize_scale(self,target,averaged=scale_error):
opt=scipy.optimize.least_squares(self.scale_error,0.20,bounds=(-1,1),kwargs={'target':target,'averaged':averaged})
#print(opt)
return opt['x']
def optimize_logutil(self,target,source):
'''
analytical compensated consumption
does not implement final reward, hence duration 110 y
'''
n_time=110
gy=np.empty(n_time)
g=1
gx=np.empty(n_time)
for t in range(0,n_time):
gx[t]=g
g*=self.gamma
for t in range(1,n_time):
gy[t]=np.sum(gx[0:t])
gf=np.mean(gy[1:])/10
lx=(target-source)
opt=np.exp(lx/gf)-1.0
print(opt)
def min_max(self):
min_wage=np.min(self.infostats_pop_wage)
max_wage=np.max(self.infostats_pop_wage)
max_pension=np.max(self.infostats_pop_pension)
min_pension=np.min(self.infostats_pop_pension)
print(f'min wage {min_wage} max wage {max_wage}')
print(f'min pension {min_pension} max pension {max_pension}')
def setup_labels(self):
self.labels=self.lab.get_labels(self.language)
def map_age(self,age,start_zero=False):
if start_zero:
return int((age)*self.inv_timestep)
else:
return int((age-self.min_age)*self.inv_timestep)
def map_t_to_age(self,t):
return self.min_age+t/self.inv_timestep
def episodestats_exit(self):
plt.close(self.episode_fig)
def comp_gini(self):
'''
<NAME>-kerroin populaatiolle
'''
income=np.sort(self.infostats_tulot_netto,axis=None)
n=len(income)
L=np.arange(n,0,-1)
A=np.sum(L*income)/np.sum(income)
G=(n+1-2*A)/2
return G
def comp_annual_irr(self,npv,premium,pension,empstate,doprint=False):
k=0
max_npv=int(np.ceil(npv))
cashflow=-premium+pension
x=np.zeros(cashflow.shape[0]+max_npv)
eind=np.zeros(max_npv+1)
el=1
for k in range(max_npv+1):
eind[k]=el
el=el*self.elakeindeksi
x[:cashflow.shape[0]]=cashflow
if npv>0:
x[cashflow.shape[0]-1:]=cashflow[-2]*eind[:max_npv+1]
y=np.zeros(int(np.ceil(x.shape[0]/4)))
for k in range(y.shape[0]):
y[k]=np.sum(x[4*k:4*k+4])
irri=npf.irr(y)*100
#if np.isnan(irri):
# if np.sum(pension)<0.1 and np.sum(empstate[0:self.map_age(63)]==15)>0: # vain maksuja, joista ei saa tuottoja, joten tappio 100%
# irri=-100
if irri<0.01 and doprint:
print('---------\nirri {}\nnpv {}\nx {}\ny {}\nprem {}\npens {}\nemps {}\n---------\n'.format(irri,npv,x,y,premium,pension,empstate))
if irri>100 and doprint:
print('---------\nirri {}\nnpv {}\nx {}\ny {}\nprem {}\npens {}\nemps {}\n---------\n'.format(irri,npv,x,y,premium,pension,empstate))
if np.isnan(irri) and doprint:
print('---------\nirri {}\nnpv {}\nx {}\ny {}\nprem {}\npens {}\nemps {}\n---------\n'.format(irri,npv,x,y,premium,np.sum(pension),empstate))
#print('---------\nirri {}\nnpv {}\n\ny {}\nprem {}\npens {}\nemps {}\n---------\n'.format(irri,npv,x,y,premium,np.sum(pension),np.sum(empstate==15)))
if irri<-50 and doprint:
print('---------\nirri {}\nnpv {}\nx {}\ny {}\nprem {}\npens {}\nemps {}\n---------\n'.format(irri,npv,x,y,premium,pension,empstate))
return irri
def comp_irr(self):
'''
Laskee sisäisen tuottoasteen (IRR)
Indeksointi puuttuu npv:n osalta
Tuloksiin lisättävä inflaatio+palkkojen reaalikasvu = palkkojen nimellinen kasvu
'''
for k in range(self.n_pop):
self.infostats_irr[k]=self.reaalinen_palkkojenkasvu*100+self.comp_annual_irr(self.infostats_npv0[k,0],self.infostats_tyelpremium[:,k],self.infostats_paid_tyel_pension[:,k],self.popempstate[:,k])
def comp_aggirr(self):
'''
Laskee aggregoidun sisäisen tuottoasteen (IRR)
Indeksointi puuttuu npv:n osalta
Tuloksiin lisättävä inflaatio+palkkojen reaalikasvu = palkkojen nimellinen kasvu
'''
maxnpv=np.max(self.infostats_npv0)
agg_premium=np.sum(self.infostats_tyelpremium,axis=1)
agg_pensions=np.sum(self.infostats_paid_tyel_pension,axis=1)
agg_irr=self.reaalinen_palkkojenkasvu*100+self.comp_annual_irr(maxnpv,agg_premium,agg_pensions,self.popempstate[:,0])
x=np.zeros(self.infostats_paid_tyel_pension.shape[0]+int(np.ceil(maxnpv)))
max_npv=int(max(np.ceil(self.infostats_npv0[:,0])))
eind=np.zeros(max_npv)
el=1
for k in range(max_npv):
eind[k]=el
el=el*self.elakeindeksi
cfn=self.infostats_tyelpremium.shape[0]
for k in range(self.n_pop):
if np.sum(self.popempstate[0:self.map_age(63),k]==15)<1: # ilman kuolleita
n=int(np.ceil(self.infostats_npv0[k,0]))
cashflow=-self.infostats_tyelpremium[:,k]+self.infostats_paid_tyel_pension[:,k]
# indeksointi puuttuu
x[:cfn]+=cashflow
if n>0:
x[cfn-1:cfn+n-1]+=cashflow[-2]*eind[:n] # ei indeksoida, pitäisi huomioida takuueläkekin
y=np.zeros(int(np.ceil(x.shape[0]/4)))
for k in range(y.shape[0]):
y[k]=np.sum(x[4*k:4*k+101])
irri=npf.irr(y)*100
print('aggregate irr {}'.format(agg_irr))
def comp_unemp_durations(self,popempstate=None,popunemprightused=None,putki=True,\
tmtuki=False,laaja=False,outsider=False,ansiosid=True,tyott=False,kaikki=False,\
return_q=True,max_age=100):
'''
Poikkileikkaushetken työttömyyskestot
'''
unempset=[]
if tmtuki:
unempset.append(13)
if outsider:
unempset.append(11)
if putki:
unempset.append(4)
if ansiosid:
unempset.append(0)
if tyott:
unempset=[0,4,13]
if laaja:
unempset=[0,4,11,13]
if kaikki:
unempset=[0,2,3,4,5,6,7,8,9,11,12,13,14]
unempset=set(unempset)
if popempstate is None:
popempstate=self.popempstate
if popunemprightused is None:
popunemprightused=self.popunemprightused
keskikesto=np.zeros((5,5)) # 20-29, 30-39, 40-49, 50-59, 60-69, vastaa TYJin tilastoa
n=np.zeros(5)
for k in range(self.n_pop):
for t in range(1,self.n_time):
age=self.min_age+t*self.timestep
if age<=max_age:
if popempstate[t,k] in unempset:
if age<29:
l=0
elif age<39:
l=1
elif age<49:
l=2
elif age<59:
l=3
else:
l=4
n[l]+=1
if self.popunemprightused[t,k]<=0.51:
keskikesto[l,0]+=1
elif self.popunemprightused[t,k]<=1.01:
keskikesto[l,1]+=1
elif self.popunemprightused[t,k]<=1.51:
keskikesto[l,2]+=1
elif self.popunemprightused[t,k]<=2.01:
keskikesto[l,3]+=1
else:
keskikesto[l,4]+=1
for k in range(5):
keskikesto[k,:] /= n[k]
if return_q:
return self.empdur_to_dict(keskikesto)
else:
return keskikesto
def empdur_to_dict(self,empdur):
q={}
q['20-29']=empdur[0,:]
q['30-39']=empdur[1,:]
q['40-49']=empdur[2,:]
q['50-59']=empdur[3,:]
q['60-65']=empdur[4,:]
return q
def comp_unemp_durations_v2(self,popempstate=None,putki=True,tmtuki=False,laaja=False,\
outsider=False,ansiosid=True,tyott=False,kaikki=False,\
return_q=True,max_age=100):
'''
Poikkileikkaushetken työttömyyskestot
Tässä lasketaan tulos tiladatasta, jolloin kyse on viimeisimmän jakson kestosta
'''
unempset=[]
if tmtuki:
unempset.append(13)
if outsider:
unempset.append(11)
if putki:
unempset.append(4)
if ansiosid:
unempset.append(0)
if tyott:
unempset=[0,4,13]
if laaja:
unempset=[0,4,11,13]
if kaikki:
unempset=[0,2,3,4,5,6,7,8,9,11,12,13,14]
unempset=set(unempset)
if popempstate is None:
popempstate=self.popempstate
keskikesto=np.zeros((5,5)) # 20-29, 30-39, 40-49, 50-59, 60-69, vastaa TYJin tilastoa
n=np.zeros(5)
for k in range(self.n_pop):
prev_state=popempstate[0,k]
prev_trans=0
for t in range(1,self.n_time):
age=self.min_age+t*self.timestep
if age<=max_age:
if popempstate[t,k]!=prev_state:
if prev_state in unempset and popempstate[t,k] not in unempset:
prev_state=popempstate[t,k]
duration=(t-prev_trans)*self.timestep
prev_trans=t
if age<29:
l=0
elif age<39:
l=1
elif age<49:
l=2
elif age<59:
l=3
else:
l=4
n[l]+=1
if duration<=0.51:
keskikesto[l,0]+=1
elif duration<=1.01:
keskikesto[l,1]+=1
elif duration<=1.51:
keskikesto[l,2]+=1
elif duration<=2.01:
keskikesto[l,3]+=1
else:
keskikesto[l,4]+=1
elif prev_state not in unempset and popempstate[t,k] in unempset:
prev_trans=t
prev_state=popempstate[t,k]
else: # some other state
prev_state=popempstate[t,k]
prev_trans=t
for k in range(5):
keskikesto[k,:] /= n[k]
if return_q:
return self.empdur_to_dict(keskikesto)
else:
return keskikesto
def comp_virrat(self,popempstate=None,putki=True,tmtuki=True,laaja=False,outsider=False,ansiosid=True,tyott=False,kaikki=False,max_age=100):
tyoll_virta=np.zeros((self.n_time,1))
tyot_virta=np.zeros((self.n_time,1))
unempset=[]
empset=[]
if tmtuki:
unempset.append(13)
if outsider:
unempset.append(11)
if putki:
unempset.append(4)
if ansiosid:
unempset.append(0)
if tyott:
unempset=[0,4,13]
if laaja:
unempset=[0,4,11,13]
if kaikki:
unempset=[0,2,3,4,5,6,7,8,9,11,12,13,14]
empset=set([1,10])
unempset=set(unempset)
if popempstate is None:
popempstate=self.popempstate
for k in range(self.n_pop):
prev_state=popempstate[0,k]
prev_trans=0
for t in range(1,self.n_time):
age=self.min_age+t*self.timestep
if age<=max_age:
if popempstate[t,k]!=prev_state:
if prev_state in unempset and popempstate[t,k] in empset:
tyoll_virta[t]+=1
prev_state=popempstate[t,k]
elif prev_state in empset and popempstate[t,k] in unempset:
tyot_virta[t]+=1
prev_state=popempstate[t,k]
else: # some other state
prev_state=popempstate[t,k]
return tyoll_virta,tyot_virta
def comp_tyollistymisdistribs(self,popempstate=None,popunemprightleft=None,putki=True,tmtuki=True,laaja=False,outsider=False,ansiosid=True,tyott=False,max_age=100):
tyoll_distrib=[]
tyoll_distrib_bu=[]
unempset=[]
if tmtuki:
unempset.append(13)
if outsider:
unempset.append(11)
if putki:
unempset.append(4)
if ansiosid:
unempset.append(0)
if tyott:
unempset=[0,4,13]
if laaja:
unempset=[0,4,11,13]
empset=set([1,10])
unempset=set(unempset)
if popempstate is None or popunemprightleft is None:
popempstate=self.popempstate
popunemprightleft=self.popunemprightleft
for k in range(self.n_pop):
prev_state=popempstate[0,k]
prev_trans=0
for t in range(1,self.n_time):
age=self.min_age+t*self.timestep
if age<=max_age:
if popempstate[t,k]!=prev_state:
if prev_state in unempset and popempstate[t,k] in empset:
tyoll_distrib.append((t-prev_trans)*self.timestep)
tyoll_distrib_bu.append(popunemprightleft[t,k])
prev_state=popempstate[t,k]
prev_trans=t
else: # some other state
prev_state=popempstate[t,k]
prev_trans=t
return tyoll_distrib,tyoll_distrib_bu
def comp_empdistribs(self,popempstate=None,popunemprightleft=None,putki=True,tmtuki=True,laaja=False,outsider=False,ansiosid=True,tyott=False,max_age=100):
unemp_distrib=[]
unemp_distrib_bu=[]
emp_distrib=[]
unempset=[]
if tmtuki:
unempset.append(13)
if outsider:
unempset.append(11)
if putki:
unempset.append(4)
if ansiosid:
unempset.append(0)
if tyott:
unempset=[0,4,13]
if laaja:
unempset=[0,4,11,13]
if popempstate is None or popunemprightleft is None:
popempstate=self.popempstate
popunemprightleft=self.popunemprightleft
empset=set([1,10])
unempset=set(unempset)
for k in range(self.n_pop):
prev_state=popempstate[0,k]
prev_trans=0
for t in range(1,self.n_time):
age=self.min_age+t*self.timestep
if age<=max_age:
if self.popempstate[t,k]!=prev_state:
if prev_state in unempset and popempstate[t,k] not in unempset:
unemp_distrib.append((t-prev_trans)*self.timestep)
unemp_distrib_bu.append(popunemprightleft[t,k])
prev_state=popempstate[t,k]
prev_trans=t
elif prev_state in empset and popempstate[t,k] not in unempset:
emp_distrib.append((t-prev_trans)*self.timestep)
prev_state=popempstate[t,k]
prev_trans=t
else: # some other state
prev_state=popempstate[t,k]
prev_trans=t
return unemp_distrib,emp_distrib,unemp_distrib_bu
def empdist_stat(self):
ratio=np.array([1,0.287024901703801,0.115508955875928,0.0681083442551332,0.0339886413280909,0.0339886413280909,0.0114460463084316,0.0114460463084316,0.0114460463084316,0.00419397116644823,0.00419397116644823,0.00419397116644823,0.00419397116644823,0.00419397116644823,0.00419397116644823,0.00419397116644823,0.00419397116644823,0.00166011358671909,0.00166011358671909,0.00166011358671909,0.00166011358671909,0.00166011358671909,0.00166011358671909,0.00166011358671909,0.00166011358671909,0.00104849279161206,0.00104849279161206,0.00104849279161206,0.00104849279161206,0.00104849279161206,0.00104849279161206,0.00104849279161206,0.00104849279161206])
return ratio
def comp_gempratios(self,unempratio=True,gender='men'):
if gender=='men': # men
gempstate=np.sum(self.gempstate[:,:,0:3],axis=2)
alive=np.zeros((self.galive.shape[0],1))
alive[:,0]=np.sum(self.galive[:,0:3],1)
mother_in_workforce=0
else: # women
gempstate=np.sum(self.gempstate[:,:,3:6],axis=2)
alive=np.zeros((self.galive.shape[0],1))
alive[:,0]=np.sum(self.galive[:,3:6],1)
mother_in_workforce=self.infostats_mother_in_workforce
tyollisyysaste,osatyoaste,tyottomyysaste,ka_tyottomyysaste=self.comp_empratios(gempstate,alive,unempratio=unempratio,mother_in_workforce=mother_in_workforce)
return tyollisyysaste,osatyoaste,tyottomyysaste,ka_tyottomyysaste
def comp_empratios(self,emp,alive,unempratio=True,mother_in_workforce=0):
employed=emp[:,1]
retired=emp[:,2]
unemployed=emp[:,0]
if self.version in set([1,2,3,4]):
disabled=emp[:,3]
piped=emp[:,4]
mother=emp[:,5]
dad=emp[:,6]
kotihoidontuki=emp[:,7]
vetyo=emp[:,9]
veosatyo=emp[:,8]
osatyo=emp[:,10]
outsider=emp[:,11]
student=emp[:,12]
tyomarkkinatuki=emp[:,13]
tyollisyysaste=100*(employed+osatyo+veosatyo+vetyo+dad+mother_in_workforce)/alive[:,0]
osatyoaste=100*(osatyo+veosatyo)/(employed+osatyo+veosatyo+vetyo)
if unempratio:
tyottomyysaste=100*(unemployed+piped+tyomarkkinatuki)/(tyomarkkinatuki+unemployed+employed+piped+osatyo+veosatyo+vetyo)
ka_tyottomyysaste=100*np.sum(unemployed+tyomarkkinatuki+piped)/np.sum(tyomarkkinatuki+unemployed+employed+piped+osatyo+veosatyo+vetyo)
else:
tyottomyysaste=100*(unemployed+piped+tyomarkkinatuki)/alive[:,0]
ka_tyottomyysaste=100*np.sum(unemployed+tyomarkkinatuki+piped)/np.sum(alive[:,0])
elif self.version in set([0,101]):
if False:
osatyo=emp[:,3]
else:
osatyo=0
tyollisyysaste=100*(employed+osatyo)/alive[:,0]
#osatyoaste=np.zeros(employed.shape)
osatyoaste=100*(osatyo)/(employed+osatyo)
if unempratio:
tyottomyysaste=100*(unemployed)/(unemployed+employed+osatyo)
ka_tyottomyysaste=100*np.sum(unemployed)/np.sum(unemployed+employed+osatyo)
else:
tyottomyysaste=100*(unemployed)/alive[:,0]
ka_tyottomyysaste=100*np.sum(unemployed)/np.sum(alive[:,0])
return tyollisyysaste,osatyoaste,tyottomyysaste,ka_tyottomyysaste
def plot_ratiostats(self,t):
'''
Tee kuvia tuloksista
'''
x=np.linspace(self.min_age,self.max_age,self.n_time)
fig,ax=plt.subplots()
ax.set_xlabel('palkat')
ax.set_ylabel('freq')
ax.hist(self.infostats_pop_wage[t,:])
plt.show()
fig,ax=plt.subplots()
ax.set_xlabel('aika')
ax.set_ylabel('palkat')
meansal=np.mean(self.infostats_pop_wage,axis=1)
stdsal=np.std(self.infostats_pop_wage,axis=1)
ax.plot(x,meansal)
ax.plot(x,meansal+stdsal)
ax.plot(x,meansal-stdsal)
plt.show()
def plot_empdistribs(self,emp_distrib):
fig,ax=plt.subplots()
ax.set_xlabel('työsuhteen pituus [v]')
ax.set_ylabel('freq')
ax.set_yscale('log')
max_time=50
nn_time = int(np.round((max_time)*self.inv_timestep))+1
x=np.linspace(0,max_time,nn_time)
scaled,x2=np.histogram(emp_distrib,x)
scaled=scaled/np.sum(emp_distrib)
#ax.hist(emp_distrib)
ax.bar(x2[1:-1],scaled[1:],align='center')
plt.show()
def plot_compare_empdistribs(self,emp_distrib,emp_distrib2,label2='vaihtoehto',label1=''):
fig,ax=plt.subplots()
ax.set_xlabel('työsuhteen pituus [v]')
ax.set_ylabel(self.labels['probability'])
ax.set_yscale('log')
max_time=50
nn_time = int(np.round((max_time)*self.inv_timestep))+1
x=np.linspace(0,max_time,nn_time)
scaled,x2=np.histogram(emp_distrib,x)
scaled=scaled/np.sum(emp_distrib)
x=np.linspace(0,max_time,nn_time)
scaled3,x3=np.histogram(emp_distrib2,x)
scaled3=scaled3/np.sum(emp_distrib2)
ax.plot(x3[:-1],scaled3,label=label1)
ax.plot(x2[:-1],scaled,label=label2)
ax.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
plt.show()
def plot_vlines_unemp(self,point=0):
axvcolor='gray'
lstyle='--'
plt.axvline(x=300/(12*21.5),ls=lstyle,color=axvcolor)
plt.text(310/(12*21.5),point,'300',rotation=90)
plt.axvline(x=400/(12*21.5),ls=lstyle,color=axvcolor)
plt.text(410/(12*21.5),point,'400',rotation=90)
plt.axvline(x=500/(12*21.5),ls=lstyle,color=axvcolor)
plt.text(510/(12*21.5),point,'500',rotation=90)
def plot_tyolldistribs(self,emp_distrib,tyoll_distrib,tyollistyneet=True,max=10,figname=None):
max_time=55
nn_time = int(np.round((max_time)*self.inv_timestep))+1
x=np.linspace(0,max_time,nn_time)
scaled0,x0=np.histogram(emp_distrib,x)
if not tyollistyneet:
scaled=scaled0
x2=x0
else:
scaled,x2=np.histogram(tyoll_distrib,x)
jaljella=np.cumsum(scaled0[::-1])[::-1] # jäljellä olevien kumulatiivinen summa
scaled=scaled/jaljella
fig,ax=plt.subplots()
ax.set_xlabel('työttömyysjakson pituus [v]')
if tyollistyneet:
ax.set_ylabel('työllistyneiden osuus')
point=0.5
else:
ax.set_ylabel('pois siirtyneiden osuus')
point=0.9
self.plot_vlines_unemp(point)
ax.plot(x2[1:-1],scaled[1:])
#ax.bar(x2[1:-1],scaled[1:],align='center',width=self.timestep)
plt.xlim(0,max)
if figname is not None:
plt.savefig(figname+'tyollistyneetdistrib.eps', format='eps')
plt.show()
def plot_tyolldistribs_both(self,emp_distrib,tyoll_distrib,max=10,figname=None):
max_time=50
nn_time = int(np.round((max_time)*self.inv_timestep))+1
x=np.linspace(0,max_time,nn_time)
scaled0,x0=np.histogram(emp_distrib,x)
scaled=scaled0
scaled_tyoll,x2=np.histogram(tyoll_distrib,x)
jaljella=np.cumsum(scaled0[::-1])[::-1] # jäljellä olevien summa
scaled=scaled/jaljella
jaljella_tyoll=np.cumsum(scaled0[::-1])[::-1] # jäljellä olevien summa
scaled_tyoll=scaled_tyoll/jaljella_tyoll
fig,ax=plt.subplots()
ax.set_xlabel('työttömyysjakson pituus [v]')
point=0.6
self.plot_vlines_unemp(point)
ax.plot(x2[1:-1],scaled[1:],label='pois siirtyneiden osuus')
ax.plot(x2[1:-1],scaled_tyoll[1:],label='työllistyneiden osuus')
#ax.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
ax.legend()
ax.set_ylabel('pois siirtyneiden osuus')
plt.xlim(0,max)
plt.ylim(0,0.8)
if figname is not None:
plt.savefig(figname+'tyolldistribs.eps', format='eps')
plt.show()
def plot_tyolldistribs_both_bu(self,emp_distrib,tyoll_distrib,max=2):
max_time=4
nn_time = int(np.round((max_time)*self.inv_timestep))+1
x=np.linspace(-max_time,0,nn_time)
scaled0,x0=np.histogram(emp_distrib,x)
scaled=scaled0
scaled_tyoll,x2=np.histogram(tyoll_distrib,x)
jaljella=np.cumsum(scaled0[::-1])[::-1] # jäljellä olevien summa
#jaljella=np.cumsum(scaled0)
scaled=scaled/jaljella
jaljella_tyoll=np.cumsum(scaled0[::-1])[::-1] # jäljellä olevien summa
#jaljella_tyoll=np.cumsum(scaled0)
scaled_tyoll=scaled_tyoll/jaljella_tyoll
fig,ax=plt.subplots()
ax.set_xlabel('aika ennen ansiopäivärahaoikeuden loppua [v]')
point=0.6
#self.plot_vlines_unemp(point)
ax.plot(x2[1:-1],scaled[1:],label='pois siirtyneiden osuus')
ax.plot(x2[1:-1],scaled_tyoll[1:],label='työllistyneiden osuus')
ax.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
ax.set_ylabel('pois siirtyneiden osuus')
plt.xlim(-max,0)
#plt.ylim(0,0.8)
plt.show()
def plot_compare_tyolldistribs(self,emp_distrib1,tyoll_distrib1,emp_distrib2,
tyoll_distrib2,tyollistyneet=True,max=4,label1='perus',label2='vaihtoehto',
figname=None):
max_time=50
nn_time = int(np.round((max_time)*self.inv_timestep))+1
x=np.linspace(0,max_time,nn_time)
# data1
scaled01,x0=np.histogram(emp_distrib1,x)
if not tyollistyneet:
scaled1=scaled01
x1=x0
else:
scaled1,x1=np.histogram(tyoll_distrib1,x)
jaljella1=np.cumsum(scaled01[::-1])[::-1] # jäljellä olevien summa
scaled1=scaled1/jaljella1
# data2
scaled02,x0=np.histogram(emp_distrib2,x)
if not tyollistyneet:
scaled2=scaled02
x2=x0
else:
scaled2,x2=np.histogram(tyoll_distrib2,x)
jaljella2=np.cumsum(scaled02[::-1])[::-1] # jäljellä olevien summa
scaled2=scaled2/jaljella2
fig,ax=plt.subplots()
ax.set_xlabel('työttömyysjakson pituus [v]')
if tyollistyneet:
ax.set_ylabel('työllistyneiden osuus')
else:
ax.set_ylabel('pois siirtyneiden osuus')
self.plot_vlines_unemp()
ax.plot(x2[1:-1],scaled2[1:],label=label2)
ax.plot(x1[1:-1],scaled1[1:],label=label1)
#ax.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
ax.legend()
plt.xlim(0,max)
if figname is not None:
plt.savefig(figname+'comp_tyollistyneetdistrib.eps', format='eps')
plt.show()
def plot_unempdistribs(self,unemp_distrib,max=4,figname=None,miny=None,maxy=None):
#fig,ax=plt.subplots()
max_time=50
nn_time = int(np.round((max_time)*self.inv_timestep))+1
x=np.linspace(0,max_time,nn_time)
scaled,x2=np.histogram(unemp_distrib,x)
scaled=scaled/np.sum(unemp_distrib)
fig,ax=plt.subplots()
self.plot_vlines_unemp(0.6)
ax.set_xlabel(self.labels['unemp duration'])
ax.set_ylabel(self.labels['probability'])
ax.plot(x[:-1],scaled)
ax.set_yscale('log')
plt.xlim(0,max)
if miny is not None:
plt.ylim(miny,maxy)
if figname is not None:
plt.savefig(figname+'unempdistribs.eps', format='eps')
plt.show()
def plot_saldist(self,t=0,sum=False,all=False,n=10,bins=30):
if all:
fig,ax=plt.subplots()
for t in range(1,self.n_time-1,5):
scaled,x=np.histogram(self.infostats_pop_wage[t,:],bins=bins)
x2=0.5*(x[1:]+x[0:-1])
ax.plot(x2,scaled,label=t)
plt.legend()
plt.show()
else:
if sum:
scaled,x=np.histogram(np.sum(self.infostats_pop_wage,axis=0),bins=bins)
x2=0.5*(x[1:]+x[0:-1])
plt.plot(x2,scaled)
else:
fig,ax=plt.subplots()
for t1 in range(t,t+n,1):
scaled,x=np.histogram(self.infostats_pop_wage[t1,:],bins=bins)
x2=0.5*(x[1:]+x[0:-1])
ax.plot(x2,scaled,label=t1)
plt.legend()
plt.show()
def test_salaries(self):
n=self.n_pop
palkat_ika_miehet=12.5*np.array([2339.01,2489.09,2571.40,2632.58,2718.03,2774.21,2884.89,2987.55,3072.40,3198.48,3283.81,3336.51,3437.30,3483.45,3576.67,3623.00,3731.27,3809.58,3853.66,3995.90,4006.16,4028.60,4104.72,4181.51,4134.13,4157.54,4217.15,4165.21,4141.23,4172.14,4121.26,4127.43,4134.00,4093.10,4065.53,4063.17,4085.31,4071.25,4026.50,4031.17,4047.32,4026.96,4028.39,4163.14,4266.42,4488.40,4201.40,4252.15,4443.96,3316.92,3536.03,3536.03])
palkat_ika_naiset=12.5*np.array([2223.96,2257.10,2284.57,2365.57,2443.64,2548.35,2648.06,2712.89,2768.83,2831.99,2896.76,2946.37,2963.84,2993.79,3040.83,3090.43,3142.91,3159.91,3226.95,3272.29,3270.97,3297.32,3333.42,3362.99,3381.84,3342.78,3345.25,3360.21,3324.67,3322.28,3326.72,3326.06,3314.82,3303.73,3302.65,3246.03,3244.65,3248.04,3223.94,3211.96,3167.00,3156.29,3175.23,3228.67,3388.39,3457.17,3400.23,3293.52,2967.68,2702.05,2528.84,2528.84])
g_r=[0.77,1.0,1.23]
data_range=np.arange(20,72)
sal20=np.zeros((n,1))
sal25=np.zeros((n,1))
sal30=np.zeros((n,1))
sal40=np.zeros((n,1))
sal50=np.zeros((n,1))
sal60=np.zeros((n,1))
sal=np.zeros((n,72))
p=np.arange(700,17500,100)*12.5
palkka20=np.array([10.3,5.6,4.5,14.2,7.1,9.1,22.8,22.1,68.9,160.3,421.6,445.9,501.5,592.2,564.5,531.9,534.4,431.2,373.8,320.3,214.3,151.4,82.3,138.0,55.6,61.5,45.2,19.4,32.9,13.1,9.6,7.4,12.3,12.5,11.5,5.3,2.4,1.6,1.2,1.2,14.1,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0])
palkka25=np.array([12.4,11.3,30.2,4.3,28.5,20.3,22.5,23.7,83.3,193.0,407.9,535.0,926.5,1177.1,1540.9,1526.4,1670.2,1898.3,1538.8,1431.5,1267.9,1194.8,1096.3,872.6,701.3,619.0,557.2,465.8,284.3,291.4,197.1,194.4,145.0,116.7,88.7,114.0,56.9,57.3,55.0,25.2,24.4,20.1,25.2,37.3,41.4,22.6,14.1,9.4,6.3,7.5,8.1,9.0,4.0,3.4,5.4,4.1,5.2,1.0,2.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0])
palkka30=np.array([1.0,2.0,3.0,8.5,12.1,22.9,15.8,21.8,52.3,98.2,295.3,392.8,646.7,951.4,1240.5,1364.5,1486.1,1965.2,1908.9,1729.5,1584.8,1460.6,1391.6,1551.9,1287.6,1379.0,1205.6,1003.6,1051.6,769.9,680.5,601.2,552.0,548.3,404.5,371.0,332.7,250.0,278.2,202.2,204.4,149.8,176.7,149.0,119.6,76.8,71.4,56.3,75.9,76.8,58.2,50.2,46.8,48.9,30.1,32.2,28.8,31.1,45.5,41.2,36.5,18.1,11.6,8.5,10.2,4.3,13.5,12.3,4.9,13.9,5.4,5.9,7.4,14.1,9.6,8.4,11.5,0.0,3.3,9.0,5.2,5.0,3.1,7.4,2.0,4.0,4.1,14.0,2.0,3.0,1.0,0.0,6.2,2.0,1.2,2.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0])
palkka50=np.array([2.0,3.1,2.4,3.9,1.0,1.0,11.4,30.1,29.3,34.3,231.9,341.9,514.4,724.0,1076.8,1345.2,1703.0,1545.8,1704.0,1856.1,1805.4,1608.1,1450.0,1391.4,1338.5,1173.2,1186.3,1024.8,1105.6,963.0,953.0,893.7,899.8,879.5,857.0,681.5,650.5,579.2,676.8,498.0,477.5,444.3,409.1,429.0,340.5,297.2,243.1,322.5,297.5,254.1,213.1,249.3,212.1,212.8,164.4,149.3,158.6,157.4,154.1,112.7,93.4,108.4,87.3,86.7,82.0,115.9,66.9,84.2,61.4,43.7,58.1,40.9,73.9,50.0,51.6,25.7,43.2,48.2,43.0,32.6,21.6,22.4,36.3,28.3,19.4,21.1,21.9,21.5,19.2,15.8,22.6,9.3,14.0,22.4,14.0,13.0,11.9,18.7,7.3,21.6,9.5,11.2,12.0,18.2,12.9,2.2,10.7,6.1,11.7,7.6,1.0,4.7,8.5,6.4,3.3,4.6,1.2,3.7,5.8,1.0,1.0,1.0,1.0,3.2,1.2,3.1,2.2,2.3,2.1,1.1,2.0,2.1,2.2,4.6,2.2,1.0,1.0,1.0,0.0,3.0,1.2,0.0,8.2,3.0,1.0,1.0,2.1,1.2,3.2,1.0,5.2,1.1,5.2,1.0,1.2,2.3,1.0,3.1,1.0,1.0,1.1,1.6,1.1,1.1,1.0,1.0,1.0,1.0])
m20=0
m25=0
m30=0
m40=0
m50=0
m60=0
salx=np.zeros((self.n_time+2,1))
saln=np.zeros((self.n_time+2,1))
salx_m=np.zeros((self.n_time+2,1))
saln_m=np.zeros((self.n_time+2,1))
salx_f=np.zeros((self.n_time+2,1))
saln_f=np.zeros((self.n_time+2,1))
for k in range(self.n_pop):
for t in range(self.n_time-2):
if self.popempstate[t,k] in set([1,10,8,9]):
salx[t]=salx[t]+self.infostats_pop_wage[t,k]
saln[t]=saln[t]+1
if self.infostats_group[k]>2:
salx_f[t]=salx_f[t]+self.infostats_pop_wage[t,k]
saln_f[t]=saln_f[t]+1
else:
salx_m[t]=salx_m[t]+self.infostats_pop_wage[t,k]
saln_m[t]=saln_m[t]+1
if self.popempstate[self.map_age(20),k] in set([1,10]):
sal20[m20]=self.infostats_pop_wage[self.map_age(20),k]
m20=m20+1
if self.popempstate[self.map_age(25),k] in set([1,10]):
sal25[m25]=self.infostats_pop_wage[self.map_age(25),k]
m25=m25+1
if self.popempstate[self.map_age(30),k] in set([1,10]):
sal30[m30]=self.infostats_pop_wage[self.map_age(30),k]
m30=m30+1
if self.popempstate[self.map_age(40),k] in set([1,10]):
sal40[m40]=self.infostats_pop_wage[self.map_age(40),k]
m40=m40+1
if self.popempstate[self.map_age(50),k] in set([1,10]):
sal50[m50]=self.infostats_pop_wage[self.map_age(50),k]
m50=m50+1
if self.popempstate[self.map_age(60),k] in set([1,10]):
sal60[m60]=self.infostats_pop_wage[self.map_age(60),k]
m60=m60+1
salx=salx/np.maximum(1,saln)
salx_f=salx_f/np.maximum(1,saln_f)
salx_m=salx_m/np.maximum(1,saln_m)
#print(sal25,self.infostats_pop_wage)
def kuva(sal,ika,m,p,palkka):
plt.hist(sal[:m],bins=50,density=True)
ave=np.mean(sal[:m])/12
palave=np.sum(palkka*p)/12/np.sum(palkka)
plt.title('{}: ave {} vs {}'.format(ika,ave,palave))
plt.plot(p,palkka/sum(palkka)/2000)
plt.show()
def kuva2(sal,ika,m):
plt.hist(sal[:m],bins=50,density=True)
ave=np.mean(sal[:m])/12
plt.title('{}: ave {}'.format(ika,ave))
plt.show()
kuva(sal20,20,m20,p,palkka20)
kuva(sal25,25,m25,p,palkka25)
kuva(sal30,30,m30,p,palkka30)
kuva2(sal40,40,m40)
kuva(sal50,50,m50,p,palkka50)
kuva2(sal60,60,m60)
data_range=np.arange(21,72)
plt.plot(data_range,np.mean(self.infostats_pop_wage[::4],axis=1),label='malli kaikki')
plt.plot(data_range,salx[::4],label='malli töissä')
data_range=np.arange(20,72)
plt.plot(data_range,0.5*palkat_ika_miehet+0.5*palkat_ika_naiset,label='data')
plt.legend()
plt.show()
data_range=np.arange(21,72)
plt.plot(data_range,salx_m[::4],label='malli töissä miehet')
plt.plot(data_range,salx_f[::4],label='malli töissä naiset')
data_range=np.arange(20,72)
plt.plot(data_range,palkat_ika_miehet,label='data miehet')
plt.plot(data_range,palkat_ika_naiset,label='data naiset')
plt.legend()
plt.show()
def plot_rewdist(self,t=0,sum=False,all=False):
if all:
fig,ax=plt.subplots()
for t in range(1,self.n_time-1,5):
scaled,x=np.histogram(self.poprewstate[t,:])
x2=0.5*(x[1:]+x[0:-1])
ax.plot(x2,scaled,label=t)
plt.legend()
plt.show()
else:
if sum:
scaled,x=np.histogram(np.sum(self.poprewstate,axis=0))
x2=0.5*(x[1:]+x[0:-1])
plt.plot(x2,scaled)
else:
fig,ax=plt.subplots()
for t in range(t,t+10,1):
scaled,x=np.histogram(self.poprewstate[t,:])
x2=0.5*(x[1:]+x[0:-1])
ax.plot(x2,scaled,label=t)
plt.legend()
plt.show()
def plot_unempdistribs_bu(self,unemp_distrib,max=2):
#fig,ax=plt.subplots()
max_time=50
nn_time = int(np.round((max_time)*self.inv_timestep))+1
x=np.linspace(-max_time,0,nn_time)
scaled,x2=np.histogram(unemp_distrib,x)
scaled=scaled/np.abs(np.sum(unemp_distrib))
fig,ax=plt.subplots()
#self.plot_vlines_unemp(0.6)
ax.set_xlabel(self.labels['unemp duration'])
ax.set_ylabel(self.labels['probability'])
#x3=np.flip(x[:-1])
#ax.plot(x3,scaled)
ax.plot(x[:-1],scaled)
#ax.set_yscale('log')
plt.xlim(-max,0)
plt.show()
def plot_compare_unempdistribs(self,unemp_distrib1,unemp_distrib2,max=4,
label2='none',label1='none',logy=True,diff=False,figname=None):
#fig,ax=plt.subplots()
max_time=50
nn_time = int(np.round((max_time)*self.inv_timestep))+1
x=np.linspace(self.timestep,max_time,nn_time)
scaled1,x1=np.histogram(unemp_distrib1,x)
print('{} keskikesto {} v {} keskikesto {} v'.format(label1,np.mean(unemp_distrib1),label2,np.mean(unemp_distrib2)))
print('Skaalaamaton {} lkm {} v {} lkm {} v'.format(label1,len(unemp_distrib1),label2,len(unemp_distrib2)))
print('Skaalaamaton {} työtpäiviä yht {} v {} työtpäiviä yht {} v'.format(label1,np.sum(unemp_distrib1),label2,np.sum(unemp_distrib2)))
#scaled=scaled/np.sum(unemp_distrib)
scaled1=scaled1/np.sum(scaled1)
scaled2,x1=np.histogram(unemp_distrib2,x)
scaled2=scaled2/np.sum(scaled2)
fig,ax=plt.subplots()
if not diff:
self.plot_vlines_unemp(0.5)
ax.set_xlabel(self.labels['unemp duration'])
ax.set_ylabel(self.labels['osuus'])
if diff:
ax.plot(x[:-1],scaled1-scaled2,label=label1+'-'+label2)
else:
ax.plot(x[:-1],scaled2,label=label2)
ax.plot(x[:-1],scaled1,label=label1)
if logy and not diff:
ax.set_yscale('log')
if not diff:
plt.ylim(1e-4,1.0)
#ax.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
ax.legend()
plt.xlim(0,max)
if figname is not None:
plt.savefig(figname+'comp_unempdistrib.eps', format='eps')
plt.show()
def plot_compare_virrat(self,virta1,virta2,min_time=25,max_time=65,label1='perus',label2='vaihtoehto',virta_label='työllisyys',ymin=None,ymax=None):
x=np.linspace(self.min_age,self.max_age,self.n_time)
demog2=self.empstats.get_demog()
scaled1=virta1*demog2/self.n_pop #/self.alive
scaled2=virta2*demog2/self.n_pop #/self.alive
fig,ax=plt.subplots()
plt.xlim(min_time,max_time)
ax.set_xlabel(self.labels['age'])
ax.set_ylabel(virta_label+'virta')
ax.plot(x,scaled1,label=label1)
ax.plot(x,scaled2,label=label2)
ax.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
if ymin is not None and ymax is not None:
plt.ylim(ymin,ymax)
plt.show()
def plot_outsider(self,printtaa=True):
x=np.linspace(self.min_age,self.max_age,self.n_time)
fig,ax=plt.subplots()
ax.plot(x,100*(self.empstate[:,11]+self.empstate[:,5]+self.empstate[:,7])/self.alive[:,0],label='työvoiman ulkopuolella, ei opiskelija, sis. vanh.vapaat')
emp_statsratio=100*self.empstats.outsider_stats()
ax.plot(x,emp_statsratio,label='havainto')
ax.set_xlabel(self.labels['age'])
ax.set_ylabel(self.labels['ratio'])
ax.legend()
plt.show()
x=np.linspace(self.min_age,self.max_age,self.n_time)
fig,ax=plt.subplots()
ax.plot(x,100*np.sum(self.gempstate[:,11,3:5]+self.gempstate[:,5,3:5]+self.gempstate[:,7,3:5],1,keepdims=True)/np.sum(self.galive[:,3:5],1,keepdims=True),label='työvoiman ulkopuolella, naiset')
ax.plot(x,100*np.sum(self.gempstate[:,11,0:2]+self.gempstate[:,5,0:2]+self.gempstate[:,7,0:2],1,keepdims=True)/np.sum(self.galive[:,3:5],1,keepdims=True),label='työvoiman ulkopuolella, miehet')
emp_statsratio=100*self.empstats.outsider_stats(g=1)
ax.plot(x,emp_statsratio,label=self.labels['havainto, naiset'])
emp_statsratio=100*self.empstats.outsider_stats(g=2)
ax.plot(x,emp_statsratio,label=self.labels['havainto, miehet'])
ax.set_xlabel(self.labels['age'])
ax.set_ylabel(self.labels['ratio'])
ax.legend()
plt.show()
if printtaa:
#print('yht',100*(self.empstate[:,11]+self.empstate[:,5]+self.empstate[:,6]+self.empstate[:,7])/self.alive[:,0])
nn=np.sum(self.galive[:,3:5],1,keepdims=True)
n=np.sum(100*(self.gempstate[:,5,3:5]+self.gempstate[:,6,3:5]+self.gempstate[:,7,3:5]),1,keepdims=True)/nn
mn=np.sum(self.galive[:,0:2],1,keepdims=True)
m=np.sum(100*(self.gempstate[:,5,0:2]+self.gempstate[:,6,0:2]+self.gempstate[:,7,0:2]),1,keepdims=True)/mn
#print('naiset vv',n[1::4,0])
#print('miehet vv',m[1::4,0])
def plot_pinkslip(self):
x=np.linspace(self.min_age,self.max_age,self.n_time)
fig,ax=plt.subplots()
ax.plot(x,100*self.infostats_pinkslip[:,0]/self.empstate[:,0],label='ansiosidonnaisella')
ax.plot(x,100*self.infostats_pinkslip[:,4]/self.empstate[:,4],label='putkessa')
ax.plot(x,100*self.infostats_pinkslip[:,13]/self.empstate[:,13],label='työmarkkinatuella')
ax.set_xlabel(self.labels['age'])
ax.set_ylabel('Irtisanottujen osuus tilassa [%]')
ax.legend()
plt.show()
def plot_student(self):
x=np.linspace(self.min_age,self.max_age,self.n_time)
fig,ax=plt.subplots()
ax.plot(x+self.timestep,100*self.empstate[:,12]/self.alive[:,0],label='opiskelija tai armeijassa')
emp_statsratio=100*self.empstats.student_stats()
ax.plot(x,emp_statsratio,label='havainto')
ax.set_xlabel(self.labels['age'])
ax.set_ylabel(self.labels['ratio'])
ax.legend()
plt.show()
def plot_kassanjasen(self):
x=np.linspace(self.min_age,self.max_age,self.n_time)
fig,ax=plt.subplots()
ax.plot(x+self.timestep,100*self.infostats_kassanjasen[:]/self.alive[:,0],label='työttömyyskassan jäsenien osuus kaikista')
ax.set_xlabel(self.labels['age'])
ax.set_ylabel(self.labels['ratio'])
ax.legend()
plt.show()
mini=np.nanmin(100*self.infostats_kassanjasen[:]/self.alive[:,0])
maxi=np.nanmax(100*self.infostats_kassanjasen[:]/self.alive[:,0])
print('Kassanjäseniä min {} % max {} %'.format(mini,maxi))
def plot_group_student(self):
fig,ax=plt.subplots()
for gender in range(2):
if gender==0:
leg='Opiskelijat+Armeija Miehet'
opiskelijat=np.sum(self.gempstate[:,12,0:3],axis=1)
alive=np.zeros((self.galive.shape[0],1))
alive[:,0]=np.sum(self.galive[:,0:3],1)
else:
leg='Opiskelijat+Armeija Naiset'
opiskelijat=np.sum(self.gempstate[:,12,3:6],axis=1)
alive=np.zeros((self.galive.shape[0],1))
alive[:,0]=np.sum(self.galive[:,3:6],1)
opiskelijat=np.reshape(opiskelijat,(self.galive.shape[0],1))
osuus=100*opiskelijat/alive
x=np.linspace(self.min_age,self.max_age,self.n_time)
ax.plot(x,osuus,label=leg)
emp_statsratio=100*self.empstats.student_stats(g=1)
ax.plot(x,emp_statsratio,label=self.labels['havainto, naiset'])
emp_statsratio=100*self.empstats.student_stats(g=2)
ax.plot(x,emp_statsratio,label=self.labels['havainto, miehet'])
ax.set_xlabel(self.labels['age'])
ax.set_ylabel(self.labels['ratio'])
ax.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
plt.show()
def plot_group_disab(self):
fig,ax=plt.subplots()
for gender in range(2):
if gender==0:
leg='TK Miehet'
opiskelijat=np.sum(self.gempstate[:,3,0:3],axis=1)
alive=np.zeros((self.galive.shape[0],1))
alive[:,0]=np.sum(self.galive[:,0:3],1)
else:
leg='TK Naiset'
opiskelijat=np.sum(self.gempstate[:,3,3:6],axis=1)
alive=np.zeros((self.galive.shape[0],1))
alive[:,0]=np.sum(self.galive[:,3:6],1)
opiskelijat=np.reshape(opiskelijat,(self.galive.shape[0],1))
osuus=100*opiskelijat/alive
x=np.linspace(self.min_age,self.max_age,self.n_time)
ax.plot(x,osuus,label=leg)
emp_statsratio=100*self.empstats.disab_stat(g=1)
ax.plot(x,emp_statsratio,label=self.labels['havainto, naiset'])
emp_statsratio=100*self.empstats.disab_stat(g=2)
ax.plot(x,emp_statsratio,label=self.labels['havainto, miehet'])
ax.set_xlabel(self.labels['age'])
ax.set_ylabel(self.labels['ratio'])
ax.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
plt.show()
def plot_taxes(self,figname=None):
valtionvero_ratio=100*self.infostats_valtionvero_distrib/np.reshape(np.sum(self.infostats_valtionvero_distrib,1),(-1,1))
kunnallisvero_ratio=100*self.infostats_kunnallisvero_distrib/np.reshape(np.sum(self.infostats_kunnallisvero_distrib,1),(-1,1))
vero_ratio=100*(self.infostats_kunnallisvero_distrib+self.infostats_valtionvero_distrib)/(np.reshape(np.sum(self.infostats_valtionvero_distrib,1),(-1,1))+np.reshape(np.sum(self.infostats_kunnallisvero_distrib,1),(-1,1)))
if figname is not None:
self.plot_states(vero_ratio,ylabel='Valtioneronmaksajien osuus tilassa [%]',stack=True,figname=figname+'_stack')
else:
self.plot_states(vero_ratio,ylabel='Valtioneronmaksajien osuus tilassa [%]',stack=True)
if figname is not None:
self.plot_states(valtionvero_ratio,ylabel='Veronmaksajien osuus tilassa [%]',stack=True,figname=figname+'_stack')
else:
self.plot_states(valtionvero_ratio,ylabel='Veronmaksajien osuus tilassa [%]',stack=True)
if figname is not None:
self.plot_states(kunnallisvero_ratio,ylabel='Kunnallisveron maksajien osuus tilassa [%]',stack=True,figname=figname+'_stack')
else:
self.plot_states(kunnallisvero_ratio,ylabel='Kunnallisveron maksajien osuus tilassa [%]',stack=True)
valtionvero_osuus,kunnallisvero_osuus,vero_osuus=self.comp_taxratios()
print('Valtionveron maksajien osuus\n{}'.format(self.v2_groupstates(valtionvero_osuus)))
print('Kunnallisveron maksajien osuus\n{}'.format(self.v2_groupstates(kunnallisvero_osuus)))
print('Veronmaksajien osuus\n{}'.format(self.v2_groupstates(vero_osuus)))
def group_taxes(self,ratios):
if len(ratios.shape)>1:
vv_osuus=np.zeros((ratios.shape[0],5))
vv_osuus[:,0]=ratios[:,0]+ratios[:,4]+ratios[:,5]+ratios[:,6]+\
ratios[:,7]+ratios[:,8]+ratios[:,9]+ratios[:,11]+\
ratios[:,12]+ratios[:,13]
vv_osuus[:,1]=ratios[:,1]+ratios[:,10]
vv_osuus[:,2]=ratios[:,2]+ratios[:,3]+ratios[:,8]+ratios[:,9]
vv_osuus[:,3]=ratios[:,1]+ratios[:,10]+ratios[:,8]+ratios[:,9]
else:
vv_osuus=np.zeros((4))
vv_osuus[0]=ratios[0]+ratios[4]+ratios[5]+ratios[6]+\
ratios[7]+ratios[8]+ratios[9]+ratios[11]+\
ratios[12]+ratios[13]
vv_osuus[1]=ratios[1]+ratios[10]
vv_osuus[2]=ratios[2]+ratios[3]+ratios[8]+ratios[9]
vv_osuus[3]=ratios[1]+ratios[10]+ratios[8]+ratios[9]
return vv_osuus
def comp_taxratios(self,grouped=False):
valtionvero_osuus=100*np.sum(self.infostats_valtionvero_distrib,0)/np.sum(self.infostats_valtionvero_distrib)
kunnallisvero_osuus=100*np.sum(self.infostats_kunnallisvero_distrib,0)/np.sum(self.infostats_kunnallisvero_distrib)
vero_osuus=100*(np.sum(self.infostats_kunnallisvero_distrib,0)+np.sum(self.infostats_valtionvero_distrib,0))/(np.sum(self.infostats_kunnallisvero_distrib)+np.sum(self.infostats_valtionvero_distrib))
if grouped:
vv_osuus=self.group_taxes(valtionvero_osuus)
kv_osuus=self.group_taxes(kunnallisvero_osuus)
v_osuus=self.group_taxes(vero_osuus)
else:
vv_osuus=valtionvero_osuus
kv_osuus=kunnallisvero_osuus
v_osuus=vero_osuus
return vv_osuus,kv_osuus,v_osuus
def comp_verokiila(self,include_retwork=True,debug=False):
'''
Computes the tax effect as in Lundberg 2017
However, this applies the formulas for averages
'''
if debug:
print('comp_verokiila')
demog2=self.empstats.get_demog()
scalex=demog2/self.n_pop
valtionvero_osuus=np.sum(self.infostats_valtionvero_distrib*scalex,0)
kunnallisvero_osuus=np.sum(self.infostats_kunnallisvero_distrib*scalex,0)
taxes_distrib=np.sum(self.infostats_taxes_distrib*scalex,0)
taxes=self.group_taxes(taxes_distrib)
q=self.comp_budget()
q2=self.comp_participants(scale=True,include_retwork=include_retwork)
#htv=q2['palkansaajia']
#muut_tulot=q['muut tulot']
# kulutuksen verotus
tC=0.24*max(0,q['tyotulosumma']-taxes[3])
# (työssäolevien verot + ta-maksut + kulutusvero)/(työtulosumma + ta-maksut)
kiila=(taxes[3]+q['ta_maksut']+tC)/(q['tyotulosumma']+q['ta_maksut'])
qq={}
qq['tI']=taxes[3]/q['tyotulosumma']
qq['tC']=tC/q['tyotulosumma']
qq['tP']=q['ta_maksut']/q['tyotulosumma']
if debug:
print('qq',qq,'kiila',kiila)
return kiila,qq
def comp_verokiila_kaikki_ansiot(self):
demog2=self.empstats.get_demog()
scalex=demog2/self.n_pop
valtionvero_osuus=np.sum(self.infostats_valtionvero_distrib*scalex,0)
kunnallisvero_osuus=np.sum(self.infostats_kunnallisvero_distrib*scalex,0)
taxes_distrib=np.sum(self.infostats_taxes_distrib*scalex,0)
taxes=self.group_taxes(taxes_distrib)
q=self.comp_budget()
q2=self.comp_participants(scale=True)
htv=q2['palkansaajia']
muut_tulot=q['muut tulot']
# kulutuksen verotus
tC=0.2*max(0,q['tyotulosumma']-taxes[3])
# (työssäolevien verot + ta-maksut + kulutusvero)/(työtulosumma + ta-maksut)
kiila=(taxes[0]+q['ta_maksut']+tC)/(q['tyotulosumma']+q['verotettava etuusmeno']+q['ta_maksut'])
qq={}
qq['tI']=taxes[0]/q['tyotulosumma']
qq['tC']=tC/q['tyotulosumma']
qq['tP']=q['ta_maksut']/q['tyotulosumma']
#print(qq)
return kiila,qq
def v2_states(self,x):
return 'Ansiosidonnaisella {:.2f}\nKokoaikatyössä {:.2f}\nVanhuuseläkeläiset {:.2f}\nTyökyvyttömyyseläkeläiset {:.2f}\n'.format(x[0],x[1],x[2],x[3])+\
'Putkessa {:.2f}\nÄitiysvapaalla {:.2f}\nIsyysvapaalla {:.2f}\nKotihoidontuella {:.2f}\n'.format(x[4],x[5],x[6],x[7])+\
'VE+OA {:.2f}\nVE+kokoaika {:.2f}\nOsa-aikatyö {:.2f}\nTyövoiman ulkopuolella {:.2f}\n'.format(x[8],x[9],x[10],x[11])+\
'Opiskelija/Armeija {:.2f}\nTM-tuki {:.2f}\n'.format(x[12],x[13])
def v2_groupstates(self,xx):
x=self.group_taxes(xx)
return 'Etuudella olevat {:.2f}\nTyössä {:.2f}\nEläkkeellä {:.2f}\n'.format(x[0],x[1],x[2])
def plot_emp(self,figname=None):
tyollisyysaste,osatyoaste,tyottomyysaste,ka_tyottomyysaste=self.comp_empratios(self.empstate,self.alive,unempratio=False)
age_label=self.labels['age']
ratio_label=self.labels['osuus']
x=np.linspace(self.min_age,self.max_age,self.n_time)
fig,ax=plt.subplots()
ax.plot(x,tyollisyysaste,label=self.labels['malli'])
#ax.plot(x,tyottomyysaste,label=self.labels['tyottomien osuus'])
emp_statsratio=100*self.empstats.emp_stats()
ax.plot(x,emp_statsratio,ls='--',label=self.labels['havainto'])
ax.set_xlabel(age_label)
ax.set_ylabel(self.labels['tyollisyysaste %'])
ax.legend()
if figname is not None:
plt.savefig(figname+'tyollisyysaste.eps', format='eps')
plt.show()
#if self.version in set([1,2,3]):
fig,ax=plt.subplots()
ax.stackplot(x,osatyoaste,100-osatyoaste,
labels=('osatyössä','kokoaikaisessa työssä')) #, colors=pal) pal=sns.color_palette("hls", self.n_employment) # hls, husl, cubehelix
ax.legend()
plt.show()
empstate_ratio=100*self.empstate/self.alive
if figname is not None:
self.plot_states(empstate_ratio,ylabel=ratio_label,stack=True,figname=figname+'_stack')
else:
self.plot_states(empstate_ratio,ylabel=ratio_label,stack=True)
if self.version in set([1,2,3,4]):
self.plot_states(empstate_ratio,ylabel=ratio_label,ylimit=20,stack=False)
self.plot_states(empstate_ratio,ylabel=ratio_label,parent=True,stack=False)
self.plot_parents_in_work()
self.plot_states(empstate_ratio,ylabel=ratio_label,unemp=True,stack=False)
if figname is not None:
self.plot_states(empstate_ratio,ylabel=ratio_label,start_from=60,stack=True,figname=figname+'_stack60')
else:
self.plot_states(empstate_ratio,ylabel=ratio_label,start_from=60,stack=True)
def plot_savings(self):
savings_0=np.zeros(self.n_time)
savings_1=np.zeros(self.n_time)
savings_2=np.zeros(self.n_time)
act_savings_0=np.zeros(self.n_time)
act_savings_1=np.zeros(self.n_time)
act_savings_2=np.zeros(self.n_time)
for t in range(self.n_time):
state_0=np.argwhere(self.popempstate[t,:]==0)
savings_0[t]=np.mean(self.infostats_savings[t,state_0[:]])
act_savings_0[t]=np.mean(self.sav_actions[t,state_0[:]])
state_1=np.argwhere(self.popempstate[t,:]==1)
savings_1[t]=np.mean(self.infostats_savings[t,state_1[:]])
act_savings_1[t]=np.mean(self.sav_actions[t,state_1[:]])
state_2=np.argwhere(self.popempstate[t,:]==2)
savings_2[t]=np.mean(self.infostats_savings[t,state_2[:]])
act_savings_2[t]=np.mean(self.sav_actions[t,state_2[:]])
fig,ax=plt.subplots()
x=np.linspace(self.min_age,self.max_age,self.n_time)
savings=np.mean(self.infostats_savings,axis=1)
ax.plot(x,savings,label='savings all')
ax.legend()
plt.title('Savings all')
plt.show()
fig,ax=plt.subplots()
x=np.linspace(self.min_age,self.max_age,self.n_time)
savings=np.mean(self.infostats_savings,axis=1)
ax.plot(x,savings_0,label='unemp')
ax.plot(x,savings_1,label='emp')
ax.plot(x,savings_2,label='retired')
plt.title('Savings by emp state')
ax.legend()
plt.show()
fig,ax=plt.subplots()
x=np.linspace(self.min_age,self.max_age,self.n_time)
savings=np.mean(self.sav_actions-20,axis=1)
ax.plot(x[1:],savings[1:],label='savings action')
ax.legend()
plt.title('Saving action')
plt.show()
fig,ax=plt.subplots()
x=np.linspace(self.min_age,self.max_age,self.n_time)
savings=np.mean(self.infostats_savings,axis=1)
ax.plot(x[1:],act_savings_0[1:]-20,label='unemp')
ax.plot(x[1:],act_savings_1[1:]-20,label='emp')
ax.plot(x[1:],act_savings_2[1:]-20,label='retired')
plt.title('Saving action by emp state')
ax.legend()
plt.show()
def plot_emp_by_gender(self,figname=None):
x=np.linspace(self.min_age,self.max_age,self.n_time)
for gender in range(2):
if gender<1:
empstate_ratio=100*np.sum(self.gempstate[:,:,0:3],axis=2)/(np.sum(self.galive[:,0:3],axis=1)[:,None])
genderlabel='miehet'
else:
empstate_ratio=100*np.sum(self.gempstate[:,:,3:6],axis=2)/(np.sum(self.galive[:,3:6],axis=1)[:,None])
genderlabel='naiset'
if figname is not None:
self.plot_states(empstate_ratio,ylabel=self.labels['osuus tilassa x'].format(genderlabel),stack=True,figname=figname+'_stack')
else:
self.plot_states(empstate_ratio,ylabel=self.labels['osuus tilassa x'].format(genderlabel),stack=True)
if self.version in set([1,2,3,4]):
self.plot_states(empstate_ratio,ylabel=self.labels['osuus tilassa x'].format(genderlabel),ylimit=20,stack=False)
self.plot_states(empstate_ratio,ylabel=self.labels['osuus tilassa x'].format(genderlabel),parent=True,stack=False)
self.plot_states(empstate_ratio,ylabel=self.labels['osuus tilassa x'].format(genderlabel),unemp=True,stack=False)
if figname is not None:
self.plot_states(empstate_ratio,ylabel=self.labels['osuus tilassa x'].format(genderlabel),start_from=60,stack=True,figname=figname+'_stack60')
else:
self.plot_states(empstate_ratio,ylabel=self.labels['osuus tilassa x'].format(genderlabel),start_from=60,stack=True)
def plot_parents_in_work(self):
empstate_ratio=100*self.empstate/self.alive
ml=100*self.infostats_mother_in_workforce/self.alive
x=np.linspace(self.min_age,self.max_age,self.n_time)
fig,ax=plt.subplots()
ax.plot(x,ml,label='äitiysvapaa')
ax.plot(x,empstate_ratio[:,6],label='isyysvapaa')
ax.legend()
plt.show()
def plot_spouse(self,figname=None):
x=np.linspace(self.min_age,self.max_age,self.n_time)
fig,ax=plt.subplots()
ax.set_xlabel(self.labels['age'])
spouseratio=self.infostats_puoliso/self.alive[:,0]
ax.set_ylabel('spouses')
ax.plot(x,spouseratio)
if figname is not None:
plt.savefig(figname+'spouses.eps', format='eps')
plt.show()
def plot_unemp(self,unempratio=True,figname=None,grayscale=False):
'''
Plottaa työttömyysaste (unempratio=True) tai työttömien osuus väestöstö (False)
'''
x=np.linspace(self.min_age,self.max_age,self.n_time)
if unempratio:
tyollisyysaste,osatyoaste,tyottomyysaste,ka_tyottomyysaste=self.comp_empratios(self.empstate,self.alive,unempratio=True)
unempratio_stat=100*self.empstats.unempratio_stats()
if self.language=='Finnish':
labeli='keskimääräinen työttömyysaste '+str(ka_tyottomyysaste)
ylabeli=self.labels['tyottomyysaste']
labeli2='työttömyysaste'
else:
labeli='average unemployment rate '+str(ka_tyottomyysaste)
ylabeli=self.labels['tyottomyysaste']
labeli2='Unemployment rate'
else:
tyollisyysaste,osatyoaste,tyottomyysaste,ka_tyottomyysaste=self.comp_empratios(self.empstate,self.alive,unempratio=False)
unempratio_stat=100*self.empstats.unemp_stats()
if self.language=='Finnish':
labeli='keskimääräinen työttömien osuus väestöstö '+str(ka_tyottomyysaste)
ylabeli='Työttömien osuus väestöstö [%]'
labeli2='työttömien osuus väestöstö'
else:
labeli='proportion of unemployed'+str(ka_tyottomyysaste)
ylabeli='Proportion of unemployed [%]'
labeli2='proportion of unemployed'
fig,ax=plt.subplots()
ax.set_xlabel(self.labels['age'])
ax.set_ylabel(ylabeli)
ax.plot(x,tyottomyysaste,label=self.labels['malli'])
ax.plot(x,unempratio_stat,ls='--',label=self.labels['havainto'])
ax.legend()
if figname is not None:
plt.savefig(figname+'tyottomyysaste.eps', format='eps')
plt.show()
fig,ax=plt.subplots()
ax.set_xlabel(self.labels['age'])
ax.set_ylabel(ylabeli)
ax.plot(x,unempratio_stat,label=self.labels['havainto'])
ax.legend()
if grayscale:
pal=sns.light_palette("black", 8, reverse=True)
else:
pal=sns.color_palette("hls", self.n_employment) # hls, husl, cubehelix
ax.stackplot(x,tyottomyysaste,colors=pal) #,label=self.labels['malli'])
#ax.plot(x,tyottomyysaste)
plt.show()
fig,ax=plt.subplots()
for gender in range(2):
if gender==0:
leg='Miehet'
gempstate=np.sum(self.gempstate[:,:,0:3],axis=2)
alive=np.zeros((self.galive.shape[0],1))
alive[:,0]=np.sum(self.galive[:,0:3],1)
color='darkgray'
else:
gempstate=np.sum(self.gempstate[:,:,3:6],axis=2)
alive=np.zeros((self.galive.shape[0],1))
alive[:,0]=np.sum(self.galive[:,3:6],1)
leg='Naiset'
color='black'
tyollisyysaste,osatyoaste,tyottomyysaste,ka_tyottomyysaste=self.comp_empratios(gempstate,alive,unempratio=unempratio)
ax.plot(x,tyottomyysaste,color=color,label='{} {}'.format(labeli2,leg))
if grayscale:
lstyle='--'
else:
lstyle='--'
if self.version in set([1,2,3,4]):
if unempratio:
ax.plot(x,100*self.empstats.unempratio_stats(g=1),ls=lstyle,label=self.labels['havainto, naiset'])
ax.plot(x,100*self.empstats.unempratio_stats(g=2),ls=lstyle,label=self.labels['havainto, miehet'])
labeli='keskimääräinen työttömyysaste '+str(ka_tyottomyysaste)
ylabeli=self.labels['tyottomyysaste']
else:
ax.plot(x,100*self.empstats.unemp_stats(g=1),ls=lstyle,label=self.labels['havainto, naiset'])
ax.plot(x,100*self.empstats.unemp_stats(g=2),ls=lstyle,label=self.labels['havainto, miehet'])
labeli='keskimääräinen työttömien osuus väestöstö '+str(ka_tyottomyysaste)
ylabeli=self.labels['tyottomien osuus']
ax.set_xlabel(self.labels['age'])
ax.set_ylabel(ylabeli)
if False:
ax.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
else:
ax.legend()
if figname is not None:
plt.savefig(figname+'tyottomyysaste_spk.eps', format='eps')
plt.show()
def plot_parttime_ratio(self,grayscale=True,figname=None):
'''
Plottaa osatyötä tekevien osuus väestöstö
'''
x=np.linspace(self.min_age,self.max_age,self.n_time)
labeli2='Osatyötä tekevien osuus'
fig,ax=plt.subplots()
for gender in range(2):
if gender==0:
leg='Miehet'
g='men'
pstyle='-'
else:
g='women'
leg='Naiset'
pstyle=''
tyollisyysaste,osatyoaste,tyottomyysaste,ka_tyottomyysaste=self.comp_gempratios(gender=g,unempratio=False)
ax.plot(x,osatyoaste,'{}'.format(pstyle),label='{} {}'.format(labeli2,leg))
o_x=np.array([20,30,40,50,60,70])
f_osatyo=np.array([55,21,16,12,18,71])
m_osatyo=np.array([32,8,5,4,9,65])
if grayscale:
ax.plot(o_x,f_osatyo,ls='--',label=self.labels['havainto, naiset'])
ax.plot(o_x,m_osatyo,ls='--',label=self.labels['havainto, miehet'])
else:
ax.plot(o_x,f_osatyo,label=self.labels['havainto, naiset'])
ax.plot(o_x,m_osatyo,label=self.labels['havainto, miehet'])
labeli='osatyöaste '#+str(ka_tyottomyysaste)
ylabeli='Osatyön osuus työnteosta [%]'
ax.set_xlabel(self.labels['age'])
ax.set_ylabel(ylabeli)
if False:
ax.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
else:
ax.legend()
if figname is not None:
plt.savefig(figname+'osatyoaste_spk.eps', format='eps')
plt.show()
def plot_unemp_shares(self):
empstate_ratio=100*self.empstate/self.alive
self.plot_states(empstate_ratio,ylabel='Osuus tilassa [%]',onlyunemp=True,stack=True)
def plot_group_emp(self,grayscale=False,figname=None):
fig,ax=plt.subplots()
if grayscale:
lstyle='--'
else:
lstyle='--'
for gender in range(2):
if gender==0:
leg='Miehet'
gempstate=np.sum(self.gempstate[:,:,0:3],axis=2)
alive=np.zeros((self.galive.shape[0],1))
alive[:,0]=np.sum(self.galive[:,0:3],1)
color='darkgray'
else:
gempstate=np.sum(self.gempstate[:,:,3:6],axis=2)
alive=np.zeros((self.galive.shape[0],1))
alive[:,0]=np.sum(self.galive[:,3:6],1)
leg='Naiset'
color='black'
tyollisyysaste,osatyoaste,tyottomyysaste,ka_tyottomyysaste=self.comp_empratios(gempstate,alive)
x=np.linspace(self.min_age,self.max_age,self.n_time)
ax.plot(x,tyollisyysaste,color=color,label='työllisyysaste {}'.format(leg))
#ax.plot(x,tyottomyysaste,label='työttömyys {}'.format(leg))
emp_statsratio=100*self.empstats.emp_stats(g=2)
ax.plot(x,emp_statsratio,ls=lstyle,color='darkgray',label=self.labels['havainto, miehet'])
emp_statsratio=100*self.empstats.emp_stats(g=1)
ax.plot(x,emp_statsratio,ls=lstyle,color='black',label=self.labels['havainto, naiset'])
ax.set_xlabel(self.labels['age'])
ax.set_ylabel(self.labels['ratio'])
if False:
ax.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
else:
ax.legend()
if figname is not None:
plt.savefig(figname+'tyollisyysaste_spk.eps', format='eps')
plt.show()
def plot_pensions(self):
if self.version in set([1,2,3,4]):
self.plot_ratiostates(self.stat_pension,ylabel='Tuleva eläke [e/v]',stack=False)
def plot_career(self):
if self.version in set([1,2,3,4]):
self.plot_ratiostates(self.stat_tyoura,ylabel='Työuran pituus [v]',stack=False)
def plot_ratiostates(self,statistic,ylabel='',ylimit=None, show_legend=True, parent=False,\
unemp=False,start_from=None,stack=False,no_ve=False,figname=None,emp=False,oa_unemp=False):
self.plot_states(statistic/self.empstate,ylabel=ylabel,ylimit=ylimit,no_ve=no_ve,\
show_legend=show_legend,parent=parent,unemp=unemp,start_from=start_from,\
stack=stack,figname=figname,emp=emp,oa_unemp=oa_unemp)
def count_putki(self,emps=None):
if emps is None:
piped=np.reshape(self.empstate[:,4],(self.empstate[:,4].shape[0],1))
demog2=self.empstats.get_demog()
putkessa=self.timestep*np.nansum(piped[1:]/self.alive[1:]*demog2[1:])
return putkessa
else:
piped=np.reshape(emps[:,4],(emps[:,4].shape[0],1))
demog2=self.empstats.get_demog()
alive=np.sum(emps,axis=1,keepdims=True)
putkessa=self.timestep*np.nansum(piped[1:]/alive[1:]*demog2[1:])
return putkessa
def plot_states(self,statistic,ylabel='',ylimit=None,show_legend=True,parent=False,unemp=False,no_ve=False,
start_from=None,stack=True,figname=None,yminlim=None,ymaxlim=None,
onlyunemp=False,reverse=False,grayscale=False,emp=False,oa_unemp=False):
if start_from is None:
x=np.linspace(self.min_age,self.max_age,self.n_time)
else:
x_n = self.max_age-60+1
x_t = int(np.round((x_n-1)*self.inv_timestep))+2
x=np.linspace(start_from,self.max_age,x_t)
#x=np.linspace(start_from,self.max_age,self.n_time)
statistic=statistic[self.map_age(start_from):]
ura_emp=statistic[:,1]
ura_ret=statistic[:,2]
ura_unemp=statistic[:,0]
if self.version in set([1,2,3,4]):
ura_disab=statistic[:,3]
ura_pipe=statistic[:,4]
ura_mother=statistic[:,5]
ura_dad=statistic[:,6]
ura_kht=statistic[:,7]
ura_vetyo=statistic[:,9]
ura_veosatyo=statistic[:,8]
ura_osatyo=statistic[:,10]
ura_outsider=statistic[:,11]
ura_student=statistic[:,12]
ura_tyomarkkinatuki=statistic[:,13]
ura_army=statistic[:,14]
else:
ura_osatyo=0 #statistic[:,3]
if no_ve:
ura_ret[-2:-1]=None
fig,ax=plt.subplots()
if stack:
if grayscale:
pal=sns.light_palette("black", 8, reverse=True)
else:
pal=sns.color_palette("hls", self.n_employment) # hls, husl, cubehelix
reverse=True
if parent:
if self.version in set([1,2,3,4]):
ax.stackplot(x,ura_mother,ura_dad,ura_kht,
labels=('äitiysvapaa','isyysvapaa','khtuki'), colors=pal)
elif unemp:
if self.version in set([1,2,3,4]):
ax.stackplot(x,ura_unemp,ura_pipe,ura_student,ura_outsider,ura_tyomarkkinatuki,
labels=('tyött','putki','opiskelija','ulkona','tm-tuki'), colors=pal)
else:
ax.stackplot(x,ura_unemp,labels=('tyött'), colors=pal)
elif onlyunemp:
if self.version in set([1,2,3,4]):
#urasum=np.nansum(statistic[:,[0,4,11,13]],axis=1)/100
urasum=np.nansum(statistic[:,[0,4,13]],axis=1)/100
osuus=(1.0-np.array([0.84,0.68,0.62,0.58,0.57,0.55,0.53,0.50,0.29]))*100
xx=np.array([22.5,27.5,32.5,37.5,42.5,47.5,52.5,57.5,62.5])
#ax.stackplot(x,ura_unemp/urasum,ura_pipe/urasum,ura_outsider/urasum,ura_tyomarkkinatuki/urasum,
# labels=('ansiosidonnainen','lisäpäivät','työvoiman ulkopuolella','tm-tuki'), colors=pal)
ax.stackplot(x,ura_unemp/urasum,ura_pipe/urasum,ura_tyomarkkinatuki/urasum,
labels=('ansiosidonnainen','lisäpäivät','tm-tuki'), colors=pal)
ax.plot(xx,osuus,color='k')
else:
ax.stackplot(x,ura_unemp,labels=('tyött'), colors=pal)
else:
if self.version in set([1,2,3,4]):
#ax.stackplot(x,ura_emp,ura_osatyo,ura_vetyo,ura_veosatyo,ura_unemp,ura_tyomarkkinatuki,ura_pipe,ura_disab,ura_mother,ura_dad,ura_kht,ura_ret,ura_student,ura_outsider,ura_army,
# labels=('työssä','osatyö','ve+työ','ve+osatyö','työtön','tm-tuki','työttömyysputki','tk-eläke','äitiysvapaa','isyysvapaa','kh-tuki','vanhuuseläke','opiskelija','työvoiman ulkop.','armeijassa'),
# colors=pal)
ax.stackplot(x,ura_emp,ura_osatyo,ura_vetyo,ura_veosatyo,ura_unemp,ura_tyomarkkinatuki,ura_pipe,ura_ret,ura_disab,ura_mother,ura_dad,ura_kht,ura_student,ura_outsider,ura_army,
labels=('työssä','osatyö','ve+työ','ve+osatyö','työtön','tm-tuki','työttömyysputki','vanhuuseläke','tk-eläke','äitiysvapaa','isyysvapaa','kh-tuki','opiskelija','työvoiman ulkop.','armeijassa'),
colors=pal)
else:
#ax.stackplot(x,ura_emp,ura_osatyo,ura_unemp,ura_ret,
# labels=('työssä','osa-aikatyö','työtön','vanhuuseläke'), colors=pal)
ax.stackplot(x,ura_emp,ura_unemp,ura_ret,
labels=('työssä','työtön','vanhuuseläke'), colors=pal)
if start_from is None:
ax.set_xlim(self.min_age,self.max_age)
else:
ax.set_xlim(60,self.max_age)
if ymaxlim is None:
ax.set_ylim(0, 100)
else:
ax.set_ylim(yminlim,ymaxlim)
else:
if parent:
if self.version in set([1,2,3,4]):
ax.plot(x,ura_mother,label='äitiysvapaa')
ax.plot(x,ura_dad,label='isyysvapaa')
ax.plot(x,ura_kht,label='khtuki')
elif unemp:
ax.plot(x,ura_unemp,label='tyött')
if self.version in set([1,2,3,4]):
ax.plot(x,ura_tyomarkkinatuki,label='tm-tuki')
ax.plot(x,ura_student,label='student')
ax.plot(x,ura_outsider,label='outsider')
ax.plot(x,ura_pipe,label='putki')
elif oa_unemp:
ax.plot(x,ura_unemp,label='tyött')
if self.version in set([1,2,3,4]):
ax.plot(x,ura_tyomarkkinatuki,label='tm-tuki')
ax.plot(x,ura_student,label='student')
ax.plot(x,ura_outsider,label='outsider')
ax.plot(x,ura_pipe,label='putki')
ax.plot(x,ura_osatyo,label='osa-aika')
elif emp:
ax.plot(x,ura_emp,label='työssä')
#if self.version in set([1,2,3,4]):
ax.plot(x,ura_osatyo,label='osatyö')
else:
ax.plot(x,ura_unemp,label='tyött')
ax.plot(x,ura_ret,label='eläke')
ax.plot(x,ura_emp,label='työ')
if self.version in set([1,2,3,4]):
ax.plot(x,ura_osatyo,label='osatyö')
ax.plot(x,ura_disab,label='tk')
ax.plot(x,ura_pipe,label='putki')
ax.plot(x,ura_tyomarkkinatuki,label='tm-tuki')
ax.plot(x,ura_mother,label='äitiysvapaa')
ax.plot(x,ura_dad,label='isyysvapaa')
ax.plot(x,ura_kht,label='khtuki')
ax.plot(x,ura_vetyo,label='ve+työ')
ax.plot(x,ura_veosatyo,label='ve+osatyö')
ax.plot(x,ura_student,label='student')
ax.plot(x,ura_outsider,label='outsider')
ax.plot(x,ura_army,label='armeijassa')
ax.set_xlabel(self.labels['age'])
ax.set_ylabel(ylabel)
if show_legend:
if not reverse:
lgd=ax.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
else:
handles, labels = ax.get_legend_handles_labels()
lgd=ax.legend(handles[::-1], labels[::-1], bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
if ylimit is not None:
ax.set_ylim([0,ylimit])
#fig.tight_layout()
if figname is not None:
if show_legend:
plt.savefig(figname,bbox_inches='tight',bbox_extra_artists=(lgd,), format='eps')
else:
plt.savefig(figname,bbox_inches='tight', format='eps')
plt.show()
def plot_toe(self):
if self.version in set([1,2,3,4]):
self.plot_ratiostates(self.stat_toe,'työssäolo-ehdon pituus 28 kk aikana [v]',stack=False)
def plot_sal(self):
self.plot_ratiostates(self.salaries_emp,'Keskipalkka [e/v]',stack=False)
def plot_moved(self):
siirtyneet_ratio=self.siirtyneet/self.alive*100
self.plot_states(siirtyneet_ratio,ylabel='Siirtyneet tilasta',stack=True,
yminlim=0,ymaxlim=min(100,1.1*np.nanmax(np.cumsum(siirtyneet_ratio,1))))
pysyneet_ratio=self.pysyneet/self.alive*100
self.plot_states(pysyneet_ratio,ylabel='Pysyneet tilassa',stack=True,
yminlim=0,ymaxlim=min(100,1.1*np.nanmax(np.cumsum(pysyneet_ratio,1))))
siirtyneet_ratio=self.siirtyneet_det[:,:,1]/self.alive*100
self.plot_states(siirtyneet_ratio,ylabel='Siirtyneet työhön tilasta',stack=True,
yminlim=0,ymaxlim=min(100,1.1*np.nanmax(np.cumsum(siirtyneet_ratio,1))))
siirtyneet_ratio=self.siirtyneet_det[:,:,4]/self.alive*100
self.plot_states(siirtyneet_ratio,ylabel='Siirtyneet putkeen tilasta',stack=True,
yminlim=0,ymaxlim=min(100,1.1*np.nanmax(np.cumsum(siirtyneet_ratio,1))))
siirtyneet_ratio=self.siirtyneet_det[:,:,0]/self.alive*100
self.plot_states(siirtyneet_ratio,ylabel='Siirtyneet työttömäksi tilasta',stack=True,
yminlim=0,ymaxlim=min(100,1.1*np.nanmax(np.cumsum(siirtyneet_ratio,1))))
siirtyneet_ratio=self.siirtyneet_det[:,:,13]/self.alive*100
self.plot_states(siirtyneet_ratio,ylabel='Siirtyneet tm-tuelle tilasta',stack=True,
yminlim=0,ymaxlim=min(100,1.1*np.nanmax(np.cumsum(siirtyneet_ratio,1))))
siirtyneet_ratio=self.siirtyneet_det[:,:,10]/self.alive*100
self.plot_states(siirtyneet_ratio,ylabel='Siirtyneet osa-aikatyöhön tilasta',stack=True,
yminlim=0,ymaxlim=min(100,1.1*np.nanmax(np.cumsum(siirtyneet_ratio,1))))
# def plot_army(self):
# x=np.linspace(self.min_age,self.max_age,self.n_time)
# fig,ax=plt.subplots()
# ax.plot(x,100*self.empstate[:,14]/self.alive[:,0],label='armeijassa ja siviilipalveluksessa olevat')
# emp_statsratio=100*self.army_stats()
# ax.plot(x,emp_statsratio,label='havainto')
# ax.set_xlabel(self.labels['age'])
# ax.set_ylabel(self.labels['ratio'])
# ax.legend()
# plt.show()
#
# def plot_group_army(self):
# fig,ax=plt.subplots()
# for gender in range(2):
# if gender==0:
# leg='Armeija Miehet'
# opiskelijat=np.sum(self.gempstate[:,14,0:3],axis=1)
# alive=np.zeros((self.galive.shape[0],1))
# alive[:,0]=np.sum(self.galive[:,0:3],1)
# else:
# leg='Armeija Naiset'
# opiskelijat=np.sum(self.gempstate[:,14,3:6],axis=1)
# alive=np.zeros((self.galive.shape[0],1))
# alive[:,0]=np.sum(self.galive[:,3:6],1)
#
# opiskelijat=np.reshape(opiskelijat,(self.galive.shape[0],1))
# osuus=100*opiskelijat/alive
# x=np.linspace(self.min_age,self.max_age,self.n_time)
# ax.plot(x,osuus,label=leg)
#
# emp_statsratio=100*self.army_stats(g=1)
# ax.plot(x,emp_statsratio,label=self.labels['havainto, naiset'])
# emp_statsratio=100*self.army_stats(g=2)
# ax.plot(x,emp_statsratio,label=self.labels['havainto, miehet'])
# ax.set_xlabel(self.labels['age'])
# ax.set_ylabel(self.labels['ratio'])
# ax.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
# plt.show()
#
def plot_ave_stay(self):
self.plot_ratiostates(self.time_in_state,ylabel='Ka kesto tilassa',stack=False)
fig,ax=plt.subplots()
x=np.linspace(self.min_age,self.max_age,self.n_time)
plt.plot(x,self.time_in_state[:,1]/self.empstate[:,1])
ax.set_xlabel('Aika')
ax.set_ylabel('Ka kesto työssä')
plt.show()
fig,ax=plt.subplots()
ax.set_xlabel('Aika')
ax.set_ylabel('ka kesto työttömänä')
plt.plot(x,self.time_in_state[:,0]/self.empstate[:,0])
plt.show()
def plot_ove(self):
self.plot_ratiostates(self.infostats_ove,ylabel='Ove',stack=False)
def plot_reward(self):
self.plot_ratiostates(self.rewstate,ylabel='Keskireward tilassa',stack=False)
self.plot_ratiostates(self.rewstate,ylabel='Keskireward tilassa',stack=False,no_ve=True)
self.plot_ratiostates(self.rewstate,ylabel='Keskireward tilassa',stack=False,oa_unemp=True)
x=np.linspace(self.min_age,self.max_age,self.n_time)
total_reward=np.sum(self.rewstate,axis=1)
fig,ax=plt.subplots()
ax.plot(x,total_reward)
ax.set_xlabel('Aika')
ax.set_ylabel('Koko reward tilassa')
ax.legend()
plt.show()
def vector_to_array(self,x):
return x[:,None]
def comp_scaled_consumption(self,x0,averaged=False,t0=1):
'''
Computes discounted actual reward at each time point
with a given scaling x
averaged determines whether the value is averaged over time or not
'''
x=x0[0]
u=np.zeros(self.n_time)
for k in range(self.n_pop):
#g=self.infostats_group[k]
for t in range(1,self.n_time-1):
age=t+self.min_age
income=self.infostats_poptulot_netto[t,k]
employment_state=self.popempstate[t,k]
v,_=self.env.log_utility((1+x)*income,employment_state,age)
if np.isnan(v):
print('NaN',v,income,employment_state,age)
v=0
u[t]+=v
#print(age,v)
t=self.n_time-1
age=t+self.min_age
income=self.infostats_poptulot_netto[t,k]
employment_state=self.popempstate[t,k]
v0,_=self.env.log_utility(income,employment_state,age)
factor=self.poprewstate[t,k]/v0 # life expectancy
v,_=self.env.log_utility((1+x)*income,employment_state,age)
if np.isnan(v):
print('NaN',v,income,employment_state,age)
if np.isnan(factor):
print('NaN',factor,v0)
#print(age,v*factor,factor)
u[t]+=v*factor
if np.isnan(u[t]):
print('NaN',age,v,v*factor,factor,u[t],income,employment_state)
u=u/self.n_pop
w=np.zeros(self.n_time)
w[-1]=u[-1]
for t in range(self.n_time-2,0,-1):
w[t]=u[t]+self.gamma*w[t+1]
if averaged:
ret=np.mean(w[t0:])
else:
ret=w[t0]
if np.isnan(ret):
print(u,w)
u=np.zeros(self.n_time)
for k in range(self.n_pop):
#g=self.infostats_group[k]
for t in range(1,self.n_time-1):
age=t+self.min_age
income=self.infostats_poptulot_netto[t,k]
employment_state=self.popempstate[t,k]
v,_=self.env.log_utility((1+x)*income,employment_state,age) #,g=g,pinkslip=pinkslip)
#print(t,k,v,income)
u[t]+=v
t=self.n_time-1
age=t-1+self.min_age
income=self.infostats_poptulot_netto[t,k]
employment_state=self.popempstate[t,k]
v0,_=self.env.log_utility(income,employment_state,age) #,g=g,pinkslip=pinkslip)
factor=self.poprewstate[t,k]/v0 # life expectancy
v,_=self.env.log_utility((1+x)*income,employment_state,age) #,g=g,pinkslip=pinkslip)
#print(t,k,v,income)
u[t]+=v*factor
#print(x,ret)
return ret
def comp_presentvalue(self):
'''
Computes discounted actual reward at each time point
with a given scaling x
averaged determines whether the value is averaged over time or not
'''
u=np.zeros((self.n_time,self.n_pop))
u[self.n_time-1,:]=self.poprewstate[self.n_time-1,:]
for t in range(self.n_time-2,-1,-1):
u[t,:]=self.poprewstate[t,:]+self.gamma*u[t+1,:]
return u
def comp_realoptimrew(self,discountfactor=None):
'''
Computes discounted actual reward at each time point
'''
if discountfactor is None:
discountfactor=self.gamma
realrew=np.zeros(self.n_time)
for k in range(self.n_pop):
prew=np.zeros(self.n_time)
prew[-1]=self.poprewstate[-1,k]
for t in range(self.n_time-2,0,-1):
prew[t]=discountfactor*prew[t+1]+self.poprewstate[t,k]
realrew+=prew
realrew/=self.n_pop
realrew=np.mean(realrew[1:])
return realrew
def get_reward(self,discounted=False):
return self.comp_total_reward(output=False,discounted=discounted) #np.sum(self.rewstate)/self.n_pop
def comp_total_reward(self,output=False,discounted=False,discountfactor=None):
if not discounted:
total_reward=np.sum(self.rewstate)
rr=total_reward/self.n_pop
disco='undiscounted'
else:
#discount=discountfactor**np.arange(0,self.n_time*self.timestep,self.timestep)[:,None]
#total_reward=np.sum(self.poprewstate*discount)
rr=self.comp_realoptimrew(discountfactor) #total_reward/self.n_pop
disco='discounted'
#print('total rew1 {} rew2 {}'.format(total_reward,np.sum(self.poprewstate)))
#print('ave rew1 {} rew2 {}'.format(rr,np.mean(np.sum(self.poprewstate,axis=0))))
#print('shape rew2 {} pop {} alive {}'.format(self.poprewstate.shape,self.n_pop,self.alive[0]))
if output:
print(f'Ave {disco} reward {rr}')
return rr
def comp_total_netincome(self,output=True):
rr=np.sum(self.infostats_tulot_netto)/self.n_pop/(self.n_time+21.0) # 21 approximates the time in pension
eq=np.sum(self.infostats_equivalent_income)/self.n_pop/(self.n_time+21.0) # 21 approximates the time in pension
if output:
print('Ave net income {} Ave equivalent net income {}'.format(rr,eq))
return rr,eq
def plot_wage_reduction(self):
self.plot_ratiostates(self.stat_wage_reduction,ylabel='wage-reduction tilassa',stack=False)
self.plot_ratiostates(self.stat_wage_reduction,ylabel='wage-reduction tilassa',stack=False,unemp=True)
self.plot_ratiostates(self.stat_wage_reduction,ylabel='wage-reduction tilassa',stack=False,emp=True)
#self.plot_ratiostates(np.log(1.0+self.stat_wage_reduction),ylabel='log 5wage-reduction tilassa',stack=False)
self.plot_ratiostates(np.sum(self.stat_wage_reduction_g[:,:,0:3],axis=2),ylabel='wage-reduction tilassa naiset',stack=False)
self.plot_ratiostates(np.sum(self.stat_wage_reduction_g[:,:,3:6],axis=2),ylabel='wage-reduction tilassa miehet',stack=False)
self.plot_ratiostates(np.sum(self.stat_wage_reduction_g[:,:,0:3],axis=2),ylabel='wage-reduction tilassa, naiset',stack=False,unemp=True)
self.plot_ratiostates(np.sum(self.stat_wage_reduction_g[:,:,3:6],axis=2),ylabel='wage-reduction tilassa, miehet',stack=False,unemp=True)
self.plot_ratiostates(np.sum(self.stat_wage_reduction_g[:,:,0:3],axis=2),ylabel='wage-reduction tilassa, naiset',stack=False,emp=True)
self.plot_ratiostates(np.sum(self.stat_wage_reduction_g[:,:,3:6],axis=2),ylabel='wage-reduction tilassa, miehet',stack=False,emp=True)
def plot_distrib(self,label='',plot_emp=False,plot_bu=False,ansiosid=False,tmtuki=False,putki=False,outsider=False,max_age=500,laaja=False,max=4,figname=None):
unemp_distrib,emp_distrib,unemp_distrib_bu=self.comp_empdistribs(ansiosid=ansiosid,tmtuki=tmtuki,putki=putki,outsider=outsider,max_age=max_age,laaja=laaja)
tyoll_distrib,tyoll_distrib_bu=self.comp_tyollistymisdistribs(ansiosid=ansiosid,tmtuki=tmtuki,putki=putki,outsider=outsider,max_age=max_age,laaja=laaja)
if plot_emp:
self.plot_empdistribs(emp_distrib)
if plot_bu:
self.plot_unempdistribs_bu(unemp_distrib_bu)
else:
self.plot_unempdistribs(unemp_distrib,figname=figname)
#self.plot_tyolldistribs(unemp_distrib,tyoll_distrib,tyollistyneet=False)
if plot_bu:
self.plot_tyolldistribs_both_bu(unemp_distrib_bu,tyoll_distrib_bu,max=max)
else:
self.plot_tyolldistribs_both(unemp_distrib,tyoll_distrib,max=max,figname=figname)
def plot_irr(self,figname=''):
self.comp_aggirr()
self.comp_irr()
self.plot_irrdistrib(self.infostats_irr,figname=figname)
def plot_irrdistrib(self,irr_distrib,grayscale=True,figname=''):
if grayscale:
plt.style.use('grayscale')
plt.rcParams['figure.facecolor'] = 'white' # Or any suitable colour...
print('Nans {} out of {}'.format(np.sum(np.isnan(irr_distrib)),irr_distrib.shape[0]))
fig,ax=plt.subplots()
ax.set_xlabel('Sisäinen tuottoaste [%]')
lbl=ax.set_ylabel('Taajuus')
#ax.set_yscale('log')
#max_time=50
#nn_time = int(np.round((max_time)*self.inv_timestep))+1
x=np.linspace(-5,5,100)
scaled,x2=np.histogram(irr_distrib,x)
#scaled=scaled/np.nansum(np.abs(irr_distrib))
ax.bar(x2[1:-1],scaled[1:],align='center')
if figname is not None:
plt.savefig(figname+'irrdistrib.eps', bbox_inches='tight', format='eps')
plt.show()
fig,ax=plt.subplots()
ax.hist(irr_distrib,bins=40)
plt.show()
print('Keskimääräinen irr {:.3f} %'.format(np.nanmean(irr_distrib)))
print('Mediaani irr {:.3f} %'.format(np.nanmedian(irr_distrib)))
count = (irr_distrib < 0).sum(axis=0)
percent = np.true_divide(count,irr_distrib.shape[0])
print('Osuus irr<0 {} %:lla'.format(100*percent))
count = (irr_distrib <=-50).sum(axis=0)
percent = np.true_divide(count,irr_distrib.shape[0])
print('Osuus irr<-50 {} %:lla'.format(100*percent))
count = (np.sum(self.infostats_paid_tyel_pension,axis=0)<0.1).sum()
percent = np.true_divide(count,irr_distrib.shape[0])
print('Osuus eläke ei maksussa {} %:lla'.format(100*percent))
count1 = np.sum(self.popempstate[0:self.map_age(63),:]==15)
count = (np.sum(self.infostats_paid_tyel_pension,axis=0)<0.1).sum()-count1
percent = np.true_divide(count,irr_distrib.shape[0])
print('Osuus eläke ei maksussa, ei kuollut {} %:lla'.format(100*percent))
count = np.sum(self.popempstate==15)
percent = np.true_divide(count,irr_distrib.shape[0])
print('Osuus kuolleet {} %:lla'.format(100*percent))
def get_initial_reward(self,startage=None):
real=self.comp_presentvalue()
if startage is None:
startage=self.min_age
age=max(1,startage-self.min_age)
realage=max(self.min_age+1,startage)
print('Initial discounted reward at age {}: {}'.format(realage,np.mean(real[age,:])))
return np.mean(real[age,:])
def plot_stats(self,grayscale=False,figname=None):
if grayscale:
plt.style.use('grayscale')
plt.rcParams['figure.facecolor'] = 'white' # Or any suitable colour...
self.comp_total_reward()
self.comp_total_reward(discounted=True)
self.comp_total_netincome()
#self.plot_rewdist()
#self.plot_emp(figname=figname)
if self.version in set([1,2,3,4]):
q=self.comp_budget(scale=True)
q_stat=self.stat_budget()
df1 = pd.DataFrame.from_dict(q,orient='index',columns=['e/v'])
df2 = pd.DataFrame.from_dict(q_stat,orient='index',columns=['toteuma'])
df=df1.copy()
df['toteuma']=df2['toteuma']
df['ero']=df1['e/v']-df2['toteuma']
print('Rahavirrat skaalattuna väestötasolle')
print(tabulate(df, headers='keys', tablefmt='psql', floatfmt=",.2f"))
q=self.comp_participants(scale=True)
q_stat=self.stat_participants_2018()
q_days=self.stat_days_2018()
df1 = pd.DataFrame.from_dict(q,orient='index',columns=['arvio (htv)'])
df2 = pd.DataFrame.from_dict(q_stat,orient='index',columns=['toteuma'])
df3 = pd.DataFrame.from_dict(q_days,orient='index',columns=['htv_tot'])
df=df1.copy()
df['toteuma (kpl)']=df2['toteuma']
df['toteuma (htv)']=df3['htv_tot']
df['ero (htv)']=df['arvio (htv)']-df['toteuma (htv)']
print('Henkilöitä tiloissa skaalattuna väestötasolle')
print(tabulate(df, headers='keys', tablefmt='psql', floatfmt=",.0f"))
else:
q=self.comp_participants(scale=True)
q_stat=self.stat_participants_2018()
q_days=self.stat_days_2018()
df1 = pd.DataFrame.from_dict(q,orient='index',columns=['arvio (htv)'])
df2 = pd.DataFrame.from_dict(q_stat,orient='index',columns=['toteuma'])
df3 = pd.DataFrame.from_dict(q_days,orient='index',columns=['htv_tot'])
df=df1.copy()
df['toteuma (kpl)']=df2['toteuma']
df['toteuma (htv)']=df3['htv_tot']
df['ero (htv)']=df['arvio (htv)']-df['toteuma (htv)']
print('Henkilöitä tiloissa skaalattuna väestötasolle')
print(tabulate(df, headers='keys', tablefmt='psql', floatfmt=",.0f"))
G=self.comp_gini()
print('Gini coefficient is {}'.format(G))
print('Real discounted reward {}'.format(self.comp_realoptimrew()))
print('vrt reward {}'.format(self.comp_scaled_consumption(np.array([0]))))
real=self.comp_presentvalue()
print('Initial discounted reward {}'.format(np.mean(real[1,:])))
self.plot_emp(figname=figname)
if self.version in set([1,2,3,4]):
self.plot_outsider()
print('Keskikestot käytettyjen ansiosidonnaisten päivärahojen mukaan')
keskikesto=self.comp_unemp_durations()
df = pd.DataFrame.from_dict(keskikesto,orient='index',columns=['0-6 kk','6-12 kk','12-18 kk','18-24kk','yli 24 kk'])
print(tabulate(df, headers='keys', tablefmt='psql', floatfmt=",.2f"))
print('Keskikestot viimeisimmän työttömyysjakson mukaan')
keskikesto=self.comp_unemp_durations_v2()
df = pd.DataFrame.from_dict(keskikesto,orient='index',columns=['0-6 kk','6-12 kk','12-18 kk','18-24kk','yli 24 kk'])
print(tabulate(df, headers='keys', tablefmt='psql', floatfmt=",.2f"))
if self.version in set([1,2,3,4]):
print('Lisäpäivillä on {:.0f} henkilöä'.format(self.count_putki()))
if self.version in set([4]):
self.plot_spouse()
if self.version==101:
self.plot_savings()
if self.version in set([3]):
self.plot_ove()
self.plot_unemp(unempratio=True,figname=figname)
self.plot_unemp(unempratio=False)
self.plot_unemp_shares()
if self.version in set([1,2,3,4]):
self.plot_group_emp(figname=figname)
self.plot_parttime_ratio(figname=figname)
self.plot_sal()
if self.version in set([1,2,3,4]):
self.plot_taxes()
self.plot_pinkslip()
self.plot_outsider()
self.plot_student()
self.plot_kassanjasen()
#self.plot_army()
self.plot_group_student()
#self.plot_group_army()
self.plot_group_disab()
self.plot_moved()
self.plot_ave_stay()
self.plot_reward()
self.plot_pensions()
self.plot_career()
self.plot_toe()
self.plot_wage_reduction()
#self.plot_distrib(label='Jakauma ansiosidonnainen+tmtuki+putki, no max age',ansiosid=True,tmtuki=True,putki=True,outsider=False)
self.plot_distrib(label='Jakauma ansiosidonnainen+tmtuki+putki, jakso päättynyt ennen 50v ikää',ansiosid=True,tmtuki=True,putki=True,outsider=False,max_age=50,figname=figname)
if self.version in set([1,2,3,4]):
#self.plot_distrib(label='Jakauma ansiosidonnainen+tmtuki+putki, jakso päättynyt ennen 50v ikää, jäljellä oleva aika',plot_bu=True,ansiosid=True,tmtuki=True,putki=True,outsider=False,max_age=50)
self.plot_distrib(label='Jakauma ansiosidonnainen+putki, jakso päättynyt ennen 50v ikää, jäljellä oleva aika',plot_bu=False,ansiosid=True,tmtuki=False,putki=True,outsider=False,max_age=50)
#self.plot_distrib(label='Jakauma ansiosidonnainen+tmtuki ilman putkea',ansiosid=True,tmtuki=True,putki=False,outsider=False)
#self.plot_distrib(label='Jakauma ansiosidonnainen+tmtuki ilman putkea, max Ikä 50v',ansiosid=True,tmtuki=True,putki=False,outsider=False,max_age=50)
self.plot_distrib(label='Jakauma tmtuki',ansiosid=False,tmtuki=True,putki=False,outsider=False)
#self.plot_distrib(label='Jakauma työvoiman ulkopuoliset',ansiosid=False,tmtuki=False,putki=False,outsider=True)
#self.plot_distrib(label='Jakauma laaja (ansiosidonnainen+tmtuki+putki+ulkopuoliset)',laaja=True)
def plot_final(self):
print('Keskikestot käytettyjen ansiosidonnaisten päivärahojen mukaan')
keskikesto=self.comp_unemp_durations()
df = pd.DataFrame.from_dict(keskikesto,orient='index',columns=['0-6 kk','6-12 kk','12-18 kk','18-24kk','yli 24 kk'])
print(tabulate(df, headers='keys', tablefmt='psql', floatfmt=",.2f"))
print('Keskikestot viimeisimmän työttömyysjakson mukaan')
keskikesto=self.comp_unemp_durations_v2()
df = pd.DataFrame.from_dict(keskikesto,orient='index',columns=['0-6 kk','6-12 kk','12-18 kk','18-24kk','yli 24 kk'])
print(tabulate(df, headers='keys', tablefmt='psql', floatfmt=",.2f"))
self.plot_emp()
if self.version in set([1,2,3,4]):
print('Lisäpäivillä on {:.0f} henkilöä'.format(self.count_putki()))
self.plot_unemp(unempratio=True)
self.plot_unemp(unempratio=False)
self.plot_unemp_shares()
if self.version in set([1,2,3,4]):
self.plot_group_emp()
self.plot_parttime_ratio()
self.plot_sal()
self.plot_distrib(label='Jakauma ansiosidonnainen+tmtuki+putki, no max age',ansiosid=True,tmtuki=True,putki=True,outsider=False)
self.plot_distrib(label='Jakauma ansiosidonnainen+tmtuki+putki, jakso päättynyt ennen 50v ikää',ansiosid=True,tmtuki=True,putki=True,outsider=False,max_age=50)
#self.plot_distrib(label='Jakauma ansiosidonnainen+tmtuki+putki, jakso päättynyt ennen 50v ikää, jäljellä oleva aika',plot_bu=True,ansiosid=True,tmtuki=True,putki=True,outsider=False,max_age=50)
self.plot_distrib(label='Jakauma ansiosidonnainen+putki, jakso päättynyt ennen 50v ikää, jäljellä oleva aika',plot_bu=False,ansiosid=True,tmtuki=False,putki=True,outsider=False,max_age=50)
#self.plot_distrib(label='Jakauma ansiosidonnainen+tmtuki ilman putkea',ansiosid=True,tmtuki=True,putki=False,outsider=False)
#self.plot_distrib(label='Jakauma ansiosidonnainen+tmtuki ilman putkea, max Ikä 50v',ansiosid=True,tmtuki=True,putki=False,outsider=False,max_age=50)
self.plot_distrib(label='Jakauma tmtuki',ansiosid=False,tmtuki=True,putki=False,outsider=False)
#self.plot_distrib(label='Jakauma työvoiman ulkopuoliset',ansiosid=False,tmtuki=False,putki=False,outsider=True)
#self.plot_distrib(label='Jakauma laaja (ansiosidonnainen+tmtuki+putki+ulkopuoliset)',laaja=True)
if self.version in set([1,2,3,4]):
self.plot_outsider()
self.plot_student()
#self.plot_army()
self.plot_group_student()
#self.plot_group_army()
self.plot_group_disab()
self.plot_moved()
self.plot_ave_stay()
self.plot_reward()
self.plot_pensions()
self.plot_career()
self.plot_toe()
self.plot_wage_reduction()
def plot_img(self,img,xlabel="eläke",ylabel="Palkka",title="Employed"):
fig, ax = plt.subplots()
im = ax.imshow(img)
heatmap = plt.pcolor(img)
plt.colorbar(heatmap)
ax.set_xlabel(xlabel)
ax.set_ylabel(ylabel)
plt.title(title)
plt.show()
def save_sim(self,filename):
f = h5py.File(filename, 'w')
ftype='float64'
_ = f.create_dataset('version', data=self.version, dtype=ftype)
_ = f.create_dataset('n_pop', data=self.n_pop, dtype=int)
_ = f.create_dataset('empstate', data=self.empstate, dtype=int,compression="gzip", compression_opts=9)
_ = f.create_dataset('gempstate', data=self.gempstate, dtype=int,compression="gzip", compression_opts=9)
_ = f.create_dataset('deceiced', data=self.deceiced, dtype=int,compression="gzip", compression_opts=9)
_ = f.create_dataset('rewstate', data=self.rewstate, dtype=ftype,compression="gzip", compression_opts=9)
_ = f.create_dataset('salaries_emp', data=self.salaries_emp, dtype=ftype,compression="gzip", compression_opts=9)
_ = f.create_dataset('actions', data=self.actions, dtype=int,compression="gzip", compression_opts=9)
_ = f.create_dataset('alive', data=self.alive, dtype=int,compression="gzip", compression_opts=9)
_ = f.create_dataset('galive', data=self.galive, dtype=int,compression="gzip", compression_opts=9)
_ = f.create_dataset('siirtyneet', data=self.siirtyneet, dtype=int,compression="gzip", compression_opts=9)
_ = f.create_dataset('siirtyneet_det', data=self.siirtyneet_det, dtype=int,compression="gzip", compression_opts=9)
_ = f.create_dataset('pysyneet', data=self.pysyneet, dtype=int,compression="gzip", compression_opts=9)
if self.dynprog:
_ = f.create_dataset('aveV', data=self.aveV, dtype=ftype,compression="gzip", compression_opts=9)
_ = f.create_dataset('pop_predrew', data=self.pop_predrew, dtype=ftype,compression="gzip", compression_opts=9)
_ = f.create_dataset('time_in_state', data=self.time_in_state, dtype=ftype,compression="gzip", compression_opts=9)
_ = f.create_dataset('stat_tyoura', data=self.stat_tyoura, dtype=ftype,compression="gzip", compression_opts=9)
_ = f.create_dataset('stat_toe', data=self.stat_toe, dtype=int,compression="gzip", compression_opts=9)
_ = f.create_dataset('stat_pension', data=self.stat_pension, dtype=ftype,compression="gzip", compression_opts=9)
_ = f.create_dataset('stat_paidpension', data=self.stat_paidpension, dtype=ftype,compression="gzip", compression_opts=9)
_ = f.create_dataset('stat_unemp_len', data=self.stat_unemp_len, dtype=ftype,compression="gzip", compression_opts=9)
_ = f.create_dataset('popempstate', data=self.popempstate, dtype=int,compression="gzip", compression_opts=9)
_ = f.create_dataset('stat_wage_reduction', data=self.stat_wage_reduction, dtype=ftype,compression="gzip", compression_opts=9)
_ = f.create_dataset('stat_wage_reduction_g', data=self.stat_wage_reduction_g, dtype=ftype,compression="gzip", compression_opts=9)
_ = f.create_dataset('popunemprightleft', data=self.popunemprightleft, dtype=ftype,compression="gzip", compression_opts=9)
_ = f.create_dataset('popunemprightused', data=self.popunemprightused, dtype=ftype,compression="gzip", compression_opts=9)
_ = f.create_dataset('infostats_taxes', data=self.infostats_taxes, dtype=ftype,compression="gzip", compression_opts=9)
_ = f.create_dataset('infostats_wagetaxes', data=self.infostats_wagetaxes, dtype=ftype,compression="gzip", compression_opts=9)
_ = f.create_dataset('infostats_taxes_distrib', data=self.infostats_taxes_distrib, dtype=ftype,compression="gzip", compression_opts=9)
_ = f.create_dataset('infostats_etuustulo', data=self.infostats_etuustulo, dtype=ftype,compression="gzip", compression_opts=9)
_ = f.create_dataset('infostats_etuustulo_group', data=self.infostats_etuustulo_group, dtype=ftype,compression="gzip", compression_opts=9)
_ = f.create_dataset('infostats_perustulo', data=self.infostats_perustulo, dtype=ftype,compression="gzip", compression_opts=9)
_ = f.create_dataset('infostats_palkkatulo', data=self.infostats_palkkatulo, dtype=ftype,compression="gzip", compression_opts=9)
_ = f.create_dataset('infostats_palkkatulo_eielakkeella', data=self.infostats_palkkatulo_eielakkeella, dtype=ftype,compression="gzip", compression_opts=9)
_ = f.create_dataset('infostats_ansiopvraha', data=self.infostats_ansiopvraha, dtype=ftype,compression="gzip", compression_opts=9)
_ = f.create_dataset('infostats_asumistuki', data=self.infostats_asumistuki, dtype=ftype,compression="gzip", compression_opts=9)
_ = f.create_dataset('infostats_valtionvero', data=self.infostats_valtionvero, dtype=ftype,compression="gzip", compression_opts=9)
_ = f.create_dataset('infostats_kunnallisvero', data=self.infostats_kunnallisvero, dtype=ftype,compression="gzip", compression_opts=9)
_ = f.create_dataset('infostats_valtionvero_distrib', data=self.infostats_valtionvero_distrib, dtype=ftype,compression="gzip", compression_opts=9)
_ = f.create_dataset('infostats_kunnallisvero_distrib', data=self.infostats_kunnallisvero_distrib, dtype=ftype)
_ = f.create_dataset('infostats_ptel', data=self.infostats_ptel, dtype=ftype,compression="gzip", compression_opts=9)
_ = f.create_dataset('infostats_tyotvakmaksu', data=self.infostats_tyotvakmaksu, dtype=ftype,compression="gzip", compression_opts=9)
_ = f.create_dataset('infostats_tyoelake', data=self.infostats_tyoelake, dtype=ftype,compression="gzip", compression_opts=9)
_ = f.create_dataset('infostats_kokoelake', data=self.infostats_kokoelake, dtype=ftype,compression="gzip", compression_opts=9)
_ = f.create_dataset('infostats_opintotuki', data=self.infostats_opintotuki, dtype=ftype,compression="gzip", compression_opts=9)
_ = f.create_dataset('infostats_isyyspaivaraha', data=self.infostats_isyyspaivaraha, dtype=ftype)
_ = f.create_dataset('infostats_aitiyspaivaraha', data=self.infostats_aitiyspaivaraha, dtype=ftype)
_ = f.create_dataset('infostats_kotihoidontuki', data=self.infostats_kotihoidontuki, dtype=ftype)
_ = f.create_dataset('infostats_sairauspaivaraha', data=self.infostats_sairauspaivaraha, dtype=ftype)
_ = f.create_dataset('infostats_toimeentulotuki', data=self.infostats_toimeentulotuki, dtype=ftype)
_ = f.create_dataset('infostats_tulot_netto', data=self.infostats_tulot_netto, dtype=ftype)
_ = f.create_dataset('poprewstate', data=self.poprewstate, dtype=ftype,compression="gzip", compression_opts=9)
_ = f.create_dataset('infostats_pinkslip', data=self.infostats_pinkslip, dtype=int)
if self.version<2:
_ = f.create_dataset('infostats_pop_pinkslip', data=self.infostats_pop_pinkslip, dtype=int)
_ = f.create_dataset('infostats_paid_tyel_pension', data=self.infostats_paid_tyel_pension, dtype=ftype,compression="gzip", compression_opts=9)
_ = f.create_dataset('infostats_tyelpremium', data=self.infostats_tyelpremium, dtype=ftype,compression="gzip", compression_opts=9)
_ = f.create_dataset('infostats_npv0', data=self.infostats_npv0, dtype=ftype,compression="gzip", compression_opts=9)
_ = f.create_dataset('infostats_irr', data=self.infostats_irr, dtype=ftype,compression="gzip", compression_opts=9)
_ = f.create_dataset('infostats_group', data=self.infostats_group, dtype=int,compression="gzip", compression_opts=9)
_ = f.create_dataset('infostats_sairausvakuutus', data=self.infostats_sairausvakuutus, dtype=ftype,compression="gzip", compression_opts=9)
_ = f.create_dataset('infostats_pvhoitomaksu', data=self.infostats_pvhoitomaksu, dtype=ftype,compression="gzip", compression_opts=9)
_ = f.create_dataset('infostats_ylevero', data=self.infostats_ylevero, dtype=ftype)
_ = f.create_dataset('infostats_ylevero_distrib', data=self.infostats_ylevero_distrib, dtype=ftype,compression="gzip", compression_opts=9)
_ = f.create_dataset('infostats_mother_in_workforce', data=self.infostats_mother_in_workforce, dtype=ftype)
_ = f.create_dataset('infostats_children_under3', data=self.infostats_children_under3, dtype=int,compression="gzip", compression_opts=9)
_ = f.create_dataset('infostats_children_under7', data=self.infostats_children_under7, dtype=int,compression="gzip", compression_opts=9)
_ = f.create_dataset('infostats_unempwagebasis', data=self.infostats_unempwagebasis, dtype=ftype,compression="gzip", compression_opts=9)
_ = f.create_dataset('infostats_unempwagebasis_acc', data=self.infostats_unempwagebasis_acc, dtype=ftype,compression="gzip", compression_opts=9)
_ = f.create_dataset('infostats_toe', data=self.infostats_toe, dtype=ftype,compression="gzip", compression_opts=9)
_ = f.create_dataset('infostats_ove', data=self.infostats_ove, dtype=int)
_ = f.create_dataset('infostats_kassanjasen', data=self.infostats_kassanjasen, dtype=int)
_ = f.create_dataset('infostats_poptulot_netto', data=self.infostats_poptulot_netto, dtype=ftype,compression="gzip", compression_opts=9)
_ = f.create_dataset('infostats_equivalent_income', data=self.infostats_equivalent_income, dtype=ftype)
_ = f.create_dataset('infostats_pop_wage', data=self.infostats_pop_wage, dtype=ftype,compression="gzip", compression_opts=9)
_ = f.create_dataset('infostats_pop_pension', data=self.infostats_pop_pension, dtype=ftype,compression="gzip", compression_opts=9)
_ = f.create_dataset('infostats_puoliso', data=self.infostats_puoliso, dtype=ftype)
_ = f.create_dataset('infostats_alv', data=self.infostats_alv)
_ = f.create_dataset('params', data=str(self.params))
if self.version==101:
_ = f.create_dataset('infostats_savings', data=self.infostats_savings, dtype=ftype,compression="gzip", compression_opts=9)
_ = f.create_dataset('sav_actions', data=self.sav_actions, dtype=ftype,compression="gzip", compression_opts=9)
f.close()
def save_to_hdf(self,filename,nimi,arr,dtype):
f = h5py.File(filename, 'w')
dset = f.create_dataset(nimi, data=arr, dtype=dtype)
f.close()
def load_hdf(self,filename,nimi):
f = h5py.File(filename, 'r')
val=f.get(nimi).value
f.close()
return val
def load_sim(self,filename,n_pop=None,print_pop=False):
f = h5py.File(filename, 'r')
if 'version' in f.keys():
version=int(f['version'][()])
else:
version=1
self.empstate=f['empstate'][()]
self.gempstate=f['gempstate'][()]
self.deceiced=f['deceiced'][()]
self.rewstate=f['rewstate'][()]
if 'poprewstate' in f.keys():
self.poprewstate=f['poprewstate'][()]
if 'pop_predrew' in f.keys():
self.pop_predrew=f['pop_predrew'][()]
self.salaries_emp=f['salaries_emp'][()]
self.actions=f['actions'][()]
self.alive=f['alive'][()]
self.galive=f['galive'][()]
self.siirtyneet=f['siirtyneet'][()]
self.pysyneet=f['pysyneet'][()]
if 'aveV' in f.keys():
self.aveV=f['aveV'][()]
self.time_in_state=f['time_in_state'][()]
self.stat_tyoura=f['stat_tyoura'][()]
self.stat_toe=f['stat_toe'][()]
self.stat_pension=f['stat_pension'][()]
self.stat_paidpension=f['stat_paidpension'][()]
self.stat_unemp_len=f['stat_unemp_len'][()]
self.popempstate=f['popempstate'][()]
self.stat_wage_reduction=f['stat_wage_reduction'][()]
self.popunemprightleft=f['popunemprightleft'][()]
self.popunemprightused=f['popunemprightused'][()]
if 'infostats_wagetaxes' in f.keys(): # older runs do not have these
self.infostats_wagetaxes=f['infostats_wagetaxes'][()]
if 'infostats_taxes' in f.keys(): # older runs do not have these
self.infostats_taxes=f['infostats_taxes'][()]
self.infostats_etuustulo=f['infostats_etuustulo'][()]
self.infostats_perustulo=f['infostats_perustulo'][()]
self.infostats_palkkatulo=f['infostats_palkkatulo'][()]
self.infostats_ansiopvraha=f['infostats_ansiopvraha'][()]
self.infostats_asumistuki=f['infostats_asumistuki'][()]
self.infostats_valtionvero=f['infostats_valtionvero'][()]
self.infostats_kunnallisvero=f['infostats_kunnallisvero'][()]
self.infostats_ptel=f['infostats_ptel'][()]
self.infostats_tyotvakmaksu=f['infostats_tyotvakmaksu'][()]
self.infostats_tyoelake=f['infostats_tyoelake'][()]
self.infostats_kokoelake=f['infostats_kokoelake'][()]
self.infostats_opintotuki=f['infostats_opintotuki'][()]
self.infostats_isyyspaivaraha=f['infostats_isyyspaivaraha'][()]
self.infostats_aitiyspaivaraha=f['infostats_aitiyspaivaraha'][()]
self.infostats_kotihoidontuki=f['infostats_kotihoidontuki'][()]
self.infostats_sairauspaivaraha=f['infostats_sairauspaivaraha'][()]
self.infostats_toimeentulotuki=f['infostats_toimeentulotuki'][()]
self.infostats_tulot_netto=f['infostats_tulot_netto'][()]
if 'infostats_etuustulo_group' in f.keys(): # older runs do not have these
self.infostats_etuustulo_group=f['infostats_etuustulo_group'][()]
if 'infostats_valtionvero_distrib' in f.keys(): # older runs do not have these
self.infostats_valtionvero_distrib=f['infostats_valtionvero_distrib'][()]
self.infostats_kunnallisvero_distrib=f['infostats_kunnallisvero_distrib'][()]
if 'infostats_taxes_distrib' in f.keys(): # older runs do not have these
self.infostats_taxes_distrib=f['infostats_taxes_distrib'][()]
self.infostats_ylevero_distrib=f['infostats_ylevero_distrib'][()]
if 'infostats_pinkslip' in f.keys(): # older runs do not have these
self.infostats_pinkslip=f['infostats_pinkslip'][()]
if 'infostats_pop_pinkslip' in f.keys():
self.infostats_pop_pinkslip=f['infostats_pop_pinkslip'][()]
if 'infostats_paid_tyel_pension' in f.keys(): # older runs do not have these
self.infostats_paid_tyel_pension=f['infostats_paid_tyel_pension'][()]
self.infostats_tyelpremium=f['infostats_tyelpremium'][()]
if 'infostats_npv0' in f.keys(): # older runs do not have these
self.infostats_npv0=f['infostats_npv0'][()]
self.infostats_irr=f['infostats_irr'][()]
if 'infostats_chilren7' in f.keys(): # older runs do not have these
self.infostats_chilren7=f['infostats_chilren7'][()]
if 'infostats_chilren18' in f.keys(): # older runs do not have these
self.infostats_chilren18=f['infostats_chilren18'][()]
if 'infostats_group' in f.keys(): # older runs do not have these
self.infostats_group=f['infostats_group'][()]
if 'infostats_sairausvakuutus' in f.keys():
self.infostats_sairausvakuutus=f['infostats_sairausvakuutus'][()]
self.infostats_pvhoitomaksu=f['infostats_pvhoitomaksu'][()]
self.infostats_ylevero=f['infostats_ylevero'][()]
if 'infostats_mother_in_workforce' in f.keys():
self.infostats_mother_in_workforce=f['infostats_mother_in_workforce'][()]
if 'stat_wage_reduction_g' in f.keys():
self.stat_wage_reduction_g=f['stat_wage_reduction_g'][()]
if 'siirtyneet_det' in f.keys():
self.siirtyneet_det=f['siirtyneet_det'][()]
if 'infostats_kassanjasen' in f.keys():
self.infostats_kassanjasen=f['infostats_kassanjasen'][()]
if 'n_pop' in f.keys():
self.n_pop=int(f['n_pop'][()])
else:
self.n_pop=np.sum(self.empstate[0,:])
if 'infostats_puoliso' in f.keys():
self.infostats_puoliso=f['infostats_puoliso'][()]
if 'infostats_ove' in f.keys():
self.infostats_ove=f['infostats_ove'][()]
if 'infostats_children_under3' in f.keys():
self.infostats_children_under3=f['infostats_children_under3'][()]
self.infostats_children_under7=f['infostats_children_under7'][()]
self.infostats_unempwagebasis=f['infostats_unempwagebasis'][()]
self.infostats_unempwagebasis_acc=f['infostats_unempwagebasis_acc'][()]
self.infostats_toe=f['infostats_toe'][()]
if 'infostats_palkkatulo_eielakkeella' in f.keys():
self.infostats_palkkatulo_eielakkeella=f['infostats_palkkatulo_eielakkeella'][()]
if 'infostats_tulot_netto' in f.keys():
self.infostats_tulot_netto=f['infostats_tulot_netto'][()]
if 'infostats_poptulot_netto' in f.keys():
self.infostats_poptulot_netto=f['infostats_poptulot_netto'][()]
if 'infostats_equivalent_income' in f.keys():
self.infostats_equivalent_income=f['infostats_equivalent_income'][()]
if 'infostats_pop_wage' in f.keys():
self.infostats_pop_wage=f['infostats_pop_wage'][()]
self.infostats_pop_pension=f['infostats_pop_pension'][()]
if 'infostats_savings' in f.keys():
self.infostats_savings=f['infostats_savings'][()]
self.sav_actions=f['sav_actions'][()]
if 'infostats_alv' in f.keys():
self.infostats_alv=f['infostats_alv'][()]
if n_pop is not None:
self.n_pop=n_pop
if 'params' in f.keys():
self.params=f['params'][()]
else:
self.params=None
if print_pop:
print('n_pop {}'.format(self.n_pop))
f.close()
def scatter_density(self,x,y,label1='',label2=''):
# Calculate the point density
xy = np.vstack([x,y])
z = gaussian_kde(xy)(xy)
# Sort the points by density, so that the densest points are plotted last
#idx = z.argsort()
#x, y, z = x[idx], y[idx], z[idx]
fig,ax=plt.subplots()
ax.scatter(x,y,c=z)
ax.set_xlabel(label1)
ax.set_ylabel(label2)
#plt.legend()
# plt.title('number of agents by pension level')
plt.show()
def plot_Vk(self,k,getV=None):
obsV=np.zeros((self.n_time))
#obsV[-1]=self.poprewstate[-1,k]
for t in range(self.n_time-2,-1,-1):
obsV[t]=self.poprewstate[t+1,k]+self.gamma*obsV[t+1]
rewerr=self.poprewstate[t+1,k]-self.pop_predrew[t+1,k]
delta=obsV[t]-self.aveV[t+1,k]
wage=self.infostats_pop_wage[t,k]
old_wage=self.infostats_pop_wage[max(0,t-1),k]
age=self.map_t_to_age(t)
old_age=int(self.map_t_to_age(max(0,t-1)))
emp=self.popempstate[t,k]
predemp=self.popempstate[max(0,t-1),k]
pen=self.infostats_pop_pension[t,k]
predwage=self.env.wage_process_mean(old_wage,old_age,state=predemp)
print(f'{age}: {obsV[t]:.4f} vs {self.aveV[t+1,k]:.4f} d {delta:.4f} re {rewerr:.6f} in state {emp} ({k},{wage:.2f},{pen:.2f}) ({predwage:.2f}) ({self.poprewstate[t+1,k]:.5f},{self.pop_predrew[t+1,k]:.5f})')
err=obsV-self.aveV[t,k]
obsV_error= | np.abs(obsV-self.aveV[t,k]) | numpy.abs |
import os
import sys
import random
import math
import re
import time
import numpy as np
import cv2
import matplotlib
import matplotlib.pyplot as plt
from tqdm import tqdm
from skimage import io
import json
from models.mask_rcnn.cell_dataset import CellsDataset
from models.mask_rcnn.config import CellConfig
from models.mask_rcnn import utils
from models.mask_rcnn import model as modellib
from models.mask_rcnn.model import log
# TODO: Remove this and make a nicer file structure
from models.unet.common import create_predicted_folders
# Root directory of the project
ROOT_DIR = os.getcwd()
# Directory to load checkpoints from
CHECKPOINT_DIR = os.path.join(ROOT_DIR, "checkpoints", "mask_rcnn")
TENSORBOARD_DIR = os.path.join(ROOT_DIR, ".tensorboard", "mask_rcnn")
class InferenceConfig(CellConfig):
GPU_COUNT = 1
IMAGES_PER_GPU = 1
def ensemble_mask_rcnn(test_ids, test_path, checkpoint_dir, augments):
inference_config = InferenceConfig()
# Create the model in inference mode
model = modellib.MaskRCNN(mode="inference",
config=inference_config,
checkpoint_dir=checkpoint_dir,
tensorboard_dir=TENSORBOARD_DIR)
# Get path to saved weights
# Either set a specific path or find last trained weights
# model_path = os.path.join(ROOT_DIR, ".h5 file name here")
model_path = model.find_last()
# Load trained weights (fill in path to trained weights here)
assert model_path != "", "Provide path to trained weights"
print("Loading weights from ", model_path)
model.load_weights(model_path, by_name=True)
roi_class = []
create_predicted_folders(test_ids)
dataset_test = CellsDataset()
dataset_test.load_cells(test_ids)
dataset_test.prepare()
# Process all images
for id in dataset_test.image_ids:
img = dataset_test.load_image(id)
# baseline detection
detection = model.detect([img], verbose=1)
baseline_masks = detection[0]["masks"]
baseline_scores = detection[0]["scores"]
# augments detection
augment_masks = []
augment_scores = []
for augment in augments:
if augment["name"] == "angle":
width = img.shape[1]
height = img.shape[0]
width_big = width * 2
height_big = height * 2
img_big = cv2.resize(img, (width_big, height_big))
center=tuple(np.array(img_big.shape[1::-1])//2)
rot_mat = cv2.getRotationMatrix2D(center, augment["angle"], 0.5)
inv_rot_mat = cv2.invertAffineTransform(rot_mat)
img_rot = cv2.warpAffine(img_big, rot_mat, img_big.shape[1::-1], flags=cv2.INTER_LINEAR)
detection = model.detect([img_rot], verbose=1)
masks = detection[0]["masks"]
masks_small = []
for i in range(masks.shape[2]):
masks[:,:,i] = cv2.warpAffine(masks[:,:,i], inv_rot_mat, masks.shape[1::-1], flags=cv2.INTER_NEAREST)
masks_small.append(cv2.resize(masks[:,:,i], (width, height)))
detection[0]["masks"] = np.stack(masks_small, axis=2)
elif augment["name"] == "fliplr":
img_flipped = np.fliplr(img)
detection = model.detect([img_flipped], verbose=1)
masks = detection[0]["masks"]
for i in range(masks.shape[2]):
masks[:,:,i] = np.fliplr(masks[:,:,i])
augment_masks.append(detection[0]["masks"])
augment_scores.append(detection[0]["scores"])
if len(augment_masks) > 0:
augment_masks = np.concatenate(augment_masks, axis=2)
augment_scores = | np.concatenate(augment_scores) | numpy.concatenate |
'''
Author: <NAME>
Main_utils script to run training and evaluation
of a residual network model on chest x-ray images
'''
import os
from tqdm import tqdm, trange
import logging
from scipy.stats import logistic
import numpy as np
import sklearn
from sklearn.metrics import precision_recall_fscore_support
from sklearn.metrics import accuracy_score
from sklearn.metrics import mean_squared_error as mse
import csv
from scipy.special import softmax
from scipy.special import expit
import time
import cv2
import torch
import torchvision
import torch.optim as optim
import torch.optim.lr_scheduler as lr_scheduler
from torch.nn import CrossEntropyLoss, BCEWithLogitsLoss
from torch.utils.tensorboard import SummaryWriter
from torch.utils.data import DataLoader
from .model import build_resnet256_6_2_1, build_resnet512_6_2_1
from .model import build_resnet1024_7_2_1, build_resnet2048_7_2_1
from .model_utils import CXRImageDataset, convert_to_onehot
import eval_metrics
def build_training_dataset(data_dir, img_size: int, dataset_metadata='../data/training.csv',
random_degrees=[-20,20], random_translate=[0.1,0.1], label_key='edema_severity'):
transform=torchvision.transforms.Compose([
torchvision.transforms.Lambda(lambda img: img.astype(np.int16)),
torchvision.transforms.ToPILImage(),
torchvision.transforms.RandomAffine(degrees=random_degrees, translate=random_translate),
torchvision.transforms.CenterCrop(img_size),
torchvision.transforms.Lambda(
lambda img: np.array(img).astype(np.float32)),
torchvision.transforms.Lambda(
lambda img: img / img.max())
])
training_dataset = CXRImageDataset(data_dir=data_dir,
dataset_metadata=dataset_metadata,
transform=transform,
label_key=label_key)
return training_dataset
def build_evaluation_dataset(data_dir, img_size: int, dataset_metadata='../data/test.csv', label_key='edema_severity'):
transform=torchvision.transforms.Compose([
torchvision.transforms.Lambda(lambda img: img.astype(np.int16)),
torchvision.transforms.ToPILImage(),
torchvision.transforms.CenterCrop(img_size),
torchvision.transforms.Lambda(
lambda img: np.array(img).astype(np.float32)),
torchvision.transforms.Lambda(
lambda img: img / img.max())
])
evaluation_dataset = CXRImageDataset(data_dir=data_dir,
dataset_metadata=dataset_metadata,
transform=transform,
label_key=label_key)
return evaluation_dataset
def build_model(model_name, checkpoint_path=None, output_channels=4):
if checkpoint_path == None:
if model_name == 'resnet256_6_2_1':
model = build_resnet256_6_2_1(output_channels=output_channels)
if model_name == 'resnet512_6_2_1':
model = build_resnet512_6_2_1(output_channels=output_channels)
if model_name == 'resnet1024_7_2_1':
model = build_resnet1024_7_2_1(output_channels=output_channels)
if model_name == 'resnet2048_7_2_1':
model = build_resnet2048_7_2_1(output_channels=output_channels)
else:
if model_name == 'resnet256_6_2_1':
model = build_resnet256_6_2_1(pretrained=True,
pretrained_model_path=checkpoint_path,
output_channels=output_channels)
if model_name == 'resnet512_6_2_1':
model = build_resnet512_6_2_1(pretrained=True,
pretrained_model_path=checkpoint_path,
output_channels=output_channels)
if model_name == 'resnet1024_7_2_1':
model = build_resnet1024_7_2_1(pretrained=True,
pretrained_model_path=checkpoint_path,
output_channels=output_channels)
if model_name == 'resnet2048_7_2_1':
model = build_resnet2048_7_2_1(pretrained=True,
pretrained_model_path=checkpoint_path,
output_channels=output_channels)
return model
class ModelManager:
def __init__(self, model_name, img_size, output_channels=4):
self.model_name = model_name
self.output_channels = output_channels
self.model = build_model(self.model_name, output_channels=self.output_channels)
self.img_size = img_size
self.logger = logging.getLogger(__name__)
def train(self, device, args):
# data_dir, dataset_metadata, save_dir,
# batch_size=64, num_train_epochs=300,
# device='cuda', init_lr=5e-4, logging_steps=50,
# label_key='edema_severity', loss_method='CrossEntropyLoss'):
'''
Create a logger for logging model training
'''
logger = logging.getLogger(__name__)
'''
Create an instance of traning data loader
'''
print('***** Instantiate a data loader *****')
dataset = build_training_dataset(data_dir=args.data_dir,
img_size=self.img_size,
dataset_metadata=args.dataset_metadata,
label_key=args.label_key)
data_loader = DataLoader(dataset, batch_size=args.batch_size,
shuffle=True, num_workers=8,
pin_memory=True)
print(f'Total number of training images: {len(dataset)}')
'''
Create an instance of loss
'''
print('***** Instantiate the training loss *****')
if args.loss_method == 'CrossEntropyLoss':
loss_criterion = CrossEntropyLoss().to(device)
elif args.loss_method == 'BCEWithLogitsLoss':
loss_criterion = BCEWithLogitsLoss().to(device)
'''
Create an instance of optimizer and learning rate scheduler
'''
print('***** Instantiate an optimizer *****')
optimizer = optim.Adam(self.model.parameters(), lr=args.init_lr)
'''
Train the model
'''
print('***** Train the model *****')
self.model = self.model.to(device)
self.model.train()
train_iterator = trange(int(args.num_train_epochs), desc="Epoch")
for epoch in train_iterator:
start_time = time.time()
epoch_loss = 0
epoch_iterator = tqdm(data_loader, desc="Iteration")
for i, batch in enumerate(epoch_iterator, 0):
# Parse the batch
images, labels, image_ids = batch
images = images.to(device, non_blocking=True)
labels = labels.to(device, non_blocking=True)
# Zero out the parameter gradients
optimizer.zero_grad()
# Forward + backward + optimize
outputs = self.model(images)
pred_logits = outputs[-1]
# Note that the logits are used here
if args.loss_method == 'BCEWithLogitsLoss':
labels = torch.reshape(labels, pred_logits.size())
# pred_logits[labels<0] = 0
# labels[labels<0] = 0.5
loss = loss_criterion(pred_logits, labels)
loss.backward()
optimizer.step()
# Record training statistics
epoch_loss += loss.item()
if not loss.item()>0:
logger.info(f"loss: {loss.item()}")
logger.info(f"pred_logits: {pred_logits}")
logger.info(f"labels: {labels}")
self.model.save_pretrained(args.save_dir, epoch=epoch + 1)
interval = time.time() - start_time
print(f'Epoch {epoch+1} finished! Epoch loss: {epoch_loss:.5f}')
logger.info(f" Epoch {epoch+1} loss = {epoch_loss:.5f}")
logger.info(f" Epoch {epoch+1} took {interval:.3f} s")
return
def eval(self, device, args, checkpoint_path):
'''
Load the checkpoint (essentially create a "different" model)
'''
self.model = build_model(model_name=self.model_name,
output_channels=self.output_channels,
checkpoint_path=checkpoint_path)
'''
Create an instance of evaluation data loader
'''
print('***** Instantiate a data loader *****')
dataset = build_evaluation_dataset(data_dir=args.data_dir,
img_size=self.img_size,
dataset_metadata=args.dataset_metadata,
label_key=args.label_key)
data_loader = DataLoader(dataset, batch_size=args.batch_size,
shuffle=True, num_workers=8,
pin_memory=True)
print(f'Total number of evaluation images: {len(dataset)}')
'''
Evaluate the model
'''
print('***** Evaluate the model *****')
self.model = self.model.to(device)
self.model.eval()
# For storing labels and model predictions
all_preds_prob = []
all_preds_logit = []
all_labels = []
epoch_iterator = tqdm(data_loader, desc="Iteration")
for i, batch in enumerate(epoch_iterator, 0):
# Parse the batch
images, labels, image_ids = batch
images = images.to(device, non_blocking=True)
labels = labels.to(device, non_blocking=True)
with torch.no_grad():
outputs = self.model(images)
preds_prob = outputs[0]
preds_logit = outputs[-1]
if not args.label_key == 'edema_severity':
labels = torch.reshape(labels, preds_logit.size())
preds_prob = preds_prob.detach().cpu().numpy()
preds_logit = preds_logit.detach().cpu().numpy()
labels = labels.detach().cpu().numpy()
all_preds_prob += \
[preds_prob[j] for j in range(len(labels))]
all_preds_logit += \
[preds_logit[j] for j in range(len(labels))]
all_labels += \
[labels[j] for j in range(len(labels))]
all_preds_class = np.argmax(all_preds_prob, axis=1)
inference_results = {'all_preds_prob': all_preds_prob,
'all_preds_class': all_preds_class,
'all_preds_logit': all_preds_logit,
'all_labels': all_labels}
eval_results = {}
if args.label_key == 'edema_severity':
all_onehot_labels = [convert_to_onehot(label) for label in all_labels]
ordinal_aucs = eval_metrics.compute_ordinal_auc(all_onehot_labels, all_preds_prob)
eval_results['ordinal_aucs'] = ordinal_aucs
ordinal_acc_f1 = eval_metrics.compute_ordinal_acc_f1_metrics(all_onehot_labels,
all_preds_prob)
eval_results.update(ordinal_acc_f1)
eval_results['mse'] = eval_metrics.compute_mse(all_labels, all_preds_prob)
results_acc_f1, _, _ = eval_metrics.compute_acc_f1_metrics(all_labels, all_preds_prob)
eval_results.update(results_acc_f1)
else:
all_preds_prob = [1 / (1 + | np.exp(-logit) | numpy.exp |
# ===========================================================================
# This module is created based on the code from 2 libraries: Lasagne and keras
# Original work Copyright (c) 2014-2015 keras contributors
# Original work Copyright (c) 2014-2015 Lasagne contributors
# Modified work Copyright 2016-2017 TrungNT
# ===========================================================================
from __future__ import division, absolute_import, print_function
import numpy as np
import scipy as sp
from ..config import floatX
# ===========================================================================
# RandomStates
# ===========================================================================
_MAGIC_SEED = 12082518
_SEED_GENERATOR = np.random.RandomState(_MAGIC_SEED)
def set_magic_seed(seed):
global _MAGIC_SEED, _SEED_GENERATOR
_MAGIC_SEED = seed
_SEED_GENERATOR = np.random.RandomState(_MAGIC_SEED)
def get_magic_seed():
return _MAGIC_SEED
def get_random_magic_seed():
return _SEED_GENERATOR.randint(10e6)
def get_random_generator():
return _SEED_GENERATOR
# ===========================================================================
# Main
# ===========================================================================
def is_ndarray(x):
return isinstance(x, np.ndarray)
def np_masked_output(X, X_mask):
'''
Example
-------
X: [[1,2,3,0,0],
[4,5,0,0,0]]
X_mask: [[1,2,3,0,0],
[4,5,0,0,0]]
return: [[1,2,3],[4,5]]
'''
res = []
for x, mask in zip(X, X_mask):
x = x[np.nonzero(mask)]
res.append(x.tolist())
return res
def np_one_hot(y, n_classes=None):
'''Convert class vector (integers from 0 to nb_classes)
to binary class matrix, for use with categorical_crossentropy
'''
y = np.asarray(y, dtype='int32')
if not n_classes:
n_classes = np.max(y) + 1
Y = np.zeros((len(y), n_classes))
for i in range(len(y)):
Y[i, y[i]] = 1.
return Y
def np_split_chunks(a, maxlen, overlap):
'''
Example
-------
>>> print(split_chunks(np.array([1, 2, 3, 4, 5, 6, 7, 8]), 5, 1))
>>> [[1, 2, 3, 4, 5],
[4, 5, 6, 7, 8]]
'''
chunks = []
nchunks = int((max(a.shape) - maxlen) / (maxlen - overlap)) + 1
for i in xrange(nchunks):
start = i * (maxlen - overlap)
chunks.append(a[start: start + maxlen])
# ====== Some spare frames at the end ====== #
wasted = max(a.shape) - start - maxlen
if wasted >= (maxlen - overlap) / 2:
chunks.append(a[-maxlen:])
return chunks
def np_ordered_set(seq):
seen = {}
result = []
for marker in seq:
if marker in seen: continue
seen[marker] = 1
result.append(marker)
return np.asarray(result)
def np_shrink_labels(labels, maxdist=1):
'''
Example
-------
>>> print(shrink_labels(np.array([0, 0, 1, 0, 1, 1, 0, 0, 4, 5, 4, 6, 6, 0, 0]), 1))
>>> [0, 1, 0, 1, 0, 4, 5, 4, 6, 0]
>>> print(shrink_labels(np.array([0, 0, 1, 0, 1, 1, 0, 0, 4, 5, 4, 6, 6, 0, 0]), 2))
>>> [0, 1, 0, 4, 6, 0]
Notes
-----
Different from ordered_set, the resulted array still contain duplicate
if they a far away each other.
'''
maxdist = max(1, maxdist)
out = []
l = len(labels)
i = 0
while i < l:
out.append(labels[i])
last_val = labels[i]
dist = min(maxdist, l - i - 1)
j = 1
while (i + j < l and labels[i + j] == last_val) or (j < dist):
j += 1
i += j
return out
# ===========================================================================
# Special random algorithm for weights initialization
# ===========================================================================
def np_normal(shape, mean=0., std=1.):
return np.cast[floatX()](
get_random_generator().normal(mean, std, size=shape))
def np_uniform(shape, range=0.05):
if isinstance(range, (int, float, long)):
range = (-abs(range), abs(range))
return np.cast[floatX()](
get_random_generator().uniform(low=range[0], high=range[1], size=shape))
def np_constant(shape, val=0.):
return np.cast[floatX()](np.zeros(shape) + val)
def np_symmetric_uniform(shape, range=0.01, std=None, mean=0.0):
if std is not None:
a = mean - np.sqrt(3) * std
b = mean + np.sqrt(3) * std
else:
try:
a, b = range # range is a tuple
except TypeError:
a, b = -range, range # range is a number
return np.cast[floatX()](
get_random_generator().uniform(low=a, high=b, size=shape))
def np_glorot_uniform(shape, gain=1.0, c01b=False):
orig_shape = shape
if c01b:
if len(shape) != 4:
raise RuntimeError(
"If c01b is True, only shapes of length 4 are accepted")
n1, n2 = shape[0], shape[3]
receptive_field_size = shape[1] * shape[2]
else:
if len(shape) < 2:
shape = (1,) + tuple(shape)
n1, n2 = shape[:2]
receptive_field_size = np.prod(shape[2:])
std = gain * np.sqrt(2.0 / ((n1 + n2) * receptive_field_size))
a = 0.0 - np.sqrt(3) * std
b = 0.0 + np.sqrt(3) * std
return np.cast[floatX()](
get_random_generator().uniform(low=a, high=b, size=orig_shape))
def np_glorot_normal(shape, gain=1.0, c01b=False):
orig_shape = shape
if c01b:
if len(shape) != 4:
raise RuntimeError(
"If c01b is True, only shapes of length 4 are accepted")
n1, n2 = shape[0], shape[3]
receptive_field_size = shape[1] * shape[2]
else:
if len(shape) < 2:
shape = (1,) + tuple(shape)
n1, n2 = shape[:2]
receptive_field_size = np.prod(shape[2:])
std = gain * np.sqrt(2.0 / ((n1 + n2) * receptive_field_size))
return np.cast[floatX()](
get_random_generator().normal(0.0, std, size=orig_shape))
def np_he_normal(shape, gain=1.0, c01b=False):
if gain == 'relu':
gain = np.sqrt(2)
if c01b:
if len(shape) != 4:
raise RuntimeError(
"If c01b is True, only shapes of length 4 are accepted")
fan_in = np.prod(shape[:3])
else:
if len(shape) <= 2:
fan_in = shape[0]
elif len(shape) > 2:
fan_in = np.prod(shape[1:])
std = gain * np.sqrt(1.0 / fan_in)
return np.cast[floatX()](
get_random_generator().normal(0.0, std, size=shape))
def np_he_uniform(shape, gain=1.0, c01b=False):
if gain == 'relu':
gain = np.sqrt(2)
if c01b:
if len(shape) != 4:
raise RuntimeError(
"If c01b is True, only shapes of length 4 are accepted")
fan_in = np.prod(shape[:3])
else:
if len(shape) <= 2:
fan_in = shape[0]
elif len(shape) > 2:
fan_in = np.prod(shape[1:])
std = gain * np.sqrt(1.0 / fan_in)
a = 0.0 - np.sqrt(3) * std
b = 0.0 + np.sqrt(3) * std
return np.cast[floatX()](
get_random_generator().uniform(low=a, high=b, size=shape))
def np_orthogonal(shape, gain=1.0):
if gain == 'relu':
gain = | np.sqrt(2) | numpy.sqrt |
# Copyright (c) 2021 Graphcore Ltd. 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 glob
import pickle
import random
import logging
import argparse
import multiprocessing
import numpy as np
import poptorch
import popdist
import popdist.poptorch
import torch
import torch.nn as nn
import horovod.torch as hvd
import torch.nn.utils.rnn as rnn_utils
from torch import float16, float32
from torch.utils.data import Dataset, IterableDataset
from poptorch.optim import LAMB, AdamW, Adam
from tfrecord.reader import tfrecord_loader
from transformers import (get_constant_schedule,
get_cosine_schedule_with_warmup,
get_linear_schedule_with_warmup)
TFRECORD_KEYS = ['input_ids'] # Torch Model Keys
def str_to_bool(value):
if isinstance(value, bool) or value is None:
return value
if value.lower() in {'false', 'f', '0', 'no', 'n'}:
return False
elif value.lower() in {'true', 't', '1', 'yes', 'y'}:
return True
raise argparse.ArgumentTypeError(f'{value} is not a valid boolean value')
def expand_glob_files(files):
result = []
for filepath in files:
expanded = glob.glob(filepath)
if len(expanded) < 1:
raise FileNotFoundError(f"Could not find file: {filepath}")
result += expanded
return result
class TFRecordPretrainingDataset(IterableDataset):
"""
Preprocessed GPT2 pretraining dataset read from TFRecord files.
This Dataset is compatible with multiprocessing. Each Dataloader worker
will only read a shard of each TFRecord file, which will speed up the Dataloader
and ensure no worker loads the same data as another worker. You are strongly
advised to use a large number (e.g. 64) of dataloader workers because firstly,
more workers could support high throughput, and secondly, more workers could
give us more stochasticity and thus better convergence.
Parameters
----------
files: List of TFRecord files containing the preprocessed pretraining data
shuffle: Shuffle the data?
"""
def __init__(self,
input_files,
shuffle=True):
self.files = expand_glob_files(input_files)
self.shuffle = shuffle
self.reset()
def reset(self):
self.file_index = 0
self.reader = iter([])
def samples_per_file(self, filename):
index_filename = filename.replace(".tfrecord", ".index")
count = sum(1 for _ in open(index_filename))
return count
def __len__(self):
if getattr(self, "_len", None) is None:
pool = multiprocessing.Pool(
min(multiprocessing.cpu_count(), len(self.files)))
num_samples = pool.map(self.samples_per_file, self.files)
pool.close()
pool.join()
self._len = sum(num_samples)
return self._len
def __iter__(self):
worker_info = torch.utils.data.get_worker_info()
if worker_info is not None:
if popdist.isPopdistEnvSet():
self.worker_id = worker_info.id + worker_info.num_workers * popdist.getInstanceIndex()
self.shard = worker_info.id + worker_info.num_workers * popdist.getInstanceIndex(), worker_info.num_workers * popdist.getNumInstances()
else:
self.worker_id = worker_info.id
self.shard = worker_info.id, worker_info.num_workers
else:
self.shard = None
self.reset()
if self.shuffle:
np.random.shuffle(self.files)
return self
def __next__(self):
try:
datum = next(self.reader)
except StopIteration:
if self.file_index >= len(self.files):
raise StopIteration
self.reader = tfrecord_loader(self.files[self.file_index],
self.files[self.file_index].replace(".tfrecord", ".index"),
list(TFRECORD_KEYS),
self.shard)
self.file_index += 1
datum = next(self.reader)
input_ids = torch.tensor(datum[TFRECORD_KEYS[0]], dtype=torch.long)
return input_ids
class MyDataset(Dataset):
def __init__(self, input_list, max_len):
self.input_list = input_list
self.max_len = max_len
def __getitem__(self, index):
input_ids = self.input_list[index]
if len(input_ids) > self.max_len:
input_ids = input_ids[:self.max_len]
input_ids = torch.tensor(input_ids, dtype=torch.long)
return input_ids
def __len__(self):
return len(self.input_list)
def load_dataset(logger, args, vocab_size):
"""
load train and valid dataset
"""
logger("loading training dataset and validating dataset")
train_path = args.train_path
if train_path == 'generated':
num_instances = args.popdist_size if args.use_popdist else 1
generated = np.random.randint(low=1, high=vocab_size,
size=(4 * num_instances * args.replication_factor *
args.batches_per_step * args.batch_size * args.gradient_accumulation,
args.max_len + 1))
train_dataset = MyDataset(generated, args.max_len + 1)
val_dataset = MyDataset(generated, args.max_len + 1)
elif 'tfrecord' in args.train_path:
train_dataset = TFRecordPretrainingDataset(args.tfrecord_path[:])
val_dataset = TFRecordPretrainingDataset(args.tfrecord_path[-1:])
elif 'dynamic' in args.train_path:
from data.indexed_dataset import make_indexed_dataset, GPTDataset
data_prefix = args.data_prefix
indexed_dataset = make_indexed_dataset(data_prefix)
total_num_of_documents = indexed_dataset.sizes.shape[0]
documents = np.arange(start=0, stop=total_num_of_documents, step=1, dtype=np.int32)
train_dataset = GPTDataset(args, data_prefix, documents[:int(total_num_of_documents*0.997)], indexed_dataset)
val_dataset = GPTDataset(args, data_prefix, documents[int(total_num_of_documents*0.997):], indexed_dataset, num_epochs=1)
else:
try:
with open(train_path, "rb") as f:
input_list = pickle.load(f)
samples = []
for article in input_list:
start_point = 0
while start_point < len(article) - args.max_len:
samples.append(article[start_point: start_point + args.max_len])
start_point += args.stride
if start_point < len(article) and len(article) >= (args.max_len // 2):
samples.append(article[len(article) - args.max_len:])
random.shuffle(samples)
# split train and valid dataset
val_num = args.val_num
input_list_train = samples[val_num:]
input_list_val = samples[:val_num]
train_dataset = MyDataset(input_list_train, args.max_len)
val_dataset = MyDataset(input_list_val, args.max_len)
except:
raise RuntimeError(f"Unknown dataset '{train_path}', you can try \'generated\'.")
return train_dataset, val_dataset
class GeneratedPretrainingDataset(Dataset):
def __init__(self, vocab_size, sequence_length, seed=42):
self.vocab_size = vocab_size
self.sequence_length = sequence_length
self.seed = seed
self.data = self.generate_data()
def generate_data(self):
with torch.random.fork_rng():
torch.manual_seed(self.seed)
input_ids = torch.randint(0, self.vocab_size, [self.sequence_length],dtype=torch.long)
label = input_ids
return input_ids, label
def __len__(self):
return self.length
def __getitem__(self, __):
return self.data
def get_generated_datum(config, vocab_size):
samples_per_step = config.replication_factor * config.gradient_accumulation * config.batch_size * config.batches_per_step
result = []
dataset = GeneratedPretrainingDataset(vocab_size, config.max_len)
data = (dataset[i] for i in range(samples_per_step))
for batches in zip(*data):
result.append(torch.stack(batches))
return result
def calculate_acc(logit, labels, ignore_index=-100, reduction='mean'):
mask = (labels != ignore_index).float()
non_pad_mask = mask.sum(-1).unsqueeze(-1)
if reduction == 'sum':
return (logit.argmax(dim=-1) == labels).float().mul(mask).sum(-1)
return (logit.argmax(dim=-1) == labels).float().mul(mask).div(non_pad_mask).sum(-1).mean()
def collate_fn(batch):
input_ids = rnn_utils.pad_sequence(batch, batch_first=True, padding_value=0)
labels = rnn_utils.pad_sequence(batch, batch_first=True, padding_value=-100)
return input_ids, labels
class _WorkerInit:
def __init__(self, seed):
self.seed = seed
def __call__(self, worker_id):
np.random.seed((self.seed + worker_id) % | np.iinfo(np.uint32) | numpy.iinfo |
import pandas as pd
import numpy as np
import sqlite3
def create_df():
in1 = np.linspace(19.27, 19.35, 60)
in2 = np.linspace(19.35, 19.51, 240)
in3 = np.linspace(19.51, 19.98, 600)
in4 = | np.linspace(19.98, 21.24, 1200) | numpy.linspace |
# [setup]
import math
import os
import cv2
import magnum as mn
import numpy as np
import habitat_sim
import habitat_sim.utils.common as ut
dir_path = os.path.dirname(os.path.realpath(__file__))
data_path = os.path.join(dir_path, "../../data")
output_path = os.path.join(dir_path, "rigid_object_tutorial_output/")
def make_video_cv2(observations, prefix="", open_vid=True, multi_obs=False):
videodims = (720, 540)
fourcc = cv2.VideoWriter_fourcc("m", "p", "4", "v")
video = cv2.VideoWriter(output_path + prefix + ".mp4", fourcc, 60, videodims)
thumb_size = (int(videodims[0] / 5), int(videodims[1] / 5))
outline_frame = np.ones((thumb_size[1] + 2, thumb_size[0] + 2, 3), np.uint8) * 150
for ob in observations:
# If in RGB/RGBA format, change first to RGB and change to BGR
bgr_im_1st_person = ob["rgba_camera_1stperson"][..., 0:3][..., ::-1]
if multi_obs:
# embed the 1st person RBG frame into the 3rd person frame
bgr_im_3rd_person = ob["rgba_camera_3rdperson"][..., 0:3][..., ::-1]
resized_1st_person_rgb = cv2.resize(
bgr_im_1st_person, thumb_size, interpolation=cv2.INTER_AREA
)
x_offset = 50
y_offset_rgb = 50
bgr_im_3rd_person[
y_offset_rgb - 1 : y_offset_rgb + outline_frame.shape[0] - 1,
x_offset - 1 : x_offset + outline_frame.shape[1] - 1,
] = outline_frame
bgr_im_3rd_person[
y_offset_rgb : y_offset_rgb + resized_1st_person_rgb.shape[0],
x_offset : x_offset + resized_1st_person_rgb.shape[1],
] = resized_1st_person_rgb
# embed the 1st person DEPTH frame into the 3rd person frame
# manually normalize depth into [0, 1] so that images are always consistent
d_im = np.clip(ob["depth_camera_1stperson"], 0, 10)
d_im /= 10.0
bgr_d_im = cv2.cvtColor((d_im * 255).astype(np.uint8), cv2.COLOR_GRAY2BGR)
resized_1st_person_depth = cv2.resize(
bgr_d_im, thumb_size, interpolation=cv2.INTER_AREA
)
y_offset_d = y_offset_rgb + 10 + thumb_size[1]
bgr_im_3rd_person[
y_offset_d - 1 : y_offset_d + outline_frame.shape[0] - 1,
x_offset - 1 : x_offset + outline_frame.shape[1] - 1,
] = outline_frame
bgr_im_3rd_person[
y_offset_d : y_offset_d + resized_1st_person_depth.shape[0],
x_offset : x_offset + resized_1st_person_depth.shape[1],
] = resized_1st_person_depth
# write the video frame
video.write(bgr_im_3rd_person)
else:
# write the 1st person observation to video
video.write(bgr_im_1st_person)
video.release()
if open_vid:
os.system("open " + output_path + prefix + ".mp4")
def remove_all_objects(sim):
for id in sim.get_existing_object_ids():
sim.remove_object(id)
def place_agent(sim):
# place our agent in the scene
agent_state = habitat_sim.AgentState()
agent_state.position = [-0.15, -0.7, 1.0]
# agent_state.position = [-0.15, -1.6, 1.0]
agent_state.rotation = np.quaternion(-0.83147, 0, 0.55557, 0)
agent = sim.initialize_agent(0, agent_state)
return agent.scene_node.transformation_matrix()
def make_configuration():
# simulator configuration
backend_cfg = habitat_sim.SimulatorConfiguration()
backend_cfg.scene.id = "data/scene_datasets/habitat-test-scenes/apartment_1.glb"
backend_cfg.enable_physics = True
# sensor configurations
# Note: all sensors must have the same resolution
# setup 2 rgb sensors for 1st and 3rd person views
camera_resolution = [540, 720]
sensors = {
"rgba_camera_1stperson": {
"sensor_type": habitat_sim.SensorType.COLOR,
"resolution": camera_resolution,
"position": [0.0, 0.6, 0.0],
"orientation": [0.0, 0.0, 0.0],
},
"depth_camera_1stperson": {
"sensor_type": habitat_sim.SensorType.DEPTH,
"resolution": camera_resolution,
"position": [0.0, 0.6, 0.0],
"orientation": [0.0, 0.0, 0.0],
},
"rgba_camera_3rdperson": {
"sensor_type": habitat_sim.SensorType.COLOR,
"resolution": camera_resolution,
"position": [0.0, 1.0, 0.3],
"orientation": [-45, 0.0, 0.0],
},
}
sensor_specs = []
for sensor_uuid, sensor_params in sensors.items():
sensor_spec = habitat_sim.SensorSpec()
sensor_spec.uuid = sensor_uuid
sensor_spec.sensor_type = sensor_params["sensor_type"]
sensor_spec.resolution = sensor_params["resolution"]
sensor_spec.position = sensor_params["position"]
sensor_spec.orientation = sensor_params["orientation"]
sensor_specs.append(sensor_spec)
# agent configuration
agent_cfg = habitat_sim.agent.AgentConfiguration()
agent_cfg.sensor_specifications = sensor_specs
return habitat_sim.Configuration(backend_cfg, [agent_cfg])
def simulate(sim, dt=1.0, get_frames=True):
# simulate dt seconds at 60Hz to the nearest fixed timestep
print("Simulating " + str(dt) + " world seconds.")
observations = []
start_time = sim.get_world_time()
while sim.get_world_time() < start_time + dt:
sim.step_physics(1.0 / 60.0)
if get_frames:
observations.append(sim.get_sensor_observations())
return observations
# [/setup]
# This is wrapped such that it can be added to a unit test
def main(make_video=True, show_video=True):
if make_video:
if not os.path.exists(output_path):
os.mkdir(output_path)
# [initialize]
# create the simulator
cfg = make_configuration()
sim = habitat_sim.Simulator(cfg)
agent_transform = place_agent(sim)
# [/initialize]
# [basics]
# load some object templates from configuration files
sphere_template_id = sim.load_object_configs(
str(os.path.join(data_path, "test_assets/objects/sphere"))
)[0]
# add an object to the scene
id_1 = sim.add_object(sphere_template_id)
sim.set_translation(np.array([2.50, 0, 0.2]), id_1)
# simulate
observations = simulate(sim, dt=1.5, get_frames=make_video)
if make_video:
make_video_cv2(observations, prefix="sim_basics", open_vid=show_video)
# [/basics]
remove_all_objects(sim)
# [dynamic_control]
observations = []
# search for an object template by key sub-string
cheezit_template_handle = sim.get_template_handles("data/objects/cheezit")[0]
box_positions = [
np.array([2.39, -0.37, 0]),
np.array([2.39, -0.64, 0]),
np.array([2.39, -0.91, 0]),
np.array([2.39, -0.64, -0.22]),
np.array([2.39, -0.64, 0.22]),
]
box_orientation = mn.Quaternion.rotation(
mn.Rad(math.pi / 2.0), np.array([-1.0, 0, 0])
)
# instance and place the boxes
box_ids = []
for b in range(5):
box_ids.append(sim.add_object_by_handle(cheezit_template_handle))
sim.set_translation(box_positions[b], box_ids[b])
sim.set_rotation(box_orientation, box_ids[b])
# get the object's initialization attributes (all boxes initialized with same mass)
object_init_template = sim.get_object_initialization_template(box_ids[0])
# anti-gravity force f=m(-g)
anti_grav_force = -1.0 * sim.get_gravity() * object_init_template.get_mass()
# throw a sphere at the boxes from the agent position
sphere_template = sim.get_object_template(sphere_template_id)
sphere_template.set_scale(np.array([0.5, 0.5, 0.5]))
sphere_id = sim.add_object(sphere_template_id)
sim.set_translation(
sim.agents[0].get_state().position + np.array([0, 1.0, 0]), sphere_id
)
# get the vector from the sphere to a box
target_direction = sim.get_translation(box_ids[0]) - sim.get_translation(sphere_id)
# apply an initial velocity for one step
sim.set_linear_velocity(target_direction * 5, sphere_id)
sim.set_angular_velocity(np.array([0, -1.0, 0]), sphere_id)
start_time = sim.get_world_time()
dt = 3.0
while sim.get_world_time() < start_time + dt:
# set forces/torques before stepping the world
for box_id in box_ids:
sim.apply_force(anti_grav_force, np.array([0, 0.0, 0]), box_id)
sim.apply_torque(np.array([0, 0.01, 0]), box_id)
sim.step_physics(1.0 / 60.0)
observations.append(sim.get_sensor_observations())
if make_video:
make_video_cv2(observations, prefix="dynamic_control", open_vid=show_video)
# [/dynamic_control]
remove_all_objects(sim)
# [kinematic_interactions]
chefcan_template_handle = sim.get_template_handles("data/objects/chefcan")[0]
id_1 = sim.add_object_by_handle(chefcan_template_handle)
sim.set_translation(np.array([2.4, -0.64, 0]), id_1)
# set one object to kinematic
sim.set_object_motion_type(habitat_sim.physics.MotionType.KINEMATIC, id_1)
# drop some dynamic objects
id_2 = sim.add_object_by_handle(chefcan_template_handle)
sim.set_translation(np.array([2.4, -0.64, 0.28]), id_2)
id_3 = sim.add_object_by_handle(chefcan_template_handle)
sim.set_translation(np.array([2.4, -0.64, -0.28]), id_3)
id_4 = sim.add_object_by_handle(chefcan_template_handle)
sim.set_translation(np.array([2.4, -0.3, 0]), id_4)
# simulate
observations = simulate(sim, dt=1.5, get_frames=True)
if make_video:
make_video_cv2(
observations, prefix="kinematic_interactions", open_vid=show_video
)
# [/kinematic_interactions]
remove_all_objects(sim)
# [kinematic_update]
observations = []
clamp_template_handle = sim.get_template_handles("data/objects/largeclamp")[0]
id_1 = sim.add_object_by_handle(clamp_template_handle)
sim.set_object_motion_type(habitat_sim.physics.MotionType.KINEMATIC, id_1)
sim.set_translation(np.array([0.8, 0, 0.5]), id_1)
start_time = sim.get_world_time()
dt = 1.0
while sim.get_world_time() < start_time + dt:
# manually control the object's kinematic state
sim.set_translation(sim.get_translation(id_1) + np.array([0, 0, 0.01]), id_1)
sim.set_rotation(
mn.Quaternion.rotation(mn.Rad(0.05), np.array([-1.0, 0, 0]))
* sim.get_rotation(id_1),
id_1,
)
sim.step_physics(1.0 / 60.0)
observations.append(sim.get_sensor_observations())
if make_video:
make_video_cv2(observations, prefix="kinematic_update", open_vid=show_video)
# [/kinematic_update]
# [velocity_control]
# get object VelocityControl structure and setup control
vel_control = sim.get_object_velocity_control(id_1)
vel_control.linear_velocity = np.array([0, 0, -1.0])
vel_control.angular_velocity = np.array([4.0, 0, 0])
vel_control.controlling_lin_vel = True
vel_control.controlling_ang_vel = True
observations = simulate(sim, dt=1.0, get_frames=True)
# reverse linear direction
vel_control.linear_velocity = np.array([0, 0, 1.0])
observations += simulate(sim, dt=1.0, get_frames=True)
make_video_cv2(observations, prefix="velocity_control", open_vid=True)
# [/velocity_control]
# [local_velocity_control]
vel_control.linear_velocity = | np.array([0, 0, 2.3]) | numpy.array |
import scipy.io as sio
import os
import numpy as np
import pickle
def readMat(filename, folder, mode):
filename = os.path.join(os.getcwd(), os.path.join(folder, filename))
print(filename)
f = sio.loadmat(filename)
# import h5py
# with h5py.File(filename, 'r') as f:
#
# items = f['data']
# print(list(items.keys()))
# f = f[mode[:2]][0]
f = f['data'][0]
R = []
t = []
x1_list = []
x2_list = []
flag = []
idx1 = []
idx2 = []
for item in f:
R.append(item['T'][0:3,0:3])
t.append(item['T'][0:3,3])
# x1 = item['x1']
# x1 = x1/10
x1_list.append(item['x1'])
x2_list.append(item['x2'])
fl = np.array(item['flag'])
flag.append(fl.reshape(fl.shape[0]))
idx1.append(item['idx1'])
idx2.append(item['idx2'])
data = {}
data['R'] = R
data['t'] = t
data['x1'] = x1_list
data['x2'] = x2_list
data['flag'] = flag
data['idx1'] = idx1
data['idx2'] = idx2
return data
def createFlags(x1, x2, T):
ones = np.ones((x1.shape[0], 1))
flag = ones.reshape(x1.shape[0])
error = 0.1
x1_h = np.concatenate([x1, ones], axis=1)
err = np.matmul(T, np.transpose(x1_h))
err = x2 - np.transpose(err[:3])
err = np.linalg.norm(err, axis=1)
flag[err > error] = 0
print('Number of Inliers = {}\tPercentage = {}'.format(np.sum(flag), | np.sum(flag) | numpy.sum |
#!/usr/bin/env python
u"""
read_cryosat_L2.py
Written by <NAME> (05/2021)
Reads CryoSat Level-2 data products from baselines A, B and C
Reads CryoSat Level-2 netCDF4 data products from baseline D
Supported CryoSat Modes: LRM, SAR, SARin, FDM, SID, GDR
INPUTS:
full_filename: full path of CryoSat .DBL or .nc file
OUTPUTS:
Data_1Hz: Time and Orbit Parameters
Corrections: Elevation Corrections and Flags
Data_20Hz: Geolocation and Elevation Measurements with Quality Parameters
METADATA: MPH, SPH and DSD Header data
PYTHON DEPENDENCIES:
numpy: Scientific Computing Tools For Python
https://numpy.org
https://numpy.org/doc/stable/user/numpy-for-matlab-users.html
netCDF4: Python interface to the netCDF C library
https://unidata.github.io/netcdf4-python/netCDF4/index.html
UPDATE HISTORY:
Updated 05/2021: use raw binary string prefixes (rb) for regular expressions
Updated 02/2021: replaced numpy bool to prevent deprecation warning
Updated 06/2020: patch error in CryoSat-2 GDR pointer variables
using the 1Hz mapping variable ind_meas_1hz_20_ku to remap the index
Updated 02/2020: tilde-expansion of cryosat-2 files before opening
add scale factors function for converting packed units in binary files
convert from hard to soft tabulation
Updated 11/2019: empty placeholder dictionary for baseline D DSD headers
Updated 09/2019: added netCDF4 read function for baseline D
will output with same variable names as the binary read functions
output 20Hz data as masked arrays for all baselines
Updated 08/2019: generalize regular expression patterns in read_DSD function
Updated 10/2018: updated header read functions for python3
Updated 11/2016: added Abs_Orbit and Ascending_flag to Data_1Hz outputs
Abs_Orbit should be same as in read_cryosat_ground_tracks.py
Ascending_flag can use in surface regression fits (McMillan, 2014)
Updated 05/2016: using __future__ print and division functions
Written 03/2016
"""
from __future__ import print_function
from __future__ import division
import os
import re
import netCDF4
import numpy as np
#-- PURPOSE: Initiate L2 MDS variables for CryoSat Baselines A and B
def cryosat_baseline_AB(fid,record_size,n_records):
#-- CryoSat-2 1 Hz data fields (Location Group)
#-- Time and Orbit Parameters plus Measurement Mode
Data_1Hz = {}
#-- Time: day part
Data_1Hz['Day'] = np.zeros((n_records),dtype=np.int32)
#-- Time: second part
Data_1Hz['Second'] = np.zeros((n_records),dtype=np.int32)
#-- Time: microsecond part
Data_1Hz['Micsec'] = np.zeros((n_records),dtype=np.int32)
#-- SIRAL mode
Data_1Hz['Siral_mode'] = np.zeros((n_records),dtype=np.uint64)
#-- Lat_1Hz: packed units (0.1 micro-degree, 1e-7 degrees)
Data_1Hz['Lat_1Hz'] = np.zeros((n_records),dtype=np.int32)
#-- Lon_1Hz: packed units (0.1 micro-degree, 1e-7 degrees)
Data_1Hz['Lon_1Hz'] = np.zeros((n_records),dtype=np.int32)
#-- Alt_1Hz: packed units (mm, 1e-3 m)
#-- Altitude of COG above reference ellipsoid (interpolated value)
Data_1Hz['Alt_1Hz'] = np.zeros((n_records),dtype=np.int32)
#-- Mispointing: packed units (millidegrees, 1e-3 degrees)
Data_1Hz['Mispointing'] = np.zeros((n_records),dtype=np.int16)
#-- Number of valid records in the block of twenty that contain data
#-- Last few records of the last block of a dataset may be blank blocks
#-- inserted to bring the file up to a multiple of twenty.
Data_1Hz['N_valid'] = np.zeros((n_records),dtype=np.int16)
#-- CryoSat-2 geophysical corrections (External Corrections Group)
Corrections = {}
#-- Dry Tropospheric Correction packed units (mm, 1e-3 m)
Corrections['dryTrop'] = np.zeros((n_records),dtype=np.int16)
#-- Wet Tropospheric Correction packed units (mm, 1e-3 m)
Corrections['wetTrop'] = np.zeros((n_records),dtype=np.int16)
#-- Inverse Barometric Correction packed units (mm, 1e-3 m)
Corrections['InvBar'] = np.zeros((n_records),dtype=np.int16)
#-- Dynamic Atmosphere Correction packed units (mm, 1e-3 m)
Corrections['DAC'] = np.zeros((n_records),dtype=np.int16)
#-- Ionospheric Correction packed units (mm, 1e-3 m)
Corrections['Iono'] = np.zeros((n_records),dtype=np.int16)
#-- Sea State Bias Correction packed units (mm, 1e-3 m)
Corrections['SSB'] = np.zeros((n_records),dtype=np.int16)
#-- Ocean tide Correction packed units (mm, 1e-3 m)
Corrections['ocTideElv'] = np.zeros((n_records),dtype=np.int16)
#-- Long period equilibrium ocean tide Correction packed units (mm, 1e-3 m)
Corrections['lpeTideElv'] = np.zeros((n_records),dtype=np.int16)
#-- Ocean loading tide Correction packed units (mm, 1e-3 m)
Corrections['olTideElv'] = np.zeros((n_records),dtype=np.int16)
#-- Solid Earth tide Correction packed units (mm, 1e-3 m)
Corrections['seTideElv'] = np.zeros((n_records),dtype=np.int16)
#-- Geocentric Polar tide Correction packed units (mm, 1e-3 m)
Corrections['gpTideElv'] = np.zeros((n_records),dtype=np.int16)
Corrections['Spare1'] = np.zeros((n_records),dtype=np.int16)
#-- Surface Type: Packed in groups of three bits for each of the 20 records
Corrections['Surf_type'] = np.zeros((n_records),dtype=np.uint64)
#-- Mean Sea Surface or Geoid packed units (mm, 1e-3 m)
Corrections['MSS_Geoid'] = np.zeros((n_records),dtype=np.int32)
#-- Ocean Depth/Land Elevation Model (ODLE) packed units (mm, 1e-3 m)
Corrections['ODLE'] = np.zeros((n_records),dtype=np.int32)
#-- Ice Concentration packed units (%/100)
Corrections['Ice_conc'] = np.zeros((n_records),dtype=np.int16)
#-- Snow Depth packed units (mm, 1e-3 m)
Corrections['Snow_depth'] = np.zeros((n_records),dtype=np.int16)
#-- Snow Density packed units (kg/m^3)
Corrections['Snow_density'] = np.zeros((n_records),dtype=np.int16)
Corrections['Spare2'] = np.zeros((n_records),dtype=np.int16)
#-- Corrections Status Flag
Corrections['C_status'] = np.zeros((n_records),dtype=np.uint32)
#-- Significant Wave Height (SWH) packed units (mm, 1e-3)
Corrections['SWH'] = np.zeros((n_records),dtype=np.int16)
#-- Wind Speed packed units (mm/s, 1e-3 m/s)
Corrections['Wind_speed'] = np.zeros((n_records),dtype=np.uint16)
Corrections['Spare3'] = np.zeros((n_records),dtype=np.int16)
Corrections['Spare4'] = np.zeros((n_records),dtype=np.int16)
Corrections['Spare5'] = np.zeros((n_records),dtype=np.int16)
Corrections['Spare6'] = np.zeros((n_records),dtype=np.int16)
#-- CryoSat-2 20 Hz data fields (Measurement Group)
#-- Derived from instrument measurement parameters
n_blocks = 20
Data_20Hz = {}
#-- Delta between the timestamps for 20Hz record and the 1Hz record
#-- D_time_mics packed units (microseconds)
Data_20Hz['D_time_mics'] = np.ma.zeros((n_records,n_blocks),dtype=np.int32)
Data_20Hz['D_time_mics'].mask = np.ones((n_records,n_blocks),dtype=bool)
#-- Lat: packed units (0.1 micro-degree, 1e-7 degrees)
Data_20Hz['Lat'] = np.ma.zeros((n_records,n_blocks),dtype=np.int32)
Data_20Hz['Lat'].mask = | np.ones((n_records,n_blocks),dtype=bool) | numpy.ones |
# -*- coding: utf-8 -*-
from ..data import Data, DataSamples
from ..cross import DecisionTree, Crosses
#from ..woe import WOE
import pandas as pd
#import math as m
import numpy as np
import matplotlib
import matplotlib.colors as colors
import matplotlib.pyplot as plt
from matplotlib.ticker import FuncFormatter
import seaborn as sns
from sklearn.model_selection import cross_val_score, StratifiedKFold, train_test_split, GridSearchCV, PredefinedSplit
from sklearn.linear_model import LogisticRegression, LinearRegression
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import roc_auc_score, roc_curve, auc, r2_score
from scipy.stats import chi2, chisquare, ks_2samp, ttest_ind
#import statsmodels.formula.api as sm
import warnings
from abc import ABCMeta, abstractmethod
#from sklearn.feature_selection import GenericUnivariateSelect, f_classif
from patsy import dmatrices
from statsmodels.stats.outliers_influence import variance_inflation_factor
import re
import ast
import os
import xlsxwriter
from PIL import Image
import datetime
from dateutil.relativedelta import *
from scipy.optimize import minimize
import copy
import itertools
import calendar
warnings.simplefilter('ignore')
plt.rc('font', family='Verdana')
plt.style.use('seaborn-darkgrid')
pd.set_option('display.precision', 3)
class ScoringModel(metaclass = ABCMeta):
'''
Base class for binary scoring models
'''
@abstractmethod
def __init__(self, model):
self.model = model
self.features = []
@abstractmethod
def fit(self, data):
pass
def predict(self, data, woe_transform=None):
'''
Predicts probability of target = 1
Parameters
-----------
data: Data to use for prediction, Data type
woe_transform: a WOE object to perform WoE-transformation before using model
Returns
-----------
matrix with shape [(sample size) X (number of classes)]
'''
if woe_transform is not None:
data=woe_transform.transform(data, keep_essential=True, original_values=True, calc_gini=False)
if self.features == []:
self.features = data.features
return self.model.predict_proba(data.dataframe[self.features])
def roc_curve(self, data, woe_transform=None, figsize=(10,7), filename = 'roc_curve', verbose = True):
'''
Displays ROC-curve and Gini coefficient for the model
Parameters
-----------
data: a Data or DataSamples object
woe_transform: a WOE object to perform WoE-transformation before using model
figsize: a tuple for graph size
filename: name of the picture with roc_curve
verbose: show/not show roc_curve in output
Returns
----------
a list of gini values per input sample
'''
if woe_transform is not None:
data=woe_transform.transform(data, keep_essential=True, original_values=True, calc_gini=False)
tpr={}
fpr={}
roc_auc={}
if type(data)==DataSamples:
samples=[data.train, data.validate, data.test]
sample_names=['Train', 'Validate', 'Test']
for si in range(len(samples)):
if samples[si] is not None:
preds = self.predict(samples[si])[:,1]
fpr[samples[si].name], tpr[samples[si].name], _ = roc_curve(samples[si].dataframe[samples[si].target], preds)
roc_auc[samples[si].name] = auc(fpr[samples[si].name], tpr[samples[si].name])
else:
fpr[sample_names[si]]=None
tpr[sample_names[si]]=None
roc_auc[sample_names[si]]=None
else:
preds = self.predict(data)[:,1]
fpr['Data'], tpr['Data'], _ = roc_curve(data.dataframe[data.target], preds)
roc_auc['Data'] = auc(fpr['Data'], tpr['Data'])
if verbose or (filename is not None):
fig = plt.figure(figsize=figsize)
ax = fig.add_subplot(111)
# Plot tpr vs 1-fpr
for sample in roc_auc:
if roc_auc[sample] is not None:
ax.plot(fpr[sample], tpr[sample], label=sample+' (AUC = %f)' % roc_auc[sample])
ax.plot(tpr[list(tpr)[0]],tpr[list(tpr)[0]])
ax.set_xlabel('False Positive Rate')
ax.set_ylabel('True Positive Rate')
ax.legend()
if filename is not None:
plt.savefig(filename + ".png", dpi=100, bbox_inches='tight')
if verbose:
plt.show()
if verbose or (filename is not None):
plt.close()
ginis=[]
for sample in roc_auc:
if roc_auc[sample] is not None:
gini = round((roc_auc[sample]*2 - 1)*100, 2)
ginis.append(gini)
if verbose:
print ('Gini '+sample, gini)
return ginis
#---------------------------------------------------------------
class DecisionTreeModel(ScoringModel):
'''
Decision tree classifier
'''
def __init__(self, **args):
self.model = DecisionTreeClassifier(**args)
self.features = []
def fit(self, data):
if data.weights != None:
self.model.fit(data.dataframe[data.features], data.dataframe[data.target], sample_weight = | np.array(data.dataframe[data.weights]) | numpy.array |
"""
An interface to output the data in various format
"""
import numpy
import os
import sys
from pysph.base.particle_array import ParticleArray
from pysph.base.utils import get_particles_info, get_particle_array
from pysph import has_h5py
output_formats = ('hdf5', 'npz')
COMPRESSION_LEVEL = 6
def _to_str(s):
if isinstance(s, bytes) and sys.version_info[0] > 2:
return s.decode('utf-8')
else:
return str(s)
def gather_array_data(all_array_data, comm):
"""Given array_data from the current processor and an MPI
communicator,return a joined array_data from all processors
on rank 0 and the same array_data on the other machines.
"""
array_names = all_array_data.keys()
# gather the data from all processors
collected_data = comm.gather(all_array_data, root=0)
if comm.Get_rank() == 0:
all_array_data = {}
size = comm.Get_size()
# concatenate the arrays
for array_name in array_names:
array_data = {}
all_array_data[array_name] = array_data
_props = collected_data[0][array_name].keys()
for prop in _props:
data = [collected_data[pid][array_name][prop]
for pid in range(size)]
prop_arr = numpy.concatenate(data)
array_data[prop] = prop_arr
return all_array_data
class Output(object):
""" Class that handles output for simulation """
def __init__(self, detailed_output=False, only_real=True, mpi_comm=None,
compress=False):
self.compress = compress
self.detailed_output = detailed_output
self.only_real = only_real
self.mpi_comm = mpi_comm
def dump(self, fname, particles, solver_data):
self.particle_data = dict(get_particles_info(particles))
self.all_array_data = {}
for array in particles:
self.all_array_data[array.name] = array.get_property_arrays(
all=self.detailed_output,
only_real=self.only_real
)
mpi_comm = self.mpi_comm
if mpi_comm is not None:
self.all_array_data = gather_array_data(
self.all_array_data, mpi_comm
)
self.solver_data = solver_data
if mpi_comm is None or mpi_comm.Get_rank() == 0:
self._dump(fname)
def load(self, fname):
return self._load(fname)
def _dump(self, fname):
""" Implement the method for writing the output to a file here """
raise NotImplementedError()
def _load(self, fname):
""" Implement the method for loading from file here """
raise NotImplementedError()
def _dict_bytes_to_str(d):
# This craziness is needed as if the npz file is saved in Python2
# then all the strings are bytes and if this is loaded in Python 3,
# the keys will be bytes and not strings leading to strange errors.
res = {}
for key, value in d.items():
if isinstance(value, dict):
value = _dict_bytes_to_str(value)
if isinstance(value, bytes):
value = _to_str(value)
if isinstance(value, list):
if value and isinstance(value[0], bytes):
value = [_to_str(x) for x in value]
res[_to_str(key)] = value
return res
def _get_dict_from_arrays(arrays):
arrays.shape = (1,)
res = arrays[0]
if res and isinstance(list(res.keys())[0], bytes):
return _dict_bytes_to_str(res)
else:
return res
class NumpyOutput(Output):
def _dump(self, filename):
save_method = numpy.savez_compressed if self.compress else numpy.savez
output_data = {"particles": self.particle_data,
"solver_data": self.solver_data}
for name, arrays in self.all_array_data.items():
self.particle_data[name]["arrays"] = arrays
save_method(filename, version=2, **output_data)
def _load(self, fname):
data = | numpy.load(fname, encoding='bytes', allow_pickle=True) | numpy.load |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.