prompt
stringlengths 19
879k
| completion
stringlengths 3
53.8k
| api
stringlengths 8
59
|
---|---|---|
import warnings
from typing import Optional, Tuple, Union
import numpy as np
import numpy.typing as npt
from pybasic.linalg import dct2d, idct2d, fro_norm, l1_norm
from pybasic.utils import timed_ctx
rng = np.random.default_rng(seed=0)
def scalar_shrink(arr: npt.NDArray, epsilon: float) -> npt.NDArray:
return np.sign(arr) * np.maximum(np.abs(arr) - epsilon, 0)
def inexact_alm_rspca_l1(
ims: npt.NDArray,
*,
flatfield_reg: float,
darkfield_reg: float,
optim_tol: float,
max_iters: int,
weight: Optional[npt.NDArray] = None,
compute_darkfield: bool = False,
# darkfield_upper_lim: float = 1e7,
) -> Tuple[npt.NDArray, ...]:
if weight is not None:
if weight.shape != ims.shape:
raise ValueError(
f"Mismatch between dims of weight ({weight.shape}) and images ({ims.shape})"
)
weight = np.ones(ims.shape)
lm1 = 0 # lagrange multiplier
# lm2 = 0
ent1 = 1 # ?
ent2 = 10
# convenience shapes
n = ims.shape[0]
im_dims = ims.shape[1:3]
full_dims = ims.shape
# variables
im_res = np.zeros(full_dims)
base = np.ones((n, 1, 1))
dark_res = np.zeros(im_dims)
flat = np.zeros(im_dims)
# adaptive penalty
ims_vec = ims.reshape((n, -1))
norm_two = np.linalg.svd(ims_vec, compute_uv=False, full_matrices=False)[0]
pen = 12.5 / norm_two # initial penalty
pen_max = pen * 1e7
pen_mult = 1.5
# TODO: can we set the initial penalty to something reasonable without having to
# compute the SVD?
# convenience constants
ims_norm = fro_norm(ims)
ims_min = ims.min()
dark_mean = 0
# A_upper_lim = ims.min(axis=0)
# A_inmask = np.zeros((h, w))
# A_inmask[h // 6 : h // 6 * 5, w // 6 : w // 6 * 5] = 1
it = 0
while True:
# update flatfield
im_base = base * flat + dark_res
_diff = (ims - im_base - im_res + lm1 / pen) / ent1
_diff = _diff.mean(axis=0)
flat_f = dct2d(flat) + dct2d(_diff)
flat_f = scalar_shrink(flat_f, flatfield_reg / (ent1 * pen))
flat = idct2d(flat_f)
# update residual
im_base = base * flat + dark_res
im_res += (ims - im_base - im_res + lm1 / pen) / ent1
im_res = scalar_shrink(im_res, weight / (ent1 * pen))
# update baseline
im_diff = ims - im_res
base = im_diff.mean(axis=(1, 2), keepdims=True) / im_diff.mean()
base[base < 0] = 0
if compute_darkfield:
# calculate dark_mean using least-square fitting
base_valid_ind = (base < 1).squeeze()
im_diff_valid = im_diff[base_valid_ind]
base_valid = base[base_valid_ind]
flat_mean = flat.mean()
_flat_gt = flat > (flat_mean - 1e-6)
_flat_lt = flat < (flat_mean + 1e-6)
diff = (im_diff_valid[:, _flat_gt].mean(axis=-1)) - (
im_diff_valid[:, _flat_lt].mean(axis=-1)
)
n_valid = np.count_nonzero(base_valid_ind)
_temp1 = np.square(base_valid).sum()
_temp2 = base_valid.sum()
_temp3 = diff.sum()
_temp4 = (base_valid * diff).sum()
_temp5 = _temp2 * _temp3 - n_valid * _temp4
if _temp5 == 0:
dark_mean = 0
else:
dark_mean = (_temp1 * _temp3 - _temp2 * _temp4) / _temp5
# clip to reasonable values
dark_mean = max(dark_mean, 0)
dark_mean = min(dark_mean, ims_min / flat_mean)
# optimize dark_res
_diff = (im_diff_valid - base_valid * flat).mean(axis=0)
dark_diff = dark_mean * (flat_mean - flat)
dark_res = _diff - _diff.mean() - dark_diff
dark_res_f = dct2d(dark_res)
dark_res_f = scalar_shrink(dark_res_f, darkfield_reg / (ent2 * pen))
dark_res = idct2d(dark_res_f)
dark_res = scalar_shrink(dark_res, darkfield_reg / (ent2 * pen))
dark_res += dark_diff
# update lagrangian multiplier
# if I'm understanding Table 1 in the supplementary section correctly, the next
# line is missing from the MATLAB implementation
im_base = base * flat + dark_res
im_diff = ims - im_base - im_res
lm1 += pen * im_diff
# update penalty
pen = min(pen * pen_mult, pen_max)
# check for stop condition
it += 1
is_converged = (fro_norm(im_diff) / ims_norm) < optim_tol
if is_converged:
print(f"Converged in {it} iterations")
break
if not is_converged and it >= max_iters:
warnings.warn("Maximum iterations reached")
break
dark_res += dark_mean * flat
return im_base, im_res, dark_res
def basic(
images: npt.NDArray,
*,
flatfield_reg: Optional[float] = None,
darkfield_reg: Optional[float] = None,
optim_tol: float = 1e-6,
max_iters: int = 500,
compute_darkfield: bool = False,
eps: float = 0.1,
reweight_tol: float = 1e-3,
max_reweight_iters: int = 10,
) -> Union[npt.NDArray, Tuple[npt.NDArray, npt.NDArray]]:
if images.ndim != 3:
raise ValueError("Images must be 3D (IYX)")
ims = images
orig_dims = ims.shape[1:3]
# resize to working size
full_dims = ims.shape
im_dims = ims.shape[1:3]
# apply automatic regularization coefficient strategy
if flatfield_reg is None or darkfield_reg is None:
ims_norm = ims.mean(axis=0)
ims_norm /= ims_norm.mean()
ims_dct = dct2d(ims_norm)
ims_l1 = l1_norm(ims_dct)
if flatfield_reg is None:
flatfield_reg = ims_l1 / 800
if darkfield_reg is None:
darkfield_reg = ims_l1 / 2_000
print(f"Flat reg: {flatfield_reg:,.3f}, dark reg: {darkfield_reg:,.3f}")
ims = | np.sort(ims, axis=0) | numpy.sort |
#!/usr/bin/env python3
import os
import numpy as np
from shutil import copytree, rmtree, copy2
import subprocess
import shlex
import sqlite3
from tqdm import tqdm
import shutil
import torch
from .torch_matchers import mutual_nn_matcher
from .colmap_read_model import CAMERA_MODELS, CAMERA_MODEL_IDS
from .colmap_read_model import read_cameras_binary, read_images_binary, read_points3d_binary
model_bins = ['images.bin', 'cameras.bin', 'points3D.bin']
model_txts = ['images.txt', 'cameras.txt', 'points3D.txt']
cam_model_name_to_id = dict([(cm.model_name, cm.model_id) for cm in CAMERA_MODELS])
supported_custom_ftrs = ['d2-net']
class MapperOptions:
def __init__(self):
self.params = {
"filter_max_reproj_error": 4,
"filter_min_tri_angle": 1.5,
"ba_global_max_refinements": 5,
"ba_global_max_refinement_change": 0.0005
}
self.pref = "Mapper."
class SiftMatchingOptions:
def __init__(self):
self.params = {"max_ratio": 0.8,
"max_distance": 0.7,
"max_error": 4,
"min_inlier_ratio": 0.25}
self.pref = "SiftMatching."
def getImgNameToImgIdMap(database):
connection = sqlite3.connect(database)
cursor = connection.cursor()
img_nm_to_id = {}
cursor.execute("SELECT name, image_id FROM images;")
for row in cursor:
img_nm_to_id[row[0]] = row[1]
cursor.close()
connection.close()
return img_nm_to_id
def getCameraIds(database):
connection = sqlite3.connect(database)
cursor = connection.cursor()
camera_ids = []
cursor.execute("SELECT camera_id FROM cameras;")
for row in cursor:
camera_ids.append(row[0])
cursor.close()
connection.close()
return camera_ids
def nextCameraId(database):
return max(getCameraIds(database)) + 1
def getImageIds(database):
connection = sqlite3.connect(database)
cursor = connection.cursor()
image_ids = []
cursor.execute("SELECT image_id FROM images;")
for row in cursor:
image_ids.append(row[0])
cursor.close()
connection.close()
return image_ids
def addColmapCameras(colmap_cams, database, cam_ids, prior_focal_length=False):
connection = sqlite3.connect(database)
cursor = connection.cursor()
for colmap_cam, cam_id in zip(colmap_cams, cam_ids):
cursor.execute("INSERT INTO cameras VALUES (?, ?, ?, ?, ?, ?)",
(cam_id, cam_model_name_to_id[colmap_cam.model],
colmap_cam.width, colmap_cam.height, colmap_cam.params.tostring(),
prior_focal_length))
connection.commit()
cursor.close()
connection.close()
def setCameraIdForImages(images, cam_ids, database):
connection = sqlite3.connect(database)
cursor = connection.cursor()
for img, cam_id in zip(images, cam_ids):
cursor.execute("UPDATE images SET camera_id=? WHERE name=?;", (cam_id, img))
connection.commit()
cursor.close()
connection.close()
def imgIdsToPairId(image_id1, image_id2):
if image_id1 > image_id2:
return 2147483647 * image_id2 + image_id1
else:
return 2147483647 * image_id1 + image_id2
def extractFeaturesFromImages(database, img_dir, input_imgs_rel_path, method,
tmp_dir='/tmp', pref=''):
if method is None:
extr_img_list = os.path.join(tmp_dir, pref+'extractor_img_list.txt')
print("- write image list for extraction in {}".format(extr_img_list))
with open(extr_img_list, 'w') as f:
f.writelines([v+'\n' for v in input_imgs_rel_path])
extract_cmd = ('colmap feature_extractor --database_path {} --image_path {} '
'--image_list_path {} ').format(database, img_dir, extr_img_list)
subprocess.call(shlex.split(extract_cmd))
elif method in supported_custom_ftrs:
new_img_id_s = max(getImageIds(database)) + 1
new_cam_id_s = max(getCameraIds(database)) + 1
new_img_ids = list(range(new_img_id_s, new_img_id_s + len(input_imgs_rel_path)))
new_cam_ids = list(range(new_cam_id_s, new_cam_id_s + len(input_imgs_rel_path)))
print("New image ids: ", new_img_id_s)
print("New camera ids: ", new_cam_id_s)
addImagesAndCameras(database, input_imgs_rel_path, new_img_ids, new_cam_ids)
importCustomFeatures(input_imgs_rel_path, new_img_ids, img_dir, database, method)
else:
assert False, 'Unknown method type {}.'.format(method)
def triangulatePointsFromModel(database, img_dir, model_dir, mapper_options):
output_dir = os.path.join(model_dir, 'output')
if not os.path.exists(output_dir):
os.makedirs(output_dir)
triangulation_cmd = ("colmap point_triangulator --database_path {} "
"--image_path {} --input_path {} --output_path {} "
).format(
database, img_dir, model_dir, output_dir)
for k, v in mapper_options.params.items():
triangulation_cmd += " --{} {}".format(mapper_options.pref+k, v)
subprocess.call(shlex.split(triangulation_cmd))
convert_cmd = ("colmap model_converter --input_path {} "
"--output_path {} --output_type TXT").format(output_dir, output_dir)
subprocess.call(shlex.split(convert_cmd))
for v in model_txts:
os.remove(os.path.join(model_dir, v))
for v in (model_bins + model_txts):
shutil.copy2(os.path.join(output_dir, v), os.path.join(model_dir, v))
shutil.rmtree(output_dir)
def makeEmpty3DPoints(model_dir):
point_fn = os.path.join(model_dir, 'points3D.txt')
if os.path.exists(point_fn):
os.remove(point_fn)
os.mknod(point_fn)
def matchFeaturesInList(database, img_dir, match_list, method, sift_match_options):
if method is None:
pass
elif method in supported_custom_ftrs:
all_img_nm_to_id = getImgNameToImgIdMap(database)
matchCustomFeatures(all_img_nm_to_id, img_dir, match_list,
database, method)
else:
assert False, 'Unknown method type {}.'.format(method)
matcher_import_cmd = ("colmap matches_importer --database_path {} "
"--match_list_path {} --match_type pairs ").format(
database, match_list)
for k, v in sift_match_options.params.items():
matcher_import_cmd += " --{} {}".format(sift_match_options.pref+k, v)
subprocess.call(shlex.split(matcher_import_cmd))
def importCustomFeatures(image_names, image_ids, img_dir, database, method):
connection = sqlite3.connect(database)
cursor = connection.cursor()
for image_name, image_id in tqdm(zip(image_names, image_ids), total=len(image_names)):
features_path = os.path.join(
img_dir, '%s.%s' % (image_name, method))
keypoints = np.load(features_path)['keypoints']
n_keypoints = keypoints.shape[0]
# Keep only x, y coordinates.
keypoints = keypoints[:, : 2]
# Add placeholder scale, orientation.
keypoints = np.concatenate([keypoints, np.ones((n_keypoints, 1)), np.zeros(
(n_keypoints, 1))], axis=1).astype(np.float32)
keypoints_str = keypoints.tostring()
cursor.execute("INSERT INTO keypoints(image_id, rows, cols, data) VALUES(?, ?, ?, ?);",
(image_id, keypoints.shape[0], keypoints.shape[1], keypoints_str))
# Close the connection to the database.
connection.commit()
cursor.close()
connection.close()
def addImagesAndCameras(database, names, image_ids, camera_ids):
connection = sqlite3.connect(database)
cursor = connection.cursor()
for nm, img_id, cam_id in zip(names, image_ids, camera_ids):
cursor.execute(
"INSERT INTO images VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
(img_id, nm, cam_id, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan))
# copy the first camera
rows = cursor.execute("SELECT * FROM cameras")
_, model, width, height, params, prior = next(rows)
for cam_id in camera_ids:
cursor.execute("INSERT INTO cameras VALUES (?, ?, ?, ?, ?, ?)",
(cam_id, model, width, height, params, prior))
connection.commit()
cursor.close()
connection.close()
def matchCustomFeatures(img_nm_to_id, img_dir, match_list, database, method):
connection = sqlite3.connect(database)
cursor = connection.cursor()
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
with open(match_list, 'r') as f:
raw_pairs = f.readlines()
print('Found {} pairs.'.format(len(raw_pairs)))
image_pair_ids = set()
for raw_pair in tqdm(raw_pairs, total=len(raw_pairs)):
image_name1, image_name2 = raw_pair.strip('\n').split(' ')
if image_name1 not in img_nm_to_id or image_name2 not in img_nm_to_id:
print("Failed to find {} - {} in known images. Skip".format(
image_name1, image_name2))
continue
features_path1 = os.path.join(img_dir, '%s.%s' % (image_name1, method))
features_path2 = os.path.join(img_dir, '%s.%s' % (image_name2, method))
descriptors1 = torch.from_numpy(
np.load(features_path1)['descriptors']).to(device)
descriptors2 = torch.from_numpy(
np.load(features_path2)['descriptors']).to(device)
matches = mutual_nn_matcher(
descriptors1, descriptors2).astype(np.uint32)
image_id1, image_id2 = img_nm_to_id[image_name1], img_nm_to_id[image_name2]
image_pair_id = imgIdsToPairId(image_id1, image_id2)
if image_pair_id in image_pair_ids:
continue
image_pair_ids.add(image_pair_id)
if image_id1 > image_id2:
matches = matches[:, [1, 0]]
matches_str = matches.tostring()
cursor.execute("INSERT INTO matches(pair_id, rows, cols, data) VALUES(?, ?, ?, ?);",
(image_pair_id, matches.shape[0], matches.shape[1], matches_str))
connection.commit()
cursor.close()
connection.close()
def sqliteExecuteAtomic(database, cmds):
connection = sqlite3.connect(database)
cursor = connection.cursor()
for cmd in cmds:
cursor.execute(cmd)
connection.commit()
cursor.close()
connection.close()
def getModelDirs(sparse_top_dir):
model_dirs = []
for dirpath, dirnames, filenames in os.walk(sparse_top_dir):
if not dirnames:
if 'points3D.bin' in filenames or 'points3D.txt' in filenames:
model_dirs.append(dirpath)
return sorted(model_dirs)
def readMultipleModels(model_dirs):
all_images = []
all_points = []
all_cameras = []
img_nm_to_img_id = {}
for md in model_dirs:
print("- processing {}...".format(md))
img_fn = os.path.join(md, 'images.bin')
if not os.path.exists(img_fn):
print(" - cannot find {}, skip.".format(img_fn))
continue
cur_imgs = read_images_binary(img_fn)
n_del = 0
for img_id in cur_imgs:
img_nm_to_img_id[cur_imgs[img_id].name] = img_id
for prev_imgs in all_images:
if img_id in prev_imgs:
del prev_imgs[img_id]
n_del += 1
print(" - delete {} duplicate images from previous models".format(n_del))
all_images.append(cur_imgs)
cur_points = read_points3d_binary(os.path.join(md, 'points3D.bin'))
all_points.append(cur_points)
cur_cameras = read_cameras_binary(os.path.join(md, 'cameras.bin'))
all_cameras.append(cur_cameras)
print('Read {} images, {} 3D points and {} cameras'.format(
sum([len(v) for v in all_images]), sum([len(v) for v in all_points]),
sum([len(v) for v in all_cameras])))
return all_images, all_points, all_cameras, img_nm_to_img_id
def writeEmptyImageList(in_fn, out_fn):
with open(os.path.join(out_fn), 'w') as fout:
with open(os.path.join(in_fn), 'r') as fin:
cnt = 0
for line in fin:
if line.startswith('#'):
continue
if cnt % 2 == 0:
fout.write('{}\n\n'.format(line.strip()))
cnt += 1
def convertModel(md, output_type):
convert_cmd = ("colmap model_converter --input_path {} "
"--output_path {} --output_type {}").format(md, md, output_type)
subprocess.call(shlex.split(convert_cmd))
def cleanModel(md, clean_type):
if clean_type == 'TXT':
for v in model_txts:
os.remove(os.path.join(md, v))
elif clean_type == 'BIN':
for v in model_bins:
os.remove(os.path.join(md, v))
else:
assert False, "Clean type: {}".format(clean_type)
def copyModel(in_dir, out_dir, model_type):
if model_type == 'TXT':
for b in model_txts:
copy2(os.path.join(in_dir, b), os.path.join(out_dir, b))
elif model_type == 'BIN':
for b in model_bins:
copy2(os.path.join(in_dir, b), os.path.join(out_dir, b))
else:
assert False, "Type: {}".format(model_type)
def ftrType2Suffix(ftr_type):
suffix = '' if ftr_type is None else '_{}'.format(ftr_type)
return suffix
def checkWorkspaceAndGetPath(colmap_ws, ftr_type=None, img_dir='images',
sparse_dir='sparse', database='database'):
assert os.path.exists(colmap_ws)
suffix = ftrType2Suffix(ftr_type)
base_sparse_dir = os.path.join(colmap_ws, sparse_dir+suffix)
base_img_dir = os.path.join(colmap_ws, img_dir)
base_db = os.path.join(colmap_ws, '{}{}.db'.format(database, suffix))
assert os.path.isdir(base_sparse_dir) and os.path.isdir(base_img_dir) and\
os.path.exists(base_db)
print("Found Colmap workspace:")
print(" - {}: {}".format('sparse dir', base_sparse_dir))
print(" - {}: {}".format('image dir', base_img_dir))
print(" - {}: {}".format('database', base_db))
return base_sparse_dir, base_img_dir, base_db
def cloneColmapWorkspace(input_ws, output_ws, ftr_type=None,
overwrite_sparse=True, overwrite_database=False):
print("Copying COLMAP workspace...")
input_sparse_dir, input_img_dir, input_database = checkWorkspaceAndGetPath(input_ws, ftr_type)
suffix = ftrType2Suffix(ftr_type)
img_dir = os.path.join(output_ws, 'images')
sparse_dir = os.path.join(output_ws, 'sparse'+suffix)
database = os.path.join(output_ws, 'database{}.db'.format(suffix))
if os.path.exists(output_ws):
print("- Output workspace exist.")
else:
os.makedirs(output_ws)
if not os.path.exists(img_dir):
copytree(input_img_dir, img_dir)
else:
print("- Image folder exists, skip.")
if os.path.exists(sparse_dir) and overwrite_sparse:
print("- Remove old sparse dir.")
rmtree(sparse_dir)
if not os.path.exists(sparse_dir):
copytree(input_sparse_dir, sparse_dir)
if not os.path.exists(database) or overwrite_database:
print("- Copy database.")
copy2(input_database, database)
def getKeypointsImgId(cursor, img_id, n_col=6):
# https://github.com/colmap/colmap/blob/dev/src/base/database.cc#L54
# The keypoints are stored as 6 columns anyway
cursor.execute("SELECT data FROM keypoints WHERE image_id=?;",
(img_id,))
row = next(cursor)
assert row[0]
return np.frombuffer(row[0], dtype=np.float32).reshape(-1, n_col)
def getTwoViewGeoMatchIndices(cursor, pair_id):
cursor.execute("SELECT data from two_view_geometries where pair_id=?;",
(pair_id, ))
row = next(cursor)
assert row[0]
return np.frombuffer(row[0], dtype=np.uint32).reshape(-1, 2)
def getCameraIdImageId(cursor, img_id):
cursor.execute("SELECT camera_id FROM images WHERE image_id=?;",
(img_id,))
row = next(cursor)
assert row[0]
return row[0]
def getCameraWidthAndHeight(cursor, cam_id):
cursor.execute("SELECT width FROM cameras WHERE camera_id=?;",
(cam_id,))
row = next(cursor)
w = row[0]
cursor.execute("SELECT height FROM cameras WHERE camera_id=?;",
(cam_id,))
row = next(cursor)
h = row[0]
return w, h
def getCameraPrincipalPoint(cursor, cam_id):
cursor.execute("SELECT model FROM cameras WHERE camera_id=?;",
(cam_id,))
row = next(cursor)
assert row[0]
model_name = CAMERA_MODEL_IDS[row[0]].model_name
print("Camera model: {}".format(model_name))
cursor.execute("SELECT params FROM cameras WHERE camera_id=?;",
(cam_id,))
row = next(cursor)
assert row[0]
if model_name == 'PINHOLE':
params = np.frombuffer(row[0], dtype=np.float64).reshape(4,)
return params[2], params[3]
elif model_name == 'SIMPLE_RADIAL':
params = np.frombuffer(row[0], dtype=np.float64).reshape(4,)
return params[1], params[2]
else:
assert False
def getDescriptorsImgId(cursor, img_id):
cursor.execute("SELECT data FROM descriptors WHERE image_id=?;",
(img_id,))
row = next(cursor)
assert row[0]
return np.frombuffer(row[0], dtype=np.uint8).reshape(-1, 128)
def affineToThetaScale(affine):
# see https://github.com/colmap/colmap/blob/dev/src/feature/types.cc
assert affine.shape == (4,)
scale = | np.sqrt(affine[0]**2 + affine[1]**2) | numpy.sqrt |
from typing import Tuple, Union, Callable, Optional, Sequence
from typing_extensions import Literal # < 3.8
from scanpy import logging as logg
from anndata import AnnData
from numba import njit
from scipy.sparse import issparse, spmatrix, csr_matrix, isspmatrix_csr
from sklearn.metrics import pairwise_distances
import numpy as np
import pandas as pd
from squidpy._docs import d, inject_docs
from squidpy._utils import Signal, SigQueue, parallelize, _get_n_cores
from squidpy.gr._utils import (
_save_data,
_extract_expression,
_assert_spatial_basis,
_assert_connectivity_key,
_assert_non_empty_sequence,
)
from squidpy._constants._pkg_constants import Key
__all__ = ["sepal"]
@d.dedent
@inject_docs(key=Key.obsp.spatial_conn())
def sepal(
adata: AnnData,
max_neighs: Literal[4, 6],
genes: Optional[Union[str, Sequence[str]]] = None,
n_iter: Optional[int] = 30000,
dt: float = 0.001,
thresh: float = 1e-8,
connectivity_key: str = Key.obsp.spatial_conn(),
spatial_key: str = Key.obsm.spatial,
layer: Optional[str] = None,
use_raw: bool = False,
copy: bool = False,
n_jobs: Optional[int] = None,
backend: str = "loky",
show_progress_bar: bool = True,
) -> Optional[pd.DataFrame]:
"""
Identify spatially variable genes with *Sepal*.
*Sepal* is a method that simulates a diffusion process to quantify spatial structure in tissue.
See :cite:`andersson2021` for reference.
Parameters
----------
%(adata)s
max_neighs
Maximum number of neighbors of a node in the graph. Valid options are:
- `4` - for a square-grid (ST, Dbit-seq).
- `6` - for a hexagonal-grid (Visium).
genes
List of gene names, as stored in :attr:`anndata.AnnData.var_names`, used to compute sepal score.
If `None`, it's computed :attr:`anndata.AnnData.var` ``['highly_variable']``, if present.
Otherwise, it's computed for all genes.
n_iter
Maximum number of iterations for the diffusion simulation.
If ``n_iter`` iterations are reached, the simulation will terminate
even though convergence has not been achieved.
dt
Time step in diffusion simulation.
thresh
Entropy threshold for convergence of diffusion simulation.
%(conn_key)s
%(spatial_key)s
layer
Layer in :attr:`anndata.AnnData.layers` to use. If `None`, use :attr:`anndata.AnnData.X`.
use_raw
Whether to access :attr:`anndata.AnnData.raw`.
%(copy)s
%(parallelize)s
Returns
-------
If ``copy = True``, returns a :class:`pandas.DataFrame` with the sepal scores.
Otherwise, modifies the ``adata`` with the following key:
- :attr:`anndata.AnnData.uns` ``['sepal_score']`` - the sepal scores.
Notes
-----
If some genes in :attr:`anndata.AnnData.uns` ``['sepal_score']`` are `NaN`,
consider re-running the function with increased ``n_iter``.
"""
_assert_connectivity_key(adata, connectivity_key)
_assert_spatial_basis(adata, key=spatial_key)
if max_neighs not in (4, 6):
raise ValueError(f"Expected `max_neighs` to be either `4` or `6`, found `{max_neighs}`.")
spatial = adata.obsm[spatial_key].astype(np.float_)
if genes is None:
genes = adata.var_names.values
if "highly_variable" in adata.var.columns:
genes = genes[adata.var["highly_variable"].values]
genes = _assert_non_empty_sequence(genes, name="genes")
n_jobs = _get_n_cores(n_jobs)
g = adata.obsp[connectivity_key]
if not isspmatrix_csr(g):
g = csr_matrix(g)
g.eliminate_zeros()
max_n = np.diff(g.indptr).max()
if max_n != max_neighs:
raise ValueError(f"Expected `max_neighs={max_neighs}`, found node with `{max_n}` neighbors.")
# get saturated/unsaturated nodes
sat, sat_idx, unsat, unsat_idx = _compute_idxs(g, spatial, max_neighs, "l1")
# get counts
vals, genes = _extract_expression(adata, genes=genes, use_raw=use_raw, layer=layer)
start = logg.info(f"Calculating sepal score for `{len(genes)}` genes using `{n_jobs}` core(s)")
score = parallelize(
_score_helper,
collection=np.arange(len(genes)),
extractor=np.hstack,
use_ixs=False,
n_jobs=n_jobs,
backend=backend,
show_progress_bar=show_progress_bar,
)(
vals=vals,
max_neighs=max_neighs,
n_iter=n_iter,
sat=sat,
sat_idx=sat_idx,
unsat=unsat,
unsat_idx=unsat_idx,
dt=dt,
thresh=thresh,
)
key_added = "sepal_score"
sepal_score = pd.DataFrame(score, index=genes, columns=[key_added])
if sepal_score[key_added].isna().any():
logg.warning("Found `NaN` in sepal scores, consider increasing `n_iter` to a higher value")
sepal_score.sort_values(by=key_added, ascending=False, inplace=True)
if copy:
logg.info("Finish", time=start)
return sepal_score
_save_data(adata, attr="uns", key=key_added, data=sepal_score, time=start)
def _score_helper(
ixs: Sequence[int],
vals: Union[spmatrix, np.ndarray],
max_neighs: int,
n_iter: int,
sat: np.ndarray,
sat_idx: np.ndarray,
unsat: np.ndarray,
unsat_idx: np.ndarray,
dt: np.float_,
thresh: np.float_,
queue: Optional[SigQueue] = None,
) -> np.ndarray:
if max_neighs == 4:
fun = _laplacian_rect
elif max_neighs == 6:
fun = _laplacian_hex
else:
raise NotImplementedError(f"Laplacian for `{max_neighs}` neighbors is not yet implemented.")
score, sparse = [], issparse(vals)
for i in ixs:
conc = vals[:, i].A.flatten() if sparse else vals[:, i].copy()
time_iter = _diffusion(conc, fun, n_iter, sat, sat_idx, unsat, unsat_idx, dt=dt, thresh=thresh)
score.append(dt * time_iter)
if queue is not None:
queue.put(Signal.UPDATE)
if queue is not None:
queue.put(Signal.FINISH)
return np.array(score)
@njit(fastmath=True)
def _diffusion(
conc: np.ndarray,
laplacian: Callable[[np.ndarray, np.ndarray, np.ndarray], np.float_],
n_iter: int,
sat: np.ndarray,
sat_idx: np.ndarray,
unsat: np.ndarray,
unsat_idx: np.ndarray,
dt: float = 0.001,
D: float = 1.0,
thresh: float = 1e-8,
) -> np.float_:
"""Simulate diffusion process on a regular graph."""
sat_shape, conc_shape = sat.shape[0], conc.shape[0]
entropy_arr = np.zeros(n_iter)
prev_ent = 1.0
nhood = np.zeros(sat_shape)
weights = np.ones(sat_shape)
for i in range(n_iter):
for j in range(sat_shape):
nhood[j] = np.sum(conc[sat_idx[j]])
d2 = laplacian(conc[sat], nhood, weights)
dcdt = | np.zeros(conc_shape) | numpy.zeros |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
range = getattr(__builtins__, 'xrange', range)
# end of py2 compatability boilerplate
"""Tests for `mass_ts` package."""
import os
import pytest
import numpy as np
import mass_ts
from mass_ts import _mass_ts as mts
MODULE_PATH = mass_ts.__path__[0]
def test_mass():
ts = np.array([1, 1, 1, 2, 1, 1, 4, 5])
query = np.array([2, 1, 1, 4])
actual = mts.mass(ts, query)
desired = np.array([
3.43092352e+00, 3.43092352e+00, 2.98023224e-08, 1.85113597e+00
])
np.testing.assert_almost_equal(actual, desired)
def test_mass_corr_coef():
ts = | np.array([1, 1, 1, 2, 1, 1, 4, 5]) | numpy.array |
import numpy as np
import matplotlib.pyplot as plt
from os import makedirs
from os.path import isfile, exists
from scipy.constants import mu_0
# from numba import njit
def calcDipolMomentAnalytical(remanence, volume):
""" Calculating the magnetic moment from the remanence in T and the volume in m^3"""
m = remanence * volume / mu_0 # [A * m^2]
return m
def plotSimple(data, FOV, fig, ax, cbar=True, **args):
""" Generate simple colorcoded plot of 2D grid data with contour. Returns axes object."""
im = ax.imshow(data, extent=FOV, origin="lower", **args)
cs = ax.contour(data, colors="k", extent=FOV, origin="lower", linestyles="dotted")
class nf(float):
def __repr__(self):
s = f"{self:.1f}"
return f"{self:.0f}" if s[-1] == "0" else s
cs.levels = [nf(val) for val in cs.levels]
if plt.rcParams["text.usetex"]:
fmt = r"%r"
else:
fmt = "%r"
ax.clabel(cs, cs.levels, inline=True, fmt=fmt, fontsize=10)
if cbar == True:
fig.colorbar(im, ax=ax)
return im
def centerCut(field, axis):
"""return a slice of the data at the center for the specified axis"""
dims = np.shape(field)
return np.take(field, indices=int(dims[axis] / 2), axis=axis)
def isHarmonic(field, sphericalMask, shellMask):
"""Checks if the extrema of the field are in the shell."""
fullField = np.multiply(field, sphericalMask) # [T]
reducedField = np.multiply(field, shellMask)
if int(ptpPPM(fullField)) > int(ptpPPM(reducedField)):
print(
"ptpPPM of field:",
ptpPPM(fullField),
"ptpPPM on surface",
ptpPPM(reducedField),
)
print("Masked field is NOT a harmonic function...")
return False
else:
print(
"ptpPPM of field:",
ptpPPM(fullField),
"ptpPPM on surface",
ptpPPM(reducedField),
)
print("Masked field is harmonic.")
sizeSpherical = int(np.nansum(sphericalMask))
sizeShell = int(np.nansum(shellMask))
print(
"Reduced size of field from {} to {} ({}%)".format(
sizeSpherical, sizeShell, int(100 * sizeShell / sizeSpherical)
)
)
return True
def genQmesh(field, resolution):
"""Generate a mesh of quadratic coordinates"""
mask = np.zeros(np.shape(field))
xAxis = np.linspace(
-(np.size(field, 0) - 1) * resolution / 2,
(np.size(field, 0) - 1) * resolution / 2,
np.size(field, 0),
)
yAxis = np.linspace(
-(np.size(field, 1) - 1) * resolution / 2,
(np.size(field, 1) - 1) * resolution / 2,
np.size(field, 1),
)
zAxis = np.linspace(
-(np.size(field, 2) - 1) * resolution / 2,
(np.size(field, 2) - 1) * resolution / 2,
np.size(field, 2),
)
xAxis, yAxis, zAxis = np.meshgrid(xAxis, yAxis, zAxis)
xAxisSquare = np.square(xAxis)
yAxisSquare = np.square(yAxis)
zAxisSquare = np.square(zAxis)
return mask, xAxisSquare, yAxisSquare, zAxisSquare
def genMask(
field, resolution, diameter=False, shellThickness=False, axis=False, debug=False
):
"""Generate a mask for a spherical shell"""
mask, xAxisSquare, yAxisSquare, zAxisSquare = genQmesh(field, resolution)
if (shellThickness != False) and (diameter != False):
if debug == True:
print(
"Creating shell mask. (resolution = {}, diameter = {}, shellThickness = {})".format(
resolution, diameter, shellThickness
)
)
print("The shell is added inside the sphere surface!")
rAxisSquare = xAxisSquare + yAxisSquare + zAxisSquare
innerRadiusSquare = (diameter / 2 - shellThickness) ** 2
outerRadiusSquare = (diameter / 2) ** 2
mask[
(rAxisSquare <= outerRadiusSquare) & (rAxisSquare >= innerRadiusSquare)
] = 1
mask[mask == 0] = "NaN"
return mask
def genSphericalMask(field, diameter, resolution):
"""generate spherical mask
with >>diameter<<
for a >>field<< and a given >>resolution<<
"""
mask, xAxisSquare, yAxisSquare, zAxisSquare = genQmesh(field, resolution)
mask[xAxisSquare + yAxisSquare + zAxisSquare <= (diameter / 2) ** 2] = 1
mask[mask == 0] = "NaN"
return mask
def genSliceMask(field, diameter, resolution, axis="x"):
"""generate mask for a circular slice
with >>diameter<<
for a >>field<< and a given >>resolution<<
Every input variable has to have the same unit (mm or m or ...)
"""
mask, xAxisSquare, yAxisSquare, zAxisSquare = genQmesh(field, resolution)
if axis == "z":
mask[
(xAxisSquare + yAxisSquare <= (diameter / 2) ** 2) & (zAxisSquare == 0)
] = 1
if axis == "y":
mask[
(xAxisSquare + zAxisSquare <= (diameter / 2) ** 2) & (yAxisSquare == 0)
] = 1
if axis == "x":
mask[
(yAxisSquare + zAxisSquare <= (diameter / 2) ** 2) & (xAxisSquare == 0)
] = 1
mask[mask == 0] = "NaN"
return mask
def genEllipseSliceMask(field, a, b, resolution, axis="x"):
"""generate mask for a circulat slice
with >>diameter<<
for a >>field<< and a given >>resolution<<
Every input variable has to have the same unit (mm or m or ...)
"""
# generate spherical mask
mask, xAxisSquare, yAxisSquare, zAxisSquare = genQmesh(field, resolution)
if axis == "z":
mask[
(xAxisSquare / (a / 2) ** 2 + yAxisSquare / (b / 2) ** 2 <= 1)
& (zAxisSquare == 0)
] = 1
elif axis == "y":
mask[
(xAxisSquare / (a / 2) ** 2 + zAxisSquare / (b / 2) ** 2 <= 1)
& (yAxisSquare == 0)
] = 1
elif axis == "x":
mask[
(yAxisSquare / (a / 2) ** 2 + zAxisSquare / (b / 2) ** 2 <= 1)
& (xAxisSquare == 0)
] = 1
mask[mask == 0] = "NaN"
return mask
def ptpPPM(field):
"""Calculate the peak-to-peak homogeneity in ppm."""
return 1e6 * (np.nanmax(field) - np.nanmin(field)) / np.nanmean(field)
def saveParameters(parameters, folder):
"""Saving a dict to the file parameters.npy .
If the file exist it is beeing updated, if the parameters are not stored already.
__future__: Fix usecase: Some parameters are in dict which are identical to the
stored ones and some are new!
"""
try:
print("Saving parameters to file...", end=" ")
print("\x1b[6;30;42m", *parameters.keys(), "\x1b[0m", end=" ")
oldParameters = loadParameters(folder)
if parameters.items() <= oldParameters.items():
print(" ... the parameters are already saved and identical.")
elif set(parameters).issubset(
set(oldParameters)
): # here just keys are compared!
print(
" ...\x1b[6;37;41m"
+ " parameters are NOT saved. Other parameters are stored. Please cleanup! "
+ "\x1b[0m"
)
else:
oldParameters.update(parameters)
np.save(folder + "/parameters", oldParameters)
print(" ... added.")
except FileNotFoundError or AttributeError:
np.save(folder + "/parameters", parameters)
oldParameters = parameters
# print('The following parameters are currently stored:\n', *oldParameters.keys())
def loadParameters(folder):
return np.load(folder + "/parameters.npy", allow_pickle=True).item()
def loadParameter(key, folder):
return loadParameters(folder)[key]
def displayParameters(folder):
print(loadParameters(folder))
def createShimfieldsShimRingV2(
numMagnets=(32, 44),
rings=4,
radii=(0.074, 0.097),
zRange=(-0.08, -0.039, 0.039, 0.08),
resolution=1000,
kValue=2,
simDimensions=(0.04, 0.04, 0.04),
numRotations=2,
):
""" Calculating the magnetic field distributions for a single or multiple Halbach Rings.
This has to be multiplied with the magnetic moment amplitude of a magnet to get the real distribution
For every magnet position we set 4 different rotations: 0°, 45°, 90°, 135°. This has to be considered in the cost function
otherwise two magnets are placed in one position
resolution is the amount of sample points times data points in one dimension
"""
mu = mu_0
# positioning of the magnets in a circle
if len(zRange) == 2:
rings = np.linspace(zRange[0], zRange[1], rings)
elif rings == len(zRange):
rings = np.array(zRange)
else:
print("No clear definition how to place shims...")
rotation_elements = np.linspace(0, np.pi, numRotations, endpoint=False)
# create array to store field data
count = 0
if type(numMagnets) in (list, tuple):
totalNumMagnets = np.sum(numMagnets) * np.size(rings) * numRotations
else:
totalNumMagnets = numMagnets * np.size(rings) * numRotations * len(radii)
print(totalNumMagnets, numMagnets, np.size(rings), np.size(numRotations))
shimFields = np.zeros(
(
int(simDimensions[0] * resolution) + 1,
int(simDimensions[1] * resolution) + 1,
int(simDimensions[2] * resolution) + 1,
3,
totalNumMagnets,
),
dtype=np.float32,
)
for rotation in rotation_elements:
# create halbach array
for row in rings:
for i, radius in enumerate(radii):
angle_elements = np.linspace(
-np.pi, np.pi, numMagnets[i], endpoint=False
)
for angle in angle_elements:
print(
"Simulating magnet "
+ str(count + 1)
+ " of "
+ str(totalNumMagnets),
end="\t",
)
position = (row, radius * np.cos(angle), radius * np.sin(angle))
print(
"@ position {:2.2},\t {:2.2},\t {:2.2}".format(*position),
end="\r",
)
angle = kValue * angle + rotation
dip_vec = [0, np.sin(angle), -np.cos(angle)]
dip_vec = np.multiply(dip_vec, mu)
dip_vec = np.divide(dip_vec, 4 * np.pi)
# create mesh coordinates
x = np.linspace(
-simDimensions[0] / 2 + position[0],
simDimensions[0] / 2 + position[0],
int(simDimensions[0] * resolution) + 1,
dtype=np.float32,
)
y = np.linspace(
-simDimensions[1] / 2 + position[1],
simDimensions[1] / 2 + position[1],
int(simDimensions[1] * resolution) + 1,
dtype=np.float32,
)
z = np.linspace(
-simDimensions[2] / 2 + position[2],
simDimensions[2] / 2 + position[2],
int(simDimensions[2] * resolution) + 1,
dtype=np.float32,
)
x, y, z = np.meshgrid(x, y, z)
vec_dot_dip = 3 * (y * dip_vec[1] + z * dip_vec[2])
# calculate the distance of each mesh point to magnet, optimised for speed
# for improved memory performance move in to b0 calculations
vec_mag = np.square(x) + np.square(y) + np.square(z)
# if the magnet is in the origin, we divide by 0, therefore we set it to nan to
# avoid getting and error. if this has any effect on speed just leave it out
# as we do not care about the values outside of the FOV and even less inside the magnets
vec_mag[(vec_mag <= 1e-15) & (vec_mag >= -1e-15)] = "NaN"
vec_mag_3 = np.power(vec_mag, 1.5)
vec_mag_5 = np.power(vec_mag, 2.5)
del vec_mag
# calculate contributions of magnet to total field, dipole always points in yz plane
# so second term is zero for the x component
shimFields[:, :, :, 0, count] = np.divide(
np.multiply(x, vec_dot_dip), vec_mag_5
)
shimFields[:, :, :, 1, count] = np.divide(
np.multiply(y, vec_dot_dip), vec_mag_5
) - np.divide(dip_vec[1], vec_mag_3)
shimFields[:, :, :, 2, count] = np.divide(
np.multiply(z, vec_dot_dip), vec_mag_5
) - np.divide(dip_vec[2], vec_mag_3)
count += 1
print(
"All magnets are simulated, the shim field array has shape:",
np.shape(shimFields),
"\t\t\t",
)
return shimFields.swapaxes(
0, 1
) # using i,j indexing as the other is too confusing....
def createShimfieldsDoubleRings(
numMagnets=72,
rings=1,
radii=(0.115, 0.12),
zRange=(0, 0),
resolution=1000,
kValue=2,
simDimensions=(0.04, 0.04, 0.04),
numRotations=4,
):
""" Calculating the magnetic field distributions for a single or multiple Halbach Rings.
This has to be multiplied with the magnetic moment amplitude of a magnet to get the real distribution
For every magnet position we set 4 different rotations: 0°, 45°, 90°, 135°. This has to be considered in the cost function
otherwise two magnets are placed in one position
resolution is the amount of sample points times data points in one dimension
"""
mu = mu_0
# positioning of the magnets in a circle
if len(zRange) == 2:
rings = np.linspace(zRange[0], zRange[1], rings)
elif rings == len(zRange):
rings = np.array(zRange)
else:
print("No clear definition how to place shims...")
rotation_elements = np.linspace(0, np.pi, numRotations, endpoint=False)
# create array to store field data
count = 0
totalNumMagnets = numMagnets * np.size(rings) * numRotations * len(radii)
print(totalNumMagnets, numMagnets, np.size(rings), np.size(numRotations))
shimFields = np.zeros(
(
int(simDimensions[0] * resolution) + 1,
int(simDimensions[1] * resolution) + 1,
int(simDimensions[2] * resolution) + 1,
3,
totalNumMagnets,
),
dtype=np.float32,
)
for rotation in rotation_elements:
angle_elements = np.linspace(-np.pi, np.pi, numMagnets, endpoint=False)
# create halbach array
for row in rings:
for angle in angle_elements:
for radius in radii:
print(
"Simulating magnet "
+ str(count + 1)
+ " of "
+ str(totalNumMagnets),
end="\t",
)
position = (row, radius * np.cos(angle), radius * np.sin(angle))
print(
"@ position {:2.2},\t {:2.2},\t {:2.2}".format(*position),
end="\r",
)
angle = kValue * angle + rotation
dip_vec = [0, np.sin(angle), -np.cos(angle)]
dip_vec = np.multiply(dip_vec, mu)
dip_vec = np.divide(dip_vec, 4 * np.pi)
# create mesh coordinates
x = np.linspace(
-simDimensions[0] / 2 + position[0],
simDimensions[0] / 2 + position[0],
int(simDimensions[0] * resolution) + 1,
dtype=np.float32,
)
y = np.linspace(
-simDimensions[1] / 2 + position[1],
simDimensions[1] / 2 + position[1],
int(simDimensions[1] * resolution) + 1,
dtype=np.float32,
)
z = np.linspace(
-simDimensions[2] / 2 + position[2],
simDimensions[2] / 2 + position[2],
int(simDimensions[2] * resolution) + 1,
dtype=np.float32,
)
x, y, z = np.meshgrid(x, y, z)
vec_dot_dip = 3 * (y * dip_vec[1] + z * dip_vec[2])
# calculate the distance of each mesh point to magnet, optimised for speed
# for improved memory performance move in to b0 calculations
vec_mag = np.square(x) + np.square(y) + np.square(z)
# if the magnet is in the origin, we divide by 0, therefore we set it to nan to
# avoid getting and error. if this has any effect on speed just leave it out
# as we do not care about the values outside of the FOV and even less inside the magnets
vec_mag[(vec_mag <= 1e-15) & (vec_mag >= -1e-15)] = "NaN"
vec_mag_3 = np.power(vec_mag, 1.5)
vec_mag_5 = np.power(vec_mag, 2.5)
del vec_mag
# calculate contributions of magnet to total field, dipole always points in yz plane
# so second term is zero for the x component
shimFields[:, :, :, 0, count] = np.divide(
np.multiply(x, vec_dot_dip), vec_mag_5
)
shimFields[:, :, :, 1, count] = np.divide(
np.multiply(y, vec_dot_dip), vec_mag_5
) - np.divide(dip_vec[1], vec_mag_3)
shimFields[:, :, :, 2, count] = np.divide(
np.multiply(z, vec_dot_dip), vec_mag_5
) - np.divide(dip_vec[2], vec_mag_3)
count += 1
print(
"All magnets are simulated, the shim field array has shape:",
np.shape(shimFields),
"\t\t\t",
)
return shimFields.swapaxes(
0, 1
) # using i,j indexing as the other is too confusing....
def createShimfields(
numMagnets=72,
rings=1,
radius=0.115,
zRange=(0, 0),
resolution=1000,
kValue=2,
simDimensions=(0.04, 0.04, 0.04),
numRotations=4,
):
""" Calculating the magnetic field distributions for a single or multiple Halbach Rings.
This has to be multiplied with the magnetic moment amplitude of a magnet to get the real distribution
For every magnet position we set 4 different rotations: 0°, 45°, 90°, 135°. This has to be considered in the cost function
otherwise two magnets are placed in one position
resolution is the amount of sample points times data points in one dimension
"""
mu_0 = mu
# positioning of the magnets in a circle
if len(zRange) == 2:
rings = np.linspace(zRange[0], zRange[1], rings)
elif rings == len(zRange):
rings = np.array(zRange)
else:
print("No clear definition how to place shims...")
rotation_elements = np.linspace(0, np.pi, numRotations, endpoint=False)
# create array to store field data
count = 0
totalNumMagnets = numMagnets * np.size(rings) * numRotations
print(totalNumMagnets, numMagnets, np.size(rings), np.size(numRotations))
shimFields = np.zeros(
(
int(simDimensions[0] * resolution) + 1,
int(simDimensions[1] * resolution) + 1,
int(simDimensions[2] * resolution) + 1,
3,
totalNumMagnets,
),
dtype=np.float32,
)
for rotation in rotation_elements:
angle_elements = np.linspace(-np.pi, np.pi, numMagnets, endpoint=False)
# create halbach array
for row in rings:
for angle in angle_elements:
print(
"Simulating magnet "
+ str(count + 1)
+ " of "
+ str(totalNumMagnets),
end="\t",
)
position = (row, radius * np.cos(angle), radius * np.sin(angle))
print(
"@ position {:2.2},\t {:2.2},\t {:2.2}".format(*position), end="\r"
)
angle = kValue * angle + rotation
dip_vec = [0, np.sin(angle), -np.cos(angle)]
dip_vec = np.multiply(dip_vec, mu)
dip_vec = np.divide(dip_vec, 4 * np.pi)
# create mesh coordinates
x = np.linspace(
-simDimensions[0] / 2 + position[0],
simDimensions[0] / 2 + position[0],
int(simDimensions[0] * resolution) + 1,
dtype=np.float32,
)
y = np.linspace(
-simDimensions[1] / 2 + position[1],
simDimensions[1] / 2 + position[1],
int(simDimensions[1] * resolution) + 1,
dtype=np.float32,
)
z = np.linspace(
-simDimensions[2] / 2 + position[2],
simDimensions[2] / 2 + position[2],
int(simDimensions[2] * resolution) + 1,
dtype=np.float32,
)
x, y, z = np.meshgrid(x, y, z)
vec_dot_dip = 3 * (y * dip_vec[1] + z * dip_vec[2])
# calculate the distance of each mesh point to magnet, optimised for speed
# for improved memory performance move in to b0 calculations
vec_mag = np.square(x) + np.square(y) + np.square(z)
# if the magnet is in the origin, we divide by 0, therefore we set it to nan to
# avoid getting and error. if this has any effect on speed just leave it out
# as we do not care about the values outside of the FOV and even less inside the magnets
vec_mag[(vec_mag <= 1e-15) & (vec_mag >= -1e-15)] = "NaN"
vec_mag_3 = np.power(vec_mag, 1.5)
vec_mag_5 = np.power(vec_mag, 2.5)
del vec_mag
# calculate contributions of magnet to total field, dipole always points in yz plane
# so second term is zero for the x component
shimFields[:, :, :, 0, count] = np.divide(
np.multiply(x, vec_dot_dip), vec_mag_5
)
shimFields[:, :, :, 1, count] = np.divide(
np.multiply(y, vec_dot_dip), vec_mag_5
) - np.divide(dip_vec[1], vec_mag_3)
shimFields[:, :, :, 2, count] = np.divide(
np.multiply(z, vec_dot_dip), vec_mag_5
) - np.divide(dip_vec[2], vec_mag_3)
count += 1
print(
"All magnets are simulated, the shim field array has shape:",
np.shape(shimFields),
"\t\t\t",
)
return shimFields.swapaxes(
0, 1
) # using i,j indexing as the other is too confusing....
# @njit # this can increase calculation time significantly
# # the individual in the genetic algorithm needs to be changed to
# # a numpy array, check "One Max Problem: Using Numpy" in the deap documentation!
def dna2vector(dna, dipolMoments, numRotations, numMagnets):
"""Casts structured *dna to shim *vector*.
The *dna* is structured each element of the dna vector
stands for one magnet position and its value represents the type.
The values of each element are structured in the following way:
0 -------------> No magnet,
1 -------------> Magnet of type 1 rotated by 0°
...
2*rotations ---> Magnet of type 1 rotated to the last angle before 360°
2*rotations+1 -> Magnet of type 2 rotated by 0°
... *(Type x stands for Magnet with dipol moment x)
The resulting *vector* will contain the dipol strengths as values and the rotations
will be written successively, meaning first all magnets / dipol strengths with 0°
deviation from the Halbach Dipole orientation will be written, then the first rotation
and so on...
*dipolMoments* is a list of all dipole moments ordered in the same order as the dna.
This list should only contain positive values!
*numRotations* is the number of rotations of the magnets possible in one half circle,
so there are in total 2*rotations possible for each magnet.
*numMagnets* is the number of possible magnets to be placed.
"""
vector = [0] * numMagnets * numRotations # np.zeros((len(dna))*numRotations)
for magnetPos, gene in enumerate(dna):
if gene != 0:
magnetType, rotation = divmod((gene - 1), (2 * numRotations))
if rotation >= numRotations:
sign = -1
rotation = rotation % numRotations
else:
sign = 1
index = int(magnetPos + rotation * numMagnets)
vector[index] = sign * dipolMoments[magnetType]
return vector
def saveResults(parameters, shimmedField, folder):
counter = 0
filename = folder + "/results{}.npy"
while isfile(filename.format(counter)):
counter += 1
filename = filename.format(counter)
np.save(filename, parameters)
np.save(folder + "/shimmedField{}".format(counter), shimmedField)
def initSimulation(name):
if not exists(name):
makedirs(name)
print("New folder", name, "created.")
def importComsol(filename):
"""Imports 3D Grid Data from Comsol Multiphysics
Export the data with Comsol in the following manner:
Expressions: Bx, By, Bz, Bmean
Output: File type: Text
Data format: Spreadsheet
For "Points to evaluate in" you have two options:
a) Grid: use range(start, step, end) with the same value
of step for each direction
b) Regular Grid: The number of points for each dimension
should be such that the resolution is equal in each direction
"""
raw = np.loadtxt(filename, skiprows=9, delimiter=",")
x = raw[:, 0]
y = raw[:, 1]
z = raw[:, 2]
Bx = raw[:, 3]
By = raw[:, 4]
Bz = raw[:, 5]
Bnorm = raw[:, 6]
def getRes(x):
res = np.abs(np.unique(x)[1] - np.unique(x)[0])
return res
def getShift(x):
shift = x[np.argmin(np.abs(x))]
return shift
res = (getRes(x), getRes(y), getRes(z))
shift = (getShift(x), getShift(y), getShift(z))
xInd = np.array((x - shift[0]) / res[0], dtype=int)
yInd = np.array((y - shift[1]) / res[1], dtype=int)
zInd = np.array((z - shift[2]) / res[2], dtype=int)
xInd -= np.min(xInd)
yInd -= np.min(yInd)
zInd -= np.min(zInd)
dims = (np.unique(x).shape[0], | np.unique(y) | numpy.unique |
import numpy as np
import matplotlib.pyplot as plt
def create_donut():
N = 1000
Inner_R = 10
Outer_R = 20
print(N)
#Distance from the origin = radius + random normal
#Angle theta is uniformly distributed between (0, 2pi)
R1 = np.random.randn(N) + Inner_R
theta = 2*np.pi*np.random.random(N)
X_inner = np.concatenate([[R1 * np.cos(theta)], [R1 * np.sin(theta)]]).T #Create concentric circle inner
R2 = | np.random.randn(N) | numpy.random.randn |
"""
This module has one function named calculate() that uses Numpy
to output the mean, variance, standard deviation, max, min, and sum of
the rows, columns, and elements in a 3 x 3 matrix.
The input of the function is a list containing 9 digits.
The function converts the list into a 3 x 3 Numpy array,
and then returns a dictionary containing the mean, variance,
standard deviation, max, min, and sum along both axes and for the flattened matrix.
"""
from typing import Union
import numpy as np
def calculate(num_list: list) -> dict[str, list[list[Union[int, float]]]]:
"""Calculate the mean, variance, standard deviation, max, min and sum
along both axes and for a flattened matrix.
The input list must have 9 elements. Not more nor less.
Args:
num_list (list): Input list of numbers for the matrix.
Raises:
ValueError: Raise Value Error if the elements are not exactly 9 elements.
Returns:
dict[str, list[list[Union[int, float]]]]: Dictionary with all calculations.
"""
if len(num_list) != 9:
raise ValueError("List must contain nine numbers.")
num_matrix: np.array = np.array(num_list).reshape((3, 3))
calculations: dict[str, list[list[Union[int, float]]]] = {
"mean": [
np.mean(num_matrix, axis=0).tolist(),
np.mean(num_matrix, axis=1).tolist(),
np.mean(num_matrix.tolist()),
],
"variance": [
np.var(num_matrix, axis=0).tolist(),
np.var(num_matrix, axis=1).tolist(),
np.var(num_matrix.tolist()),
],
"standard deviation": [
np.std(num_matrix, axis=0).tolist(),
| np.std(num_matrix, axis=1) | numpy.std |
import os
import fire
import numpy as np
import torch
from torch import optim
from torch.utils.tensorboard import SummaryWriter
from torchvision import datasets, transforms
from libs.Visualize import Visualize
from models.VAE import VAE
class Main():
def __init__(self, z_dim):
"""Constructor
Args:
z_dim (int): Dimensions of the latent variable.
Returns:
None.
"""
self.z_dim = z_dim
self.dataloader_train = None
self.dataloader_valid = None
self.dataloader_test = None
self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
self.model = VAE(self.z_dim).to(self.device)
self.writer = SummaryWriter(log_dir="./logs")
self.lr = 0.001
self.optimizer = optim.Adam(self.model.parameters(), lr=self.lr)
self.num_max_epochs = 1000
self.num_no_improved = 0
self.num_batch_train = 0
self.num_batch_valid = 0
self.loss_valid = 10 ** 7 # Initialize with a large value
self.loss_valid_min = 10 ** 7 # Initialize with a large value
self.Visualize = Visualize(self.z_dim, self.dataloader_test, self.model, self.device)
def createDirectories(self):
"""Create directories for the tensorboard and learned model
Args:
None.
Returns:
None.
"""
if not os.path.exists("./logs"):
os.makedirs("./logs")
if not os.path.exists("./params"):
os.makedirs("./params")
def createDataLoader(self):
"""Download MNIST and convert it to data loaders
Args:
None.
Returns:
None.
"""
transform = transforms.Compose([transforms.ToTensor(), transforms.Lambda(lambda x: x.view(-1))]) # Preprocessing for MNIST images
dataset_train_valid = datasets.MNIST("./", train=True, download=True, transform=transform) # Separate train data and test data to get a dataset
dataset_test = datasets.MNIST("./", train=False, download=True, transform=transform)
# Use 20% of train data as validation data
size_train_valid = len(dataset_train_valid) # 60000
size_train = int(size_train_valid * 0.8) # 48000
size_valid = size_train_valid - size_train # 12000
dataset_train, dataset_valid = torch.utils.data.random_split(dataset_train_valid, [size_train, size_valid])
# Create dataloaders from the datasets
self.dataloader_train = torch.utils.data.DataLoader(dataset_train, batch_size=1000, shuffle=True)
self.dataloader_valid = torch.utils.data.DataLoader(dataset_valid, batch_size=1000, shuffle=False)
self.dataloader_test = torch.utils.data.DataLoader(dataset_test, batch_size=1000, shuffle=False)
self.Visualize.dataloader_test = self.dataloader_test
def train_batch(self):
"""Batch-based learning for training data
Args:
None.
Returns:
None.
"""
self.model.train()
for x, _ in self.dataloader_train:
lower_bound, _, _ = self.model(x, self.device)
loss = -sum(lower_bound)
self.model.zero_grad()
loss.backward()
self.optimizer.step()
self.writer.add_scalar("Loss_train/KL", -lower_bound[0].cpu().detach().numpy(), self.num_iter + self.num_batch_train)
self.writer.add_scalar("Loss_train/Reconst", -lower_bound[1].cpu().detach().numpy(), self.num_iter + self.num_batch_train)
self.num_batch_train += 1
self.num_batch_train -= 1
def valid_batch(self):
"""Batch-based learning for validating data
Args:
None.
Returns:
None.
"""
loss = []
self.model.eval()
for x, _ in self.dataloader_valid:
lower_bound, _, _ = self.model(x, self.device)
loss.append(-sum(lower_bound).cpu().detach().numpy())
self.writer.add_scalar("Loss_valid/KL", -lower_bound[0].cpu().detach().numpy(), self.num_iter + self.num_batch_valid)
self.writer.add_scalar("Loss_valid/Reconst", -lower_bound[1].cpu().detach().numpy(), self.num_iter + self.num_batch_valid)
self.num_batch_valid += 1
self.num_batch_valid -= 1
self.loss_valid = | np.mean(loss) | numpy.mean |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# #########################################################################
# Copyright (c) 2016, UChicago Argonne, LLC. All rights reserved. #
# #
# Copyright 2016. UChicago Argonne, LLC. This software was produced #
# under U.S. Government contract DE-AC02-06CH11357 for Argonne National #
# Laboratory (ANL), which is operated by UChicago Argonne, LLC for the #
# U.S. Department of Energy. The U.S. Government has rights to use, #
# reproduce, and distribute this software. NEITHER THE GOVERNMENT NOR #
# UChicago Argonne, LLC MAKES ANY WARRANTY, EXPRESS OR IMPLIED, OR #
# ASSUMES ANY LIABILITY FOR THE USE OF THIS SOFTWARE. If software is #
# modified to produce derivative works, such modified software should #
# be clearly marked, so as not to confuse it with the version available #
# from ANL. #
# #
# Additionally, redistribution and use in source and binary forms, with #
# or without modification, are permitted provided that the following #
# conditions are met: #
# #
# * Redistributions of source code must retain the above copyright #
# notice, this list of conditions and the following disclaimer. #
# #
# * Redistributions in binary form must reproduce the above copyright #
# notice, this list of conditions and the following disclaimer in #
# the documentation and/or other materials provided with the #
# distribution. #
# #
# * Neither the name of UChicago Argonne, LLC, Argonne National #
# Laboratory, ANL, the U.S. Government, nor the names of its #
# contributors may be used to endorse or promote products derived #
# from this software without specific prior written permission. #
# #
# THIS SOFTWARE IS PROVIDED BY UChicago Argonne, LLC AND CONTRIBUTORS #
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT #
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS #
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL UChicago #
# Argonne, LLC OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, #
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, #
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; #
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER #
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT #
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN #
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE #
# POSSIBILITY OF SUCH DAMAGE. #
# #########################################################################
"""Defines methods for reconstructing data from the :mod:`.acquisition` module.
The algorithm module contains methods for reconstructing tomographic data
including gridrec, SIRT, ART, and MLEM. These methods can be used as benchmarks
for custom reconstruction methods or as an easy way to access reconstruction
algorithms for developing other methods such as noise correction.
.. note::
Using `tomopy <https://github.com/tomopy/tomopy>`_ is recommended instead
of these functions for heavy computation.
.. moduleauthor:: <NAME> <<EMAIL>>
"""
import logging
import numpy as np
from xdesign.acquisition import thv_to_zxy
logger = logging.getLogger(__name__)
__author__ = "<NAME>"
__copyright__ = "Copyright (c) 2016, UChicago Argonne, LLC."
__docformat__ = 'restructuredtext en'
__all__ = ['art', 'sirt', 'mlem', 'update_progress']
def update_progress(progress):
"""Draw a process bar in the terminal.
Parameters
-------------
process : float
The percentage completed e.g. 0.10 for 10%
"""
percent = progress * 100
nbars = int(progress * 10)
print(
'\r[{0}{1}] {2:.2f}%'.format('#' * nbars, ' ' * (10 - nbars), percent),
end=''
)
if progress == 1:
print('')
def get_mids_and_lengths(x0, y0, x1, y1, gx, gy):
"""Return the midpoints and intersection lengths of a line and a grid.
Parameters
----------
x0,y0,x1,y1 : float
Two points which define the line. Points must be outside the grid
gx,gy : :py:class:`np.array`
Defines positions for the gridlines
Return
------
xm,ym : :py:class:`np.array`
Coordinates along the line within each intersected grid pixel.
dist : :py:class:`np.array`
Lengths of the line segments crossing each pixel
"""
# avoid upper-right boundary errors
if (x1 - x0) == 0:
x0 += 1e-6
if (y1 - y0) == 0:
y0 += 1e-6
# vector lengths (ax, ay)
ax = (gx - x0) / (x1 - x0)
ay = (gy - y0) / (y1 - y0)
# edges of alpha (a0, a1)
ax0 = min(ax[0], ax[-1])
ax1 = max(ax[0], ax[-1])
ay0 = min(ay[0], ay[-1])
ay1 = max(ay[0], ay[-1])
a0 = max(max(ax0, ay0), 0)
a1 = min(min(ax1, ay1), 1)
# sorted alpha vector
cx = (ax >= a0) & (ax <= a1)
cy = (ay >= a0) & (ay <= a1)
alpha = np.sort(np.r_[ax[cx], ay[cy]])
# lengths
xv = x0 + alpha * (x1 - x0)
yv = y0 + alpha * (y1 - y0)
lx = np.ediff1d(xv)
ly = np.ediff1d(yv)
dist = np.sqrt(lx**2 + ly**2)
# indexing
mid = alpha[:-1] + np.ediff1d(alpha) / 2.
xm = x0 + mid * (x1 - x0)
ym = y0 + mid * (y1 - y0)
return xm, ym, dist
def art(
gmin,
gsize,
data,
theta,
h,
init,
niter=10,
weights=None,
save_interval=None
):
"""Reconstruct data using ART algorithm. :cite:`Gordon1970`."""
assert data.size == theta.size == h.size, "theta, h, must be" \
"the equal lengths"
data = data.ravel()
theta = theta.ravel()
h = h.ravel()
if weights is None:
weights = np.ones(data.shape)
if save_interval is None:
save_interval = niter
archive = list()
# Convert from probe to global coords
srcx, srcy, detx, dety = thv_to_zxy(theta, h)
# grid frame (gx, gy)
sx, sy = init.shape
gx = np.linspace(gmin[0], gmin[0] + gsize[0], sx + 1, endpoint=True)
gy = np.linspace(gmin[1], gmin[1] + gsize[1], sy + 1, endpoint=True)
midlengths = dict() # cache the result of get_mids_and_lengths
for n in range(niter):
if n % save_interval == 0:
archive.append(init.copy())
# update = np.zeros(init.shape)
# nupdate = np.zeros(init.shape, dtype=np.uint)
update_progress(n / niter)
for m in range(data.size):
# get intersection locations and lengths
if m in midlengths:
xm, ym, dist = midlengths[m]
else:
xm, ym, dist = get_mids_and_lengths(
srcx[m], srcy[m], detx[m], dety[m], gx, gy
)
midlengths[m] = (xm, ym, dist)
# convert midpoints of line segments to indices
ix = np.floor(sx * (xm - gmin[0]) / gsize[0]).astype('int')
iy = np.floor(sy * (ym - gmin[1]) / gsize[1]).astype('int')
# simulate acquistion from initial guess
dist2 = np.dot(dist, dist)
if dist2 != 0:
ind = (dist != 0) & (0 <= ix) & (ix < sx) \
& (0 <= iy) & (iy < sy)
sim = np.dot(dist[ind], init[ix[ind], iy[ind]])
upd = np.true_divide((data[m] - sim), dist2)
init[ix[ind], iy[ind]] += dist[ind] * upd
archive.append(init.copy())
update_progress(1)
if save_interval == niter:
return init
else:
return archive
def sirt(
gmin,
gsize,
data,
theta,
h,
init,
niter=10,
weights=None,
save_interval=None
):
"""Reconstruct data using SIRT algorithm. :cite:`Gilbert1972`."""
assert data.size == theta.size == h.size, "theta, h, must be" \
"the equal lengths"
data = data.ravel()
theta = theta.ravel()
h = h.ravel()
if weights is None:
weights = np.ones(data.shape)
if save_interval is None:
save_interval = niter
archive = list()
# Convert from probe to global coords
srcx, srcy, detx, dety = thv_to_zxy(theta, h)
# grid frame (gx, gy)
sx, sy = init.shape
gx = np.linspace(gmin[0], gmin[0] + gsize[0], sx + 1, endpoint=True)
gy = np.linspace(gmin[1], gmin[1] + gsize[1], sy + 1, endpoint=True)
midlengths = dict() # cache the result of get_mids_and_lengths
for n in range(niter):
if n % save_interval == 0:
archive.append(init.copy())
update = np.zeros(init.shape)
nupdate = np.zeros(init.shape, dtype=np.uint)
update_progress(n / niter)
for m in range(data.size):
# get intersection locations and lengths
if m in midlengths:
xm, ym, dist = midlengths[m]
else:
xm, ym, dist = get_mids_and_lengths(
srcx[m], srcy[m], detx[m], dety[m], gx, gy
)
midlengths[m] = (xm, ym, dist)
# convert midpoints of line segments to indices
ix = np.floor(sx * (xm - gmin[0]) / gsize[0]).astype('int')
iy = np.floor(sy * (ym - gmin[1]) / gsize[1]).astype('int')
# simulate acquistion from initial guess
dist2 = np.dot(dist, dist)
if dist2 != 0:
ind = (dist != 0) & (0 <= ix) & (ix < sx) \
& (0 <= iy) & (iy < sy)
sim = np.dot(dist[ind], init[ix[ind], iy[ind]])
upd = np.true_divide((data[m] - sim), dist2)
update[ix[ind], iy[ind]] += dist[ind] * upd
nupdate[ix[ind], iy[ind]] += 1
nupdate[nupdate == 0] = 1
init += np.true_divide(update, nupdate)
archive.append(init.copy())
update_progress(1)
if save_interval == niter:
return init
else:
return archive
def mlem(gmin, gsize, data, theta, h, init, niter=10):
"""Reconstruct data using MLEM algorithm."""
assert data.size == theta.size == h.size, "theta, h, must be" \
"the equal lengths"
data = data.ravel()
theta = theta.ravel()
h = h.ravel()
# if weights is None:
# weights = np.ones(data.shape)
# if save_interval is None:
# save_interval = niter
# archive = list()
# Convert from probe to global coords
srcx, srcy, detx, dety = thv_to_zxy(theta, h)
# grid frame (gx, gy)
sx, sy = init.shape
gx = | np.linspace(gmin[0], gmin[0] + gsize[0], sx + 1, endpoint=True) | numpy.linspace |
from datasets import register_dataset
from datasets.reid_dataset import ReidDataset
from datasets.pose_dataset import PoseDataset
from builders import transform_builder
import os
import numpy as np
from datasets.utils import HeaderItem
from datasets.lip import make_joint_info
from datasets.reid.market_seg import make_seg_info
from settings import Config
from PIL import Image
import csv
from datasets.reid_dataset import make_pid_dataset
def make_reid_annotated(csv_file, data_dir, seg_dir=None, attribute_file=None, pose_file=None, pid_limit=None):
data, header, info = make_pid_dataset(csv_file, data_dir, pid_limit)
if pose_file is not None:
joint_info = make_joint_info()
info['joint_info'] = joint_info
info['num_joints'] = joint_info.n_joints
header['coords'] = HeaderItem((joint_info.n_joints, 2), np.ndarray((16, 2), dtype=np.float32)),
with open(pose_file, 'r') as f:
reader = csv.reader(f, delimiter=',')
length = sum(1 for row in reader)
f.seek(0)
if length == len(data):
for d, row in zip(data, reader):
row = list(map(float, row))
coords = np.asarray(row).reshape(16, 2)
d['coords'] = coords
d['head_size'] = np.linalg.norm(coords[joint_info.ids.b_head] - coords[joint_info.ids.b_neck])
else:
data_iter = iter(data)
d = next(data_iter)
for idx, row in enumerate(reader):
if idx == d['row_idx']:
row = list(map(float, row))
coords = np.asarray(row).reshape(16, 2)
d['coords'] = coords
d['head_size'] = | np.linalg.norm(coords[joint_info.ids.b_head] - coords[joint_info.ids.b_neck]) | numpy.linalg.norm |
#!/usr/bin/env python
#
# Copyright (C) 2017 - Massachusetts Institute of Technology (MIT)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
Module used to simulate cloud code
is there a maximum amount to the number density of certain gas before it condense out?
"""
import os
import sys
import math
import cmath
import numpy as np
import scipy.special as special
#import matplotlib.pyplot as plt
class Cloud_Simulator():
"""
Placeholder base class for all cloud models...
"""
def __init__(self):
pass
class Simple_Gray_Cloud_Simulator(Cloud_Simulator):
"""
Well, Americans call it "Gray", English call it "Grey".
Simplistic Cloud model that assumed a cloud deck at a given pressure
It's assumed the same cloudiness (optical depth) below the cloud deck
It's also assumed that the cloud are wavelength/wavenumber independent.
"""
def __init__(self,
cloud_deck_pressure=100,
cloud_absorption_amount=0.1):
self.deck = cloud_deck_pressure
self.absorb = cloud_absorption_amount
def get_cloud_absorption(self, nu, pressure, wn=True):
if pressure >= self.deck:
return np.ones(len(nu))*self.absorb
else:
return np.zeros(len(nu))
class Complex_Gray_Cloud_Simulator(Cloud_Simulator):
"""
A place for testing some more interesting gray clouds, not very physical.
Precursor to implementing a more physical model in the future.
A more complex varient of the simple gray that could potentially have
1. varying absorption (optical depth)
2. multiple cloud decks and cloud truncate
3. wavelength/wavenumber dependent
a. single/multiple shapes? profiles?
4. scattering due to different objects in the sky?
5. asymetric cloud? this could be a bit difficult to implement
6. time varying cloud? this would need a dynamic transit simulation...
7. different output methods?
"""
def __init__(self,
cloud_deck_pressure=[100,10000],
cloud_absorption_amount=[0.1,1],
cloud_truncate_pressure = 100000):
self.deck = cloud_deck_pressure
self.absorb = cloud_absorption_amount
self.truncate = cloud_truncate_pressure
def simulate_profile(self, profile):
"""
Let's start with some gaussian profiles?
"""
pass
def get_cloud_cross_section(self):
"Placeholder"
pass
def get_cloud_absorption(self, nu, pressure, wn=True):
"""
returns cloud absorption
"""
if pressure >= self.deck:
return np.ones(len(nu))*self.absorb
else:
return np.zeros(len(nu))
class Physical_Cloud_Simulator():
def __init__(self,lambd,radius):
self.lambd = lambd
self.radius = radius
if type(self.radius) != type([]):
self.radius = [self.radius]
def mie_abcd(self,m,x):
nmax=round(2+x+(4*x**(1./3.)))
i = 1.0j
n = np.arange(1,nmax+1,1)
nu = (n+0.5)
z = np.multiply(m,x)
m2 = np.multiply(m,m)
sqx = np.sqrt(0.5*(math.pi)/x)
sqz = np.sqrt(0.5*(math.pi)/z)
bx = (np.multiply((special.jv(nu,x)),sqx))
bz = np.multiply((special.jv(nu,z)),sqz)
yx = np.multiply((special.yv(nu,x)),sqx)
hx = bx+(i*yx)
sinx = np.array((cmath.sin(x))/x)
b1x = np.append(sinx,bx[0:int(nmax-1)])
sinz = (cmath.sin(z))/z
b1z = np.append(sinz,bz[0:int(nmax-1)])
cosx = np.array((cmath.cos(x))/x)
y1x = np.append(-cosx,yx[0:int(nmax-1)])
h1x = b1x+(i*y1x)
ax = (np.multiply(x,b1x))-(np.multiply(n,bx))
az = (np.multiply(z,b1z))-(np.multiply(n,bz))
ahx = (np.multiply(x,h1x))-(np.multiply(n,hx))
m2bz = np.multiply(m2,bz)
antop = (np.multiply(m2bz,ax))-np.multiply(bx,az)
anbot = (m2*bz*ahx)-(hx*az)
an = np.true_divide(antop,anbot)
bn = (bz*ax-bx*az)/(bz*ahx-hx*az)
cn = (bx*ahx-hx*ax)/(bz*ahx-hx*az)
dn = m*(bx*ahx-hx*ax)/(m2*bz*ahx-hx*az)
return np.array([an, bn, cn, dn])
def Mie(self,m,x):
if np.any(x)==0: #To avoid a singularity at x=0
return 0,0,0,0
nmax=round(2+x+(4*x**(1./3.)))
n1=int(nmax-1);
n = np.arange(1,nmax+1,1)
cn=2*n+1
c1n=np.true_divide((np.multiply(n,(n+2))),(n+1))
c2n=np.true_divide((np.true_divide(cn,n)),(n+1))
x2=x*x
f=self.mie_abcd(m,x)
anp=(f[0,:]).real
anpp=(f[0,:]).imag
bnp=(f[1,:]).real
bnpp=(f[1,:]).imag
g1=np.empty([4,int(nmax)]) # displaced numbers used fo
g1[0,0:int(n1)]=anp[1:int(nmax)] # asymmetry parameter, p. 120
g1[1,0:int(n1)]=anpp[1:int(nmax)]
g1[2,0:n1]=bnp[1:int(nmax)]
g1[3,0:n1]=bnpp[1:int(nmax)]
dn=np.multiply(cn,(anp+bnp))
q=sum(dn);
qext=2*q/x2;
en=np.multiply(cn,(np.multiply(anp,anp)+
np.multiply(anpp,anpp)+
| np.multiply(bnp,bnp) | numpy.multiply |
# coding: utf-8
import numpy as np
# Libraries necessary for visualizing
import seaborn as sns
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import warnings
from scipy.signal import argrelmax,argrelmin
import matplotlib.font_manager as fm
import copy
from data_reader import DataReader
import os
from coordinate_transform import *
class forceAnalyzer(DataReader):
def __init__(self,relative_data_folder,filenames,plate_rotation=20):
super().__init__(relative_data_folder,filenames,skiprows=6,
column_name=['Fx','Fy','Fz','Mx','My','Mz','Syncro','ExtIn1','ExtIn2'])
self.plate_rotation = plate_rotation
self.set_analysis_target(0)
def set_analysis_target(self, analysis_id=0, scale=2.0):
self.extract_syncronized_data(analysis_id=analysis_id)
self.get_first_landing_point(analysis_id=analysis_id)
self.max_peek=[]
self.get_max_peek(analysis_id=analysis_id)
self.modify_force_plate_raw(analysis_id=analysis_id, scale=scale)
self.get_action_point(analysis_id=analysis_id, threshold=40)
def extract_syncronized_data(self,analysis_id=0):
df = self.df_list[analysis_id]
df_copy = df[df.ExtIn1 == 1].copy()
df_copy['time'] = df_copy['time'].values - df_copy['time'].values[0]
self.df_list[analysis_id] = df_copy
self.df_list[analysis_id] = self.df_list[analysis_id].drop(['Syncro','ExtIn1','ExtIn2'], axis=1)
def moving_filter(self,x,window_size,min_periods):
return pd.Series(x).rolling(window=window_size, min_periods=min_periods, center=True).mean().values
def EMA(self,x, alpha):
return pd.Series(x).ewm(alpha=alpha).mean()
def get_peek_action_point(self,analysis_id=0):
return [self.df_list[analysis_id]['action_x'].values[self.max_peek],
self.df_list[analysis_id]['action_y'].values[self.max_peek]]
def get_peek_action_point_for_converting(self):
xs,ys =self.get_peek_action_point()
points = []
for x,y in zip(xs,ys):
points.append([x,y,0])
return points
def get_peek_action_point_for_trans(self):
xs,ys =self.get_peek_action_point()
points = []
for x,y in zip(xs,ys):
points.append([x,y,0.,1.])
return points
def getNearestValue(self,array, num):
"""
概要: リストからある値に最も近い値を返却する関数
@param list: データ配列
@param num: 対象値
@return 対象値に最も近い値
"""
# リスト要素と対象値の差分を計算し最小値のインデックスを取得
idx = np.abs(array - num).argmin()
return array[idx]
def get_max_peek(self,threshold=5.,analysis_id=0):
force_plate_data=self.df_list[analysis_id]
self.max_peek = list(argrelmax(force_plate_data['Fz'].values,order=1000)[0])
tmp = copy.deepcopy(self.max_peek)
for i in tmp:
if force_plate_data['Fz'].values[i] < threshold:
self.max_peek.remove(i)
def get_peek_time(self,analysis_id=0):
return self.df_list[analysis_id]['time'].values[self.max_peek]
def get_first_landing_point(self, analysis_id=0):
force_plate_data = self.df_list[analysis_id].copy()
x_max_peek = argrelmax(force_plate_data['Fz'].values,order=50)
x_min_peek = argrelmin(force_plate_data['Fz'].values,order=100)
# print(x_min_peek,x_max_peek)
offset_peek_list= []
for value in x_max_peek[0]:
if abs(force_plate_data['Fz'].values[value] - force_plate_data['Fz'].values[self.getNearestValue(x_min_peek[0],value)]) > 100:
offset_peek_list.append(value)
# print(offset_peek_list)
self.first_landing_point = offset_peek_list[0]
print('first landing point is ',self.first_landing_point)
def export_from_first_landing_point(self, analysis_id=0):
force_plate_data = self.df_list[analysis_id].copy()
self.get_first_landing_point(analysis_id=analysis_id)
force_cutted_df = force_plate_data[self.first_landing_point:len(force_plate_data)]
# print(force_cutted_df)
# force_cutted_df.plot(y='Fz', figsize=(16,4), alpha=0.5)
force_cutted_df.to_csv('force_plate_cutted_data_a6.csv')
def get_action_point(self,analysis_id=0,scale=1., threshold=20):
Mx = self.df_list[analysis_id]['Mx'].values*scale
My = self.df_list[analysis_id]['My'].values*scale
Fz = self.df_list[analysis_id]['Fz'].values*scale
tmp_action_x = []
tmp_action_y = []
for mx,my,f in zip(Mx,My,Fz):
if abs(f) > threshold:
tmp_action_x.append(my/f)
tmp_action_y.append(mx/f)
else:
tmp_action_x.append(-1)
tmp_action_y.append(-1)
self.action_x = np.array(tmp_action_x)
self.action_y = np.array(tmp_action_y)
self.df_list[analysis_id]['action_x'] = self.action_x
self.df_list[analysis_id]['action_y'] = self.action_y
def modify_force_plate_raw(self, analysis_id=0, scale=1.0):
Fx = self.df_list[analysis_id]['Fx'].values*scale
Fy = self.df_list[analysis_id]['Fy'].values*scale
Fz = self.df_list[analysis_id]['Fz'].values*scale
Mx = self.df_list[analysis_id]['Mx'].values*scale
My = self.df_list[analysis_id]['My'].values*scale
Mz = self.df_list[analysis_id]['Mz'].values*scale
self.df_list[analysis_id]['Fx'] = Fx
self.df_list[analysis_id]['Fy'] = Fy
self.df_list[analysis_id]['Fz'] = Fz
self.df_list[analysis_id]['Mx'] = Mx
self.df_list[analysis_id]['My'] = My
self.df_list[analysis_id]['Mz'] = Mz
def add_motion_coordinate_action_point(self, simultaneous_trans_matrix,analysis_id=0):
motion_coordinate_action_point_x = []
motion_coordinate_action_point_y = []
motion_coordinate_action_point_z = []
for x, y in zip(self.action_x, self.action_y):
if x == -1 or y == -1:
motion_coordinate_action_point_x.append(0)
motion_coordinate_action_point_y.append(0)
motion_coordinate_action_point_z.append(0)
else:
arr = np.array([x, y, 0., 1.])
motion_pos = np.dot(simultaneous_trans_matrix, arr)
motion_coordinate_action_point_x.append(motion_pos[0])
motion_coordinate_action_point_y.append(motion_pos[1])
motion_coordinate_action_point_z.append(motion_pos[2])
self.df_list[analysis_id]['motion_coordinate_action_point_x'] = motion_coordinate_action_point_x
self.df_list[analysis_id]['motion_coordinate_action_point_y'] = motion_coordinate_action_point_y
self.df_list[analysis_id]['motion_coordinate_action_point_z'] = motion_coordinate_action_point_z
def add_corrected_force_data(self,analysis_id=0, scale=1.0):
corrected_Fx = []
corrected_Fy = []
corrected_Fz = []
Fx = self.df_list[analysis_id]['Fx'].values*scale
Fy = self.df_list[analysis_id]['Fy'].values*scale
Fz = self.df_list[analysis_id]['Fz'].values*scale
for fx, fy, fz in zip(Fx,Fy,Fz):
arr = np.array([fx, fy, fz])
corrected_force = np.dot(get_rotation_x(deg2rad(self.plate_rotation)),arr)
corrected_Fx.append(corrected_force[0])
corrected_Fy.append(corrected_force[1])
corrected_Fz.append(corrected_force[2])
self.df_list[analysis_id]['corrected_Fx'] = corrected_Fx
self.df_list[analysis_id]['corrected_Fy'] = corrected_Fy
self.df_list[analysis_id]['corrected_Fz'] = corrected_Fz
def save_data(self, save_dir, filename, analysis_id=0, update=False):
if not os.path.isdir(save_dir+'synchro'):
print('Creating new save folder ...')
print('Save path : ', save_dir+'synchro')
os.mkdir(save_dir+'synchro')
if not os.path.isfile(save_dir+'synchro\\'+filename) or update == True:
df_copy = self.df_list[analysis_id].copy()
df_copy = df_copy.set_index('time')
df_copy.to_csv(save_dir+'synchro\\'+filename)
def plot_peek_action_point(self):
xs,ys =self.get_peek_action_point()
f = plt.figure()
i = 0
for x,y in zip(xs,ys):
plt.plot(x, y, "o", color=cm.spectral(i/10.0))
i += 1
f.subplots_adjust(right=0.8)
plt.show()
plt.close()
def plot(self,analysis_id=0):
target_area = ['Fx','Fy','Fz','Mx','My','Mz']
force_plate_data = self.df_list[analysis_id].copy()
# print(force_plate_data)
column_name = force_plate_data.columns.values
column_name_tmp = []
column_name_tmp_array = []
for target_name in target_area:
column_name_tmp = [name for name in column_name if target_name in name]
column_name_tmp_array.extend(column_name_tmp)
column_name = column_name_tmp_array
# print(column_name)
f = plt.figure()
plt.title('Force plate csv data when liftting up object', color='black')
force_plate_data.plot(x='time',y=column_name[0:3], figsize=(16,4), alpha=0.5,ax=f.gca())
plt.plot(force_plate_data['time'].values[self.max_peek], force_plate_data['Fz'].values[self.max_peek], "ro")
if self.first_landing_point is not 0:
plt.plot(force_plate_data['time'].values[self.first_landing_point], force_plate_data['Fz'].values[self.first_landing_point], "bo")
plt.legend(loc='center left', bbox_to_anchor=(1.0, 0.5))
f.subplots_adjust(right=0.8)
plt.show()
plt.close()
class motionAnalyzer(DataReader):
def __init__(self,relative_data_folder,filename,key_label):
super().__init__(relative_data_folder,filename,data_freq=100,key_label_name=key_label)
self.simple_modify_data()
self.peek_time = 0
def simple_modify_data(self):
for df in self.df_list:
for i in range(len(df)-1):
tmp = df.iloc[i+1]
for j,x in enumerate(tmp[0:9]):
if x == 0:
df.iloc[i+1,j] = df.iloc[i,j]
def set_peek_time(self,peek_time):
self.peek_time = peek_time
self.get_nearest_time()
def getNearestValue(self,array, num):
"""
概要: リストからある値に最も近い値を返却する関数
@param list: データ配列
@param num: 対象値
@return 対象値に最も近い値
"""
# リスト要素と対象値の差分を計算し最小値のインデックスを取得
idx = np.abs(array - num).argmin()
return array[idx]
def getNearestIndex(self,array, num):
"""
概要: リストからある値に最も近い値を返却する関数
@param list: データ配列
@param num: 対象値
@return 対象値に最も近い値のインデックス
"""
# リスト要素と対象値の差分を計算し最小値のインデックスを取得
return np.abs(array - num).argmin()
def get_nearest_time(self,analysis_id=0):
tmp = copy.deepcopy(self.peek_time)
self.peek_time = []
for x in tmp:
self.peek_time.append(self.getNearestIndex(self.df_list[analysis_id]['time'].values ,x))
def get_peek_points(self, analysis_id=0):
tmp = self.df_list[analysis_id].iloc[self.peek_time].values
return tmp[:,:9]
def get_euclid_distance(self,vec):
return np.linalg.norm(vec)
def get_nearest_two_points(self):
for points in self.get_peek_points():
each_point = [[points[0:3]],[points[3:6]],[points[6:9]]]
points_num = [[0,1],[1,2],[2,0]]
distance = []
distance.append(np.array(each_point[0])-np.array(each_point[1]))
distance.append(np.array(each_point[1])-np.array(each_point[2]))
distance.append(np.array(each_point[2])-np.array(each_point[0]))
tmp = [100000,-1]
for i,dis in enumerate(distance):
tmp_dis = self.get_euclid_distance(dis)
if tmp_dis < tmp[0]:
tmp = [tmp_dis,i]
break
two_points = []
for points in self.get_peek_points():
each_point = [[points[0:3]],[points[3:6]],[points[6:9]]]
two_points.append([each_point[points_num[tmp[1]][0]],each_point[points_num[tmp[1]][1]]])
return two_points
def get_middle_point(self,two_points):
return (np.array(two_points[0])+ | np.array(two_points[1]) | numpy.array |
"""
Defines classes with represent SPAM operations, along with supporting
functionality.
"""
#***************************************************************************************************
# Copyright 2015, 2019 National Technology & Engineering Solutions of Sandia, LLC (NTESS).
# Under the terms of Contract DE-NA0003525 with NTESS, the U.S. Government retains certain rights
# in this software.
# 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 or in the LICENSE file in the root pyGSTi directory.
#***************************************************************************************************
import numpy as _np
import scipy.sparse as _sps
import collections as _collections
import numbers as _numbers
import itertools as _itertools
import functools as _functools
import copy as _copy
from .. import optimize as _opt
from ..tools import matrixtools as _mt
from ..tools import optools as _gt
from ..tools import basistools as _bt
from ..tools import listtools as _lt
from ..tools import slicetools as _slct
from ..tools import compattools as _compat
from ..tools import symplectic as _symp
from .basis import Basis as _Basis
from .protectedarray import ProtectedArray as _ProtectedArray
from . import modelmember as _modelmember
from . import term as _term
from . import stabilizer as _stabilizer
from .polynomial import Polynomial as _Polynomial
from . import replib
from .opcalc import bulk_eval_compact_polys_complex as _bulk_eval_compact_polys_complex
IMAG_TOL = 1e-8 # tolerance for imaginary part being considered zero
def optimize_spamvec(vecToOptimize, targetVec):
"""
Optimize the parameters of vecToOptimize so that the
the resulting SPAM vector is as close as possible to
targetVec.
This is trivial for the case of FullSPAMVec
instances, but for other types of parameterization
this involves an iterative optimization over all the
parameters of vecToOptimize.
Parameters
----------
vecToOptimize : SPAMVec
The vector to optimize. This object gets altered.
targetVec : SPAMVec
The SPAM vector used as the target.
Returns
-------
None
"""
#TODO: cleanup this code:
if isinstance(vecToOptimize, StaticSPAMVec):
return # nothing to optimize
if isinstance(vecToOptimize, FullSPAMVec):
if(targetVec.dim != vecToOptimize.dim): # special case: gates can have different overall dimension
vecToOptimize.dim = targetVec.dim # this is a HACK to allow model selection code to work correctly
vecToOptimize.set_value(targetVec) # just copy entire overall matrix since fully parameterized
return
assert(targetVec.dim == vecToOptimize.dim) # vectors must have the same overall dimension
targetVector = _np.asarray(targetVec)
def _objective_func(param_vec):
vecToOptimize.from_vector(param_vec)
return _mt.frobeniusnorm(vecToOptimize - targetVector)
x0 = vecToOptimize.to_vector()
minSol = _opt.minimize(_objective_func, x0, method='BFGS', maxiter=10000, maxfev=10000,
tol=1e-6, callback=None)
vecToOptimize.from_vector(minSol.x)
#print("DEBUG: optimized vector to min frobenius distance %g" % _mt.frobeniusnorm(vecToOptimize-targetVector))
def convert(spamvec, toType, basis, extra=None):
"""
Convert SPAM vector to a new type of parameterization, potentially
creating a new SPAMVec object. Raises ValueError for invalid conversions.
Parameters
----------
spamvec : SPAMVec
SPAM vector to convert
toType : {"full","TP","static","static unitary","clifford",LINDBLAD}
The type of parameterizaton to convert to. "LINDBLAD" is a placeholder
for the various Lindblad parameterization types. See
:method:`Model.set_all_parameterizations` for more details.
basis : {'std', 'gm', 'pp', 'qt'} or Basis object
The basis for `spamvec`. Allowed values are Matrix-unit (std),
Gell-Mann (gm), Pauli-product (pp), and Qutrit (qt)
(or a custom basis object).
extra : object, optional
Additional information for conversion.
Returns
-------
SPAMVec
The converted SPAM vector, usually a distinct
object from the object passed as input.
"""
if toType == "full":
if isinstance(spamvec, FullSPAMVec):
return spamvec # no conversion necessary
else:
typ = spamvec._prep_or_effect if isinstance(spamvec, SPAMVec) else "prep"
return FullSPAMVec(spamvec.todense(), typ=typ)
elif toType == "TP":
if isinstance(spamvec, TPSPAMVec):
return spamvec # no conversion necessary
else:
return TPSPAMVec(spamvec.todense())
# above will raise ValueError if conversion cannot be done
elif toType == "TrueCPTP": # a non-lindbladian CPTP spamvec that hasn't worked well...
if isinstance(spamvec, CPTPSPAMVec):
return spamvec # no conversion necessary
else:
return CPTPSPAMVec(spamvec, basis)
# above will raise ValueError if conversion cannot be done
elif toType == "static":
if isinstance(spamvec, StaticSPAMVec):
return spamvec # no conversion necessary
else:
typ = spamvec._prep_or_effect if isinstance(spamvec, SPAMVec) else "prep"
return StaticSPAMVec(spamvec, typ=typ)
elif toType == "static unitary":
dmvec = _bt.change_basis(spamvec.todense(), basis, 'std')
purevec = _gt.dmvec_to_state(dmvec)
return StaticSPAMVec(purevec, "statevec", spamvec._prep_or_effect)
elif _gt.is_valid_lindblad_paramtype(toType):
if extra is None:
purevec = spamvec # right now, we don't try to extract a "closest pure vec"
# to spamvec - below will fail if spamvec isn't pure.
else:
purevec = extra # assume extra info is a pure vector
nQubits = _np.log2(spamvec.dim) / 2.0
bQubits = bool(abs(nQubits - round(nQubits)) < 1e-10) # integer # of qubits?
proj_basis = "pp" if (basis == "pp" or bQubits) else basis
typ = spamvec._prep_or_effect if isinstance(spamvec, SPAMVec) else "prep"
return LindbladSPAMVec.from_spamvec_obj(
spamvec, typ, toType, None, proj_basis, basis,
truncate=True, lazy=True)
elif toType == "clifford":
if isinstance(spamvec, StabilizerSPAMVec):
return spamvec # no conversion necessary
purevec = spamvec.flatten() # assume a pure state (otherwise would
# need to change Model dim)
return StabilizerSPAMVec.from_dense_purevec(purevec)
else:
raise ValueError("Invalid toType argument: %s" % toType)
def _convert_to_lindblad_base(vec, typ, new_evotype, mxBasis="pp"):
"""
Attempts to convert `vec` to a static (0 params) SPAMVec with
evoution type `new_evotype`. Used to convert spam vecs to
being LindbladSPAMVec objects.
"""
if vec._evotype == new_evotype and vec.num_params() == 0:
return vec # no conversion necessary
if new_evotype == "densitymx":
return StaticSPAMVec(vec.todense(), "densitymx", typ)
if new_evotype in ("svterm", "cterm"):
if isinstance(vec, ComputationalSPAMVec): # special case when conversion is easy
return ComputationalSPAMVec(vec._zvals, new_evotype, typ)
elif vec._evotype == "densitymx":
# then try to extract a (static) pure state from vec wth
# evotype 'statevec' or 'stabilizer' <=> 'svterm', 'cterm'
if isinstance(vec, DenseSPAMVec):
dmvec = _bt.change_basis(vec, mxBasis, 'std')
purestate = StaticSPAMVec(_gt.dmvec_to_state(dmvec), 'statevec', typ)
elif isinstance(vec, PureStateSPAMVec):
purestate = vec.pure_state_vec # evotype 'statevec'
else:
raise ValueError("Unable to obtain pure state from density matrix type %s!" % type(vec))
if new_evotype == "cterm": # then purestate 'statevec' => 'stabilizer' (if possible)
if typ == "prep":
purestate = StabilizerSPAMVec.from_dense_purevec(purestate.todense())
else: # type == "effect"
purestate = StabilizerEffectVec.from_dense_purevec(purestate.todense())
return PureStateSPAMVec(purestate, new_evotype, mxBasis, typ)
raise ValueError("Could not convert %s (evotype %s) to %s w/0 params!" %
(str(type(vec)), vec._evotype, new_evotype))
def finite_difference_deriv_wrt_params(spamvec, wrtFilter=None, eps=1e-7):
"""
Computes a finite-difference Jacobian for a SPAMVec object.
The returned value is a matrix whose columns are the vectorized
derivatives of the spam vector with respect to a single
parameter, matching the format expected from the spam vectors's
`deriv_wrt_params` method.
Parameters
----------
spamvec : SPAMVec
The spam vector object to compute a Jacobian for.
eps : float, optional
The finite difference step to use.
Returns
-------
numpy.ndarray
An M by N matrix where M is the number of gate elements and
N is the number of gate parameters.
"""
dim = spamvec.get_dimension()
spamvec2 = spamvec.copy()
p = spamvec.to_vector()
fd_deriv = _np.empty((dim, spamvec.num_params()), 'd') # assume real (?)
for i in range(spamvec.num_params()):
p_plus_dp = p.copy()
p_plus_dp[i] += eps
spamvec2.from_vector(p_plus_dp, close=True)
fd_deriv[:, i:i + 1] = (spamvec2 - spamvec) / eps
fd_deriv.shape = [dim, spamvec.num_params()]
if wrtFilter is None:
return fd_deriv
else:
return _np.take(fd_deriv, wrtFilter, axis=1)
def check_deriv_wrt_params(spamvec, deriv_to_check=None, wrtFilter=None, eps=1e-7):
"""
Checks the `deriv_wrt_params` method of a SPAMVec object.
This routine is meant to be used as an aid in testing and debugging
SPAMVec classes by comparing the finite-difference Jacobian that
*should* be returned by `spamvec.deriv_wrt_params` with the one that
actually is. A ValueError is raised if the two do not match.
Parameters
----------
spamvec : SPAMVec
The gate object to test.
deriv_to_check : numpy.ndarray or None, optional
If not None, the Jacobian to compare against the finite difference
result. If None, `spamvec.deriv_wrt_parms()` is used. Setting this
argument can be useful when the function is called *within* a LinearOperator
class's `deriv_wrt_params()` method itself as a part of testing.
eps : float, optional
The finite difference step to use.
Returns
-------
None
"""
fd_deriv = finite_difference_deriv_wrt_params(spamvec, wrtFilter, eps)
if deriv_to_check is None:
deriv_to_check = spamvec.deriv_wrt_params()
#print("Deriv shapes = %s and %s" % (str(fd_deriv.shape),
# str(deriv_to_check.shape)))
#print("finite difference deriv = \n",fd_deriv)
#print("deriv_wrt_params deriv = \n",deriv_to_check)
#print("deriv_wrt_params - finite diff deriv = \n",
# deriv_to_check - fd_deriv)
for i in range(deriv_to_check.shape[0]):
for j in range(deriv_to_check.shape[1]):
diff = abs(deriv_to_check[i, j] - fd_deriv[i, j])
if diff > 5 * eps:
print("deriv_chk_mismatch: (%d,%d): %g (comp) - %g (fd) = %g" %
(i, j, deriv_to_check[i, j], fd_deriv[i, j], diff))
if _np.linalg.norm(fd_deriv - deriv_to_check) > 100 * eps:
raise ValueError("Failed check of deriv_wrt_params:\n"
" norm diff = %g" %
_np.linalg.norm(fd_deriv - deriv_to_check))
class SPAMVec(_modelmember.ModelMember):
"""
Excapulates a parameterization of a state preparation OR POVM effect
vector. This class is the common base class for all specific
parameterizations of a SPAM vector.
"""
def __init__(self, rep, evotype, typ):
""" Initialize a new SPAM Vector """
if isinstance(rep, int): # For operators that have no representation themselves (term ops)
dim = rep # allow passing an integer as `rep`.
rep = None
else:
dim = rep.dim
super(SPAMVec, self).__init__(dim, evotype)
self._rep = rep
self._prep_or_effect = typ
@property
def size(self):
"""
Return the number of independent elements in this gate (when viewed as a dense array)
"""
return self.dim
@property
def outcomes(self):
"""
Return the z-value outcomes corresponding to this effect SPAM vector
in the context of a stabilizer-state simulation.
"""
raise NotImplementedError("'outcomes' property is not implemented for %s objects" % self.__class__.__name__)
def set_value(self, vec):
"""
Attempts to modify SPAMVec parameters so that the specified raw
SPAM vector becomes vec. Will raise ValueError if this operation
is not possible.
Parameters
----------
vec : array_like or SPAMVec
A numpy array representing a SPAM vector, or a SPAMVec object.
Returns
-------
None
"""
raise ValueError("Cannot set the value of a %s directly!" % self.__class__.__name__)
def set_time(self, t):
"""
Sets the current time for a time-dependent operator. For time-independent
operators (the default), this function does absolutely nothing.
Parameters
----------
t : float
The current time.
Returns
-------
None
"""
pass
def todense(self, scratch=None):
"""
Return this SPAM vector as a (dense) numpy array. The memory
in `scratch` maybe used when it is not-None.
"""
raise NotImplementedError("todense(...) not implemented for %s objects!" % self.__class__.__name__)
# def torep(self, typ, outrep=None):
# """
# Return a "representation" object for this SPAM vector.
# Such objects are primarily used internally by pyGSTi to compute
# things like probabilities more efficiently.
#
# Parameters
# ----------
# typ : {'prep','effect'}
# The type of representation (for cases when the vector type is
# not already defined).
#
# outrep : StateRep
# If not None, an existing state representation appropriate to this
# SPAM vector that may be used instead of allocating a new one.
#
# Returns
# -------
# StateRep
# """
# if typ == "prep":
# if self._evotype == "statevec":
# return replib.SVStateRep(self.todense())
# elif self._evotype == "densitymx":
# return replib.DMStateRep(self.todense())
# raise NotImplementedError("torep(%s) not implemented for %s objects!" %
# (self._evotype, self.__class__.__name__))
# elif typ == "effect":
# if self._evotype == "statevec":
# return replib.SVEffectRep_Dense(self.todense())
# elif self._evotype == "densitymx":
# return replib.DMEffectRep_Dense(self.todense())
# raise NotImplementedError("torep(%s) not implemented for %s objects!" %
# (self._evotype, self.__class__.__name__))
# else:
# raise ValueError("Invalid `typ` argument for torep(): %s" % typ)
def get_taylor_order_terms(self, order, max_poly_vars=100, return_poly_coeffs=False):
"""
Get the `order`-th order Taylor-expansion terms of this SPAM vector.
This function either constructs or returns a cached list of the terms at
the given order. Each term is "rank-1", meaning that it is a state
preparation followed by or POVM effect preceded by actions on a
density matrix `rho` of the form:
`rho -> A rho B`
The coefficients of these terms are typically polynomials of the
SPAMVec's parameters, where the polynomial's variable indices index the
*global* parameters of the SPAMVec's parent (usually a :class:`Model`)
, not the SPAMVec's local parameter array (i.e. that returned from
`to_vector`).
Parameters
----------
order : int
The order of terms to get.
return_coeff_polys : bool
Whether a parallel list of locally-indexed (using variable indices
corresponding to *this* object's parameters rather than its parent's)
polynomial coefficients should be returned as well.
Returns
-------
terms : list
A list of :class:`RankOneTerm` objects.
coefficients : list
Only present when `return_coeff_polys == True`.
A list of *compact* polynomial objects, meaning that each element
is a `(vtape,ctape)` 2-tuple formed by concatenating together the
output of :method:`Polynomial.compact`.
"""
raise NotImplementedError("get_taylor_order_terms(...) not implemented for %s objects!" %
self.__class__.__name__)
def get_highmagnitude_terms(self, min_term_mag, force_firstorder=True, max_taylor_order=3, max_poly_vars=100):
"""
Get the terms (from a Taylor expansion of this SPAM vector) that have
magnitude above `min_term_mag` (the magnitude of a term is taken to
be the absolute value of its coefficient), considering only those
terms up to some maximum Taylor expansion order, `max_taylor_order`.
Note that this function also *sets* the magnitudes of the returned
terms (by calling `term.set_magnitude(...)`) based on the current
values of this SPAM vector's parameters. This is an essential step
to using these terms in pruned-path-integral calculations later on.
Parameters
----------
min_term_mag : float
the threshold for term magnitudes: only terms with magnitudes above
this value are returned.
force_firstorder : bool, optional
if True, then always return all the first-order Taylor-series terms,
even if they have magnitudes smaller than `min_term_mag`. This
behavior is needed for using GST with pruned-term calculations, as
we may begin with a guess model that has no error (all terms have
zero magnitude!) and still need to compute a meaningful jacobian at
this point.
max_taylor_order : int, optional
the maximum Taylor-order to consider when checking whether term-
magnitudes exceed `min_term_mag`.
Returns
-------
highmag_terms : list
A list of the high-magnitude terms that were found. These
terms are *sorted* in descending order by term-magnitude.
first_order_indices : list
A list of the indices into `highmag_terms` that mark which
of these terms are first-order Taylor terms (useful when
we're forcing these terms to always be present).
"""
#NOTE: SAME as for LinearOperator class -- TODO consolidate in FUTURE
#print("DB: SPAM get_high_magnitude_terms")
v = self.to_vector()
taylor_order = 0
terms = []; last_len = -1; first_order_magmax = 1.0
while len(terms) > last_len: # while we keep adding something
if taylor_order > 1 and first_order_magmax**taylor_order < min_term_mag:
break # there's no way any terms at this order reach min_term_mag - exit now!
MAX_CACHED_TERM_ORDER = 1
if taylor_order <= MAX_CACHED_TERM_ORDER:
#print("order ",taylor_order," : ",len(terms), "terms")
terms_at_order, cpolys = self.get_taylor_order_terms(taylor_order, max_poly_vars, True)
coeffs = _bulk_eval_compact_polys_complex(
cpolys[0], cpolys[1], v, (len(terms_at_order),)) # an array of coeffs
mags = _np.abs(coeffs)
last_len = len(terms)
#OLD: terms_at_order = [ t.copy_with_magnitude(abs(coeff)) for coeff, t in zip(coeffs, terms_at_order) ]
if taylor_order == 1:
#OLD: first_order_magmax = max([t.magnitude for t in terms_at_order])
first_order_magmax = max(mags)
if force_firstorder:
terms.extend([(taylor_order, t.copy_with_magnitude(mag))
for coeff, mag, t in zip(coeffs, mags, terms_at_order)])
else:
for mag, t in zip(mags, terms_at_order):
if mag >= min_term_mag:
terms.append((taylor_order, t.copy_with_magnitude(mag)))
else:
for mag, t in zip(mags, terms_at_order):
if mag >= min_term_mag:
terms.append((taylor_order, t.copy_with_magnitude(mag)))
else:
terms.extend([(taylor_order, t) for t in
self.get_taylor_order_terms_above_mag(taylor_order,
max_poly_vars, min_term_mag)])
taylor_order += 1
if taylor_order > max_taylor_order: break
#Sort terms based on magnitude
sorted_terms = sorted(terms, key=lambda t: t[1].magnitude, reverse=True)
first_order_indices = [i for i, t in enumerate(sorted_terms) if t[0] == 1]
return [t[1] for t in sorted_terms], first_order_indices
def get_taylor_order_terms_above_mag(self, order, max_poly_vars, min_term_mag):
""" TODO: docstring """
v = self.to_vector()
terms_at_order, cpolys = self.get_taylor_order_terms(order, max_poly_vars, True)
coeffs = _bulk_eval_compact_polys_complex(
cpolys[0], cpolys[1], v, (len(terms_at_order),)) # an array of coeffs
terms_at_order = [t.copy_with_magnitude(abs(coeff)) for coeff, t in zip(coeffs, terms_at_order)]
return [t for t in terms_at_order if t.magnitude >= min_term_mag]
def frobeniusdist2(self, otherSpamVec, typ, transform=None,
inv_transform=None):
"""
Return the squared frobenius difference between this spam vector and
`otherSpamVec`, optionally transforming this vector first using
`transform` and `inv_transform` (depending on the value of `typ`).
Parameters
----------
otherSpamVec : SPAMVec
The other spam vector
typ : { 'prep', 'effect' }
Which type of SPAM vector is being transformed.
transform, inv_transform : numpy.ndarray
The transformation (if not None) to be performed.
Returns
-------
float
"""
vec = self.todense()
if typ == 'prep':
if inv_transform is None:
return _gt.frobeniusdist2(vec, otherSpamVec.todense())
else:
return _gt.frobeniusdist2(_np.dot(inv_transform, vec),
otherSpamVec.todense())
elif typ == "effect":
if transform is None:
return _gt.frobeniusdist2(vec, otherSpamVec.todense())
else:
return _gt.frobeniusdist2(_np.dot(_np.transpose(transform),
vec), otherSpamVec.todense())
else: raise ValueError("Invalid 'typ' argument: %s" % typ)
def residuals(self, otherSpamVec, typ, transform=None, inv_transform=None):
"""
Return a vector of residuals between this spam vector and
`otherSpamVec`, optionally transforming this vector first using
`transform` and `inv_transform` (depending on the value of `typ`).
Parameters
----------
otherSpamVec : SPAMVec
The other spam vector
typ : { 'prep', 'effect' }
Which type of SPAM vector is being transformed.
transform, inv_transform : numpy.ndarray
The transformation (if not None) to be performed.
Returns
-------
float
"""
vec = self.todense()
if typ == 'prep':
if inv_transform is None:
return _gt.residuals(vec, otherSpamVec.todense())
else:
return _gt.residuals(_np.dot(inv_transform, vec),
otherSpamVec.todense())
elif typ == "effect":
if transform is None:
return _gt.residuals(vec, otherSpamVec.todense())
else:
return _gt.residuals(_np.dot(_np.transpose(transform),
vec), otherSpamVec.todense())
def transform(self, S, typ):
"""
Update SPAM (column) vector V as inv(S) * V or S^T * V for preparation
or effect SPAM vectors, respectively.
Note that this is equivalent to state preparation vectors getting
mapped: `rho -> inv(S) * rho` and the *transpose* of effect vectors
being mapped as `E^T -> E^T * S`.
Generally, the transform function updates the *parameters* of
the SPAM vector such that the resulting vector is altered as
described above. If such an update cannot be done (because
the gate parameters do not allow for it), ValueError is raised.
Parameters
----------
S : GaugeGroupElement
A gauge group element which specifies the "S" matrix
(and it's inverse) used in the above similarity transform.
typ : { 'prep', 'effect' }
Which type of SPAM vector is being transformed (see above).
"""
if typ == 'prep':
Si = S.get_transform_matrix_inverse()
self.set_value(_np.dot(Si, self.todense()))
elif typ == 'effect':
Smx = S.get_transform_matrix()
self.set_value(_np.dot(_np.transpose(Smx), self.todense()))
#Evec^T --> ( Evec^T * S )^T
else:
raise ValueError("Invalid typ argument: %s" % typ)
def depolarize(self, amount):
"""
Depolarize this SPAM vector by the given `amount`.
Generally, the depolarize function updates the *parameters* of
the SPAMVec such that the resulting vector is depolarized. If
such an update cannot be done (because the gate parameters do not
allow for it), ValueError is raised.
Parameters
----------
amount : float or tuple
The amount to depolarize by. If a tuple, it must have length
equal to one less than the dimension of the gate. All but the
first element of the spam vector (often corresponding to the
identity element) are multiplied by `amount` (if a float) or
the corresponding `amount[i]` (if a tuple).
Returns
-------
None
"""
if isinstance(amount, float) or _compat.isint(amount):
D = _np.diag([1] + [1 - amount] * (self.dim - 1))
else:
assert(len(amount) == self.dim - 1)
D = _np.diag([1] + list(1.0 - _np.array(amount, 'd')))
self.set_value(_np.dot(D, self.todense()))
def num_params(self):
"""
Get the number of independent parameters which specify this SPAM vector.
Returns
-------
int
the number of independent parameters.
"""
return 0 # no parameters
def to_vector(self):
"""
Get the SPAM vector parameters as an array of values.
Returns
-------
numpy array
The parameters as a 1D array with length num_params().
"""
return _np.array([], 'd') # no parameters
def from_vector(self, v, close=False, nodirty=False):
"""
Initialize the SPAM vector using a 1D array of parameters.
Parameters
----------
v : numpy array
The 1D vector of gate parameters. Length
must == num_params()
Returns
-------
None
"""
assert(len(v) == 0) # should be no parameters, and nothing to do
def deriv_wrt_params(self, wrtFilter=None):
"""
Construct a matrix whose columns are the derivatives of the SPAM vector
with respect to a single param. Thus, each column is of length
get_dimension and there is one column per SPAM vector parameter.
An empty 2D array in the StaticSPAMVec case (num_params == 0).
Returns
-------
numpy array
Array of derivatives, shape == (dimension, num_params)
"""
dtype = complex if self._evotype == 'statevec' else 'd'
derivMx = _np.zeros((self.dim, 0), dtype)
if wrtFilter is None:
return derivMx
else:
return _np.take(derivMx, wrtFilter, axis=1)
def has_nonzero_hessian(self):
"""
Returns whether this SPAM vector has a non-zero Hessian with
respect to its parameters, i.e. whether it only depends
linearly on its parameters or not.
Returns
-------
bool
"""
#Default: assume Hessian can be nonzero if there are any parameters
return self.num_params() > 0
def hessian_wrt_params(self, wrtFilter1=None, wrtFilter2=None):
"""
Construct the Hessian of this SPAM vector with respect to its parameters.
This function returns a tensor whose first axis corresponds to the
flattened operation matrix and whose 2nd and 3rd axes correspond to the
parameters that are differentiated with respect to.
Parameters
----------
wrtFilter1, wrtFilter2 : list
Lists of indices of the paramters to take first and second
derivatives with respect to. If None, then derivatives are
taken with respect to all of the vectors's parameters.
Returns
-------
numpy array
Hessian with shape (dimension, num_params1, num_params2)
"""
if not self.has_nonzero_hessian():
return _np.zeros(self.size, self.num_params(), self.num_params())
# FUTURE: create a finite differencing hessian method?
raise NotImplementedError("hessian_wrt_params(...) is not implemented for %s objects" % self.__class__.__name__)
#Note: no __str__ fn
@staticmethod
def convert_to_vector(V):
"""
Static method that converts a vector-like object to a 2D numpy
dim x 1 column array.
Parameters
----------
V : array_like
Returns
-------
numpy array
"""
if isinstance(V, SPAMVec):
vector = V.todense().copy()
vector.shape = (vector.size, 1)
elif isinstance(V, _np.ndarray):
vector = V.copy()
if len(vector.shape) == 1: # convert (N,) shape vecs to (N,1)
vector.shape = (vector.size, 1)
else:
try:
len(V)
# XXX this is an abuse of exception handling
except:
raise ValueError("%s doesn't look like an array/list" % V)
try:
d2s = [len(row) for row in V]
except TypeError: # thrown if len(row) fails because no 2nd dim
d2s = None
if d2s is not None:
if any([len(row) != 1 for row in V]):
raise ValueError("%s is 2-dimensional but 2nd dim != 1" % V)
typ = 'd' if _np.all( | _np.isreal(V) | numpy.isreal |
# -*- coding: utf-8 -*-
from utils import *
import numpy as np
import cv2
import matplotlib.pyplot as plt
im = cv2.imread('images/cup1.jpg')
imgray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
[m, n, _] = np.shape(im)
white = np.zeros((m, n, 3))
white[:, :, 0] = 255
white[:, :, 1] = 255
white[:, :, 2] = 255
black = np.zeros((m, n, 3))
black[:, :, 0] = 0
black[:, :, 1] = 0
black[:, :, 2] = 0
d1 = im - white
f1 = np.sqrt(d1[:, :, 0] ** 2 + d1[:, :, 1] ** 2 + d1[:, :, 2] ** 2)
d2 = im - black
f2 = np.sqrt(d2[:, :, 0] ** 2 + d2[:, :, 1] ** 2 + d2[:, :, 2] ** 2)
f = f1 - f2
tau = 0.1
sigma = 0.05
mu = 1000
u = primal_dual(imgray, sigma, tau, mu, f, iters=12)
u[u>0.5] = 1
u[u<=0.5] = 0
u = | np.array(u, dtype=np.int32) | numpy.array |
import numpy as np
from static_frame.core.util import immutable_filter
class ArrayGO:
'''
A grow only, one-dimensional, object type array, specifically for usage in IndexHierarchy IndexLevel objects.
'''
__slots__ = (
'_dtype',
'_array',
'_array_mutable',
'_recache',
)
# NOTE: this can be implemented with one array, where we overallocate for growth, then grow as needed, or with an array and list. Since most instaces will not need to grow (only edge nodes), overall efficiency might be greater with a list
def __init__(self,
iterable,
*,
dtype=object,
own_iterable=False):
'''
Args:
own_iterable: flag iterable as ownable by this instance.
'''
self._dtype = dtype
if isinstance(iterable, np.ndarray):
if own_iterable:
self._array = iterable
self._array.flags.writeable = False
else:
self._array = immutable_filter(iterable)
assert self._array.dtype == self._dtype
self._recache = False
self._array_mutable = None
else:
self._array = None
self._recache = True
# always call list to get new object, or realize a generator
if own_iterable:
self._array_mutable = iterable
else:
self._array_mutable = list(iterable)
def _update_array_cache(self):
if self._array_mutable is not None:
if self._array is not None:
len_base = len(self._array)
array = np.empty(
len_base + len(self._array_mutable),
self._dtype)
array[:len_base] = self._array
array[len_base:] = self._array_mutable
array.flags.writeable = False
self._array = array
self._array_mutable = None
else:
self._array = | np.array(self._array_mutable, self._dtype) | numpy.array |
import numpy as np
import matplotlib.pyplot as plt
f = np.load('../mnist.npz')
image, label = f['x_train'][7], f['y_train'][7]
def show_conv():
filter = np.array([
[1, 1, 1],
[0, 0, 0],
[-1, -1, -1]])
plt.figure(0, figsize=(9, 5))
ax1 = plt.subplot(121)
ax1.imshow(image, cmap='gray')
plt.xticks(())
plt.yticks(())
ax2 = plt.subplot(122)
plt.ion()
texts = []
feature_map = np.zeros((26, 26))
flip_filter = np.flipud(np.fliplr(filter)) # flip both sides of the filter
for i in range(26):
for j in range(26):
if texts:
fm.remove()
for n in range(3):
for m in range(3):
if len(texts) != 9:
texts.append(ax1.text(j+m, i+n, filter[n, m], color='w', size=8, ha='center', va='center',))
else:
texts[n*3+m].set_position((j+m, i+n))
feature_map[i, j] = np.sum(flip_filter * image[i:i+3, j:j+3])
fm = ax2.imshow(feature_map, cmap='gray', vmax=255*3, vmin=-255*3)
plt.xticks(())
plt.yticks(())
plt.pause(0.001)
plt.ioff()
plt.show()
def show_result():
filters = [
np.array([
[1, 1, 1],
[0, 0, 0],
[-1, -1, -1]]),
np.array([
[-1, -1, -1],
[0, 0, 0],
[1, 1, 1]]),
np.array([
[1, 0, -1],
[1, 0, -1],
[1, 0, -1]]),
np.array([
[-1, 0, 1],
[-1, 0, 1],
[-1, 0, 1]])
]
plt.figure(0)
plt.title('Original image')
plt.imshow(image, cmap='gray')
plt.xticks(())
plt.yticks(())
plt.figure(1)
for n in range(4):
feature_map = np.zeros((26, 26))
flip_filter = np.flipud(np.fliplr(filters[n]))
for i in range(26):
for j in range(26):
feature_map[i, j] = | np.sum(image[i:i + 3, j:j + 3] * flip_filter) | numpy.sum |
import numpy as np
from copy import deepcopy
class sepCEM:
"""
Cross-entropy methods.
"""
def __init__(self, num_params,
batch_size,
mu_init=None,
sigma_init=1e-3,
sigma_init_aa=1e-3,
pop_size=256,
damp=1e-3,
damp_limit=1e-5,
damp_aa=0.2,
damp_limit_aa=0.1,
parents=None,
elitism=False,
antithetic=False):
# misc
self.num_params = num_params
self.batch_size = batch_size
# distribution parameters
if mu_init is None:
self.mu = np.zeros((self.batch_size, self.num_params))
else:
self.mu = np.array(mu_init)
self.sigma = sigma_init
self.sigma_aa = sigma_init_aa
self.damp = damp
self.damp_limit = damp_limit
self.damp_aa = damp_aa
self.damp_limit_aa = damp_limit_aa
self.tau = 0.95
self.cov = np.ones((self.batch_size, self.num_params))
self.cov[:, :3] *= self.sigma
self.cov[:, 3:] *= self.sigma_aa
# elite stuff
self.elitism = elitism
self.elite = np.random.rand(self.batch_size, self.num_params)
self.elite[:, :3] = np.sqrt(self.sigma)
self.elite[:, 3:] = | np.sqrt(self.sigma_aa) | numpy.sqrt |
import chainer
import chainer.links as L
import chainer.functions as F
import argparse
import cv2
import numpy as np
from glob import glob
import matplotlib.pyplot as plt
num_classes = 2
img_height, img_width = 64, 64
out_height, out_width = 64, 64
channel = 3
GPU = -1
class Mynet(chainer.Chain):
def __init__(self, train=False):
self.train = train
super(Mynet, self).__init__()
with self.init_scope():
self.dec1 = L.Convolution2D(None, 32, ksize=3, pad=1, stride=1)
self.dec2 = L.Convolution2D(None, 16, ksize=3, pad=1, stride=1)
self.enc2 = L.Deconvolution2D(None, 32, ksize=2, stride=2)
self.enc1 = L.Deconvolution2D(None, channel, ksize=2, stride=2)
def forward(self, x):
x = self.dec1(x)
x = F.max_pooling_2d(x, ksize=2, stride=2)
x = self.dec2(x)
x = F.max_pooling_2d(x, ksize=2, stride=2)
x = self.enc2(x)
x = self.enc1(x)
return x
CLS = {'akahara': [0,0,128],
'madara': [0,128,0]}
# get train data
def data_load(path, hf=False, vf=False, rot=False):
xs = []
paths = []
for dir_path in glob(path + '/*'):
for path in glob(dir_path + '/*'):
x = cv2.imread(path)
if channel == 1:
x = cv2.cvtColor(x, cv2.COLOR_BGR2GRAY)
x = cv2.resize(x, (img_width, img_height)).astype(np.float32)
x = x / 127.5 - 1.
if channel == 3:
x = x[..., ::-1]
xs.append(x)
paths.append(path)
if hf:
xs.append(x[:, ::-1])
paths.append(path)
if vf:
xs.append(x[::-1])
paths.append(path)
if hf and vf:
xs.append(x[::-1, ::-1])
paths.append(path)
if rot != False:
angle = 0
scale = 1
while angle < 360:
angle += rot
if channel == 1:
_h, _w = x.shape
max_side = max(_h, _w)
tmp = np.zeros([max_side, max_side])
else:
_h, _w, _c = x.shape
max_side = max(_h, _w)
tmp = np.zeros([max_side, max_side, _c])
tx = int((max_side - _w) / 2)
ty = int((max_side - _h) / 2)
tmp[ty: ty+_h, tx: tx+_w] = x.copy()
M = cv2.getRotationMatrix2D((max_side/2, max_side/2), angle, scale)
_x = cv2.warpAffine(tmp, M, (max_side, max_side))
_x = _x[tx:tx+_w, ty:ty+_h]
xs.append(_x)
paths.append(path)
xs = np.array(xs)
if channel == 1:
xs = np.expand_dims(xs, axis=-1)
xs = xs.transpose(0,3,1,2)
return xs, paths
# train
def train():
# model
model = Mynet(train=True)
if GPU >= 0:
chainer.cuda.get_device(GPU).use()
model.to_gpu()
opt = chainer.optimizers.Adam(0.001)
opt.setup(model)
#opt.add_hook(chainer.optimizer.WeightDecay(0.0005))
xs, paths = data_load('../Dataset/train/images/', hf=True, vf=True, rot=1)
# training
mb = 64
mbi = 0
train_ind = np.arange(len(xs))
np.random.seed(0)
| np.random.shuffle(train_ind) | numpy.random.shuffle |
##########################################################################
##########################################################################
##
## What are you doing looking at this file?
##
##########################################################################
##########################################################################
#
# Just kidding. There is some useful stuff in here that will help you complete
# some of the labs and your project. Feel free to adapt it.
#
# (Sorry about the awful commenting though. Do as I say, not as I do, etc...)
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import cm
from ipywidgets import interact, fixed, interactive_output, HBox, Button, VBox, Output, IntSlider, Checkbox, FloatSlider, FloatLogSlider, Dropdown
TEXTSIZE = 16
from IPython.display import clear_output
import time
from scipy.optimize import curve_fit
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm as colmap
from copy import copy
from scipy.stats import multivariate_normal
# commenting in here is pretty shocking tbh
# wairakei model
def wairakei_data():
# load some data
tq, q = np.genfromtxt('wk_production_history.csv', delimiter=',', unpack=True)
tp, p = np.genfromtxt('wk_pressure_history.csv', delimiter=',', unpack=True)
# plot some data
f,ax1 = plt.subplots(1,1,figsize=(12,6))
ax1.plot(tq,q,'b-',label='production')
ax1.plot([],[],'ro',label='pressure')
ax1.set_xlabel('time [yr]',size=TEXTSIZE)
ax1.set_ylabel('production rate [kg/s]',size=TEXTSIZE)
ax2 = ax1.twinx()
ax2.plot(tp,p,'ro')
v = 2.
for tpi,pi in zip(tp,p):
ax2.plot([tpi,tpi],[pi-v,pi+v], 'r-', lw=0.5)
ax2.set_ylabel('pressure [bar]',size=TEXTSIZE);
for ax in [ax1,ax2]:
ax.tick_params(axis='both',labelsize=TEXTSIZE)
ax.set_xlim([None,1980])
ax1.legend(prop={'size':TEXTSIZE})
plt.show()
def lpm_plot(i=1):
f,ax = plt.subplots(1,1, figsize=(12,6))
ax.axis('off')
ax.set_xlim([0,1])
ax.set_ylim([0,1])
r = 0.3
cx,cy = [0.5,0.35]
h = 0.3
dh = -0.13
dh2 = 0.05
e = 4.
th = np.linspace(0,np.pi,101)
col = 'r'
ax.fill_between([0,1],[0,0],[1,1],color='b',alpha=0.1, zorder = 0)
ax.plot(cx + r*np.cos(th), cy + r*np.sin(th)/e, color = col, ls = '-')
ax.plot(cx + r*np.cos(th), cy - r*np.sin(th)/e, color = col, ls = '-')
ax.plot(cx + r*np.cos(th), cy + r*np.sin(th)/e+h, color = col, ls = '--')
ax.plot(cx + r*np.cos(th), cy - r*np.sin(th)/e+h, color = col, ls = '--')
ax.plot([cx+r,cx+r],[cy,cy+h],color=col,ls='--')
ax.plot([cx-r,cx-r],[cy,cy+h],color=col,ls='--')
ax.plot(cx + r*np.cos(th), cy + r*np.sin(th)/e+h+(i>0)*dh+(i>1)*dh2, color = col, ls = '-')
ax.plot(cx + r*np.cos(th), cy - r*np.sin(th)/e+h+(i>0)*dh+(i>1)*dh2, color = col, ls = '-')
ax.plot([cx+r,cx+r],[cy,cy+h+(i>0)*dh+(i>1)*dh2],color=col,ls='-')
ax.plot([cx-r,cx-r],[cy,cy+h+(i>0)*dh+(i>1)*dh2],color=col,ls='-')
ax.fill_between(cx + r*np.cos(th),cy - r*np.sin(th)/e,cy + r*np.sin(th)/e+h+(i>0)*dh+(i>1)*dh2, color='r', alpha = 0.1)
if i > 0:
cube(ax, 0.90, 0.8, 0.025, 'r')
ax.arrow(cx+1.05*r,cy+1.2*(h+dh)+0.05, 0.05, 0.14, color = 'r', head_width=0.02, head_length=0.04, length_includes_head=True)
if i > 1:
cube(ax, 0.85, 0.5, 0.015, 'b')
cube(ax, 0.15, 0.5, 0.015, 'b')
cube(ax, 0.85, 0.35, 0.015, 'b')
cube(ax, 0.15, 0.35, 0.015, 'b')
cube(ax, 0.25, 0.23, 0.015, 'b')
cube(ax, 0.50, 0.18, 0.015, 'b')
cube(ax, 0.75, 0.23, 0.015, 'b')
ax.arrow(0.17,0.5,0.02,0.0, color = 'b', head_width=0.02, head_length=0.01, length_includes_head=True)
ax.arrow(0.83,0.5,-0.02,0.0, color = 'b', head_width=0.02, head_length=0.01, length_includes_head=True)
ax.arrow(0.17,0.35,0.02,0.0, color = 'b', head_width=0.02, head_length=0.01, length_includes_head=True)
ax.arrow(0.83,0.35,-0.02,0.0, color = 'b', head_width=0.02, head_length=0.01, length_includes_head=True)
ax.arrow(0.50,0.21,0.,0.04, color = 'b', head_width=0.01, head_length=0.02, length_includes_head=True)
ax.arrow(0.26,0.25,0.015,0.025, color = 'b', head_width=0.015, head_length=0.01, length_includes_head=True)
ax.arrow(0.74,0.25,-0.015,0.025, color = 'b', head_width=0.015, head_length=0.01, length_includes_head=True)
if i > 2:
for fr in [0.35,0.70,0.90]:
ax.plot(cx + r*np.cos(th), cy + r*np.sin(th)/e+h+fr*(dh+dh2), color = 'k', ls = '--')
ax.plot(cx + r*np.cos(th), cy - r*np.sin(th)/e+h+fr*(dh+dh2), color = 'k', ls = '--')
ax.fill_between(cx + r*np.cos(th), cy - r*np.sin(th)/e+h+fr*(dh+dh2), cy + r*np.sin(th)/e+h+fr*(dh+dh2), color = 'k', alpha = 0.1)
ax.arrow(0.18, cy+h, 0, dh+dh2, color = 'k', head_width=0.01, head_length=0.02, length_includes_head=True)
ax.text(0.17, cy+h+0.5*(dh+dh2), 'lowers\nover time', color='k', ha = 'right', va='center', size=TEXTSIZE-1, fontstyle = 'italic')
xt1,xt2,xt3,xt4 = [0.2,0.06,0.07,0.07]
yt = 0.85
yt2 = 0.05
ax.text(xt1,yt,r'$\dot{P}$ =', color = 'k', size = TEXTSIZE+4)
if i == 0:
ax.text(xt1+xt2,yt,r'$0$', color = 'k', size = TEXTSIZE+4)
if i > 0:
ax.text(xt1+xt2,yt,r'$-aq$', color = 'r', size = TEXTSIZE+4)
if i > 1:
ax.text(xt1+xt2+xt3,yt,r'$-bP$', color = 'b', size = TEXTSIZE+4)
if i > 2:
ax.text(xt1+xt2+xt3+xt4,yt,r'$-c\dot{q}$', color = 'k', size = TEXTSIZE+4)
if i == 0:
ax.text(0.5, yt2, 'reservoir initially at pressure equilibrium', size = TEXTSIZE+4, ha = 'center', va = 'bottom', fontstyle = 'italic')
elif i == 1:
ax.text(0.5, yt2, 'extraction from reservoir at rate, $q$', size = TEXTSIZE+4, ha = 'center', va = 'bottom', fontstyle = 'italic')
elif i == 2:
ax.text(0.5, yt2, 'recharge from surrounding rock, proportional to $P$', size = TEXTSIZE+4, ha = 'center', va = 'bottom', fontstyle = 'italic')
elif i == 3:
ax.text(0.5, yt2, 'response to extraction not instantaneous: "slow drainage", $\dot{q}$', size = TEXTSIZE+4, ha = 'center', va = 'bottom', fontstyle = 'italic')
plt.show()
def cube(ax,x0,y0,dx,col):
dy = dx*2.
s2 = 2
ax.plot([x0+dx/s2,x0, x0-dx,x0-dx,x0,x0],[y0+dy/s2,y0,y0,y0-dy,y0-dy,y0],color=col,ls='-')
ax.plot([x0-dx,x0-dx+dx/s2,x0+dx/s2,x0+dx/s2,x0],[y0,y0+dy/s2,y0+dy/s2,y0+dy/s2-dy,y0-dy],color=col,ls='-')
ax.fill_between([x0-dx,x0-dx+dx/s2,x0,x0+dx/s2],[y0-dy,y0-dy,y0-dy,y0-dy+dy/s2],[y0,y0+dy/s2,y0+dy/s2,y0+dy/s2],color=col,alpha=0.1)
def lpm_demo():
sldr = IntSlider(value=0, description='slide me!', min = 0, max = 3, step = 1, continuous_update = False, readout=False)
return VBox([sldr, interactive_output(lpm_plot, {'i':sldr})])
def plot_lpm_models(a,b,c):
# load some data
tq,q = np.genfromtxt('wk_production_history.csv', delimiter = ',')[:28,:].T
tp,p = np.genfromtxt('wk_pressure_history.csv', delimiter = ',')[:28,:].T
dqdt = 0.*q # allocate derivative vector
dqdt[1:-1] = (q[2:]-q[:-2])/(tq[2:]-tq[:-2]) # central differences
dqdt[0] = (q[1]-q[0])/(tq[1]-tq[0]) # forward difference
dqdt[-1] = (q[-1]-q[-2])/(tq[-1]-tq[-2]) # backward difference
# plot the data with error bars
f,ax = plt.subplots(1,1,figsize=(12,6))
ax.set_xlabel('time [yr]',size=TEXTSIZE)
ax.plot(tp,p,'ro', label = 'observations')
v = 2.
for tpi,pi in zip(tp,p):
ax.plot([tpi,tpi],[pi-v,pi+v], 'r-', lw=0.5)
# define derivative function
def lpm(pi,t,a,b,c): # order of variables important
qi = np.interp(t,tq,q) # interpolate (piecewise linear) flow rate
dqdti = np.interp(t,tq,dqdt) # interpolate derivative
return -a*qi - b*pi - c*dqdti # compute derivative
# implement an improved Euler step to solve the ODE
def solve_lpm(t,a,b,c):
pm = [p[0],] # initial value
for t0,t1 in zip(tp[:-1],tp[1:]): # solve at pressure steps
dpdt1 = lpm(pm[-1]-p[0], t0, a, b, c) # predictor gradient
pp = pm[-1] + dpdt1*(t1-t0) # predictor step
dpdt2 = lpm(pp-p[0], t1, a, b, c) # corrector gradient
pm.append(pm[-1] + 0.5*(t1-t0)*(dpdt2+dpdt1)) # corrector step
return np.interp(t, tp, pm) # interp onto requested times
# solve and plot model
pm = solve_lpm(tp,a,b,c)
ax.plot(tp, pm, 'k-', label='model')
# axes upkeep
ax.set_ylabel('pressure [bar]',size=TEXTSIZE);
ax.tick_params(axis='both',labelsize=TEXTSIZE)
ax.legend(prop={'size':TEXTSIZE})
plt.show()
def lpm_model():
# load flow rate data and compute derivative
tq,q = np.genfromtxt('wk_production_history.csv', delimiter = ',')[:28,:].T
tp,p = np.genfromtxt('wk_pressure_history.csv', delimiter = ',')[:28,:].T
dqdt = 0.*q # allocate derivative vector
dqdt[1:-1] = (q[2:]-q[:-2])/(tq[2:]-tq[:-2]) # central differences
dqdt[0] = (q[1]-q[0])/(tq[1]-tq[0]) # forward difference
dqdt[-1] = (q[-1]-q[-2])/(tq[-1]-tq[-2]) # backward difference
# define derivative function
def lpm(pi,t,a,b,c): # order of variables important
qi = np.interp(t,tq,q) # interpolate (piecewise linear) flow rate
dqdti = np.interp(t,tq,dqdt) # interpolate derivative
return -a*qi - b*pi - c*dqdti # compute derivative
# implement an imporved Euler step to solve the ODE
def solve_lpm(t,a,b,c):
pm = [p[0],] # initial value
for t0,t1 in zip(tp[:-1],tp[1:]): # solve at pressure steps
dpdt1 = lpm(pm[-1]-p[0], t0, a, b, c) # predictor gradient
pp = pm[-1] + dpdt1*(t1-t0) # predictor step
dpdt2 = lpm(pp-p[0], t1, a, b, c) # corrector gradient
pm.append(pm[-1] + 0.5*(t1-t0)*(dpdt2+dpdt1)) # corrector step
return | np.interp(t, tp, pm) | numpy.interp |
import os
import pickle
import numpy as np
from utils import word_utils
global_params = {
"dataset_dir": "~/AudioGrounding",
"clip_dir": "audio",
"data_splits": ["train", "val", "test"],
"jsons": ["train.json", "val.json", "test.json"],
}
word_embs = {}
emb_matrix, emb_shape = None, None
# Load vocabulary
with open(os.path.join(global_params["dataset_dir"], "vocab_info.pkl"), "rb") as store:
vocab_info = pickle.load(store)
vocabulary = vocab_info["vocabulary"]
# Gather pretrained word embeddings
for word in vocabulary:
if word != word_utils.UNK_token:
word_embs[word] = word_utils.word_vector(word)
if emb_shape is None:
emb_shape = word_embs[word].shape
if emb_matrix is None:
emb_matrix = word_embs[word]
else:
emb_matrix = | np.vstack((emb_matrix, word_embs[word])) | numpy.vstack |
import cv2
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import argparse
import glob
import os
from random import shuffle
IMAGE_SIZE = 50
BLOCKSIZE = 20
BLOCKSTRIBE = BLOCKSIZE//2
CELLSIZE = BLOCKSIZE
NBINS = 9
DERIVAPERTURE = 1
WINSIGMA = -1.
HISTOGRAMNORMTYPE = 0
L2HYSTHRESHOLD = 0.2
GAMMACORRECTION = 1
NLEVELS = 64
SINEDGRADIENTS = True
DATA_SET_NAME = "HOGFull1Font"
FILENAME = "{}-imagesize-{}-block-{}-cell-{}-bin-{}-sined-{}"
FILENAME = FILENAME.format( DATA_SET_NAME,
IMAGE_SIZE,
BLOCKSIZE,
CELLSIZE,
NBINS,
SINEDGRADIENTS)
def createHOGDescription():
winSize = (IMAGE_SIZE, IMAGE_SIZE)
blockSize = (BLOCKSIZE, BLOCKSIZE)
blockStride = (BLOCKSTRIBE, BLOCKSTRIBE)
cellSize = (CELLSIZE, CELLSIZE)
nbins = NBINS
derivAperture = DERIVAPERTURE
winSigma = WINSIGMA
histogramNormType = HISTOGRAMNORMTYPE
L2HysThreshold = L2HYSTHRESHOLD
gammaCorrection = GAMMACORRECTION
nlevels = NLEVELS
signedGradients = SINEDGRADIENTS
hog = cv2.HOGDescriptor(winSize,blockSize,blockStride,cellSize,nbins,derivAperture,winSigma,
histogramNormType,L2HysThreshold,gammaCorrection,nlevels)
return hog
path = "C:\Python_program\Machine_learning\images\SV_BL\\"
name = "SEMI_SV_B4_BL_001"
img = cv2.imread(path+name+".jpg",0)
img1 = cv2.imread(path+name+".jpg")
# img = cv2.resize(img,(100,100))
kernel = np.ones((5,5),np.float32)
kernel_3 = np.ones((3,3),np.float32)/9
kernel_chud= np.array([[0, -1, 0],
[-1, 5, -1],
[0, -1, 0]], np.float32)
# kernel_chud2= np.array([[-1, -1, -1, -1, -1],
# [-1, -1, -1, -1, -1],
# [-1, -1, 25 -1, -1],
# [-1, -1, -1, -1, -1],
# [-1, -1, -1, -1, -1]], np.float32)
laplacian_kernel = np.array(
[[-1,-1,-1,-1,-1,-1,-1],
[-1,-1,-1,-1,-1,-1,-1],
[-1,-1,-1,-1,-1,-1,-1],
[-1,-1,-1,48,-1,-1,-1],
[-1,-1,-1,-1,-1,-1,-1],
[-1,-1,-1,-1,-1,-1,-1],
[-1,-1,-1,-1,-1,-1,-1]], dtype='int')
laplacian_kernel2 = | np.array((
[-1,-1,-1,-1,-1,-1,-1,-1,-1],
[-1,-1,-1,-1,-1,-1,-1,-1,-1],
[-1,-1,-1,-1,-1,-1,-1,-1,-1],
[-1,-1,-1,-1,-1,-1,-1,-1,-1],
[-1,-1,-1,-1,80,-1,-1,-1,-1],
[-1,-1,-1,-1,-1,-1,-1,-1,-1],
[-1,-1,-1,-1,-1,-1,-1,-1,-1],
[-1,-1,-1,-1,-1,-1,-1,-1,-1],
[-1,-1,-1,-1,-1,-1,-1,-1,-1]), dtype='int')
# gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) | numpy.array |
# -*- coding: utf-8 -*-
#
# Copyright (c) 2018 Leland Stanford Junior University
# Copyright (c) 2018 The Regents of the University of California
#
# This file is part of pelicun.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its contributors
# may be used to endorse or promote products derived from this software without
# specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
# You should have received a copy of the BSD 3-Clause License along with
# pelicun. If not, see <http://www.opensource.org/licenses/>.
#
# Contributors:
# <NAME>
"""
This subpackage performs system tests on the control module of pelicun.
"""
import pytest
import numpy as np
from numpy.testing import assert_allclose
from scipy.stats import truncnorm as tnorm
from copy import deepcopy
import os, sys, inspect
current_dir = os.path.dirname(
os.path.abspath(inspect.getfile(inspect.currentframe())))
parent_dir = os.path.dirname(current_dir)
sys.path.insert(0,os.path.dirname(parent_dir))
from pelicun.control import *
from pelicun.uq import mvn_orthotope_density as mvn_od
from pelicun.tests.test_pelicun import prob_allclose, prob_approx
# -----------------------------------------------------------------------------
# FEMA_P58_Assessment
# -----------------------------------------------------------------------------
def test_FEMA_P58_Assessment_central_tendencies():
"""
Perform a loss assessment with customized inputs that reduce the
dispersion of calculation parameters to negligible levels. This allows us
to test the results against pre-defined reference values in spite of the
randomness involved in the calculations.
"""
base_input_path = 'resources/'
DL_input = base_input_path + 'input data/' + "DL_input_test.json"
EDP_input = base_input_path + 'EDP data/' + "EDP_table_test.out"
A = FEMA_P58_Assessment()
A.read_inputs(DL_input, EDP_input, verbose=False)
A.define_random_variables()
# -------------------------------------------------- check random variables
# EDP
RV_EDP = list(A._EDP_dict.values())[0]
assert RV_EDP.theta[0] == pytest.approx(0.5 * g)
assert RV_EDP.theta[1] == pytest.approx(0.5 * g * 1e-6, abs=1e-7)
assert RV_EDP._distribution == 'lognormal'
# QNT
assert A._QNT_dict is None
#RV_QNT = A._RV_dict['QNT']
#assert RV_QNT is None
# FRG
RV_FRG = list(A._FF_dict.values())
thetas, betas = np.array([rv.theta for rv in RV_FRG]).T
assert_allclose(thetas, np.array([0.444, 0.6, 0.984]) * g, rtol=0.01)
assert_allclose(betas, np.array([0.3, 0.4, 0.5]), rtol=0.01)
rho = RV_FRG[0].RV_set.Rho()
assert_allclose(rho, np.ones((3, 3)), rtol=0.01)
assert np.all([rv.distribution == 'lognormal' for rv in RV_FRG])
# RED
RV_RED = list(A._DV_RED_dict.values())
mus, sigmas = np.array([rv.theta for rv in RV_RED]).T
assert_allclose(mus, np.ones(2), rtol=0.01)
assert_allclose(sigmas, np.array([1e-4, 1e-4]), rtol=0.01)
rho = RV_RED[0].RV_set.Rho()
assert_allclose(rho, np.array([[1, 0], [0, 1]]), rtol=0.01)
assert np.all([rv.distribution == 'normal' for rv in RV_RED])
assert_allclose (RV_RED[0].truncation_limits, [0., 2.], rtol=0.01)
assert_allclose (RV_RED[1].truncation_limits, [0., 4.], rtol=0.01)
# INJ
RV_INJ = list(A._DV_INJ_dict.values())
mus, sigmas = np.array([rv.theta for rv in RV_INJ]).T
assert_allclose(mus, np.ones(4), rtol=0.01)
assert_allclose(sigmas, np.ones(4) * 1e-4, rtol=0.01)
rho = RV_INJ[0].RV_set.Rho()
rho_target = np.zeros((4, 4))
np.fill_diagonal(rho_target, 1.)
assert_allclose(rho, rho_target, rtol=0.01)
assert np.all([rv.distribution == 'normal' for rv in RV_INJ])
assert_allclose(RV_INJ[0].truncation_limits, [0., 10./3.], rtol=0.01)
assert_allclose(RV_INJ[1].truncation_limits, [0., 10./3.], rtol=0.01)
assert_allclose(RV_INJ[2].truncation_limits, [0., 10.], rtol=0.01)
assert_allclose(RV_INJ[3].truncation_limits, [0., 10.], rtol=0.01)
# REP
RV_REP = list(A._DV_REP_dict.values())
thetas, betas = np.array([rv.theta for rv in RV_REP]).T
assert_allclose(thetas, np.ones(6), rtol=0.01)
assert_allclose(betas, np.ones(6) * 1e-4, rtol=0.01)
rho = RV_REP[0].RV_set.Rho()
rho_target = np.zeros((6, 6))
np.fill_diagonal(rho_target, 1.)
assert_allclose(rho, rho_target, rtol=0.01)
assert np.all([rv.distribution == 'lognormal' for rv in RV_REP])
# ------------------------------------------------------------------------
A.define_loss_model()
# QNT (deterministic)
QNT = A._FG_dict['T0001.001']._performance_groups[0]._quantity
assert QNT == pytest.approx(50., rel=0.01)
A.calculate_damage()
# ------------------------------------------------ check damage calculation
# TIME
T_check = A._TIME.describe().T.loc[['hour','month','weekday?'],:]
assert_allclose(T_check['mean'], np.array([11.5, 5.5, 5. / 7.]), rtol=0.05)
assert_allclose(T_check['min'], np.array([0., 0., 0.]), rtol=0.01)
assert_allclose(T_check['max'], np.array([23., 11., 1.]), rtol=0.01)
assert_allclose(T_check['50%'], np.array([12., 5., 1.]), atol=1.0)
assert_allclose(T_check['count'], np.array([10000., 10000., 10000.]),
rtol=0.01)
# POP
P_CDF = A._POP.describe(np.arange(1, 27) / 27.).iloc[:, 0].values[4:]
vals, counts = np.unique(P_CDF, return_counts=True)
assert_allclose(vals, np.array([0., 2.5, 5., 10.]), rtol=0.01)
assert_allclose(counts, np.array([14, 2, 7, 5]), atol=1)
# COL
COL_check = A._COL.describe().T
assert COL_check['mean'].values[0] == pytest.approx(0.5, rel=0.05)
assert len(A._ID_dict['non-collapse']) == pytest.approx(5000, rel=0.05)
assert len(A._ID_dict['collapse']) == pytest.approx(5000, rel=0.05)
# DMG
DMG_check = A._DMG.describe().T
assert_allclose(DMG_check['mean'], np.array([17.074, 17.074, 7.9361]),
rtol=0.1, atol=1.0)
assert_allclose(DMG_check['min'], np.zeros(3), rtol=0.01)
assert_allclose(DMG_check['max'], np.ones(3) * 50.0157, rtol=0.05)
# ------------------------------------------------------------------------
A.calculate_losses()
# -------------------------------------------------- check loss calculation
# RED
DV_RED = A._DV_dict['red_tag'].describe().T
assert_allclose(DV_RED['mean'], np.array([0.341344, 0.1586555]), rtol=0.1)
# INJ - collapse
DV_INJ_C = deepcopy(A._COL[['INJ-0', 'INJ-1']])
DV_INJ_C.dropna(inplace=True)
NC_count = DV_INJ_C.describe().T['count'][0]
assert_allclose(NC_count, np.ones(2) * 5000, rtol=0.05)
# lvl 1
vals, counts = np.unique(DV_INJ_C.iloc[:, 0].values, return_counts=True)
assert_allclose(vals, np.array([0., 2.5, 5., 10.]) * 0.1, rtol=0.01)
assert_allclose(counts / NC_count, np.array([14, 2, 7, 5]) / 28., atol=0.01, rtol=0.1)
# lvl 2
vals, counts = np.unique(DV_INJ_C.iloc[:, 1].values, return_counts=True)
assert_allclose(vals, np.array([0., 2.5, 5., 10.]) * 0.9, rtol=0.01)
assert_allclose(counts / NC_count, np.array([14, 2, 7, 5]) / 28., atol=0.01, rtol=0.1)
# INJ - non-collapse
DV_INJ_NC = deepcopy(A._DV_dict['injuries'])
DV_INJ_NC[0].dropna(inplace=True)
assert_allclose(DV_INJ_NC[0].describe().T['count'], np.ones(2) * 5000,
rtol=0.05)
# lvl 1 DS2
I_CDF = DV_INJ_NC[0].iloc[:, 0]
I_CDF = np.around(I_CDF, decimals=3)
vals, counts = np.unique(I_CDF, return_counts=True)
assert_allclose(vals, np.array([0., 0.075, 0.15, 0.3]), rtol=0.01)
target_prob = np.array(
[0.6586555, 0., 0., 0.] + 0.3413445 * np.array([14, 2, 7, 5]) / 28.)
assert_allclose(counts / NC_count, target_prob, atol=0.01, rtol=0.1)
# lvl 1 DS3
I_CDF = DV_INJ_NC[0].iloc[:, 1]
I_CDF = np.around(I_CDF, decimals=3)
vals, counts = np.unique(I_CDF, return_counts=True)
assert_allclose(vals, np.array([0., 0.075, 0.15, 0.3]), rtol=0.01)
target_prob = np.array(
[0.8413445, 0., 0., 0.] + 0.1586555 * np.array([14, 2, 7, 5]) / 28.)
assert_allclose(counts / NC_count, target_prob, atol=0.01, rtol=0.1)
# lvl 2 DS2
I_CDF = DV_INJ_NC[1].iloc[:, 0]
I_CDF = np.around(I_CDF, decimals=3)
vals, counts = np.unique(I_CDF, return_counts=True)
assert_allclose(vals, np.array([0., 0.025, 0.05, 0.1]), rtol=0.01)
target_prob = np.array(
[0.6586555, 0., 0., 0.] + 0.3413445 * np.array([14, 2, 7, 5]) / 28.)
assert_allclose(counts / NC_count, target_prob, atol=0.01, rtol=0.1)
# lvl2 DS3
I_CDF = DV_INJ_NC[1].iloc[:, 1]
I_CDF = np.around(I_CDF, decimals=3)
vals, counts = np.unique(I_CDF, return_counts=True)
assert_allclose(vals, np.array([0., 0.025, 0.05, 0.1]), rtol=0.01)
target_prob = np.array(
[0.8413445, 0., 0., 0.] + 0.1586555 * np.array([14, 2, 7, 5]) / 28.)
assert_allclose(counts / NC_count, target_prob, atol=0.01, rtol=0.1)
# REP
assert len(A._ID_dict['non-collapse']) == len(A._ID_dict['repairable'])
assert len(A._ID_dict['irreparable']) == 0
# cost
DV_COST = A._DV_dict['rec_cost']
# DS1
C_CDF = DV_COST.iloc[:, 0]
C_CDF = np.around(C_CDF / 10., decimals=0) * 10.
vals, counts = np.unique(C_CDF, return_counts=True)
assert_allclose(vals, [0, 2500], rtol=0.01)
t_prob = 0.3413445
assert_allclose(counts / NC_count, [1. - t_prob, t_prob], rtol=0.1)
# DS2
C_CDF = DV_COST.iloc[:, 1]
C_CDF = np.around(C_CDF / 100., decimals=0) * 100.
vals, counts = np.unique(C_CDF, return_counts=True)
assert_allclose(vals, [0, 25000], rtol=0.01)
t_prob = 0.3413445
assert_allclose(counts / NC_count, [1. - t_prob, t_prob], rtol=0.1)
# DS3
C_CDF = DV_COST.iloc[:, 2]
C_CDF = np.around(C_CDF / 1000., decimals=0) * 1000.
vals, counts = np.unique(C_CDF, return_counts=True)
assert_allclose(vals, [0, 250000], rtol=0.01)
t_prob = 0.1586555
assert_allclose(counts / NC_count, [1. - t_prob, t_prob], rtol=0.1)
# time
DV_TIME = A._DV_dict['rec_time']
# DS1
T_CDF = DV_TIME.iloc[:, 0]
T_CDF = np.around(T_CDF, decimals=1)
vals, counts = np.unique(T_CDF, return_counts=True)
assert_allclose(vals, [0, 2.5], rtol=0.01)
t_prob = 0.3413445
assert_allclose(counts / NC_count, [1. - t_prob, t_prob], rtol=0.1)
# DS2
T_CDF = DV_TIME.iloc[:, 1]
T_CDF = np.around(T_CDF, decimals=0)
vals, counts = np.unique(T_CDF, return_counts=True)
assert_allclose(vals, [0, 25], rtol=0.01)
t_prob = 0.3413445
assert_allclose(counts / NC_count, [1. - t_prob, t_prob], rtol=0.1)
# DS3
T_CDF = DV_TIME.iloc[:, 2]
T_CDF = np.around(T_CDF / 10., decimals=0) * 10.
vals, counts = np.unique(T_CDF, return_counts=True)
assert_allclose(vals, [0, 250], rtol=0.01)
t_prob = 0.1586555
assert_allclose(counts / NC_count, [1. - t_prob, t_prob], rtol=0.1)
# ------------------------------------------------------------------------
A.aggregate_results()
# ------------------------------------------------ check result aggregation
S = A._SUMMARY
SD = S.describe().T
assert_allclose(S[('event time', 'month')], A._TIME['month'] + 1)
assert_allclose(S[('event time', 'weekday?')], A._TIME['weekday?'])
assert_allclose(S[('event time', 'hour')], A._TIME['hour'])
assert_allclose(S[('inhabitants', '')], A._POP.iloc[:, 0])
assert SD.loc[('collapses', 'collapsed'), 'mean'] == pytest.approx(0.5,
rel=0.05)
assert SD.loc[('collapses', 'mode'), 'mean'] == 0.
assert SD.loc[('collapses', 'mode'), 'count'] == pytest.approx(5000,
rel=0.05)
assert SD.loc[('red tagged', ''), 'mean'] == pytest.approx(0.5, rel=0.05)
assert SD.loc[('red tagged', ''), 'count'] == pytest.approx(5000, rel=0.05)
for col in ['irreparable', 'cost impractical', 'time impractical']:
assert SD.loc[('reconstruction', col), 'mean'] == 0.
assert SD.loc[('reconstruction', col), 'count'] == pytest.approx(5000,
rel=0.05)
RC = deepcopy(S.loc[:, ('reconstruction', 'cost')])
RC_CDF = np.around(RC / 1000., decimals=0) * 1000.
vals, counts = np.unique(RC_CDF, return_counts=True)
assert_allclose(vals, np.array([0, 2., 3., 25., 250., 300.]) * 1000.)
t_prob1 = 0.3413445 / 2.
t_prob2 = 0.1586555 / 2.
assert_allclose(counts / 10000.,
[t_prob2, t_prob1 / 2., t_prob1 / 2., t_prob1, t_prob2,
0.5], atol=0.01, rtol=0.1)
RT = deepcopy(S.loc[:, ('reconstruction', 'time-parallel')])
RT_CDF = np.around(RT, decimals=0)
vals, counts = np.unique(RT_CDF, return_counts=True)
assert_allclose(vals, np.array([0, 2., 3., 25., 250., 300.]))
t_prob1 = 0.3413445 / 2.
t_prob2 = 0.1586555 / 2.
assert_allclose(counts / 10000.,
[t_prob2, t_prob1 / 2., t_prob1 / 2., t_prob1, t_prob2,
0.5], atol=0.01, rtol=0.1)
assert_allclose(S.loc[:, ('reconstruction', 'time-parallel')],
S.loc[:, ('reconstruction', 'time-sequential')])
CAS = deepcopy(S.loc[:, ('injuries', 'sev1')])
CAS_CDF = np.around(CAS, decimals=3)
vals, counts = np.unique(CAS_CDF, return_counts=True)
assert_allclose(vals, [0, 0.075, 0.15, 0.25, 0.3, 0.5, 1.])
assert_allclose(counts / 10000.,
np.array([35, 1, 3.5, 2, 2.5, 7, 5]) / 56., atol=0.01,
rtol=0.1)
CAS = deepcopy(S.loc[:, ('injuries', 'sev2')])
CAS_CDF = np.around(CAS, decimals=3)
vals, counts = np.unique(CAS_CDF, return_counts=True)
assert_allclose(vals, [0, 0.025, 0.05, 0.1, 2.25, 4.5, 9.])
assert_allclose(counts / 10000.,
np.array([35, 1, 3.5, 2.5, 2, 7, 5]) / 56., atol=0.01,
rtol=0.1)
def test_FEMA_P58_Assessment_EDP_uncertainty_basic():
"""
Perform a loss assessment with customized inputs that focus on testing the
methods used to estimate the multivariate lognormal distribution of EDP
values. Besides the fitting, this test also evaluates the propagation of
EDP uncertainty through the analysis. Dispersions in other calculation
parameters are reduced to negligible levels. This allows us to test the
results against pre-defined reference values in spite of the randomness
involved in the calculations.
"""
base_input_path = 'resources/'
DL_input = base_input_path + 'input data/' + "DL_input_test_2.json"
EDP_input = base_input_path + 'EDP data/' + "EDP_table_test_2.out"
A = FEMA_P58_Assessment()
A.read_inputs(DL_input, EDP_input, verbose=False)
A.define_random_variables()
# -------------------------------------------------- check random variables
# EDP
RV_EDP = list(A._EDP_dict.values())
thetas, betas = np.array([rv.theta for rv in RV_EDP]).T
assert_allclose(thetas, [9.80665, 12.59198, 0.074081, 0.044932], rtol=0.02)
assert_allclose(betas, [0.25, 0.25, 0.3, 0.4], rtol=0.02)
rho = RV_EDP[0].RV_set.Rho()
rho_target = [
[1.0, 0.6, 0.3, 0.3],
[0.6, 1.0, 0.3, 0.3],
[0.3, 0.3, 1.0, 0.7],
[0.3, 0.3, 0.7, 1.0]]
assert_allclose(rho, rho_target, atol=0.05)
assert np.all([rv.distribution == 'lognormal' for rv in RV_EDP])
# ------------------------------------------------------------------------
A.define_loss_model()
A.calculate_damage()
# ------------------------------------------------ check damage calculation
# COL
COL_check = A._COL.describe().T
col_target = 1.0 - mvn_od(np.log([0.074081, 0.044932]),
np.array([[1, 0.7], [0.7, 1]]) * np.outer(
[0.3, 0.4], [0.3, 0.4]),
upper=np.log([0.1, 0.1]))[0]
assert COL_check['mean'].values[0] == pytest.approx(col_target, rel=0.1)
# DMG
DMG_check = [len(np.where(A._DMG.iloc[:, i] > 0.0)[0]) / 10000. for i in
range(8)]
DMG_1_PID = mvn_od(np.log([0.074081, 0.044932]),
np.array([[1, 0.7], [0.7, 1]]) * np.outer([0.3, 0.4],
[0.3, 0.4]),
lower=np.log([0.05488, 1e-6]), upper=np.log([0.1, 0.1]))[
0]
DMG_2_PID = mvn_od(np.log([0.074081, 0.044932]),
np.array([[1, 0.7], [0.7, 1]]) * np.outer([0.3, 0.4],
[0.3, 0.4]),
lower=np.log([1e-6, 0.05488]), upper=np.log([0.1, 0.1]))[
0]
DMG_1_PFA = mvn_od(np.log([0.074081, 9.80665]),
np.array([[1, 0.3], [0.3, 1]]) * np.outer([0.3, 0.25],
[0.3, 0.25]),
lower=np.log([1e-6, 9.80665]),
upper=np.log([0.1, np.inf]))[0]
DMG_2_PFA = mvn_od(np.log([0.074081, 12.59198]),
np.array([[1, 0.3], [0.3, 1]]) * np.outer([0.3, 0.25],
[0.3, 0.25]),
lower=np.log([1e-6, 9.80665]),
upper=np.log([0.1, np.inf]))[0]
assert DMG_check[0] == pytest.approx(DMG_check[1], rel=0.01)
assert DMG_check[2] == pytest.approx(DMG_check[3], rel=0.01)
assert DMG_check[4] == pytest.approx(DMG_check[5], rel=0.01)
assert DMG_check[6] == pytest.approx(DMG_check[7], rel=0.01)
assert DMG_check[0] == pytest.approx(DMG_1_PID, rel=0.10)
assert DMG_check[2] == pytest.approx(DMG_2_PID, rel=0.10)
assert DMG_check[4] == pytest.approx(DMG_1_PFA, rel=0.10)
assert DMG_check[6] == pytest.approx(DMG_2_PFA, rel=0.10)
# ------------------------------------------------------------------------
A.calculate_losses()
# -------------------------------------------------- check loss calculation
# COST
DV_COST = A._DV_dict['rec_cost']
DV_TIME = A._DV_dict['rec_time']
C_target = [0., 250., 1250.]
T_target = [0., 0.25, 1.25]
# PG 1011 and 1012
P_target = [
mvn_od(np.log([0.074081, 0.044932]),
np.array([[1, 0.7], [0.7, 1]]) * np.outer([0.3, 0.4],
[0.3, 0.4]),
lower=np.log([1e-6, 1e-6]), upper=np.log([0.05488, 0.1]))[0],
mvn_od(np.log([0.074081, 0.044932]),
np.array([[1, 0.7], [0.7, 1]]) * np.outer([0.3, 0.4],
[0.3, 0.4]),
lower=np.log([0.05488, 0.05488]), upper=np.log([0.1, 0.1]))[0],
mvn_od(np.log([0.074081, 0.044932]),
np.array([[1, 0.7], [0.7, 1]]) * np.outer([0.3, 0.4],
[0.3, 0.4]),
lower=np.log([0.05488, 1e-6]), upper=np.log([0.1, 0.05488]))[0],
]
for i in [0, 1]:
C_test, P_test = np.unique(
np.around(DV_COST.iloc[:, i].values / 10., decimals=0) * 10.,
return_counts=True)
C_test = C_test[np.where(P_test > 10)]
T_test, P_test = np.unique(
np.around(DV_TIME.iloc[:, i].values * 100., decimals=0) / 100.,
return_counts=True)
T_test = T_test[np.where(P_test > 10)]
P_test = P_test[np.where(P_test > 10)]
P_test = P_test / 10000.
assert_allclose(P_target, P_test, atol=0.02)
assert_allclose(C_target, C_test, rtol=0.001)
assert_allclose(T_target, T_test, rtol=0.001)
# PG 1021 and 1022
P_target = [
mvn_od(np.log([0.074081, 0.044932]),
np.array([[1, 0.7], [0.7, 1]]) * np.outer([0.3, 0.4],
[0.3, 0.4]),
lower=np.log([1e-6, 1e-6]), upper=np.log([0.1, 0.05488]))[0],
mvn_od(np.log([0.074081, 0.044932]),
np.array([[1, 0.7], [0.7, 1]]) * np.outer([0.3, 0.4],
[0.3, 0.4]),
lower=np.log([0.05488, 0.05488]), upper=np.log([0.1, 0.1]))[0],
mvn_od(np.log([0.074081, 0.044932]),
np.array([[1, 0.7], [0.7, 1]]) * np.outer([0.3, 0.4],
[0.3, 0.4]),
lower=np.log([1e-6, 0.05488]), upper=np.log([0.05488, 0.1]))[0],
]
for i in [2, 3]:
C_test, P_test = np.unique(
np.around(DV_COST.iloc[:, i].values / 10., decimals=0) * 10.,
return_counts=True)
C_test = C_test[np.where(P_test > 10)]
T_test, P_test = np.unique(
np.around(DV_TIME.iloc[:, i].values * 100., decimals=0) / 100.,
return_counts=True)
T_test = T_test[np.where(P_test > 10)]
P_test = P_test[np.where(P_test > 10)]
P_test = P_test / 10000.
assert_allclose(P_target, P_test, atol=0.02)
assert_allclose(C_target, C_test, rtol=0.001)
assert_allclose(T_target, T_test, rtol=0.001)
# PG 2011 and 2012
P_target = [
mvn_od(np.log([0.074081, 9.80665, 12.59198]),
np.array([[1.0, 0.3, 0.3], [0.3, 1.0, 0.6],
[0.3, 0.6, 1.0]]) * np.outer([0.3, 0.25, 0.25],
[0.3, 0.25, 0.25]),
lower=np.log([1e-6, 1e-6, 1e-6]),
upper=np.log([0.1, 9.80665, np.inf]))[0],
mvn_od(np.log([0.074081, 9.80665, 12.59198]),
np.array([[1.0, 0.3, 0.3], [0.3, 1.0, 0.6],
[0.3, 0.6, 1.0]]) * np.outer([0.3, 0.25, 0.25],
[0.3, 0.25, 0.25]),
lower=np.log([1e-6, 9.80665, 9.80665]),
upper=np.log([0.1, np.inf, np.inf]))[0],
mvn_od(np.log([0.074081, 9.80665, 12.59198]),
np.array([[1.0, 0.3, 0.3], [0.3, 1.0, 0.6],
[0.3, 0.6, 1.0]]) * np.outer([0.3, 0.25, 0.25],
[0.3, 0.25, 0.25]),
lower=np.log([1e-6, 9.80665, 1e-6]),
upper=np.log([0.1, np.inf, 9.80665]))[0],
]
for i in [4, 5]:
C_test, P_test = np.unique(
np.around(DV_COST.iloc[:, i].values / 10., decimals=0) * 10.,
return_counts=True)
C_test = C_test[np.where(P_test > 10)]
T_test, P_test = np.unique(
np.around(DV_TIME.iloc[:, i].values * 100., decimals=0) / 100.,
return_counts=True)
T_test = T_test[np.where(P_test > 10)]
P_test = P_test[np.where(P_test > 10)]
P_test = P_test / 10000.
assert_allclose(P_target, P_test, atol=0.02)
assert_allclose(C_target, C_test, rtol=0.001)
assert_allclose(T_target, T_test, rtol=0.001)
# PG 2021 and 2022
P_target = [
mvn_od(np.log([0.074081, 9.80665, 12.59198]),
np.array([[1.0, 0.3, 0.3], [0.3, 1.0, 0.6],
[0.3, 0.6, 1.0]]) * np.outer([0.3, 0.25, 0.25],
[0.3, 0.25, 0.25]),
lower=np.log([1e-6, 1e-6, 1e-6]),
upper=np.log([0.1, np.inf, 9.80665]))[0],
mvn_od(np.log([0.074081, 9.80665, 12.59198]),
np.array([[1.0, 0.3, 0.3], [0.3, 1.0, 0.6],
[0.3, 0.6, 1.0]]) * np.outer([0.3, 0.25, 0.25],
[0.3, 0.25, 0.25]),
lower=np.log([1e-6, 9.80665, 9.80665]),
upper=np.log([0.1, np.inf, np.inf]))[0],
mvn_od(np.log([0.074081, 9.80665, 12.59198]),
np.array([[1.0, 0.3, 0.3], [0.3, 1.0, 0.6],
[0.3, 0.6, 1.0]]) * np.outer([0.3, 0.25, 0.25],
[0.3, 0.25, 0.25]),
lower=np.log([1e-6, 1e-6, 9.80665]),
upper=np.log([0.1, 9.80665, np.inf]))[0],
]
for i in [6, 7]:
C_test, P_test = np.unique(
np.around(DV_COST.iloc[:, i].values / 10., decimals=0) * 10.,
return_counts=True)
C_test = C_test[np.where(P_test > 10)]
T_test, P_test = np.unique(
np.around(DV_TIME.iloc[:, i].values * 100., decimals=0) / 100.,
return_counts=True)
T_test = T_test[np.where(P_test > 10)]
P_test = P_test[np.where(P_test > 10)]
P_test = P_test / 10000.
assert_allclose(P_target, P_test, atol=0.02)
assert_allclose(C_target, C_test, rtol=0.001)
assert_allclose(T_target, T_test, rtol=0.001)
# RED TAG
RED_check = A._DV_dict['red_tag'].describe().T
RED_check = (RED_check['mean'] * RED_check['count'] / 10000.).values
assert RED_check[0] == pytest.approx(RED_check[1], rel=0.01)
assert RED_check[2] == pytest.approx(RED_check[3], rel=0.01)
assert RED_check[4] == pytest.approx(RED_check[5], rel=0.01)
assert RED_check[6] == pytest.approx(RED_check[7], rel=0.01)
assert RED_check[0] == pytest.approx(DMG_1_PID, rel=0.10)
assert RED_check[2] == pytest.approx(DMG_2_PID, rel=0.10)
assert RED_check[4] == pytest.approx(DMG_1_PFA, rel=0.10)
assert RED_check[6] == pytest.approx(DMG_2_PFA, rel=0.10)
DMG_on = np.where(A._DMG > 0.0)[0]
RED_on = np.where(A._DV_dict['red_tag'] > 0.0)[0]
assert_allclose(DMG_on, RED_on)
# ------------------------------------------------------------------------
A.aggregate_results()
# ------------------------------------------------ check result aggregation
P_no_RED_target = mvn_od(np.log([0.074081, 0.044932, 9.80665, 12.59198]),
np.array(
[[1.0, 0.7, 0.3, 0.3], [0.7, 1.0, 0.3, 0.3],
[0.3, 0.3, 1.0, 0.6],
[0.3, 0.3, 0.6, 1.0]]) * np.outer(
[0.3, 0.4, 0.25, 0.25],
[0.3, 0.4, 0.25, 0.25]),
lower=np.log([1e-6, 1e-6, 1e-6, 1e-6]),
upper=np.log(
[0.05488, 0.05488, 9.80665, 9.80665]))[0]
S = A._SUMMARY
SD = S.describe().T
P_no_RED_test = (1.0 - SD.loc[('red tagged', ''), 'mean']) * SD.loc[
('red tagged', ''), 'count'] / 10000.
def test_FEMA_P58_Assessment_EDP_uncertainty_detection_limit():
"""
Perform a loss assessment with customized inputs that focus on testing the
methods used to estimate the multivariate lognormal distribution of EDP
values. Besides the fitting, this test also evaluates the propagation of
EDP uncertainty through the analysis. Dispersions in other calculation
parameters are reduced to negligible levels. This allows us to test the
results against pre-defined reference values in spite of the randomness
involved in the calculations.
This test differs from the basic case in having unreliable EDP values above
a certain limit - a typical feature of interstory drifts in dynamic
simulations. Such cases should not be a problem if the limits can be
estimated and they are specified as detection limits in input file.
"""
base_input_path = 'resources/'
DL_input = base_input_path + 'input data/' + "DL_input_test_3.json"
EDP_input = base_input_path + 'EDP data/' + "EDP_table_test_3.out"
A = FEMA_P58_Assessment()
A.read_inputs(DL_input, EDP_input, verbose=False)
A.define_random_variables()
# -------------------------------------------------- check random variables
# EDP
RV_EDP = list(A._EDP_dict.values())
thetas, betas = np.array([rv.theta for rv in RV_EDP]).T
EDP_theta_test = thetas
EDP_beta_test = betas
EDP_theta_target = [9.80665, 12.59198, 0.074081, 0.044932]
EDP_beta_target = [0.25, 0.25, 0.3, 0.4]
assert_allclose(EDP_theta_test, EDP_theta_target, rtol=0.025)
assert_allclose(EDP_beta_test, EDP_beta_target, rtol=0.1)
rho = RV_EDP[0].RV_set.Rho()
EDP_rho_test = rho
EDP_rho_target = [
[1.0, 0.6, 0.3, 0.3],
[0.6, 1.0, 0.3, 0.3],
[0.3, 0.3, 1.0, 0.7],
[0.3, 0.3, 0.7, 1.0]]
EDP_COV_test = EDP_rho_test * np.outer(EDP_beta_test, EDP_beta_test)
assert_allclose(EDP_rho_test, EDP_rho_target, atol=0.15)
assert np.all([rv.distribution == 'lognormal' for rv in RV_EDP])
# ------------------------------------------------------------------------
A.define_loss_model()
A.calculate_damage()
# ------------------------------------------------ check damage calculation
# COL
COL_check = A._COL.describe().T
col_target = 1.0 - mvn_od(np.log(EDP_theta_test[2:]),
EDP_COV_test[2:, 2:],
upper=np.log([0.1, 0.1]))[0]
assert COL_check['mean'].values[0] == prob_approx(col_target, 0.03)
# DMG
DMG_check = [len(np.where(A._DMG.iloc[:, i] > 0.0)[0]) / 10000.
for i in range(8)]
DMG_1_PID = mvn_od(np.log(EDP_theta_test[2:]), EDP_COV_test[2:, 2:],
lower=np.log([0.05488, 1e-6]),
upper=np.log([0.1, 0.1]))[0]
DMG_2_PID = mvn_od(np.log(EDP_theta_test[2:]), EDP_COV_test[2:, 2:],
lower=np.log([1e-6, 0.05488]),
upper=np.log([0.1, 0.1]))[0]
DMG_1_PFA = mvn_od(np.log(EDP_theta_test), EDP_COV_test,
lower=np.log([9.80665, 1e-6, 1e-6, 1e-6]),
upper=np.log([np.inf, np.inf, 0.1, 0.1]))[0]
DMG_2_PFA = mvn_od(np.log(EDP_theta_test), EDP_COV_test,
lower=np.log([1e-6, 9.80665, 1e-6, 1e-6]),
upper=np.log([np.inf, np.inf, 0.1, 0.1]))[0]
assert DMG_check[0] == pytest.approx(DMG_check[1], rel=0.01)
assert DMG_check[2] == pytest.approx(DMG_check[3], rel=0.01)
assert DMG_check[4] == pytest.approx(DMG_check[5], rel=0.01)
assert DMG_check[6] == pytest.approx(DMG_check[7], rel=0.01)
assert DMG_check[0] == prob_approx(DMG_1_PID, 0.03)
assert DMG_check[2] == prob_approx(DMG_2_PID, 0.03)
assert DMG_check[4] == prob_approx(DMG_1_PFA, 0.03)
assert DMG_check[6] == prob_approx(DMG_2_PFA, 0.03)
# ------------------------------------------------------------------------
A.calculate_losses()
# -------------------------------------------------- check loss calculation
# COST
DV_COST = A._DV_dict['rec_cost']
DV_TIME = A._DV_dict['rec_time']
C_target = [0., 250., 1250.]
T_target = [0., 0.25, 1.25]
# PG 1011 and 1012
P_target = [
mvn_od(np.log(EDP_theta_test[2:]), EDP_COV_test[2:, 2:],
lower=np.log([1e-6, 1e-6]), upper=np.log([0.05488, 0.1]))[0],
mvn_od(np.log(EDP_theta_test[2:]), EDP_COV_test[2:, 2:],
lower=np.log([0.05488, 0.05488]), upper=np.log([0.1, 0.1]))[0],
mvn_od(np.log(EDP_theta_test[2:]), EDP_COV_test[2:, 2:],
lower=np.log([0.05488, 1e-6]), upper=np.log([0.1, 0.05488]))[0],
]
for i in [0, 1]:
C_test, P_test = np.unique(
np.around(DV_COST.iloc[:, i].values / 10., decimals=0) * 10.,
return_counts=True)
C_test = C_test[np.where(P_test > 10)]
T_test, P_test = np.unique(
np.around(DV_TIME.iloc[:, i].values * 100., decimals=0) / 100.,
return_counts=True)
T_test = T_test[np.where(P_test > 10)]
P_test = P_test[np.where(P_test > 10)]
P_test = P_test / 10000.
assert_allclose(C_target, C_test, rtol=0.001)
assert_allclose(T_target, T_test, rtol=0.001)
prob_allclose(P_target, P_test, 0.04)
# PG 1021 and 1022
P_target = [
mvn_od(np.log(EDP_theta_test[2:]), EDP_COV_test[2:, 2:],
lower=np.log([1e-6, 1e-6]), upper=np.log([0.1, 0.05488]))[0],
mvn_od(np.log(EDP_theta_test[2:]), EDP_COV_test[2:, 2:],
lower=np.log([0.05488, 0.05488]), upper=np.log([0.1, 0.1]))[0],
mvn_od(np.log(EDP_theta_test[2:]), EDP_COV_test[2:, 2:],
lower=np.log([1e-6, 0.05488]), upper=np.log([0.05488, 0.1]))[0],
]
for i in [2, 3]:
C_test, P_test = np.unique(
np.around(DV_COST.iloc[:, i].values / 10., decimals=0) * 10.,
return_counts=True)
C_test = C_test[np.where(P_test > 10)]
T_test, P_test = np.unique(
np.around(DV_TIME.iloc[:, i].values * 100., decimals=0) / 100.,
return_counts=True)
T_test = T_test[np.where(P_test > 10)]
P_test = P_test[np.where(P_test > 10)]
P_test = P_test / 10000.
assert_allclose(C_target, C_test, rtol=0.001)
assert_allclose(T_target, T_test, rtol=0.001)
prob_allclose(P_target, P_test, 0.04)
# PG 2011 and 2012
P_target = [
mvn_od(np.log(EDP_theta_test), EDP_COV_test,
lower=np.log([1e-6, 1e-6, 1e-6, 1e-6]),
upper=np.log([9.80665, np.inf, 0.1, 0.1]))[0],
mvn_od(np.log(EDP_theta_test), EDP_COV_test,
lower=np.log([9.80665, 9.80665, 1e-6, 1e-6]),
upper=np.log([np.inf, np.inf, 0.1, 0.1]))[0],
mvn_od(np.log(EDP_theta_test), EDP_COV_test,
lower=np.log([9.80665, 1e-6, 1e-6, 1e-6]),
upper=np.log([np.inf, 9.80665, 0.1, 0.1]))[0],
]
for i in [4, 5]:
C_test, P_test = np.unique(
np.around(DV_COST.iloc[:, i].values / 10., decimals=0) * 10.,
return_counts=True)
C_test = C_test[np.where(P_test > 10)]
T_test, P_test = np.unique(
np.around(DV_TIME.iloc[:, i].values * 100., decimals=0) / 100.,
return_counts=True)
T_test = T_test[np.where(P_test > 10)]
P_test = P_test[np.where(P_test > 10)]
P_test = P_test / 10000.
assert_allclose(C_target, C_test, rtol=0.001)
assert_allclose(T_target, T_test, rtol=0.001)
prob_allclose(P_target, P_test, 0.04)
# PG 2021 and 2022
P_target = [
mvn_od(np.log(EDP_theta_test), EDP_COV_test,
lower=np.log([1e-6, 1e-6, 1e-6, 1e-6]),
upper=np.log([np.inf, 9.80665, 0.1, 0.1]))[0],
mvn_od(np.log(EDP_theta_test), EDP_COV_test,
lower=np.log([9.80665, 9.80665, 1e-6, 1e-6]),
upper=np.log([np.inf, np.inf, 0.1, 0.1]))[0],
mvn_od(np.log(EDP_theta_test), EDP_COV_test,
lower=np.log([1e-6, 9.80665, 1e-6, 1e-6]),
upper=np.log([9.80665, np.inf, 0.1, 0.1]))[0],
]
for i in [6, 7]:
C_test, P_test = np.unique(
np.around(DV_COST.iloc[:, i].values / 10., decimals=0) * 10.,
return_counts=True)
C_test = C_test[np.where(P_test > 10)]
T_test, P_test = np.unique(
np.around(DV_TIME.iloc[:, i].values * 100., decimals=0) / 100.,
return_counts=True)
T_test = T_test[np.where(P_test > 10)]
P_test = P_test[np.where(P_test > 10)]
P_test = P_test / 10000.
assert_allclose(C_target, C_test, rtol=0.001)
assert_allclose(T_target, T_test, rtol=0.001)
prob_allclose(P_target, P_test, 0.04)
# RED TAG
RED_check = A._DV_dict['red_tag'].describe().T
RED_check = (RED_check['mean'] * RED_check['count'] / 10000.).values
assert RED_check[0] == pytest.approx(RED_check[1], rel=0.01)
assert RED_check[2] == pytest.approx(RED_check[3], rel=0.01)
assert RED_check[4] == pytest.approx(RED_check[5], rel=0.01)
assert RED_check[6] == pytest.approx(RED_check[7], rel=0.01)
assert RED_check[0] == prob_approx(DMG_1_PID, 0.03)
assert RED_check[2] == prob_approx(DMG_2_PID, 0.03)
assert RED_check[4] == prob_approx(DMG_1_PFA, 0.03)
assert RED_check[6] == prob_approx(DMG_2_PFA, 0.03)
DMG_on = np.where(A._DMG > 0.0)[0]
RED_on = np.where(A._DV_dict['red_tag'] > 0.0)[0]
assert_allclose(DMG_on, RED_on)
# ------------------------------------------------------------------------
A.aggregate_results()
# ------------------------------------------------ check result aggregation
P_no_RED_target = mvn_od(np.log(EDP_theta_test), EDP_COV_test,
lower=np.log([1e-6, 1e-6, 1e-6, 1e-6]),
upper=np.log([9.80665, 9.80665, 0.05488, 0.05488]))[0]
S = A._SUMMARY
SD = S.describe().T
P_no_RED_test = ((1.0 - SD.loc[('red tagged', ''), 'mean'])
* SD.loc[('red tagged', ''), 'count'] / 10000.)
assert P_no_RED_target == prob_approx(P_no_RED_test, 0.04)
def test_FEMA_P58_Assessment_EDP_uncertainty_failed_analyses():
"""
Perform a loss assessment with customized inputs that focus on testing the
methods used to estimate the multivariate lognormal distribution of EDP
values. Besides the fitting, this test also evaluates the propagation of
EDP uncertainty through the analysis. Dispersions in other calculation
parameters are reduced to negligible levels. This allows us to test the
results against pre-defined reference values in spite of the randomness
involved in the calculations.
Here we use EDP results with unique values assigned to failed analyses.
In particular, PID=1.0 and PFA=100.0 are used when an analysis fails.
These values shall be handled by detection limits of 10 and 100 for PID
and PFA, respectively.
"""
base_input_path = 'resources/'
DL_input = base_input_path + 'input data/' + "DL_input_test_4.json"
EDP_input = base_input_path + 'EDP data/' + "EDP_table_test_4.out"
A = FEMA_P58_Assessment()
A.read_inputs(DL_input, EDP_input, verbose=False)
A.define_random_variables()
# -------------------------------------------------- check random variables
# EDP
RV_EDP = list(A._EDP_dict.values())
thetas, betas = np.array([rv.theta for rv in RV_EDP]).T
EDP_theta_test = thetas
EDP_beta_test = betas
EDP_theta_target = [9.80665, 12.59198, 0.074081, 0.044932]
EDP_beta_target = [0.25, 0.25, 0.3, 0.4]
assert_allclose(EDP_theta_test, EDP_theta_target, rtol=0.025)
assert_allclose(EDP_beta_test, EDP_beta_target, rtol=0.1)
rho = RV_EDP[0].RV_set.Rho()
EDP_rho_test = rho
EDP_rho_target = [
[1.0, 0.6, 0.3, 0.3],
[0.6, 1.0, 0.3, 0.3],
[0.3, 0.3, 1.0, 0.7],
[0.3, 0.3, 0.7, 1.0]]
EDP_COV_test = EDP_rho_test * np.outer(EDP_beta_test, EDP_beta_test)
assert_allclose(EDP_rho_test, EDP_rho_target, atol=0.15)
assert np.all([rv.distribution == 'lognormal' for rv in RV_EDP])
# ------------------------------------------------------------------------
A.define_loss_model()
A.calculate_damage()
# ------------------------------------------------ check damage calculation
# COL
COL_check = A._COL.describe().T
col_target = 1.0 - mvn_od(np.log(EDP_theta_test[2:]),
EDP_COV_test[2:,2:],
upper=np.log([0.1, 0.1]))[0]
assert COL_check['mean'].values[0] == prob_approx(col_target, 0.03)
# DMG
DMG_check = [len(np.where(A._DMG.iloc[:, i] > 0.0)[0]) / 10000.
for i in range(8)]
DMG_1_PID = mvn_od(np.log(EDP_theta_test[2:]), EDP_COV_test[2:,2:],
lower=np.log([0.05488, 1e-6]),
upper=np.log([0.1, 0.1]))[0]
DMG_2_PID = mvn_od(np.log(EDP_theta_test[2:]), EDP_COV_test[2:, 2:],
lower=np.log([1e-6, 0.05488]),
upper=np.log([0.1, 0.1]))[0]
DMG_1_PFA = mvn_od(np.log(EDP_theta_test), EDP_COV_test,
lower=np.log([9.80665, 1e-6, 1e-6, 1e-6]),
upper=np.log([np.inf, np.inf, 0.1, 0.1]))[0]
DMG_2_PFA = mvn_od(np.log(EDP_theta_test), EDP_COV_test,
lower=np.log([1e-6, 9.80665, 1e-6, 1e-6]),
upper=np.log([np.inf, np.inf, 0.1, 0.1]))[0]
assert DMG_check[0] == pytest.approx(DMG_check[1], rel=0.01)
assert DMG_check[2] == pytest.approx(DMG_check[3], rel=0.01)
assert DMG_check[4] == pytest.approx(DMG_check[5], rel=0.01)
assert DMG_check[6] == pytest.approx(DMG_check[7], rel=0.01)
assert DMG_check[0] == prob_approx(DMG_1_PID, 0.03)
assert DMG_check[2] == prob_approx(DMG_2_PID, 0.03)
assert DMG_check[4] == prob_approx(DMG_1_PFA, 0.03)
assert DMG_check[6] == prob_approx(DMG_2_PFA, 0.03)
# ------------------------------------------------------------------------
A.calculate_losses()
# -------------------------------------------------- check loss calculation
# COST
DV_COST = A._DV_dict['rec_cost']
DV_TIME = A._DV_dict['rec_time']
C_target = [0., 250., 1250.]
T_target = [0., 0.25, 1.25]
# PG 1011 and 1012
P_target = [
mvn_od(np.log(EDP_theta_test[2:]), EDP_COV_test[2:, 2:],
lower=np.log([1e-6, 1e-6]), upper=np.log([0.05488, 0.1]))[0],
mvn_od(np.log(EDP_theta_test[2:]), EDP_COV_test[2:, 2:],
lower=np.log([0.05488, 0.05488]), upper=np.log([0.1, 0.1]))[0],
mvn_od(np.log(EDP_theta_test[2:]), EDP_COV_test[2:, 2:],
lower=np.log([0.05488, 1e-6]), upper=np.log([0.1, 0.05488]))[0],
]
for i in [0, 1]:
C_test, P_test = np.unique(
np.around(DV_COST.iloc[:, i].values / 10., decimals=0) * 10.,
return_counts=True)
C_test = C_test[np.where(P_test > 10)]
T_test, P_test = np.unique(
np.around(DV_TIME.iloc[:, i].values * 100., decimals=0) / 100.,
return_counts=True)
T_test = T_test[np.where(P_test > 10)]
P_test = P_test[np.where(P_test > 10)]
P_test = P_test / 10000.
assert_allclose(C_target, C_test, rtol=0.001)
| assert_allclose(T_target, T_test, rtol=0.001) | numpy.testing.assert_allclose |
from __future__ import (absolute_import, division, print_function)
import numpy as np
from .harmonics import ut_E
from .utilities import Bunch
from ._time_conversion import _normalize_time
def reconstruct(t, coef, epoch='python', verbose=True, **opts):
"""
Reconstruct a tidal signal.
Parameters
----------
t : array_like
Time in days since `epoch`.
coef : `Bunch`
Data structure returned by `utide.solve`
epoch : {string, `datetime.date`, `datetime.datetime`}, optional
Valid strings are 'python' (default); 'matlab' if `t` is
an array of Matlab datenums; or an arbitrary date in the
form 'YYYY-MM-DD'. The default corresponds to the Python
standard library `datetime` proleptic Gregorian calendar,
starting with 1 on January 1 of year 1.
verbose : {True, False}, optional
True to enable output message (default). False turns off all
messages.
Returns
-------
tide : `Bunch`
Scalar time series is returned as `tide.h`; a vector
series as `tide.u`, `tide.v`.
"""
out = Bunch()
u, v = _reconstr1(t, coef, epoch=epoch, verbose=verbose, **opts)
if coef['aux']['opt']['twodim']:
out.u, out.v = u, v
else:
out.h = u
return out
def _reconstr1(tin, coef, **opts):
# Parse inputs and options.
t, goodmask, opt = _rcninit(tin, **opts)
if opt['RunTimeDisp']:
print('reconstruct:', end='')
# Determine constituents to include.
# if ~isempty(opt.cnstit)
# if not np.empty(opt['cnstit']):
if opt['cnstit']:
# [~,ind] = ismember(cellstr(opt.cnstit),coef.name);
# opt['cnstit'] in coef['name']
ind = np.where(opt['cnstit'] == coef['name'])
# if ~isequal(length(ind),length(cellstr(opt.cnstit)))
# error(['reconstruct: one or more of input constituents Cnstit '...
# 'not found in coef.name']);
else:
ind = np.arange(len(coef['aux']['frq']))
if coef['aux']['opt']['twodim']:
SNR = ((coef['Lsmaj']**2 + coef['Lsmin']**2) /
((coef['Lsmaj_ci']/1.96)**2 + (coef['Lsmin_ci']/1.96)**2))
PE = sum(coef['Lsmaj']**2 + coef['Lsmin']**2)
PE = 100*(coef['Lsmaj']**2 + coef['Lsmin']**2)/PE
else:
SNR = (coef['A']**2)/((coef['A_ci']/1.96)**2)
PE = 100*coef['A']**2/sum(coef['A']**2)
# ind = ind[SNR[ind]>=opt['minsnr'] & PE[ind]>=opt['minpe']]
ind = np.where(np.logical_and(SNR[ind] >= opt['minsnr'],
PE[ind] >= opt['minpe']))[0]
# Complex coefficients.
rpd = np.pi/180
if coef['aux']['opt']['twodim']:
ap = 0.5 * ((coef['Lsmaj'][ind] + coef['Lsmin'][ind]) *
np.exp(1j*(coef['theta'][ind] - coef['g'][ind]) * rpd))
am = 0.5 * ((coef['Lsmaj'][ind] - coef['Lsmin'][ind]) *
np.exp(1j*(coef['theta'][ind] + coef['g'][ind]) * rpd))
else:
ap = 0.5 * coef['A'][ind] * np.exp(-1j*coef['g'][ind] * rpd)
am = np.conj(ap)
# Exponentials.
ngflgs = [coef['aux']['opt']['nodsatlint'],
coef['aux']['opt']['nodsatnone'],
coef['aux']['opt']['gwchlint'],
coef['aux']['opt']['gwchnone']]
if opt['RunTimeDisp']:
print('prep/calcs ... ', end='')
E = ut_E(t,
coef['aux']['reftime'], coef['aux']['frq'][ind],
coef['aux']['lind'][ind], coef['aux']['lat'], ngflgs,
coef['aux']['opt']['prefilt'])
# Fit.
# fit = E*ap + np.conj(E)*am
fit = np.dot(E, ap) + np.dot(np.conj(E), am)
# Mean (& trend).
u = np.nan * np.ones(tin.shape)
whr = goodmask
if coef['aux']['opt']['twodim']:
v = np.nan * np.ones(tin.shape)
if coef['aux']['opt']['notrend']:
u[whr] = np.real(fit) + coef['umean']
v[whr] = | np.imag(fit) | numpy.imag |
from __future__ import division
import numpy as np
from openmdao.api import ExplicitComponent
from openmdao.api import Group
from .empirical_data.prop_maps import propeller_map_Raymer, propeller_map_highpower, static_propeller_map_Raymer, static_propeller_map_highpower, propeller_map_scaled, propeller_map_constant_prop_efficiency
class SimplePropeller(Group):
"""This propeller is representative of a constant-speed prop.
The technology may be old.
A general, empirical efficiency map for a constant speed turboprop is used for most of the flight regime.
A static thrust coefficient map (from Raymer) is used for advance ratio < 0.2 (low speed).
Linear interpolation from static thrust to dynamic thrust tables at J = 0.1 to 0.2.
Inputs
------
shaft_power_in : float
Shaft power driving the prop (vector, W)
diameter: float
Prop diameter (scalar, m)
rpm : float
Prop RPM (vector, RPM)
fltcond|rho : float
Air density (vector, kg/m**3)
fltcond|Utrue : float
True airspeed (vector, m/s)
Outputs
-------
thrust : float
Propeller thrust (vector, N)
component_weight : float
Prop weight (scalar, kg)
Options
-------
num_nodes : int
Number of analysis points to run (sets vec length; default 1)
num_blades : int
Number of propeller blades (default 4)
design_cp : float
Design cruise power coefficient (cp)
design_J : float
Design advance ratio (J)
"""
def initialize(self):
self.options.declare('num_nodes', default=1, desc='Number of flight/control conditions')
self.options.declare('num_blades', default=4, desc='Number of prop blades')
self.options.declare('design_cp',default=0.2,desc='Design cruise power coefficient cp')
self.options.declare('design_J',default=2.2,desc='Design advance ratio J=V/n/D')
def setup(self):
nn = self.options['num_nodes']
n_blades = self.options['num_blades']
design_J = self.options['design_J']
design_cp = self.options['design_cp']
if n_blades == 3:
propmap = propeller_map_Raymer(nn)
staticpropmap = static_propeller_map_Raymer(nn)
if n_blades == 4:
propmap = propeller_map_highpower(nn)
staticpropmap = static_propeller_map_highpower(nn)
else:
raise NotImplementedError('You will need to define a propeller map valid for this number of blades')
self.add_subsystem('propcalcs',PropCoefficients(num_nodes=nn),promotes_inputs=["*"],promotes_outputs=["*"])
self.add_subsystem('propmap',propmap,promotes_outputs=["*"])
self.add_subsystem('staticpropmap',staticpropmap,promotes_outputs=["*"])
self.add_subsystem('thrustcalc',ThrustCalc(num_nodes=nn), promotes_inputs=["*"], promotes_outputs=["*"])
self.add_subsystem('propweights',WeightCalc(num_blades=n_blades), promotes_inputs=["*"], promotes_outputs=["*"])
self.connect('cp','propmap.cp')
self.connect('cp','staticpropmap.cp')
self.connect('J','propmap.J')
class WeightCalc(ExplicitComponent):
def initialize(self):
self.options.declare('num_blades', default=4, desc='Number of prop blades')
def setup(self):
self.add_input('power_rating', units='hp', desc='Propulsor power rating')
self.add_input('diameter', units='ft', desc='Prop diameter in feet')
self.add_output('component_weight', units='lb', desc='Propeller weight')
self.declare_partials('component_weight',['power_rating','diameter'])
def compute(self, inputs, outputs):
#Method from Roskam SVC6p90eq6.14
Kprop2 = 0.108 #for turboprops
n_blades = self.options['num_blades']
W_prop = Kprop2 * (inputs['diameter']*inputs['power_rating']*n_blades**0.5)**0.782
outputs['component_weight'] = W_prop
def compute_partials(self, inputs, J):
Kprop2 = 0.108 #for turboprops
n_blades = self.options['num_blades']
J['component_weight','power_rating'] = 0.782 * Kprop2 * (inputs['diameter']*inputs['power_rating']*n_blades**0.5)**(0.782-1) * (inputs['diameter']*n_blades**0.5)
J['component_weight','diameter'] = 0.782 * Kprop2 * (inputs['diameter']*inputs['power_rating']*n_blades**0.5)**(0.782-1) * (inputs['power_rating']*n_blades**0.5)
class ThrustCalc(ExplicitComponent):
def initialize(self):
self.options.declare('num_nodes', default=1, desc='Number of flight/control conditions')
def setup(self):
nn = self.options['num_nodes']
self.add_input('cp', desc='power coefficient',shape=(nn,))
self.add_input('eta_prop', desc='propulsive efficiency factor',shape=(nn,))
self.add_input('J', desc = 'advance ratio',shape=(nn,))
self.add_input('fltcond|rho', units='kg / m ** 3', desc='Air density',shape=(nn,))
self.add_input('rpm', units='rpm', val=2500*np.ones(nn), desc='Prop speed in rpm')
self.add_input('diameter', units='m', val=2.5, desc='Prop diameter in m')
self.add_input('ct_over_cp', val=1.5*np.ones(nn), desc='ct/cp from raymer for static condition')
self.add_output('thrust', desc='Propeller thrust', units='N',shape=(nn,))
self.declare_partials('thrust',['cp','eta_prop','J','fltcond|rho','rpm','ct_over_cp'], rows=range(nn), cols=range(nn))
self.declare_partials('thrust','diameter')
def compute(self, inputs, outputs):
#for advance ratio j between 0.10 and 0.20, linearly interpolate the thrust coefficient from the two surrogate models
jinterp_min = 0.10
jinterp_max = 0.20
j = inputs['J']
#print(inputs['eta_prop'])
static_idx = np.where(j<=jinterp_min)
dynamic_idx = np.where(j>=jinterp_max)
tmp = np.logical_and(j>jinterp_min, j<jinterp_max)
interp_idx = np.where(tmp)
cp = inputs['cp']
nn = self.options['num_nodes']
ct = np.zeros(nn)
ct1 = inputs['ct_over_cp'] * cp
ct2 = cp * inputs['eta_prop'] / j
#if j <= jinterp_min:
ct[static_idx] = ct1[static_idx]
#if j > jinterp_min and < jinterp_max:
interv = np.ones(nn)*jinterp_max - np.ones(nn)*jinterp_min
interp1 = (np.ones(nn)*jinterp_max - j) / interv
interp2 = (j - np.ones(nn)*jinterp_min) / interv
ct[interp_idx] = interp1[interp_idx] * ct1[interp_idx] + interp2[interp_idx] * ct2[interp_idx]
#else if j >= jinterp_max
ct[dynamic_idx] = ct2[dynamic_idx]
outputs['thrust'] = ct * inputs['fltcond|rho'] * (inputs['rpm']/60.)**2 * inputs['diameter']**4
def compute_partials(self, inputs, J):
#for advance ratio j between 0.10 and 0.20, linearly interpolate between the two surrogate models
jinterp_min = 0.10
jinterp_max = 0.20
j = inputs['J']
cp = inputs['cp']
nn = self.options['num_nodes']
static_idx = np.where(j<=jinterp_min)
dynamic_idx = np.where(j>=jinterp_max)
tmp = np.logical_and(j>jinterp_min, j<jinterp_max)
interp_idx = np.where(tmp)
dctdcp = np.zeros(nn)
ct1 = inputs['ct_over_cp'] * cp
ct2 = cp * inputs['eta_prop'] / j
dct1dcp = inputs['ct_over_cp']
dct2dcp = inputs['eta_prop'] / j
#if j <= jinterp_min:
dctdcp[static_idx] = dct1dcp[static_idx]
#if j > jinterp_min and < jinterp_max:
interv = np.ones(nn)*jinterp_max - np.ones(nn)*jinterp_min
interp1 = (np.ones(nn)*jinterp_max - j) / interv
interp2 = (j - np.ones(nn)*jinterp_min) / interv
dctdcp[interp_idx] = interp1[interp_idx] * dct1dcp[interp_idx] + interp2[interp_idx] * dct2dcp[interp_idx]
#else if j >= jinterp_max
dctdcp[dynamic_idx] = dct2dcp[dynamic_idx]
ct = cp * dctdcp
j_thrust_ct_over_cp = np.zeros(nn)
j_thrust_eta_prop = np.zeros(nn)
j_thrust_j = np.zeros(nn)
thrust_over_ct = inputs['fltcond|rho'] * (inputs['rpm']/60.)**2 * inputs['diameter']**4
thrust = ct * inputs['fltcond|rho'] * (inputs['rpm']/60.)**2 * inputs['diameter']**4
J['thrust','fltcond|rho'] = thrust / inputs['fltcond|rho']
J['thrust', 'rpm'] = 2 * thrust / inputs['rpm']
J['thrust', 'diameter'] = 4 * thrust / inputs['diameter']
J['thrust', 'cp'] = dctdcp * inputs['fltcond|rho'] * (inputs['rpm']/60.)**2 * inputs['diameter']**4
#if j <= jinterp_min:
j_thrust_ct_over_cp[static_idx] = thrust[static_idx] / inputs['ct_over_cp'][static_idx]
j_thrust_eta_prop[static_idx] = np.zeros(static_idx[0].shape)
j_thrust_j[static_idx] = np.zeros(static_idx[0].shape)
# j < jinterp_max:
j_thrust_ct_over_cp[interp_idx] = thrust_over_ct[interp_idx] * interp1[interp_idx] * (ct1[interp_idx] / inputs['ct_over_cp'][interp_idx])
j_thrust_eta_prop[interp_idx] = thrust_over_ct[interp_idx] * interp2[interp_idx] * (ct2[interp_idx] / inputs['eta_prop'][interp_idx])
j_thrust_j[interp_idx] = thrust_over_ct[interp_idx] * (-ct1[interp_idx] / interv[interp_idx] + ct2[interp_idx] / interv[interp_idx] - interp2[interp_idx] * ct2[interp_idx] / j[interp_idx])
#else:
j_thrust_ct_over_cp[dynamic_idx] = np.zeros(dynamic_idx[0].shape)
j_thrust_eta_prop[dynamic_idx] = thrust[dynamic_idx] / inputs['eta_prop'][dynamic_idx]
j_thrust_j[dynamic_idx] = - thrust[dynamic_idx] / j[dynamic_idx]
J['thrust','ct_over_cp'] = j_thrust_ct_over_cp
J['thrust','eta_prop'] = j_thrust_eta_prop
J['thrust','J'] = j_thrust_j
class PropCoefficients(ExplicitComponent):
def initialize(self):
self.options.declare('num_nodes', default=1, desc='Number of flight/control conditions')
def setup(self):
nn = self.options['num_nodes']
self.add_input('shaft_power_in', units='W', desc='Input shaft power',shape=(nn,), val=5*np.ones(nn))
self.add_input('diameter', units='m', val=2.5, desc='Prop diameter')
self.add_input('rpm', units='rpm', val=2500*np.ones(nn), desc='Propeller shaft speed')
self.add_input('fltcond|rho', units='kg / m ** 3',desc='Air density',shape=(nn,))
self.add_input('fltcond|Utrue', units='m/s', desc='Flight speed',shape=(nn,))
#outputs and partials
self.add_output('cp', desc='Power coefficient', val=0.1*np.ones(nn), lower=np.zeros(nn),upper= | np.ones(nn) | numpy.ones |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# SPDX-FileCopyrightText: 2022 Madureira, Brielen
# SPDX-License-Identifier: MIT
"""
An object to load datasets and create the datapoints for each set.
It loads probes from JSON files and representations from h5 files
and then constructs datasets for the probing classifier task.
"""
import json
import pickle
from collections import Counter, defaultdict
import h5py
import numpy as np
from torch.utils.data import Dataset
from aux import (get_reps_path, get_probes_path, get_test_lens_path,
get_embs_path)
from tasks import get_task_labels
# fixed number of turns in all train/valid dialogues
VISDIAL_LEN = 11
class ProbingDataset(Dataset):
"""Build a dataset split."""
def __init__(self, params, split):
"""
Args:
params (dataclass): All parameters of the experiment.
split (str): Train, valid or test.
"""
self.params = params
self.split = split
self.labels, self.label_names = self._define_labels()
self.representations = self._load_representations()
self.label_counter = Counter()
self.datapoints = {}
self._create_datapoints()
def __len__(self):
"""Return number of datapoints."""
return len(self.datapoints)
def __getitem__(self, index):
"""Retrieve a datapoint given its index."""
dialogue_id, _, sent_id, turn, label = self.datapoints[index]
sent_embedding = self.id2sent[sent_id]
representation = self.representations[dialogue_id, turn]
return (index, representation, sent_embedding, label)
def _define_labels(self):
"""Get labels and their names according to main task."""
return get_task_labels(self.params.bot, self.params.task)
def _load_lens(self):
"""Return dict of dialogue lens, which is constant if not test set."""
if self.split != 'test':
return defaultdict(lambda: VISDIAL_LEN)
path = get_test_lens_path()
with open(path, 'r') as f:
lens = {}
for line in f.readlines():
idx, length = line.strip('\n').split('\t')
lens[idx] = int(length)
return lens
def _load_representations(self):
"""Load dialogue representations."""
path = get_reps_path(self.params, self.split)
name = f'{self.split}_dialogue_representations'
representations = np.array(h5py.File(path, 'r').get(name))
# Define control task
if self.params.control_task == 'rand-reps' and self.split == 'train':
# replace representations by random vectors
np.random.seed(self.params.random_seed)
r_mean = np.mean(representations)
r_std = | np.std(representations) | numpy.std |
# Copyright 2022 The sunds 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.
"""Utils to encode the specs matching `sunds.specs`.
Used during data construction to create the example `dict` yield by
`_generate_examples`.
Using typed dataclass with explicitly named argument guarantee a structure
compatible with the corresponding `sunds.specs`.
There should be a one-to-one matching between `sunds.specs` and
`sunds.specs_utils`. (e.g.
`sunds.specs.frame_spec()` <> `sunds.specs_utils.Frame`).
"""
import dataclasses
import datetime
from typing import Any, Dict, List, Optional, Tuple
import numpy as np
from sunds.core import np_geometry
from sunds.core import specs_base
Array = Any # numpy or any array-like
Image = Any # str, np.array, file-object, pathlib object,...
@dataclasses.dataclass
class Scene(specs_base.SpecBase):
"""Top-level scene."""
scene_name: str
scene_box: Dict[str, Any]
nominal_time: datetime.datetime = dataclasses.field(
default_factory=lambda: datetime.datetime.utcfromtimestamp(0))
frames: List['Frame'] = dataclasses.field(default_factory=list)
@dataclasses.dataclass
class Frame(specs_base.SpecBase):
"""Top-level frame."""
scene_name: str
frame_name: str
pose: 'Pose'
cameras: Dict[str, 'Camera']
timestamp: float = 0.0
# TODO(epot): Remove pose to use Isometry directly
@dataclasses.dataclass
class Pose(specs_base.SpecBase):
"""Pose."""
R: Array # pylint: disable=invalid-name
t: Array
@classmethod
def from_transform_matrix(
cls,
transform_matrix: Array,
*,
convension: str,
) -> 'Pose':
"""Construct the pose frame wrt the scene (frame to scene transform)."""
assert convension == 'blender'
transform_matrix = np.array(transform_matrix)
scene_from_bcam = np_geometry.Isometry.from_matrix(transform_matrix)
# Transformation between blender style camera (+x along left to right,
# +y from bottom to top, +z looking back) to camera system with +x along
# left to right, +y from top to bottom, +z looking forward.
bcam_from_frame = np_geometry.Isometry(
R=np.array([[1.0, 0.0, 0.0], [0, -1.0, 0.0], [0, 0, -1.0]]),
t=np.zeros(3))
scene_from_frame = scene_from_bcam.compose(bcam_from_frame)
return cls(
R=scene_from_frame.R.astype(np.float32),
t=scene_from_frame.t.astype(np.float32),
)
@classmethod
def identity(cls) -> 'Pose':
"""Returns the identity transformation."""
return cls(
R=np.eye(3, dtype=np.float32),
t=np.zeros(3, dtype=np.float32),
)
@dataclasses.dataclass
class Camera(specs_base.SpecBase):
"""Camera."""
intrinsics: 'CameraIntrinsics'
extrinsics: Pose = dataclasses.field(default_factory=Pose.identity)
color_image: Optional[Image] = None
category_image: Optional[Image] = None
@dataclasses.dataclass
class CameraIntrinsics(specs_base.SpecBase):
"""CameraIntrinsics."""
image_width: int
image_height: int
K: Array # pylint: disable=invalid-name
type: str
distortion: Dict[str, Array]
@classmethod
def from_fov(
cls,
*,
img_shape: Tuple[int, int],
fov_in_degree: Tuple[int, int],
type: str = 'PERSPECTIVE', # pylint: disable=redefined-builtin
) -> 'CameraIntrinsics':
"""Returns camera instrinsics data."""
if type != 'PERSPECTIVE':
raise ValueError(
f"Unknown camera type: {type!r}. Only 'PERSPECTIVE' supported")
# Not sure if the height, width order is correct (shouldn't shape be (h, w)
# instead ?
camera_angle_x, camera_angle_y = fov_in_degree
image_width, image_height = img_shape
fx = .5 * image_width / | np.tan(.5 * camera_angle_x) | numpy.tan |
# This file is part of GridCal.
#
# GridCal is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# GridCal is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with GridCal. If not, see <http://www.gnu.org/licenses/>.
import numpy as np
import pandas as pd
import scipy.sparse as sp
from typing import List, Dict
from GridCal.Engine.basic_structures import Logger
import GridCal.Engine.Core.topology as tp
from GridCal.Engine.Core.multi_circuit import MultiCircuit
from GridCal.Engine.basic_structures import BranchImpedanceMode
from GridCal.Engine.basic_structures import BusMode
from GridCal.Engine.Simulations.PowerFlow.jacobian_based_power_flow import Jacobian
from GridCal.Engine.Core.common_functions import compile_types, find_different_states
class OpfTimeCircuit:
def __init__(self, nbus, nline, ntr, nvsc, nhvdc, nload, ngen, nbatt, nshunt, nstagen, ntime, sbase, time_array,
apply_temperature=False, branch_tolerance_mode: BranchImpedanceMode = BranchImpedanceMode.Specified):
"""
:param nbus: number of buses
:param nline: number of lines
:param ntr: number of transformers
:param nvsc:
:param nhvdc:
:param nload:
:param ngen:
:param nbatt:
:param nshunt:
"""
self.nbus = nbus
self.nline = nline
self.ntr = ntr
self.nvsc = nvsc
self.nhvdc = nhvdc
self.nload = nload
self.ngen = ngen
self.nbatt = nbatt
self.nshunt = nshunt
self.nstagen = nstagen
self.ntime = ntime
self.Sbase = sbase
self.apply_temperature = apply_temperature
self.branch_tolerance_mode = branch_tolerance_mode
self.time_array = time_array
# bus ----------------------------------------------------------------------------------------------------------
self.bus_names = np.empty(nbus, dtype=object)
self.bus_types = np.empty(nbus, dtype=int)
self.bus_installed_power = np.zeros(nbus, dtype=float)
self.bus_active = np.ones((ntime, nbus), dtype=int)
self.Vbus = np.ones((ntime, nbus), dtype=complex)
# branch common ------------------------------------------------------------------------------------------------
self.nbr = nline + ntr + nvsc # exclude the HVDC model since it is not a real branch
self.branch_names = np.empty(self.nbr, dtype=object)
self.branch_active = np.zeros((ntime, self.nbr), dtype=int)
self.F = np.zeros(self.nbr, dtype=int) # indices of the "from" buses
self.T = np.zeros(self.nbr, dtype=int) # indices of the "to" buses
self.branch_rates = np.zeros((ntime, self.nbr), dtype=float)
self.branch_cost = np.zeros((ntime, self.nbr), dtype=float)
self.branch_R = np.zeros(self.nbr, dtype=float)
self.branch_X = np.zeros(self.nbr, dtype=float)
self.C_branch_bus_f = sp.lil_matrix((self.nbr, nbus), dtype=int) # connectivity branch with their "from" bus
self.C_branch_bus_t = sp.lil_matrix((self.nbr, nbus), dtype=int) # connectivity branch with their "to" bus
# lines --------------------------------------------------------------------------------------------------------
self.line_names = np.zeros(nline, dtype=object)
self.line_R = np.zeros(nline, dtype=float)
self.line_X = np.zeros(nline, dtype=float)
self.line_B = np.zeros(nline, dtype=float)
self.line_temp_base = np.zeros(nline, dtype=float)
self.line_temp_oper = np.zeros(nline, dtype=float)
self.line_alpha = np.zeros(nline, dtype=float)
self.line_impedance_tolerance = np.zeros(nline, dtype=float)
self.C_line_bus = sp.lil_matrix((nline, nbus), dtype=int) # this ons is just for splitting islands
# transformer 2W + 3W ------------------------------------------------------------------------------------------
self.tr_names = np.zeros(ntr, dtype=object)
self.tr_R = np.zeros(ntr, dtype=float)
self.tr_X = np.zeros(ntr, dtype=float)
self.tr_G = np.zeros(ntr, dtype=float)
self.tr_B = np.zeros(ntr)
self.tr_tap_f = np.ones(ntr) # tap generated by the difference in nominal voltage at the form side
self.tr_tap_t = np.ones(ntr) # tap generated by the difference in nominal voltage at the to side
self.tr_tap_mod = np.ones(ntr) # normal tap module
self.tr_tap_ang = np.zeros(ntr) # normal tap angle
self.C_tr_bus = sp.lil_matrix((ntr, nbus), dtype=int) # this ons is just for splitting islands
# hvdc line ----------------------------------------------------------------------------------------------------
self.hvdc_names = np.zeros(nhvdc, dtype=object)
self.hvdc_active = np.zeros((ntime, nhvdc), dtype=bool)
self.hvdc_rate = np.zeros((ntime, nhvdc), dtype=float)
self.hvdc_Pf = np.zeros((ntime, nhvdc))
self.hvdc_Pt = np.zeros((ntime, nhvdc))
self.C_hvdc_bus_f = sp.lil_matrix((nhvdc, nbus), dtype=int) # this ons is just for splitting islands
self.C_hvdc_bus_t = sp.lil_matrix((nhvdc, nbus), dtype=int) # this ons is just for splitting islands
# vsc converter ------------------------------------------------------------------------------------------------
self.vsc_names = np.zeros(nvsc, dtype=object)
self.vsc_R1 = np.zeros(nvsc)
self.vsc_X1 = np.zeros(nvsc)
self.vsc_Gsw = np.zeros(nvsc)
self.vsc_Beq = np.zeros(nvsc)
self.vsc_m = np.zeros(nvsc)
self.vsc_theta = np.zeros(nvsc)
self.C_vsc_bus = sp.lil_matrix((nvsc, nbus), dtype=int) # this ons is just for splitting islands
# load ---------------------------------------------------------------------------------------------------------
self.load_names = np.empty(nload, dtype=object)
self.load_active = np.zeros((ntime, nload), dtype=bool)
self.load_s = np.zeros((ntime, nload), dtype=complex)
self.load_cost = np.zeros((ntime, nload))
self.C_bus_load = sp.lil_matrix((nbus, nload), dtype=int)
# static generators --------------------------------------------------------------------------------------------
self.static_generator_names = np.empty(nstagen, dtype=object)
self.static_generator_active = np.zeros((ntime, nstagen), dtype=bool)
self.static_generator_s = np.zeros((ntime, nstagen), dtype=complex)
self.C_bus_static_generator = sp.lil_matrix((nbus, nstagen), dtype=int)
# battery ------------------------------------------------------------------------------------------------------
self.battery_names = np.empty(nbatt, dtype=object)
self.battery_controllable = np.zeros(nbatt, dtype=bool)
self.battery_dispatchable = np.zeros(nbatt, dtype=bool)
self.battery_pmin = np.zeros(nbatt)
self.battery_pmax = np.zeros(nbatt)
self.battery_enom = np.zeros(nbatt)
self.battery_min_soc = np.zeros(nbatt)
self.battery_max_soc = np.zeros(nbatt)
self.battery_soc_0 = np.zeros(nbatt)
self.battery_charge_efficiency = np.zeros(nbatt)
self.battery_discharge_efficiency = np.zeros(nbatt)
self.battery_installed_p = np.zeros(nbatt)
self.battery_active = np.zeros((ntime, nbatt), dtype=bool)
self.battery_p = np.zeros((ntime, nbatt))
self.battery_pf = np.zeros((ntime, nbatt))
self.battery_v = np.zeros((ntime, nbatt))
self.battery_cost = np.zeros((ntime, nbatt))
self.C_bus_batt = sp.lil_matrix((nbus, nbatt), dtype=int)
# generator ----------------------------------------------------------------------------------------------------
self.generator_names = np.empty(ngen, dtype=object)
self.generator_controllable = np.zeros(ngen, dtype=bool)
self.generator_dispatchable = np.zeros(ngen, dtype=bool)
self.generator_installed_p = np.zeros(ngen)
self.generator_pmin = np.zeros(ngen)
self.generator_pmax = np.zeros(ngen)
self.generator_active = np.zeros((ntime, ngen), dtype=bool)
self.generator_p = | np.zeros((ntime, ngen)) | numpy.zeros |
from __future__ import print_function
import glob
import os
import random
import re
from math import ceil
import numpy as np
import scipy.misc
from PIL import Image
import laspy
def atoi(text):
return int(text) if text.isdigit() else text
def natural_keys(text):
'''
alist.sort(key=natural_keys) sorts in human order
http://nedbatchelder.com/blog/200712/human_sorting.html
(See Toothy's implementation in the comments)
'''
return [ atoi(c) for c in re.split('(\d+)', text) ]
# Data providers for dbnet-2018 data
class Provider:
def __init__(self, train_dir='data/dbnet-2018/train/',
val_dir='data/dbnet-2018/val/',
test_dir="data/dbnet-2018/test/"):
self.__initialize__(train_dir, val_dir, test_dir)
self.read()
self.transform()
def __initialize__(self, train_dir, val_dir, test_dir):
self.X_train1, self.X_train2 = [], []
self.Y_train1, self.Y_train2 = [], []
self.X_val1, self.X_val2 = [], []
self.Y_val1, self.Y_val2 = [], []
self.X_test1, self.X_test2 = [], []
self.x_train1, self.x_train2 = [], []
self.x_val1, self.x_val2 = [], []
self.x_test1, self.x_test2 = [], []
self.train_pointer = 0
self.val_pointer = 0
self.test_pointer = 0
self.train_dir = train_dir
self.val_dir = val_dir
self.test_dir = test_dir
self.cache_train = False
self.cache_val = False
self.cache_test = False
def read(self, filename="behavior.csv"):
"""
Read data and labels
:param filename: filename of labels
"""
train_sub = glob.glob(os.path.join(self.train_dir, "*"))
val_sub = glob.glob(os.path.join(self.val_dir, "*"))
test_sub = glob.glob(os.path.join(self.test_dir, "*"))
train_sub.sort(key=natural_keys)
val_sub.sort(key=natural_keys)
self.read_from(train_sub, filename, "train")
self.read_from(val_sub, filename, "val")
self.read_from(test_sub, filename, "test")
def read_from(self, sub_folders, filename, description="train"):
if description == "train":
X_train1, X_train2 = self.X_train1, self.X_train2
Y_train1, Y_train2 = self.Y_train1, self.Y_train2
elif description == "val":
X_train1, X_train2 = self.X_val1, self.X_val2
Y_train1, Y_train2 = self.Y_val1, self.Y_val2
elif description == "test":
X_train1, X_train2 = self.X_test1, self.X_test2
else:
raise NotImplementedError
if not description == "test":
for folder in sub_folders:
with open(os.path.join(folder, filename)) as f:
count = 0
for line in f:
line = line.rstrip()
X_train1.append(os.path.join(folder, "dvr_66x200/" + str(count) + ".jpg"))
X_train2.append(os.path.join(folder, "points_16384/" + str(count) + ".las"))
Y_train1.append((float(line.split(",")[1]) - 20) / 20)
Y_train2.append(float(line.split(",")[0]) * scipy.pi / 180)
count += 1
else:
for folder in sub_folders:
for count in range(len(glob.glob(os.path.join(folder, "dvr_66x200/*.jpg")))):
X_train1.append(os.path.join(folder, "dvr_66x200/" + str(count) + ".jpg"))
X_train2.append(os.path.join(folder, "points_16384/" + str(count) + ".las"))
if not description == "test":
c = list(zip(X_train1, X_train2, Y_train1, Y_train2))
else:
c = list(zip(X_train1, X_train2))
random.shuffle(c)
if description == "train":
self.X_train1, self.X_train2, self.Y_train1, self.Y_train2 = zip(*c)
elif description == "val":
self.X_val1, self.X_val2, self.Y_val1, self.Y_val2 = zip(*c)
elif description == "test":
self.X_test1, self.X_test2 = zip(*c)
else:
raise NotImplementedError
def transform(self):
self.X_train1, self.X_train2 = np.asarray(self.X_train1), np.asarray(self.X_train2)
self.Y_train = np.transpose(np.asarray((self.Y_train1, self.Y_train2)))
self.X_val1, self.X_val2 = np.asarray(self.X_val1), np.asarray(self.X_val2)
self.Y_val = np.transpose(np.asarray((self.Y_val1, self.Y_val2)))
self.num_test = len(self.X_test1)
self.X_test1, self.X_test2 = np.asarray(self.X_test1), np.asarray(self.X_test2)
self.num_train = len(self.Y_train)
self.num_val = len(self.Y_val)
def load_one_batch(self, batch_size, description='train', shape=[66, 200], reader_type="pn"):
x_out1 = []
x_out2 = []
y_out = []
if description == 'train':
if not self.cache_train:
print ("Loading training data ...")
for i in range(self.num_train):
with Image.open(self.X_train1[i]) as img:
self.x_train1.append(scipy.misc.imresize(img, shape) / 255.0)
# too many opened files
"""
self.x_train1.append(scipy.misc.imresize(scipy.misc.imread(
self.X_train1[i]), shape) / 255.0)
"""
infile = laspy.file.File(self.X_train2[i])
data = np.vstack([infile.X, infile.Y, infile.Z]).transpose()
infile.close()
self.x_train2.append(data)
self.cache_train = True
print ("Finished loading!")
for i in range(0, batch_size):
index = (self.train_pointer + i) % len(self.X_train1)
x_out1.append(self.x_train1[index])
x_out2.append(self.x_train2[index])
y_out.append(self.Y_train[index])
self.train_pointer += batch_size
elif description == "val":
if not self.cache_val:
print ("Loading validation data ...")
for i in range(0, self.num_val):
with Image.open(self.X_val1[i]) as img:
self.x_val1.append(scipy.misc.imresize(img, shape) / 255.0)
# too many opened files
"""
self.x_val1.append(scipy.misc.imresize(scipy.misc.imread(
self.X_val1[i]), shape) / 255.0)
"""
infile = laspy.file.File(self.X_val2[i])
data = np.vstack([infile.X, infile.Y, infile.Z]).transpose()
infile.close()
self.x_val2.append(data)
self.cache_val = True
print ("Finished loading!")
for i in range(0, batch_size):
index = (self.val_pointer + i) % len(self.X_val1)
x_out1.append(self.x_val1[index])
x_out2.append(self.x_val2[index])
y_out.append(self.Y_val[index])
self.val_pointer += batch_size
elif description == "test":
if not self.cache_test:
print ("Loading testing data ...")
for i in range(0, self.num_test):
with Image.open(self.X_test1[i]) as img:
self.x_test1.append(scipy.misc.imresize(img, shape) / 255.0)
"""
self.x_test1.append(scipy.misc.imresize(scipy.misc.imread(
self.X_test1[i]), shape) / 255.0)
"""
infile = laspy.file.File(self.X_test2[i])
data = np.vstack([infile.X, infile.Y, infile.Z]).transpose()
infile.close()
self.x_test2.append(data)
self.cache_test = True
print ("Finished loading!")
for i in range(0, batch_size):
index = (self.test_pointer + i) % len(self.X_test1)
x_out1.append(self.x_test1[index])
x_out2.append(self.x_test2[index])
self.test_pointer += batch_size
else:
raise NotImplementedError
if not description == "test":
if reader_type == "io": return np.stack(x_out1), np.stack(y_out)
else: return np.stack(x_out1), np.stack(x_out2), np.stack(y_out)
else:
if reader_type == "io": return np.stack(x_out1)
else: return np.stack(x_out1), np.stack(x_out2)
## Data provider for test in server
class Provider2:
def __init__(self, test_dir="data/dbnet-2018/test/"):
self.__initialize__(test_dir)
self.read()
self.transform()
def __initialize__(self, test_dir):
self.X_test1, self.X_test2 = [], []
self.Y_test1, self.Y_test2 = [], []
self.x_test1, self.x_test2 = [], []
self.test_pointer = 0
self.test_dir = test_dir
self.cache_test = False
def read(self, filename="behavior.csv"):
"""
Read data and labels
:param filename: filename of labels
"""
test_sub = glob.glob(os.path.join(self.test_dir, "*"))
test_sub.sort(key=natural_keys)
self.read_from(test_sub, filename)
def read_from(self, sub_folders, filename):
X_test1, X_test2 = self.X_test1, self.X_test2
Y_test1, Y_test2 = self.Y_test1, self.Y_test2
for folder in sub_folders:
with open(os.path.join(folder, filename)) as f:
count = 0
for line in f:
line = line.rstrip()
X_test1.append(os.path.join(folder, "dvr_66x200/" + str(count) + ".jpg"))
X_test2.append(os.path.join(folder, "points_16384/" + str(count) + ".las"))
Y_test1.append((float(line.split(",")[1]) - 20) / 20)
Y_test2.append(float(line.split(",")[0]) * scipy.pi / 180)
count += 1
c = list(zip(X_test1, X_test2, Y_test1, Y_test2))
# random.shuffle(c)
self.X_test1, self.X_test2, self.Y_test1, self.Y_test2 = zip(*c)
def transform(self):
self.num_test = len(self.X_test1)
self.X_test1, self.X_test2 = np.asarray(self.X_test1), np.asarray(self.X_test2)
self.Y_test = np.transpose( | np.asarray((self.Y_test1, self.Y_test2)) | numpy.asarray |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Built-in imports
import itertools
# 3rd party imports
import numpy as np
from scipy import constants
# Local imports
from ..pyrf import resample, ts_scalar
__author__ = "<NAME>"
__email__ = "<EMAIL>"
__copyright__ = "Copyright 2020-2021"
__license__ = "MIT"
__version__ = "2.3.7"
__status__ = "Prototype"
def calculate_epsilon(vdf, model_vdf, n_s, sc_pot, **kwargs):
r"""Calculates epsilon parameter using model distribution.
Parameters
----------
vdf : xarray.Dataset
Observed particle distribution (skymap).
model_vdf : xarray.Dataset
Model particle distribution (skymap).
n_s : xarray.DataArray
Time series of the number density.
sc_pot : xarray.DataArray
Time series of the spacecraft potential.
**kwargs : dict
Keyword arguments.
Returns
-------
epsilon : xarray.DataArray
Time series of the epsilon parameter.
Other Parameters
----------------
en_channels : array_like
Set energy channels to integrate over [min max]; min and max between
must be between 1 and 32.
Examples
--------
>>> from pyrfu import mms
>>> options = {"en_channel": [4, 32]}
>>> eps = mms.calculate_epsilon(vdf, model_vdf, n_s, sc_pot, **options)
"""
# Default energy channels used to compute epsilon, lowest energy channel
# should not be used.
energy_range = kwargs.get("en_channels", [2, 32])
int_energies = np.arange(energy_range[0], energy_range[1] + 1)
# Resample sc_pot
sc_pot = resample(sc_pot, n_s)
# Remove zero count points from final calculation
# model_vdf.data.data[vdf.data.data <= 0] = 0
model_vdf /= 1e18
vdf /= 1e18
vdf_diff = np.abs(vdf.data.data - model_vdf.data.data)
# Define constants
q_e = constants.elementary_charge
# Check whether particles are electrons or ions
if vdf.attrs["specie"] == "e":
m_s = constants.electron_mass
print("notice : Particles are electrons")
elif vdf.attrs["specie"] == "i":
sc_pot.data *= -1
m_s = constants.proton_mass
print("notice : Particles are electrons")
else:
raise ValueError("Invalid specie")
# Define lengths of variables
n_ph = len(vdf.phi.data[0, :])
# Define corrected energy levels using spacecraft potential
energy_arr = vdf.energy.data
v_s, delta_v = [np.zeros(energy_arr.shape) for _ in range(2)]
for i in range(len(vdf.time)):
energy_vec = energy_arr[i, :]
energy_log = np.log10(energy_arr[i, :])
v_s[i, :] = np.real(
| np.sqrt(2 * (energy_vec - sc_pot.data[i]) * q_e / m_s) | numpy.sqrt |
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 24 13:07:39 2018
@author: nvidia
"""
###############################################################################
import numpy as np
###############################################################################
from pyro.dynamic import mechanical
###############################################################################
###############################################################################
class SinglePendulum( mechanical.MechanicalSystem ):
"""
"""
############################
def __init__(self):
""" """
# initialize standard params
mechanical.MechanicalSystem.__init__(self, 1 )
# Name
self.name = 'Single Pendulum'
# params
self.setparams()
#############################
def setparams(self):
""" Set model parameters here """
# kinematic
self.l1 = 2
self.lc1 = 1
# dynamic
self.m1 = 1
self.I1 = 1
self.gravity = 9.81
self.d1 = 0
##############################
def trig(self, q ):
""" Compute cos and sin """
c1 = np.cos( q )
s1 = np.sin( q )
return [c1,s1]
###########################################################################
def H(self, q ):
"""
Inertia matrix
----------------------------------
dim( H ) = ( dof , dof )
such that --> Kinetic Energy = 0.5 * dq^T * H(q) * dq
"""
H = np.zeros((self.dof,self.dof))
H[0,0] = self.m1 * self.lc1**2 + self.I1
return H
###########################################################################
def C(self, q , dq ):
"""
Corriolis and Centrifugal Matrix
------------------------------------
dim( C ) = ( dof , dof )
such that --> d H / dt = C + C^T
"""
C = np.zeros((self.dof,self.dof))
return C
###########################################################################
def B(self, q ):
"""
Actuator Matrix : dof x m
"""
B = np.diag( np.ones( self.dof ) ) # identity matrix
return B
###########################################################################
def g(self, q ):
"""
Gravitationnal forces vector : dof x 1
"""
g = np.zeros( self.dof )
[c1,s1] = self.trig( q )
g[0] = self.m1 * self.gravity * self.lc1 * s1
return g
###########################################################################
def d(self, q , dq ):
"""
State-dependent dissipative forces : dof x 1
"""
d = np.zeros( self.dof )
d[0] = self.d1 * dq[0]
return d
###########################################################################
# Graphical output
###########################################################################
###########################################################################
def forward_kinematic_domain(self, q ):
"""
"""
l = 5
domain = [ (-l,l) , (-l,l) , (-l,l) ]#
return domain
###########################################################################
def forward_kinematic_lines(self, q ):
"""
Compute points p = [x;y;z] positions given config q
----------------------------------------------------
- points of interest for ploting
Outpus:
lines_pts = [] : a list of array (n_pts x 3) for each lines
"""
lines_pts = [] # list of array (n_pts x 3) for each lines
# ground line
pts = np.zeros(( 2 , 3 ))
pts[0,:] = np.array([-10,0,0])
pts[1,:] = np.array([+10,0,0])
lines_pts.append( pts )
# pendulum
pts = np.zeros(( 2 , 3 ))
pts[0,:] = np.array([0,0,0])
[c1,s1] = self.trig( q )
pts[1,:] = np.array([ s1 * self.l1 , - c1 * self.l1 ,0])
lines_pts.append( pts )
return lines_pts
##############################################################################
class DoublePendulum( mechanical.MechanicalSystem ):
"""
"""
############################
def __init__(self):
""" """
# initialize standard params
mechanical.MechanicalSystem.__init__(self, 2)
# Name
self.name = 'Double Pendulum'
# params
self.setparams()
#############################
def setparams(self):
""" Set model parameters here """
self.l1 = 1
self.l2 = 1
self.lc1 = 1
self.lc2 = 1
self.m1 = 1
self.I1 = 0
self.m2 = 1
self.I2 = 0
self.gravity = 9.81
self.d1 = 0
self.d2 = 0
##############################
def trig(self, q ):
"""
Compute cos and sin usefull in other computation
------------------------------------------------
"""
c1 = np.cos( q[0] )
s1 = np.sin( q[0] )
c2 = np.cos( q[1] )
s2 = np.sin( q[1] )
c12 = np.cos( q[0] + q[1] )
s12 = np.sin( q[0] + q[1] )
return [c1,s1,c2,s2,c12,s12]
###########################################################################
def H(self, q ):
"""
Inertia matrix
----------------------------------
dim( H ) = ( dof , dof )
such that --> Kinetic Energy = 0.5 * dq^T * H(q) * dq
"""
[c1,s1,c2,s2,c12,s12] = self.trig( q )
H = np.zeros((2,2))
H[0,0] = self.m1 * self.lc1**2 + self.I1 + self.m2 * ( self.l1**2 + self.lc2**2 + 2 * self.l1 * self.lc2 * c2 ) + self.I2
H[1,0] = self.m2 * self.lc2**2 + self.m2 * self.l1 * self.lc2 * c2 + self.I2
H[0,1] = H[1,0]
H[1,1] = self.m2 * self.lc2 ** 2 + self.I2
return H
###########################################################################
def C(self, q , dq ):
"""
Corriolis and Centrifugal Matrix
------------------------------------
dim( C ) = ( dof , dof )
such that --> d H / dt = C + C^T
"""
[c1,s1,c2,s2,c12,s12] = self.trig( q )
h = self.m2 * self.l1 * self.lc2 * s2
C = np.zeros((2,2))
C[0,0] = - h * dq[1]
C[1,0] = h * dq[0]
C[0,1] = - h * ( dq[0] + dq[1] )
C[1,1] = 0
return C
###########################################################################
def B(self, q ):
"""
Actuator Matrix : dof x m
"""
B = np.diag( np.ones( self.dof ) ) # identity matrix
return B
###########################################################################
def g(self, q ):
"""
Gravitationnal forces vector : dof x 1
"""
[c1,s1,c2,s2,c12,s12] = self.trig( q )
g1 = (self.m1 * self.lc1 + self.m2 * self.l1 ) * self.gravity
g2 = self.m2 * self.lc2 * self.gravity
G = np.zeros(2)
G[0] = - g1 * s1 - g2 * s12
G[1] = - g2 * s12
return G
###########################################################################
def d(self, q , dq ):
"""
State-dependent dissipative forces : dof x 1
"""
D = np.zeros((2,2))
D[0,0] = self.d1
D[1,0] = 0
D[0,1] = 0
D[1,1] = self.d2
d = np.dot( D , dq )
return d
###########################################################################
# Graphical output
###########################################################################
###########################################################################
def forward_kinematic_domain(self, q ):
"""
"""
l = 3
domain = [ (-l,l) , (-l,l) , (-l,l) ]#
return domain
###########################################################################
def forward_kinematic_lines(self, q ):
"""
Compute points p = [x;y;z] positions given config q
----------------------------------------------------
- points of interest for ploting
Outpus:
lines_pts = [] : a list of array (n_pts x 3) for each lines
"""
lines_pts = [] # list of array (n_pts x 3) for each lines
###############################
# ground line
###############################
pts = np.zeros(( 2 , 3 ))
pts[0,:] = | np.array([-10,0,0]) | numpy.array |
import os
import time
import os.path as osp
import numpy as np
from PIL import Image
import cv2
from torch.utils import data
import pickle
import torchvision.transforms.functional as TF
import random
Image.MAX_IMAGE_PIXELS = 2300000000
class MyTrainDataSet(data.Dataset):
def __init__(self, root='', list_path='', max_iters=None, transform=None):
self.root = root
self.list_path = list_path
self.img_ids = [i_id.strip() for i_id in open(list_path)]
if not max_iters == None:
self.img_ids = self.img_ids * int(np.ceil(float(max_iters) / len(self.img_ids)))
self.files = []
self.transform = transform
for name in self.img_ids:
img_name, label_name = name.split()
img_file = osp.join(self.root, img_name)
label_file = osp.join(self.root, label_name)
self.files.append({
"img": img_file,
"label": label_file,
"name": name,
})
print("length of train set: ", len(self.files))
def __len__(self):
return len(self.files)
def __getitem__(self, index):
datafiles = self.files[index]
# print(datafiles)
image = Image.open(datafiles["img"]).convert('RGB')
label = Image.open(datafiles["label"])
# label = cv2.imread(datafiles["label"], -1)
# label = convert_to_msk(label)
size = image.size
name = datafiles["name"]
# image, label = co_transforms(image, label)
if self.transform is not None:
image = self.transform(image)
label = np.array(label)
print(image.shape)
return image, label.copy(), np.array(size), name
class MyValDataSet(data.Dataset):
def __init__(self, root='', list_path='', transform=None):
self.root = root
self.list_path = list_path
self.img_ids = [i_id.strip() for i_id in open(list_path)]
self.files = []
self.transform = transform
for name in self.img_ids:
img_name, label_name = name.split()
img_file = osp.join(self.root, img_name)
label_file = osp.join(self.root, label_name)
# print(label_file)
self.files.append({
"img": img_file,
"label": label_file,
"name": name,
})
print("length of Validation set: ", len(self.files))
def __len__(self):
return len(self.files)
def __getitem__(self, index):
datafiles = self.files[index]
image = Image.open(datafiles["img"]).convert('RGB')
label = Image.open(datafiles["label"])
size = image.size
name = datafiles["name"]
# image, label = co_transforms(image, label)
if self.transform is not None:
image = self.transform(image)
label = np.array(label)
return image, label.copy(), np.array(size), name
class MyTestDataSet(data.Dataset):
def __init__(self, root='', list_path='', transform=None):
self.root = root
self.list_path = list_path
self.img_ids = [i_id.strip() for i_id in open(list_path)]
self.files = []
self.transform = transform
for name in self.img_ids:
img_name = name.strip()
# img_name, label_name = name.split()
img_file = osp.join(self.root, img_name)
# label_file = osp.join(self.root, label_name)
self.files.append({
"img": img_file,
# "label": label_file,
"name": name.split('/')[1].replace('.jpg', ''),
})
print("lenth of test set ", len(self.files))
def __len__(self):
return len(self.files)
def __getitem__(self, index):
datafiles = self.files[index]
image = Image.open(datafiles["img"]).convert('RGB')
size = image.size
name = datafiles["name"]
if self.transform is not None:
image = self.transform(image)
# return image.copy(), np.array(size), name
return image, np.array(size), name
class MyTrainInform:
""" To get statistical information about the train set, such as mean, std, class distribution.
The class is employed for tackle class imbalance.
"""
def __init__(self, data_dir='', classes=7, train_set_file="",
inform_data_file="", normVal=1.10):
"""
Args:
data_dir: directory where the dataset is kept
classes: number of classes in the dataset
inform_data_file: location where cached file has to be stored
normVal: normalization value, as defined in ERFNet paper
"""
self.data_dir = data_dir
self.classes = classes
self.classWeights = np.ones(self.classes, dtype=np.float32)
self.normVal = normVal
self.mean = np.zeros(3, dtype=np.float32)
self.std = np.zeros(3, dtype=np.float32)
self.train_set_file = train_set_file
self.inform_data_file = inform_data_file
def compute_class_weights(self, histogram):
"""to compute the class weights
Args:
histogram: distribution of class samples
"""
normHist = histogram / np.sum(histogram)
for i in range(self.classes):
self.classWeights[i] = 1 / ( | np.log(self.normVal + normHist[i]) | numpy.log |
# -*- coding: utf-8 -*-
"""
Created on Fri Nov 26 17:52:26 2021
@author: eng-Moshira
"""
import offtask
import math
import numpy as np
#import csv
from collections import deque
from Cloud import Cloud
from MEC import MEC
#from generate_states import read_state_from_file, get_initial_state, get_next_state
from UAV import UAV
from systemparameters import parameter
sconst=np.random.randint(1,5)*10**-3
## Variables
numOfUAV = 3 # Number of drones
numofMEC=3 # Number of MECs
numofUsers=10 # Number of users
numoftasks=50 # Number of Tasks
omega=.5
# mu = 5
# sigma = 0.15 * mu
#B = sigma * np.random.randn(numOfUAV) + mu # Available bandwidth of each drone
#T_max = np.random.randint(2, 10, size=numOfTask) # The maximum execution time allowed for each task
no_epsoides=15000 # epsoides no(uav-assisted) ,we may try 140000
s = 1000 # The number of cpu cycles required for unit bit processing is 1000
uv=UAV()
class multi_tier_env():
#U = 3 # UAV no.
def __init__(self):
self.ground_length = ground_width = 300 # The length and width of the site are both 300m,
self.UAV_hieght=100 # self.battery = Energy()
self.exe_delay = 0
self.trans_delay = 0
self.proc_energy = 0
self.trans_energy = 0
self.tot_off_cost = 0
self.total_cost = 0
self.count_wrong=0
self.waiting=deque()
self.new_queue = 0
self.info=[self.exe_delay , self.proc_energy]
self.done=False
self.is_off=[0]*(numoftasks)
self.progress=[0]*(numoftasks)
self.T=400 # total Period 400s
self.slot_num = int(self.T / 8) # 40 intervals
self.alloc_resource = [0] * (numoftasks) # 分配的资源
self.numofresources=numOfUAV+numofMEC+1
self.rest_resource = [0] * self.numofresources
#self.offtasks=self.gen_Task_List()
self.offtasks=self.get_task_info()
self.high=[1,1,1,1,1]
self.low=[-1,-1,-1,-1,-1]
self.uavs_locs=uv.uav_loc
#################### UEs ####################
# self.block_flag_list = np.random.randint(0, 2,numofUsers) # 4 ue, ue occlusion situation
self.loc_ue_list = np.random.randint(0, 301, size=[numofUsers, 2]) # Location information: x is random at 0-100
# #self.task_list = np.random.randint(1572864, 2097153, M) # Random calculation task 1.5~2Mbits -> Corresponding total task size 60
# #self.task_list = np.random.randint(2097153, 2621440, M) # Random calculation task 2~2.5Mbits -> 80
# self.Task_list=self.get_task_info(numoftasks) #generate rondom task list
self.action_bound = [-1, 1] # corresponds to tahn activation function
self.action_dim=5 # 1st digit represent ue id of the task;the next two digit represent the offloading layer selected;the last two digits represent the selected server id
#action_dim = 4 # The first digit represents the ue id of the service; the middle two digits represent the flight angle and distance; the last digit represents the current unloading rate serving the UE
#self.state_dim = 7 + numoftasks * numofUsers # uav battery remain, uav loc, remaining sum task size, all ue loc, all ue task data, all ue block_flag,uav remaining capacity,mec remaining capacity
self.state_dim = numoftasks*2+self.numofresources #+2*numofUsers+2*numOfUAV
#################### MECs,UAVs,Cloud ####################
self.mecs_info = [MEC() for i in range(numofMEC)]
self.uavs_info = [UAV() for i in range(numOfUAV)]
self.cloud_info = Cloud()
self.user_inf=[User() for i in range(numofUsers)]
# uav loc, all mec data, all ue loc, all ue task size, all ue block_flag
#self.task_data=self.get_tasks_data(numoftasks, numofUsers)
#print(task_data)
def get_tasks_data(self,numoftasks,numofUsers):
tasks_data= | np.zeros((numofUsers,numoftasks)) | numpy.zeros |
#!/usr/bin/env python
#************************************************************************
#
# Plot figures and output numbers for Fraction of Absorbed Photosynthetic Radiation (FPR) section.
# For BAMS SotC 2016
#
#************************************************************************
# SVN Info
# $Rev:: 30 $: Revision of last commit
# $Author:: rdunn $: Author of last commit
# $Date:: 2021-06-15 10:41:02 +0100 (Tue, 15 Jun #$: Date of last commit
#************************************************************************
# START
#************************************************************************
import struct
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import MultipleLocator
import utils # RJHD utilities
import settings
DATALOC = "{}/{}/data/FPR/".format(settings.ROOTLOC, settings.YEAR)
LEGEND_LOC = 'lower left'
LW = 2
DURATION = (int(settings.YEAR)-1998+1)*12
minor_tick_interval = 1
minorLocator = MultipleLocator(minor_tick_interval)
print("faking time axis - monthly")
times = np.arange(0, DURATION/12., 1/12.) + 1998
#************************************************************************
def read_binary(filename):
'''
Read from binary file - using "struct"
:param str filename: file to read
:returns: np.array
'''
with open(filename, "rb") as f:
fileContent = f.read()
data = struct.unpack("d" * (len(fileContent) // 8), fileContent)
return np.array(data) # read_binary
#************************************************************************
def read_binary_ts(filename):
'''
Read from binary file - using "struct"
:param str filename: file to read
:returns: np.array
'''
with open(filename, "rb") as f:
fileContent = f.read()
globe = np.array(struct.unpack("d" * (DURATION), fileContent[:DURATION*8]))
north = np.array(struct.unpack("d" * (DURATION), fileContent[DURATION*8:DURATION*8*2]))
south = np.array(struct.unpack("d" * (DURATION), fileContent[DURATION*8*2:DURATION*8*3]))
aver = struct.unpack("f" * (DURATION*4), fileContent[DURATION*8*3:])
aver = np.array(aver).reshape(4, DURATION)
globe = utils.Timeseries("Globe", times, globe)
north = utils.Timeseries("N. Hemisphere", times, north)
south = utils.Timeseries("S. Hemisphere", times, south)
aver = np.ma.masked_where(aver == 0, aver) # remove first/last bits and line should span any inadvertent gaps
globe_sm = utils.Timeseries("Globe Smoothed", times, aver[0, :])
north_sm = utils.Timeseries("N. Hemisphere Smoothed", times, aver[1, :])
south_sm = utils.Timeseries("S. Hemisphere Smoothed", times, aver[2, :])
return [globe, north, south, globe_sm, north_sm, south_sm] # read_binary_ts
#************************************************************************
def run_all_plots():
#************************************************************************
# Timeseries
data = read_binary_ts(DATALOC + "TimeSeries_faparanomaliesglobal_bams_v2018_C6_{}.bin".format(int(settings.YEAR)+1))
fig = plt.figure(figsize=(8, 6))
ax = plt.axes([0.16, 0.07, 0.82, 0.88])
COLOURS = settings.COLOURS["land_surface"]
for dataset in data:
print(dataset.name)
ls = "-."
lw = 1
if dataset.name.split(" ")[-1] == "Smoothed":
ls = "-"
lw = LW
ax.plot(dataset.times, dataset.data, c=COLOURS[dataset.name], ls=ls, label=dataset.name, lw=lw)
ax.axhline(0, c='0.5', ls='--')
utils.thicken_panel_border(ax)
ax.legend(loc=LEGEND_LOC, ncol=2, frameon=False, prop={'size':settings.LEGEND_FONTSIZE}, labelspacing=0.1, columnspacing=0.5)
#*******************
# prettify
fig.text(0.01, 0.5, "Anomaly (FAPAR)", va='center', rotation='vertical', fontsize=settings.FONTSIZE)
plt.xlim([1998-1, int(settings.YEAR)+2])
plt.ylim([-0.022, None])
for tick in ax.yaxis.get_major_ticks():
tick.label.set_fontsize(settings.FONTSIZE)
ax.xaxis.set_minor_locator(minorLocator)
for tick in ax.xaxis.get_major_ticks():
tick.label.set_fontsize(settings.FONTSIZE)
plt.savefig(settings.IMAGELOC + "FPR_ts{}".format(settings.OUTFMT))
plt.close()
#************************************************************************
# Hovmullers
data = read_binary(DATALOC + "Hovmuller_Global_lat_fapar1998_2010_bams_trois_C6.eps_{}.bin".format(int(settings.YEAR)+1))
# reshape - from Readme
data = data.reshape(360, DURATION)
data = np.ma.masked_where(data == 0., data)
lats = | np.arange(-90, 90, 0.5) | numpy.arange |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import copy
from .image import transform_preds
def get_pred_depth(depth):
return depth
def get_alpha(rot):
# output: (B, 8) [bin1_cls[0], bin1_cls[1], bin1_sin, bin1_cos,
# bin2_cls[0], bin2_cls[1], bin2_sin, bin2_cos]
# return rot[:, 0]
idx = rot[:, 1] > rot[:, 5]
alpha1 = np.arctan(rot[:, 2] / rot[:, 3]) + (-0.5 * np.pi)
alpha2 = np.arctan(rot[:, 6] / rot[:, 7]) + ( 0.5 * np.pi)
return alpha1 * idx + alpha2 * (1 - idx)
def dbmctdet_post_process(detections, c, s, h, w, scale, num_classes, ori_threshold):
ret = []
for i in range(detections.shape[0]):
top_preds = {}
# Apply transformation to predicteed bbox
detections[i, :, 0:2] = transform_preds(
detections[i, :, 0:2], c[i], s[i], (w, h))
detections[i, :, 2:4] = transform_preds(
detections[i, :, 2:4], c[i], s[i], (w, h))
detections[i, :, 0:4] /= scale
# classes = detections[i, :, -1]
# Dump bbox whose central region has no center point
detections = | np.concatenate(detections, axis=1) | numpy.concatenate |
# uncomment for training on AMD GPUs
# import plaidml.keras
# plaidml.keras.install_backend()
from keras.callbacks import ModelCheckpoint
from keras.models import Sequential
from keras.layers import Cropping2D, Flatten, Dense, Dropout, Lambda
from keras.layers.convolutional import Conv2D
import matplotlib.pyplot as plt
import numpy as np
import csv
import cv2
import random
# Training data was generated for different scenarios for each track;
# to make it easier to organize or re-record data, we split up data across multiple files
training_data_files = [
'./training-data-new/track-1-forwards/driving_log.csv',
'./training-data-new/track-1-reverse/driving_log.csv',
'./training-data-new/track-1-recovery/driving_log.csv',
'./training-data-new/track-1-curves/driving_log.csv',
'./training-data-new/track-2-forwards/driving_log.csv',
'./training-data-new/track-2-reverse/driving_log.csv',
'./training-data-new/track-2-recovery/driving_log.csv',
'./training-data-new/track-2-curves/driving_log.csv',
]
lines = []
# Iterate through each file and combine all the training data lines together
for i in range(len(training_data_files)):
with open(training_data_files[i]) as csvfile:
reader = csv.reader(csvfile)
for line in reader:
lines.append(line)
# Output summary of what was just read into memory, for sanity check purposes
print('Read {} lines'.format(len(lines)))
# We add/subtract correction_factor from the steering angle measurement to generate new measurements
# for the side camera images
correction_factor = 0.2
# percentage of images we want to use for validation
validation_fraction = 0.25
def validation_or_training(training, validation, data):
"""
Training, validation, and data are all tuples; at random we put data into the training or validation set
"""
is_validation = True if random.uniform(0, 1.0) < validation_fraction else False
if is_validation:
validation[0].append(data[0])
validation[1].append(data[1])
else:
training[0].append(data[0])
training[1].append(data[1])
# Vars to collect the original + augumented images and measurements
X_train, y_train = [], []
X_valid, y_valid = [], []
for line in lines:
# Image 1 = center, image 2 = left camera, image 3 = right camera
# From 3 images (center, left, right) we create 6 images (original/flipped versions for each)
measurement = float(line[3])
# Center
center_image = plt.imread(line[0])
validation_or_training((X_train, y_train), (X_valid, y_valid), (center_image, measurement))
validation_or_training((X_train, y_train), (X_valid, y_valid), (cv2.flip(center_image, 1), -measurement))
# Left
left_image = plt.imread(line[1])
validation_or_training((X_train, y_train), (X_valid, y_valid), (left_image, measurement + correction_factor))
validation_or_training((X_train, y_train), (X_valid, y_valid), (cv2.flip(left_image, 1), -(measurement + correction_factor)))
# Right
right_image = plt.imread(line[2])
validation_or_training((X_train, y_train), (X_valid, y_valid), (right_image, measurement - correction_factor))
validation_or_training((X_train, y_train), (X_valid, y_valid), (cv2.flip(right_image, 1), -(measurement - correction_factor)))
print('Training data size: {}'.format(len(X_train)))
print('Validation data size: {}'.format(len(X_valid)))
# Generate numpy arrays
# The images are the source data, the steering measurements are the labels to train against
X_train = np.array(X_train)
y_train = np.array(y_train)
X_valid = | np.array(X_valid) | numpy.array |
import datetime
from unittest import TestCase
import numpy as np
import pandas as pd
from mlnext import pipeline
class TestColumnSelector(TestCase):
def setUp(self):
data = np.arange(8).reshape(-1, 2)
cols = ['a', 'b']
self.df = pd.DataFrame(data, columns=cols)
def test_select_columns(self):
t = pipeline.ColumnSelector(keys=['a'])
expected = self.df.loc[:, ['a']]
result = t.fit_transform(self.df)
pd.testing.assert_frame_equal(result, expected)
class TestColumnDropper(TestCase):
def setUp(self):
data = np.arange(8).reshape(-1, 2)
cols = ['a', 'b']
self.df = pd.DataFrame(data, columns=cols)
def test_drop_columns(self):
t = pipeline.ColumnDropper(columns=['b'])
expected = self.df.loc[:, ['a']]
result = t.fit_transform(self.df)
pd.testing.assert_frame_equal(result, expected)
def test_drop_columns_verbose(self):
t = pipeline.ColumnDropper(columns=['b'], verbose=True)
expected = self.df.loc[:, ['a']]
result = t.transform(self.df)
pd.testing.assert_frame_equal(result, expected)
def test_drop__missing_columns(self):
t = pipeline.ColumnDropper(columns=['c'])
with self.assertWarns(Warning):
t.transform(self.df)
class TestColumnRename(TestCase):
def test_rename_columns(self):
t = pipeline.ColumnRename(lambda x: x.split('.')[-1])
df = pd.DataFrame(columns=['a.b.c', 'd.e.f'])
expected = pd.DataFrame(columns=['c', 'f'])
result = t.fit_transform(df)
pd.testing.assert_frame_equal(result, expected)
class TestNaDropper(TestCase):
def test_drop_na(self):
t = pipeline.NaDropper()
df = pd.DataFrame([1, 0, pd.NA])
expected = pd.DataFrame([1, 0], dtype=object)
result = t.fit_transform(df)
pd.testing.assert_frame_equal(result, expected)
class TestClip(TestCase):
def test_clip(self):
t = pipeline.Clip(lower=0.5, upper=1.5)
df = pd.DataFrame([[0.1, 0.4, 0.6, 0.8, 1.2, 1.5]])
expected = pd.DataFrame([[0.5, 0.5, 0.6, 0.8, 1.2, 1.5]])
result = t.fit_transform(df)
pd.testing.assert_frame_equal(result, expected)
class TestDatetimeTransformer(TestCase):
# FIXME: fails in gitlab pipeline but succeeds locally
def test_datetime(self):
t = pipeline.DatetimeTransformer(columns=['time'])
df = pd.DataFrame([['2021-01-04 14:12:31']], columns=['time'])
expected = pd.DataFrame([[datetime.datetime(2021, 1, 4, 14, 12, 31)]],
columns=['time'])
result = t.fit_transform(df)
pd.testing.assert_frame_equal(result, expected)
def test_datetime_missing_cols(self):
t = pipeline.DatetimeTransformer(columns=['t'])
df = pd.DataFrame([['2021-01-04 14:12:31']], columns=['time'])
with self.assertRaises(ValueError):
t.fit_transform(df)
class TestNumericTransformer(TestCase):
# FIXME: fails in gitlab pipeline but succeeds locally
def test_numeric(self):
t = pipeline.NumericTransformer(columns=['1'])
df = pd.DataFrame([0, 1], columns=['1'], dtype=object)
expected = pd.DataFrame([0, 1], columns=['1'], dtype=np.int64)
result = t.fit_transform(df)
pd.testing.assert_frame_equal(result, expected)
def test_numeric_missing_column(self):
t = pipeline.NumericTransformer(columns=['2'])
df = pd.DataFrame([0, 1], columns=['1'], dtype=object)
with self.assertRaises(ValueError):
t.fit_transform(df)
def test_numeric_additional_column(self):
t = pipeline.NumericTransformer(columns=['2'])
df = pd.DataFrame([[0, 1]], columns=['1', '2'], dtype=object)
expected = pd.DataFrame([[0, 1]], columns=['1', '2'], dtype=object)
expected['2'] = expected['2'].apply(pd.to_numeric)
result = t.fit_transform(df)
pd.testing.assert_frame_equal(result, expected)
def test_numeric_multiple_column(self):
t = pipeline.NumericTransformer(columns=['1', '2'])
df = pd.DataFrame([[0, 1]], columns=['1', '2'], dtype=object)
expected = pd.DataFrame([[0, 1]], columns=['1', '2'])
result = t.fit_transform(df)
pd.testing.assert_frame_equal(result, expected)
def test_numeric_all_column(self):
t = pipeline.NumericTransformer()
df = pd.DataFrame([[0, 1]], columns=['1', '2'], dtype=object)
expected = pd.DataFrame([[0, 1]], columns=['1', '2'])
result = t.fit_transform(df)
pd.testing.assert_frame_equal(result, expected)
class TestTimeframeExtractor(TestCase):
def setUp(self):
self.dates = [datetime.datetime(2021, 10, 1, 9, 50, 0),
datetime.datetime(2021, 10, 1, 10, 0, 0),
datetime.datetime(2021, 10, 1, 11, 0, 0),
datetime.datetime(2021, 10, 1, 12, 0, 0),
datetime.datetime(2021, 10, 1, 12, 10, 0)]
self.values = np.arange(len(self.dates))
self.df = pd.DataFrame(zip(self.dates, self.values),
columns=['time', 'value'])
def test_timeframe_extractor(self):
t = pipeline.TimeframeExtractor(
time_column='time', start_time=datetime.time(10, 0, 0),
end_time=datetime.time(12, 0, 0), verbose=True)
expected = pd.DataFrame(zip(self.dates[1:-1], np.arange(1, 4)),
columns=['time', 'value'])
result = t.fit_transform(self.df)
pd.testing.assert_frame_equal(result, expected)
def test_timeframe_extractor_invert(self):
t = pipeline.TimeframeExtractor(
time_column='time', start_time=datetime.time(10, 0, 0),
end_time=datetime.time(12, 0, 0), invert=True)
expected = pd.DataFrame(zip([self.dates[0], self.dates[-1]],
np.array([0, 4])),
columns=['time', 'value'])
result = t.fit_transform(self.df)
pd.testing.assert_frame_equal(result, expected)
class TestDateExtractor(TestCase):
def setUp(self):
self.dates = [datetime.datetime(2021, 10, 1, 9, 50, 0),
datetime.datetime(2021, 10, 2, 10, 0, 0),
datetime.datetime(2021, 10, 3, 11, 0, 0),
datetime.datetime(2021, 10, 4, 12, 0, 0),
datetime.datetime(2021, 10, 5, 12, 10, 0)]
self.values = np.arange(len(self.dates))
self.df = pd.DataFrame(zip(self.dates, self.values),
columns=['date', 'value'])
def test_date_extractor(self):
t = pipeline.DateExtractor(
date_column='date', start_date=datetime.date(2021, 10, 2),
end_date=datetime.date(2021, 10, 4), verbose=True)
expected = pd.DataFrame(zip(self.dates[1:-1], np.arange(1, 4)),
columns=['date', 'value'])
result = t.fit_transform(self.df)
pd.testing.assert_frame_equal(result, expected)
def test_date_extractor_invert(self):
t = pipeline.DateExtractor(
date_column='date', start_date=datetime.date(2021, 10, 2),
end_date=datetime.date(2021, 10, 4), invert=True)
expected = pd.DataFrame(zip([self.dates[0], self.dates[-1]],
np.array([0, 4])),
columns=['date', 'value'])
result = t.fit_transform(self.df)
pd.testing.assert_frame_equal(result, expected)
class TestValueMapper(TestCase):
def test_value_mapper_one_column(self):
t = pipeline.ValueMapper(columns=['b'], classes={2.0: 1.0})
df = pd.DataFrame(np.ones((3, 2)) * 2, columns=['a', 'b'])
expected = pd.DataFrame(zip(np.ones((3, 1)) * 2, np.ones((3, 1))),
columns=['a', 'b'], dtype=np.float64)
result = t.fit_transform(df)
pd.testing.assert_frame_equal(result, expected)
def test_value_mapper_all_columns(self):
t = pipeline.ValueMapper(columns=['a', 'b'], classes={2.0: 1.0})
df = pd.DataFrame(np.ones((3, 2)) * 2, columns=['a', 'b'])
expected = pd.DataFrame(np.ones((3, 2)), columns=['a', 'b'],
dtype=np.float64)
result = t.fit_transform(df)
pd.testing.assert_frame_equal(result, expected)
def test_value_mapper_missing_value(self):
t = pipeline.ValueMapper(columns=['a', 'b'], classes={2.0: 1.0})
df = pd.DataFrame(np.ones((3, 2)), columns=['a', 'b'])
expected = pd.DataFrame(np.ones((3, 2)), columns=['a', 'b'],
dtype=np.float64)
with self.assertWarns(Warning):
result = t.fit_transform(df)
pd.testing.assert_frame_equal(result, expected)
class TestSorter(TestCase):
def setUp(self):
self.df = pd.DataFrame({
'a': [2, 3, 1, 4],
'b': ['A', 'D', 'C', 'B']
})
def test_sorter(self):
t = pipeline.Sorter(columns=['a'])
result = t.fit_transform(self.df)
expected = self.df.copy().sort_values(by=['a'])
pd.testing.assert_frame_equal(result, expected)
def test_sorter_multi_col(self):
t = pipeline.Sorter(columns=['a', 'b'])
result = t.fit_transform(self.df)
expected = self.df.copy().sort_values(by=['a', 'b'])
pd.testing.assert_frame_equal(result, expected)
class TestFill(TestCase):
def setUp(self):
self.df = pd.DataFrame([[0.0, 1.0, 0.2, pd.NA, 0.5]])
def test_fill(self):
t = pipeline.Fill(value=1.0)
expected = pd.DataFrame([[0.0, 1.0, 0.2, 1.0, 0.5]])
result = t.fit_transform(self.df)
pd.testing.assert_frame_equal(result, expected)
class TestTimeOffsetTransformer(TestCase):
def test_timeoffset(self):
t = pipeline.TimeOffsetTransformer(
time_columns=['t'], timedelta=pd.Timedelta(1, 'h'))
df = pd.DataFrame({'t': [datetime.datetime(2020, 10, 1, 12, 3, 10)]})
expected = pd.DataFrame(
{'t': [datetime.datetime(2020, 10, 1, 13, 3, 10)]})
result = t.fit_transform(df)
pd.testing.assert_frame_equal(result, expected)
def test_timeoffset_multi_col(self):
t = pipeline.TimeOffsetTransformer(
time_columns=['t'], timedelta=pd.Timedelta(1, 'h'))
df = pd.DataFrame({'t': [datetime.datetime(2020, 10, 1, 12, 3, 10)],
'tt': [datetime.datetime(2020, 10, 1, 13, 3, 10)]})
expected = pd.DataFrame(
{'t': [datetime.datetime(2020, 10, 1, 13, 3, 10)],
'tt': [datetime.datetime(2020, 10, 1, 13, 3, 10)]})
result = t.fit_transform(df)
pd.testing.assert_frame_equal(result, expected)
class TestConditionedDropper(TestCase):
def setUp(self):
self.data = [0.0, 0.5, 1.0, 1.2]
self.df = pd.DataFrame({'a': self.data})
def test_dropper(self):
t = pipeline.ConditionedDropper(column='a', threshold=1.0)
expected = pd.DataFrame({'a': self.data[:-1]})
result = t.fit_transform(self.df)
pd.testing.assert_frame_equal(result, expected)
def test_dropper_invert(self):
t = pipeline.ConditionedDropper(column='a', threshold=1.0, invert=True)
expected = pd.DataFrame({'a': self.data[-2:]})
result = t.fit_transform(self.df)
pd.testing.assert_frame_equal(result, expected)
class TestZeroVarianceDropper(TestCase):
def setUp(self):
self.df = pd.DataFrame({'one': np.ones((4,)),
'zeros': np.zeros((4,)),
'mixed': np.arange(4)})
def test_dropper(self):
t = pipeline.ZeroVarianceDropper(verbose=True)
expected = pd.DataFrame({
'mixed': np.arange(4)
})
result = t.fit_transform(self.df)
pd.testing.assert_frame_equal(result, expected)
def test_dropper_fit_higher_variance(self):
t = pipeline.ZeroVarianceDropper()
expected = pd.DataFrame({
'mixed': np.arange(4)
})
t.fit(self.df)
df = self.df.copy()
df.iloc[0, 0] = 0
with self.assertWarns(Warning):
result = t.transform(df)
pd.testing.assert_frame_equal(result, expected)
class TestSignalSorter(TestCase):
def setUp(self):
self.df = pd.DataFrame({'one': np.ones((4,)),
'zeros': np.zeros((4,)),
'mixed': np.arange(4),
'binary': [0, 1, 0, 1],
'cont': [10, 11, 10, 11]})
def test_sorter(self):
t = pipeline.SignalSorter(verbose=True)
expected = self.df.loc[:, ['mixed', 'cont', 'one', 'zeros', 'binary']]
result = t.fit_transform(self.df)
pd.testing.assert_frame_equal(result, expected)
class TestColumnSorter(TestCase):
def setUp(self):
self.df = pd.DataFrame({'one': np.ones((2,)),
'zeros': | np.zeros((2,)) | numpy.zeros |
from __future__ import division
import numpy as np
import copy
from pysph.base.nnps import LinkedListNNPS
from pysph.base.utils import get_particle_array, get_particle_array_wcsph
from cyarray.api import UIntArray
from numpy.linalg import norm, matrix_power
from pysph.sph.equation import Equation
from pysph.tools.sph_evaluator import SPHEvaluator
from pysph.base.particle_array import ParticleArray
def distance(point1, point2=np.array([0.0, 0.0, 0.0])):
return np.sqrt(sum((point1 - point2) * (point1 - point2)))
def distance_2d(point1, point2=np.array([0.0, 0.0])):
return np.sqrt(sum((point1 - point2) * (point1 - point2)))
def matrix_exp(matrix):
"""
Exponential of a matrix.
Finds the exponential of a square matrix of any order using the
formula exp(A) = I + (A/1!) + (A**2/2!) + (A**3/3!) + .........
Parameters
----------
matrix : numpy matrix of order nxn (square) filled with numbers
Returns
-------
result : numpy matrix of the same order
Examples
--------
>>>A = np.matrix([[1, 2],[2, 3]])
>>>matrix_exp(A)
matrix([[19.68002699, 30.56514746],
[30.56514746, 50.24517445]])
>>>B = np.matrix([[0, 0],[0, 0]])
>>>matrix_exp(B)
matrix([[1., 0.],
[0., 1.]])
"""
matrix = np.asarray(matrix)
tol = 1.0e-16
result = matrix_power(matrix, 0)
n = 1
condition = True
while condition:
adding = matrix_power(matrix, n) / (1.0 * np.math.factorial(n))
result += adding
residue = np.sqrt(np.sum(np.square(adding)) /
np.sum(np.square(result)))
condition = (residue > tol)
n += 1
return result
def extrude(x, y, dx=0.01, extrude_dist=1.0, z_center=0.0):
"""
Extrudes a 2d geometry.
Takes a 2d geometry with x, y values and extrudes it in z direction by the
amount extrude_dist with z_center as center
Parameters
----------
x : 1d array object with numbers
y : 1d array object with numbers
dx : a number
extrude_dist : a number
z_center : a number
x, y should be of the same length and no x, y pair should be the same
Returns
-------
x_new : 1d numpy array object with new x values
y_new : 1d numpy array object with new y values
z_new : 1d numpy array object with z values
x_new, y_new, z_new are of the same length
Examples
--------
>>>x = np.array([0.0])
>>>y = np.array([0.0])
>>>extrude(x, y, 0.1, 0.2, 0.0)
(array([ 0., 0., 0.]),
array([ 0., 0., 0.]),
array([-0.1, 0., 0.1]))
"""
z = np.arange(z_center - extrude_dist / 2.,
z_center + (extrude_dist + dx) / 2., dx)
x_new = np.tile(np.asarray(x), len(z))
y_new = np.tile(np.asarray(y), len(z))
z_new = np.repeat(z, len(x))
return x_new, y_new, z_new
def translate(x, y, z, x_translate=0.0, y_translate=0.0, z_translate=0.0):
"""
Translates set of points in 3d cartisean space.
Takes set of points and translates each and every point by some
mentioned amount in all the 3 directions.
Parameters
----------
x : 1d array object with numbers
y : 1d array object with numbers
z : 1d array object with numbers
x_translate : a number
y_translate : a number
z_translate : a number
Returns
-------
x_new : 1d numpy array object with new x values
y_new : 1d numpy array object with new y values
z_new : 1d numpy array object with new z values
Examples
--------
>>>x = np.array([0.0, 1.0, 2.0])
>>>y = np.array([-1.0, 0.0, 1.5])
>>>z = np.array([0.5, -1.5, 0.0])
>>>translate(x, y, z, 1.0, -0.5, 2.0)
(array([ 1., 2., 3.]), array([-1.5, -0.5, 1.]), array([2.5, 0.5, 2.]))
"""
x_new = np.asarray(x) + x_translate
y_new = np.asarray(y) + y_translate
z_new = np.asarray(z) + z_translate
return x_new, y_new, z_new
def rotate(x, y, z, axis=np.array([0.0, 0.0, 1.0]), angle=90.0):
"""
Rotates set of points in 3d cartisean space.
Takes set of points and rotates each point with some angle w.r.t
a mentioned axis.
Parameters
----------
x : 1d array object with numbers
y : 1d array object with numbers
z : 1d array object with numbers
axis : 1d array with 3 numbers
angle(in degrees) : number
Returns
-------
x_new : 1d numpy array object with new x values
y_new : 1d numpy array object with new y values
z_new : 1d numpy array object with new z values
Examples
--------
>>>x = np.array([0.0, 1.0, 2.0])
>>>y = np.array([-1.0, 0.0, 1.5])
>>>z = np.array([0.5, -1.5, 0.0])
>>>axis = np.array([0.0, 0.0, 1.0])
>>>rotate(x, y, z, axis, 90.0)
(array([ 1.00000000e+00, 4.25628483e-17, -1.50000000e+00]),
array([-4.25628483e-17, 1.00000000e+00, 2.00000000e+00]),
array([ 0.5, -1.5, 0. ]))
"""
theta = angle * np.pi / 180.0
unit_vector = np.asarray(axis) / norm(np.asarray(axis))
matrix = np.cross(np.eye(3), unit_vector * theta)
rotation_matrix = matrix_exp(matrix)
new_points = []
for xi, yi, zi in zip(np.asarray(x), np.asarray(y), np.asarray(z)):
point = np.array([xi, yi, zi])
new = np.dot(rotation_matrix, point)
new_points.append(new)
new_points = np.array(new_points)
x_new = new_points[:, 0]
y_new = new_points[:, 1]
z_new = new_points[:, 2]
return x_new, y_new, z_new
def get_2d_wall(dx=0.01, center=np.array([0.0, 0.0]), length=1.0,
num_layers=1, up=True):
"""
Generates a 2d wall which is parallel to x-axis. The wall can be
rotated parallel to any axis using the rotate function. 3d wall
can be also generated using the extrude function after generating
particles using this function.
^
|
|
y|*******************
| wall particles
|
|____________________>
x
Parameters
----------
dx : a number which is the spacing required
center : 1d array like object which is the center of wall
length : a number which is the length of the wall
num_layers : Number of layers for the wall
up : True if the layers have to created on top of base wall
Returns
-------
x : 1d numpy array with x coordinates of the wall
y : 1d numpy array with y coordinates of the wall
"""
x = np.arange(-length / 2., length / 2. + dx, dx) + center[0]
y = np.ones_like(x) * center[1]
value = 1 if up else -1
for i in range(1, num_layers):
y1 = np.ones_like(x) * center[1] + value * i * dx
y = np.concatenate([y, y1])
return np.tile(x, num_layers), y
def get_2d_tank(dx=0.05, base_center=np.array([0.0, 0.0]), length=1.0,
height=1.0, num_layers=1, outside=True, staggered=False,
top=False):
"""
Generates an open 2d tank with the base parallel to x-axis and the side
walls parallel to y-axis. The tank can be rotated to any direction using
rotate function. 3d tank can be generated using extrude function.
^
|* *
|* 2d tank *
y|* particles *
|* *
|* * * * * * * * *
| base
|____________________>
x
Parameters
----------
dx : a number which is the spacing required
base_center : 1d array like object which is the center of base wall
length : a number which is the length of the base
height : a number which is the length of the side wall
num_layers : Number of layers for the tank
outside : A boolean value which decides if the layers are inside or outside
staggered : A boolean value which decides if the layers are staggered or not
top : A boolean value which decides if the top is present or not
Returns
-------
x : 1d numpy array with x coordinates of the tank
y : 1d numpy array with y coordinates of the tank
"""
dy = dx
fac = 1 if outside else 0
if staggered:
dx = dx/2
start = fac*(1 - num_layers)*dx
end = fac*num_layers*dx + (1 - fac) * dx
x, y = np.mgrid[start:length+end:dx, start:height+end:dy]
topset = 0 if top else 10*height
if staggered:
topset += dx
y[1::2] += dx
offset = 0 if outside else (num_layers-1)*dx
cond = ~((x > offset) & (x < length-offset) &
(y > offset) & (y < height+topset-offset))
return x[cond] + base_center[0] - length/2, y[cond] + base_center[1]
def get_2d_circle(dx=0.01, r=0.5, center=np.array([0.0, 0.0])):
"""
Generates a completely filled 2d circular area.
Parameters
----------
dx : a number which is the spacing required
r : a number which is the radius of the circle
center : 1d array like object which is the center of the circle
Returns
-------
x : 1d numpy array with x coordinates of the circle particles
y : 1d numpy array with y coordinates of the circle particles
"""
N = int(2.0 * r / dx) + 1
x, y = np.mgrid[-r:r:N * 1j, -r:r:N * 1j]
x, y = np.ravel(x), np.ravel(y)
condition = (x * x + y * y <= r * r)
x, y = x[condition], y[condition]
return x + center[0], y + center[1]
def get_2d_hollow_circle(dx=0.01, r=1.0, center=np.array([0.0, 0.0]),
num_layers=2, inside=True):
"""
Generates a hollow 2d circle with some number of layers either on the
inside or on the outside of the body which is taken as an argument
Parameters
----------
dx : a number which is the spacing required
r : a number which is the radius of the circle
center : 1d array like object which is the center of the circle
num_layers : a number (int)
inside : boolean (True or False). If this is True then the layers
are generated inside the circle
Returns
-------
x : 1d numpy array with x coordinates of the circle particles
y : 1d numpy array with y coordinates of the circle particles
"""
r_grid = r + dx * num_layers
N = int(2.0 * r_grid / dx) + 1
x, y = np.mgrid[-r_grid:r_grid:N * 1j, -r_grid:r_grid:N * 1j]
x, y = np.ravel(x), np.ravel(y)
if inside:
cond1 = (x * x + y * y <= r * r)
cond2 = (x * x + y * y >= (r - num_layers * dx)**2)
else:
cond1 = (x * x + y * y >= r * r)
cond2 = (x * x + y * y <= (r + num_layers * dx)**2)
cond = cond1 & cond2
x, y = x[cond], y[cond]
return x + center[0], y + center[0]
def get_3d_hollow_cylinder(dx=0.01, r=0.5, length=1.0,
center=np.array([0.0, 0.0, 0.0]),
num_layers=2, inside=True):
"""
Generates a 3d hollow cylinder which is a extruded geometry
of the hollow circle with a closed base.
Parameters
----------
dx : a number which is the spacing required
r : a number which is the radius of the cylinder
length : a number which is the length of the cylinder
center : 1d array like object which is the center of the cylinder
num_layers : a number (int)
inside : boolean (True or False). If this is True then the layers
are generated inside the cylinder
Returns
-------
x : 1d numpy array with x coordinates of the cylinder particles
y : 1d numpy array with y coordinates of the cylinder particles
z : 1d numpy array with z coordinates of the cylinder particles
"""
x_2d, y_2d = get_2d_hollow_circle(dx, r, center[:2], num_layers, inside)
x, y, z = extrude(x_2d, y_2d, dx, length - dx, center[2] + dx / 2.)
x_circle, y_circle = get_2d_circle(dx, r, center[:2])
z_circle = np.ones_like(x_circle) * (center[2] - length / 2.)
x = np.concatenate([x, x_circle])
y = np.concatenate([y, y_circle])
z = np.concatenate([z, z_circle])
return x, y, z
def get_2d_block(dx=0.01, length=1.0, height=1.0, center=np.array([0., 0.])):
"""
Generates a 2d rectangular block of particles with axes parallel to
the coordinate axes.
^
|
|h * * * * * * *
|e * * * * * * *
y|i * * * * * * *
|g * * * * * * *
|h * * * * * * *
|t * * * * * * *
| * * * * * * *
| length
|________________>
x
Parameters
----------
dx : a number which is the spacing required
length : a number which is the length of the block
height : a number which is the height of the block
center : 1d array like object which is the center of the block
Returns
-------
x : 1d numpy array with x coordinates of the block particles
y : 1d numpy array with y coordinates of the block particles
"""
n1 = int(length / dx) + 1
n2 = int(height / dx) + 1
x, y = np.mgrid[-length / 2.:length / 2.:n1 *
1j, -height / 2.:height / 2.:n2 * 1j]
x, y = np.ravel(x), np.ravel(y)
return x + center[0], y + center[1]
def get_3d_sphere(dx=0.01, r=0.5, center=np.array([0.0, 0.0, 0.0])):
"""
Generates a 3d sphere.
Parameters
----------
dx : a number which is the spacing required
r : a number which is the radius of the sphere
center : 1d array like object which is the center of the sphere
Returns
-------
x : 1d numpy array with x coordinates of the sphere particles
y : 1d numpy array with y coordinates of the sphere particles
z : 1d numpy array with z coordinates of the sphere particles
"""
N = int(2.0 * r / dx) + 1
x, y, z = np.mgrid[-r:r:N * 1j, -r:r:N * 1j, -r:r:N * 1j]
x, y, z = np.ravel(x), np.ravel(y), np.ravel(z)
cond = (x * x + y * y + z * z <= r * r)
x, y, z = x[cond], y[cond], z[cond]
return x + center[0], y + center[1], z + center[2]
def get_3d_block(dx=0.01, length=1.0, height=1.0, depth=1.0,
center=np.array([0., 0., 0.])):
"""
Generates a 3d block of particles with the length, height and depth
parallel to x, y and z axis respectively.
Paramters
---------
dx : a number which is the spacing required
length : a number which is the length of the block
height : a number which is the height of the block
depth : a number which is the depth of the block
center : 1d array like object which is the center of the block
Returns
-------
x : 1d numpy array with x coordinates of the block particles
y : 1d numpy array with y coordinates of the block particles
z : 1d numpy array with z coordinates of the block particles
"""
n1 = int(length / dx) + 1
n2 = int(height / dx) + 1
n3 = int(depth / dx) + 1
x, y, z = np.mgrid[-length / 2.:length / 2.:n1 * 1j, -height /
2.:height / 2.:n2 * 1j, -depth / 2.:depth / 2.:n3 * 1j]
x, y, z = np.ravel(x), np.ravel(y), np.ravel(z)
return x + center[0], y + center[1], z + center[2]
def get_4digit_naca_airfoil(dx=0.01, airfoil='0012', c=1.0):
"""
Generates a 4 digit series NACA airfoil. For a 4 digit series airfoil,
the first digit is the (maximum camber / chord) * 100, second digit is
(location of maximum camber / chord) * 10 and the third and fourth digits
are the (maximum thickness / chord) * 100. The particles generated
using this function will form a solid 2d airfoil.
Parameters
----------
dx : a number which is the spacing required
airfoil : a string of 4 characters which is the airfoil name
c : a number which is the chord of the airfoil
Returns
-------
x : 1d numpy array with x coordinates of the airfoil particles
y : 1d numpy array with y coordinates of the airfoil particles
References
----------
https://en.wikipedia.org/wiki/NACA_airfoil
"""
n = int(c / dx) + 1
x, y = np.mgrid[0:c:n * 1j, -c / 2.:c / 2.:n * 1j]
x = np.ravel(x)
y = np.ravel(y)
x_naca = []
y_naca = []
t = float(airfoil[2:]) * 0.01 * c
if airfoil[:2] == '00':
for xi, yi in zip(x, y):
yt = 5.0 * t * (0.2969 * np.sqrt(xi / c) - 0.1260 * (xi / c) -
0.3516 * ((xi / c)**2.) + 0.2843 * ((xi / c)**3.)
- 0.1015 * ((xi / c)**4.))
if abs(yi) <= yt:
x_naca.append(xi)
y_naca.append(yi)
else:
m = 0.01 * float(airfoil[0])
p = 0.1 * float(airfoil[1])
for xi, yi in zip(x, y):
yt = 5.0 * t * (0.2969 * np.sqrt(xi / c) - 0.1260 * (xi / c) -
0.3516 * ((xi / c)**2.) + 0.2843 * ((xi / c)**3.)
- 0.1015 * ((xi / c)**4.))
if xi <= p * c:
yc = (m / (p * p)) * (2. * p * (xi / c) - (xi / c)**2.)
dydx = (2. * m / (p * p)) * (p - xi / c) / c
else:
yc = (m / ((1. - p) * (1. - p))) * \
(1. - 2. * p + 2. * p * (xi / c) - (xi / c)**2.)
dydx = (2. * m / ((1. - p) * (1. - p))) * (p - xi / c) / c
theta = np.arctan(dydx)
if yi >= 0.0:
yu = yc + yt * np.cos(theta)
if yi <= yu:
xu = xi - yt * np.sin(theta)
x_naca.append(xu)
y_naca.append(yi)
else:
yl = yc - yt * np.cos(theta)
if yi >= yl:
xl = xi + yt * np.sin(theta)
x_naca.append(xl)
y_naca.append(yi)
x_naca = np.array(x_naca)
y_naca = np.array(y_naca)
return x_naca, y_naca
def _get_m_k(series):
if series == '210':
return 0.058, 361.4
elif series == '220':
return 0.126, 51.64
elif series == '230':
return 0.2025, 15.957
elif series == '240':
return 0.290, 6.643
elif series == '250':
return 0.391, 3.23
elif series == '221':
return 0.130, 51.99
elif series == '231':
return 0.217, 15.793
elif series == '241':
return 0.318, 6.52
elif series == '251':
return 0.441, 3.191
def get_5digit_naca_airfoil(dx=0.01, airfoil='23112', c=1.0):
"""
Generates a 5 digit series NACA airfoil. For a 5 digit series airfoil,
the first digit is the design lift coefficient * 20 / 3, second digit is
(location of maximum camber / chord) * 20, third digit indicates the
reflexitivity of the camber and the fourth and fifth digits are the
(maximum thickness / chord) * 100. The particles generated using this
function will form a solid 2d airfoil.
Parameters
----------
dx : a number which is the spacing required
airfoil : a string of 5 characters which is the airfoil name
c : a number which is the chord of the airfoil
Returns
-------
x : 1d numpy array with x coordinates of the airfoil particles
y : 1d numpy array with y coordinates of the airfoil particles
References
----------
https://en.wikipedia.org/wiki/NACA_airfoil
http://www.aerospaceweb.org/question/airfoils/q0041.shtml
"""
n = int(c / dx) + 1
x, y = np.mgrid[0:c:n * 1j, -c / 2.:c / 2.:n * 1j]
x = np.ravel(x)
y = np.ravel(y)
x_naca = []
y_naca = []
t = 0.01 * float(airfoil[3:])
series = airfoil[:3]
m, k = _get_m_k(series)
for xi, yi in zip(x, y):
yt = 5.0 * t * (0.2969 * np.sqrt(xi / c) - 0.1260 * (xi / c) -
0.3516 * ((xi / c)**2.) + 0.2843 * ((xi / c)**3.)
- 0.1015 * ((xi / c)**4.))
xn = xi / c
if xn <= m:
yc = c * (k / 6.) * (xn**3. - 3. * m *
xn * xn + m * m * (3. - m) * xn)
dydx = (k / 6.) * (3. * xn * xn - 6. * m * xn + m * m * (3. - m))
else:
yc = c * (k * (m**3.) / 6.) * (1. - xn)
dydx = -(k * (m**3.) / 6.)
theta = np.arctan(dydx)
if yi >= 0.0:
yu = yc + yt * | np.cos(theta) | numpy.cos |
import joblib
import math
import numba
import numpy as np
import pynndescent.sparse as sparse
from pynndescent.utils import heap_push, make_heap, seed, tau_rand_int
from pynndescent.threaded import (
new_rng_state,
per_thread_rng_state,
parallel_calls,
effective_n_jobs_with_context,
chunk_rows,
shuffle_jit,
init_rp_tree_reduce_jit,
new_build_candidates,
nn_decent_reduce_jit,
deheap_sort_map_jit,
)
# NNDescent algorithm
INT32_MIN = np.iinfo(np.int32).min + 1
INT32_MAX = np.iinfo(np.int32).max - 1
# Map Reduce functions to be jitted
@numba.njit(nogil=True)
def sparse_current_graph_map_jit(
heap, rows, n_neighbors, inds, indptr, data, rng_state, seed_per_row, sparse_dist,
):
rng_state_local = rng_state.copy()
for i in rows:
if seed_per_row:
seed(rng_state_local, i)
if heap[0][i, 0] < 0.0:
for j in range(n_neighbors - | np.sum(heap[0][i] >= 0.0) | numpy.sum |
import os
import matplotlib
import multiprocessing
import pandas as pd
import numpy as np
BACKEND = 'Agg'
if matplotlib.get_backend().lower() != BACKEND.lower():
# If backend is not set properly a call to describe will hang
matplotlib.use(BACKEND)
from matplotlib import pyplot as plt
#To plot for bi range of x axis such as 250M
plt.rcParams['agg.path.chunksize'] = 10000
from SigProfilerTopography.source.commons.TopographyCommons import getChromSizesDict
from SigProfilerTopography.source.commons.TopographyCommons import ONE_DIRECTORY_UP
from SigProfilerTopography.source.commons.TopographyCommons import LIB
from SigProfilerTopography.source.commons.TopographyCommons import NUCLEOSOME
from SigProfilerTopography.source.commons.TopographyCommons import CHRBASED
from SigProfilerTopography.source.commons.TopographyCommons import CHROM
from SigProfilerTopography.source.commons.TopographyCommons import START
from SigProfilerTopography.source.commons.TopographyCommons import END
from SigProfilerTopography.source.commons.TopographyCommons import SIGNAL
current_abs_path = os.path.dirname(os.path.realpath(__file__))
######################################################################
#Used by plotting
def readChromBasedNucleosomeDF(chrLong,nucleosomeFilename):
chrBasedNucleosmeFilename = '%s_%s' %(chrLong,nucleosomeFilename)
chrBasedNucleosmeFilePath = os.path.join(current_abs_path, ONE_DIRECTORY_UP, ONE_DIRECTORY_UP, LIB, NUCLEOSOME, CHRBASED, chrBasedNucleosmeFilename)
if (os.path.exists(chrBasedNucleosmeFilePath)):
column_names = [CHROM, START, END, SIGNAL]
chrbased_nucleosome_df = pd.read_csv(chrBasedNucleosmeFilePath, sep='\t', header=None, comment='#',names=column_names, dtype={CHROM: 'category', START: np.int32, END: np.int32, SIGNAL: np.float32})
return chrbased_nucleosome_df
else:
return None
######################################################################
######################################################################
# For plotting
# main function parallel
# parallel it does not end for big chromosomes
def plotChrBasedNucleosomeOccupancyFigures(genome,nucleosomeFilename):
#read chromnames for this nucleosome data
nucleosomeFilenameWoExtension = nucleosomeFilename[0:-4]
chromSizesDict = getChromSizesDict(genome)
chromNamesList = list(chromSizesDict.keys())
#Start the pool
numofProcesses = multiprocessing.cpu_count()
pool = multiprocessing.Pool(numofProcesses)
poolInputList = []
for chrLong in chromNamesList:
chromBasedNucleosomeDF = readChromBasedNucleosomeDF(chrLong,nucleosomeFilename)
if chromBasedNucleosomeDF is not None:
inputList = []
inputList.append(chrLong)
inputList.append(nucleosomeFilenameWoExtension)
poolInputList.append(inputList)
pool.map(plotNucleosomeOccupancySignalCountFiguresInParallel,poolInputList)
################################
pool.close()
pool.join()
################################
######################################################################
######################################################################
#main function sequential
def plotChrBasedNucleosomeOccupancyFiguresSequential(genome,nucleosomeFilename):
#read chromnames for this nucleosome data
nucleosomeFilenameWoExtension = nucleosomeFilename[0:-4]
chromSizesDict = getChromSizesDict(genome)
chromNamesList = list(chromSizesDict.keys())
for chrLong in chromNamesList:
#Actually no need for such a check
chromBasedNucleosomeDF = readChromBasedNucleosomeDF(chrLong,nucleosomeFilename)
if chromBasedNucleosomeDF is not None:
inputList = []
inputList.append(chrLong)
inputList.append(nucleosomeFilenameWoExtension)
plotNucleosomeOccupancySignalCountFiguresInParallel(inputList)
######################################################################
######################################################################
#main function
def plotChrBasedNucleosomeOccupancyFiguresFromText(genome,nucleosomeFilename):
#read chromnames for this nucleosome data
nucleosomeFilenameWoExtension = nucleosomeFilename[0:-4]
chromSizesDict = getChromSizesDict(genome)
chromNamesList = list(chromSizesDict.keys())
#Start the pool
numofProcesses = multiprocessing.cpu_count()
pool = multiprocessing.Pool(numofProcesses)
poolInputList = []
for chrLong in chromNamesList:
chromBasedNucleosomeDF = readChromBasedNucleosomeDF(chrLong,nucleosomeFilename)
if chromBasedNucleosomeDF is not None:
inputList = []
inputList.append(chrLong)
inputList.append(nucleosomeFilenameWoExtension)
poolInputList.append(inputList)
pool.map(plotNucleosomeOccupancySignalCountFiguresInParallelFromTextFiles,poolInputList)
################################
pool.close()
pool.join()
################################
######################################################################
#####################################################################
# For plotting
def plotNucleosomeOccupancySignalCountFiguresInParallel(inputList):
chrLong = inputList[0]
nucleosomeFilenameWoExtension = inputList[1]
##############################################################
signalArrayFilename = '%s_signal_%s.npy' %(chrLong,nucleosomeFilenameWoExtension)
countArrayFilename = '%s_count_%s.npy' % (chrLong, nucleosomeFilenameWoExtension)
chrBasedSignalNucleosmeFile = os.path.join(current_abs_path,ONE_DIRECTORY_UP,ONE_DIRECTORY_UP,LIB,NUCLEOSOME,CHRBASED,signalArrayFilename)
chrBasedCountNucleosmeFile = os.path.join(current_abs_path,ONE_DIRECTORY_UP,ONE_DIRECTORY_UP,LIB,NUCLEOSOME,CHRBASED,countArrayFilename)
#################################################################################################################
if (os.path.exists(chrBasedSignalNucleosmeFile) and os.path.exists(chrBasedCountNucleosmeFile)):
signal_array_npy = np.load(chrBasedSignalNucleosmeFile)
count_array_npy = np.load(chrBasedCountNucleosmeFile)
fig = plt.figure(figsize=(30, 10), facecolor=None)
plt.style.use('ggplot')
figureFilename = '%s_NucleosomeOccupancy_Signal_Count_from_npy_scatter_allChr.png' %(chrLong)
figureFilepath = os.path.join(current_abs_path, ONE_DIRECTORY_UP, ONE_DIRECTORY_UP, LIB,NUCLEOSOME,CHRBASED,figureFilename)
# This code makes the background white.
ax = plt.gca()
ax.set_facecolor('white')
# This code puts the edge line
for edge_i in ['left', 'bottom', 'right', 'top']:
ax.spines[edge_i].set_edgecolor("black")
ax.spines[edge_i].set_linewidth(3)
#All Chrom
chromSize = signal_array_npy.size
x = | np.arange(0, chromSize, 1) | numpy.arange |
import inspect
import math
import numpy as np
import pytest
import xarray as xr
import windeval.processing as processing
@pytest.fixture
def accuracy():
return 1e-12
def test_BulkFormula():
BFC = processing.BulkFormula
assert inspect.isclass(BFC)
BFI = processing.BulkFormula()
assert isinstance(BFI, BFC)
def test_BulkFormula_YT96(accuracy):
x = np.array([3, 5.9, 6, 12, 26, 27, 1])
X = xr.Dataset({"w": (("x"), x), "air_density": (("x"), np.full(x.shape, 1))})
y = np.array(
[
0.00217888888888889,
0.001036624533180121,
0.00102,
0.00144,
0.00242,
np.nan,
np.nan,
]
)
tau = processing.BulkFormula("yelland_and_taylor_1996").calculate(X, "w")
for i, _ in enumerate(X.w):
if np.isnan(y[i]):
assert np.isnan(tau[i])
else:
assert math.isclose(tau[i] / np.power(X.w[i], 2), y[i], rel_tol=accuracy)
assert tau.shape == X.w.shape
def test_BulkFormula_LP81(accuracy):
x = np.array([5, 12, 1, 26])
X = xr.Dataset({"w": (("x"), x), "air_density": (("x"), np.full(x.shape, 1))})
y = np.array([1.2e-3, 0.00127, np.nan, np.nan])
tau = processing.BulkFormula("large_and_pond_1981").calculate(X, "w")
for i, _ in enumerate(X.w):
if np.isnan(y[i]):
assert np.isnan(tau[i])
else:
assert math.isclose(tau[i] / np.power(X.w[i], 2), y[i], rel_tol=accuracy)
assert tau.shape == X.w.shape
def test_BulkFormula_KH07(accuracy):
x = np.array([1, 10])
X = xr.Dataset({"w": (("x"), x), "air_density": (("x"), np.full(x.shape, 1))})
y = 1.3e-3
tau = processing.BulkFormula("ncep_ncar_2007").calculate(X, "w")
for i, _ in enumerate(X.w):
assert math.isclose(tau[i] / np.power(X.w[i], 2), y, rel_tol=accuracy)
assert tau.shape == X.w.shape
def test_BulkFormula_T90(accuracy):
x = np.array([0.5, 1.5, 3 + 1e-10, 15])
X = xr.Dataset({"w": (("x"), x), "air_density": (("x"), np.full(x.shape, 1))})
y = | np.array([0.00218, 0.00166, 0.00114, 0.001465]) | numpy.array |
import pytest
import torch
import torch.nn.functional as F
import numpy as np
from cplxmodule import cplx
def cplx_allclose(input, other):
return torch.allclose(input.real, other.real) and \
torch.allclose(input.imag, other.imag)
def cplx_allclose_numpy(input, other):
other = np.asarray(other)
return (
torch.allclose(input.real, torch.from_numpy(other.real))
and torch.allclose(input.imag, torch.from_numpy(other.imag))
)
@pytest.fixture
def random_state():
return | np.random.RandomState(None) | numpy.random.RandomState |
# python libs
import numpy as np
import pyximport
pyximport.install(setup_args={"include_dirs": np.get_include()})
global cymodels
def initialize_models():
global cymodels
# import cymodels # to be used with compiled models for improved performance
def prediction(models, controls, history_array, prediction_horizon, history_length, initial_tick, number_of_controls, number_of_variables):
predictions = [list() for i in range(number_of_controls)]
for t in range(prediction_horizon):
new_tick = history_array[-number_of_variables:].copy()
history_array = np.concatenate([[0], history_array])
for i in range(number_of_controls):
new_tick[i] = cymodels.eval(i, history_array)
predictions[i].append(new_tick[i])
# replacing controls:
# new_tick[desired_indexes] = controls[((number_of_controls - 1) * t):((number_of_controls - 1) * (t + 1))]
# update history with current tick and remove oldest tick to enforce history length
history_array = | np.concatenate([history_array[number_of_variables:], new_tick]) | numpy.concatenate |
import os
import numpy as np
import tensorflow as tf
import gpflow
from GPcounts import branchingKernel
from GPcounts import NegativeBinomialLikelihood
from sklearn.cluster import KMeans
import scipy.stats as ss
from pathlib import Path
import pandas as pd
from gpflow.utilities import set_trainable
from tqdm import tqdm
from scipy.signal import savgol_filter
import random
import scipy as sp
from scipy import interpolate
from robustgp import ConditionalVariance
from pandas import DataFrame
from scipy.special import logsumexp
import warnings
with warnings.catch_warnings():
warnings.simplefilter('ignore')
# Get number of cores reserved by the batch system (NSLOTS is automatically set, or use 1 if not)
NUMCORES=int(os.getenv("NSLOTS",1))
# print("Using", NUMCORES, "core(s)" )
# Create session properties
config=tf.compat.v1.ConfigProto(inter_op_parallelism_threads=NUMCORES,intra_op_parallelism_threads=NUMCORES)
tf.compat.v1.Session.intra_op_parallelism_threads = NUMCORES
tf.compat.v1.Session.inter_op_parallelism_threads = NUMCORES
class Fit_GPcounts(object):
def __init__(self,X = None,Y= None,scale = None,sparse = False,M=0,nb_scaled=False,safe_mode = False):
self.safe_mode = safe_mode
self.folder_name = 'GPcounts_models/'
self.transform = True # to use log(count+1) transformation
self.sparse = sparse # use sparse or full inference
self.nb_scaled = nb_scaled
self.X = None # time points (cell,samples, spatial location)
self.M = M # number of inducing points
self.Z = None # inducing points
self.ConditionalVariance = False # set inducing points using conditional variance from robustGP method
self.Y = None # gene expression matrix
self.Y_copy = None #copy of gene expression matrix
self.D = None # number of genes
self.N = None # number of cells
self.scale = scale
self.genes_name = None
self.cells_name = None
self.Scale = None
self.kernel = None
self.bic = None
# statistical test information
self.lik_name = None # the selected likelihood name
self.models_number = None # Total number of models to fit for single gene for selected test
self.model_index = None # index the current model
self.hyper_parameters = {} # model paramaters initialization
self.user_hyper_parameters = [None,None,None,None]# user model paramaters initialization
self.model = None # GP model information
self.var = None # GP variance of posterior predictive
self.mean = None # GP mean of posterior predictive
self.fix = False # fix hyper-parameters
# save likelihood of hyper-parameters of dynamic model to initialize the constant model
self.lik_alpha = None
self.lik_km = None
self.optimize = True # optimize or load model
self.branching = None # DE kernel or RBF kernel
self.xp = -1000. # Put branching time much earlier than zero time
# single gene information
self.y = None
self.index = None
self.global_seed = 0
self.seed_value = 0 # initialize seed
self.count_fix = 0 # counter of number of trails to resolve either local optima or failure duo to numerical issues
# check the X and Y are not missing
if (X is None) or (Y is None):
print('TypeError: GPcounts() missing 2 required positional arguments: X and Y')
else:
self.set_X_Y(X,Y)
def set_X_Y(self,X,Y):
self.seed_value = 0
np.random.seed(self.seed_value)
if X.shape[0] == Y.shape[1]:
self.X = X
self.cells_name = list(map(str,list(X.index.values)))
self.X = X.values.astype(float)
if len(self.X.shape) > 1:
self.X = self.X.reshape([-1,self.X.shape[1]])
else:
self.X = self.X.reshape([-1, 1])
if self.sparse:
if self.M == 0:
self.M = int((5*(len(self.X)))/100) # number of inducing points is 5% of length of time points
self.ConditionalVariance = True
self.Y = Y
self.genes_name = self.Y.index.values.tolist() # gene expression name
self.Y = self.Y.values # gene expression matrix
'''
if self.lik_name == 'Gaussian':
self.Y = self.Y.values # gene expression matrix
else:
self.Y = self.Y.values.astype(int)
self.Y = self.Y.astype(float)
self.Y_copy = self.Y
'''
self.Y_copy = self.Y
self.D = Y.shape[0] # number of genes
self.N = Y.shape[1] # number of cells
else:
print('InvalidArgumentError: Dimension 0 in X shape must be equal to Dimension 1 in Y, but shapes are %d and %d.' %(X.shape[0],Y.shape[1]))
def Infer_trajectory(self,lik_name= 'Negative_binomial',transform = True):
if transform == True:
self.Y = self.Y.astype(int)
self.Y = self.Y.astype(float)
self.Y_copy = self.Y
genes_index = range(self.D)
genes_results = self.run_test(lik_name,1,genes_index)
return genes_results
def One_sample_test(self,lik_name= 'Negative_binomial', transform = True):
if transform == True:
self.Y = self.Y.astype(int)
self.Y = self.Y.astype(float)
self.Y_copy = self.Y
genes_index = range(self.D)
genes_results = self.run_test(lik_name,2,genes_index)
return genes_results
def Model_selection_test(self,lik_name = 'Negative_binomial',kernel = None,transform = True):
if transform == True:
self.Y = self.Y.astype(int)
self.Y = self.Y.astype(float)
self.Y_copy = self.Y
# Run GP model for linear, periodic and rbf kernels and calculate BIC
ker_list = ['Linear','Periodic','RBF']
genes_index = range(self.D)
selection_results = pd.DataFrame()
selection_results['Gene'] = 0
selection_results['Dynamic_model_log_likelihood'] = 0
selection_results['Constant_model_log_likelihood'] = 0
selection_results['log_likelihood_ratio'] = 0
selection_results['p_value'] = 0
selection_results['q_value'] = 0
selection_results['log_likelihood_ratio'] = 0
selection_results['Model'] = 0
selection_results['BIC'] = 0
for word in ker_list:
self.kernel = word
results = self.run_test(lik_name,2,genes_index)
results['BIC'] = -2*results['Dynamic_model_log_likelihood'] + self.K*np.log(self.X.shape[0])
results['Gene'] = self.genes_name
results['Model'] = word
results['p_value'] = 1 - ss.chi2.cdf(2*results['log_likelihood_ratio'], df=1)
results['q_value']= self.qvalue(results['p_value'])
selection_results = selection_results.merge(results, how = 'outer')
# Model probability estimation based on bic based on SpatialDE:identification of spatially variable genes: https://www.nature.com/articles/nmeth.4636
tr = selection_results.groupby(['Gene','Model'])['BIC'].transform(min) == selection_results['BIC']
# select bic values for each kernel and gene
bic_values = -selection_results[tr].pivot_table(values='BIC', index='Gene', columns='Model')
restore_these_settings = np.geterr()
temp_settings = restore_these_settings.copy()
temp_settings["over"] = "ignore"
temp_settings["under"] = "ignore"
np.seterr(**temp_settings)
log_v = logsumexp(bic_values,1)
log_model_prob= (bic_values.T - log_v).T
model_prob = np.exp(log_model_prob).add_suffix('_probability')
tr = selection_results.groupby('Gene')['BIC'].transform(min) == selection_results['BIC']
selection_results_prob = selection_results[tr]
selection_results_prob = selection_results_prob.join(model_prob, on='Gene')
transfer_columns = ['p_value', 'q_value']
np.seterr(**restore_these_settings)
selection_results_prob = selection_results_prob.drop(transfer_columns,1)\
.merge(selection_results,how = 'inner')
return selection_results_prob
def Two_samples_test(self,lik_name= 'Negative_binomial',transform = True):
if transform == True:
self.Y = self.Y.astype(int)
self.Y = self.Y.astype(float)
self.Y_copy = self.Y
genes_index = range(self.D)
genes_results = self.run_test(lik_name,3,genes_index)
return genes_results
def Infer_branching_location(self, cell_labels, bins_num=50, lik_name='Negative_binomial',
branching_point=-1000,transform = True):
if transform == True:
self.Y = self.Y.astype(int)
self.Y = self.Y.astype(float)
self.Y_copy = self.Y
cell_labels = | np.array(cell_labels) | numpy.array |
import numpy as np
class ENV_net():
def __init__(self,SNR_mat, UE, BS, Bh):
self.UE = UE
self.BS = BS
self.episode = 0
self.step = 0
self.max_level = 500
self.power_default = 37
self.renew_max = 60
self.renew_min = 37
self.tx_dBm = 30
self.tx_w = np.power(10, self.tx_dBm/10)/1000
self.delta = 2.6
self.grid_power_min = 200
self.grid_power_max = 200
self.QoS_pool = np.array([0.192,2.22,1.5,0.6,4.44]) ## Mbps [Audio, Video, Image, Web_bro, Email]
self.SNR_mat = SNR_mat
self.renew = (np.arange(self.BS) != self.BS-1).astype(int) #np.array([1,1,1,0])
self.grid_power = self.grid_power_min + (self.grid_power_max-self.grid_power_min)*np.random.uniform(size= [self.BS])
self.grid_power = self.grid_power * (1-self.renew)
self.Backhaul_lim = Bh
self.Backhaul = self.Backhaul_lim + (50-self.Backhaul_lim )*(1-self.renew)
self.RB = 100
self.BW = 2e+7
self.action_size_PC = self.BS
self.action_size_UA = 2*self.BS
self.reward_size_PC = 2 * self.BS #3*self.BS
self.reward_size_UA = 4*self.BS #+ 2*self.UE
self.state_size_PC = self.UE*self.BS + 5*self.BS + self.UE
self.state_size_UA = self.UE*self.BS + 2* self.BS + self.UE
self.QoS_penalty = 4.0
self.Backhaul_penalty =100
def reset(self,is_test=False):
if is_test:
self.UA_set = np.arange(self.UE)
self.H_mat = self.SNR_mat[self.episode, :, :,:].copy()
else:
self.UA_set = np.random.permutation(self.SNR_mat.shape[2])[0:self.UE]
self.H_mat = self.SNR_mat[np.mod(self.episode+int(np.random.uniform(0,self.SNR_mat.shape[0])) ,self.SNR_mat.shape[0]), :, :,:].copy()
self.H_mat = self.H_mat[:,self.UA_set,:].copy()
H = self.H_mat[0,:,:].copy()
UA = np.zeros([self.UE]).astype(int)
for i in range(self.UE):
BS_ind = np.mod(i, self.BS)
UE_ind = np.argmax(H[:,BS_ind])
H[UE_ind,:] = -1.0
UA[BS_ind * int(self.UE/self.BS) + int(i/self.BS)] = UE_ind
self.H_mat = self.H_mat[:,UA,:].copy()
self.H = self.H_mat[0, :,:].copy()
self.QoS = np.random.choice(self.QoS_pool.shape[0],[self.UE,1])+0.0
for i in range(self.QoS_pool.shape[0]):
self.QoS[self.QoS == i] = self.QoS_pool[i]
self.QoS[self.QoS==2.22] = (0.6 + (1.4-0.6)*np.random.uniform(size= [np.sum(self.QoS==2.22)]) )
self.QoS[self.QoS==4.44] = (2.0 + (6.0-2.0)*np.random.uniform(size= [np.sum(self.QoS==4.44)]) )
self.b_level = 100 * self.renew
self.res_source =(self.renew_min+ (self.renew_max - self.renew_min)*np.random.uniform(size = [self.BS]))*self.renew
self.state_PC = np.concatenate([(self.H*(self.b_level + self.grid_power - self.power_default)/260).reshape([1,-1])/2000.0, self.QoS.reshape([1,-1]), (np.maximum(self.b_level+self.grid_power - self.power_default,0.0).reshape([1,-1])/260.0), self.b_level.reshape([1,-1])/260, self.grid_power.reshape([1,-1])/260, (self.res_source).reshape([1,-1])/260,self.Backhaul.reshape([1,-1])/10.0], axis=1)
def get_state_UA(self):
self.P = np.clip( (self.renew * (0.01 + 0.69 * (self.action[0,0:self.BS]+1)/2) + (1-self.renew) * (0.01 + 0.99 * (self.action[0,0:self.BS]+1)/2))*(self.b_level + self.grid_power -self.power_default)/self.delta/self.RB,
0, 1).reshape([1,-1])
SNR = self.H * self.P
SINR = SNR/ ( 1+ np.tile(np.sum(SNR,axis=1,keepdims=True),[1, self.BS]) - SNR)
self.Rate = np.log2(1+SINR)*100*0.18 + 0.001
self.state_UA = np.concatenate([np.max(self.Rate,axis=0).reshape([1,-1]),-np.log(1+self.QoS/self.Rate).reshape([1,-1]),self.Backhaul.reshape([1,-1]), self.QoS.reshape([1,-1])],axis=1)
def get_X(self, Rate, QoS, Backhaul, mu, rho, is_print=False):
mu = np.expand_dims(mu,axis=1)
rho = np.expand_dims(rho,axis=1)
Backhaul = np.expand_dims(Backhaul,axis=1)
X = (np.expand_dims(np.argmax(Rate,axis=2),2) == np.arange(self.BS).reshape([1,1,self.BS]))+0.0
lamb = np.max(Rate*X,axis=1,keepdims=True)
count = 0
while 1:
lamb_old = lamb.copy()
if X.shape[0] > 0:
UE_order = np.random.permutation(self.UE)
else:
UE_order = np.argsort(np.min(np.maximum(QoS/Rate, QoS/Backhaul)[0,:,:],axis=1))
for UE_ind in UE_order:
X[:,UE_ind,:] = 0
lamb = np.max(Rate*X,axis=1,keepdims=True)
UE_opt = -(1+mu)*QoS * lamb/Rate - rho * QoS
## Tie Break
UE_select = np.argmax(UE_opt[:,UE_ind,:],axis=1)[0]
BB= -UE_opt[0,UE_ind,:].copy()
indices = np.argsort(BB,axis=0)
R_remain = 1-np.sum(np.sum(QoS/Rate*X,axis=1),axis=0)
B_remain = Backhaul[0,0,:] - np.sum(np.sum(QoS*X,axis=1),axis=0)
if R_remain[UE_select] < QoS[0,UE_ind,0]/Rate[0,UE_ind,UE_select] or B_remain[UE_select] < QoS[0,UE_ind,0]:
X[:,UE_ind,:] = 0.0
X[:,UE_ind,:] = (UE_select == np.arange(self.BS).reshape([1,self.BS]))+0.0
Y = self.get_Y(X[0,:,:],mu[0,:,:],rho[0,:,:])
reward_org = np.sum(self.Rate * X[0,:,:] * Y)/40 - np.sum(self.QoS > np.sum(self.Rate * X[0,:,:]*Y,axis=1,keepdims=True)+1e-7)/self.UE * 40
for B_ind in indices:
if abs(np.log(abs(BB[UE_select] / BB[B_ind])))<0.5:
X[:,UE_ind,:] = 0
X[:,UE_ind,:] = (B_ind == np.arange(self.BS).reshape([1,self.BS]))+0.0
Y=self.get_Y(X[0,:,:],mu[0,:,:],rho[0,:,:])
reward_new = np.sum(self.Rate * X[0,:,:] * Y)/40 - np.sum(self.QoS > np.sum(self.Rate * X[0,:,:]*Y,axis=1,keepdims=True)+1e-7)/self.UE * 40
if reward_new >reward_org:
UE_select = B_ind
break
X[:,UE_ind,:] = 0.0
X[:,UE_ind,:] = (UE_select == np.arange(self.BS).reshape([1,self.BS]))+0.0
lamb = np.max(Rate*X,axis=1,keepdims=True)
if np.sum(abs(lamb_old-lamb)>1e-7) == 0:
count = count+1
if count > 1:
break
Y = QoS / Rate * X #[Batch, UE, BS]
Y_opt = Y.copy()
Y_opt[Y_opt==0] = 9999999.9
Y_s = np.sort(Y_opt,axis=1)
QoS_tile = np.tile(QoS, [1,1,self.BS])
ind = np.argsort(Y_opt,axis=1)
QoS_s = np.take_along_axis(QoS_tile, ind, axis=1)
fail_rate = 1-np.sum((np.cumsum(Y_s,axis=1) < 1) * (np.cumsum(QoS_s,axis=1)<Backhaul) )/self.UE
return X.copy(), fail_rate
def get_Y(self,X,mu,rho):
Z = ( | np.argmax(self.Rate*X,axis=0) | numpy.argmax |
# Copyright (c) 2019 ipychord3 authors
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
"""This module contains some of the old function with sf_ prefix
"""
import logging
from copy import deepcopy
from collections import namedtuple
import matplotlib.pyplot as plt
from matplotlib.figure import figaspect
from matplotlib.font_manager import FontProperties
from matplotlib.patches import Wedge
from matplotlib.path import Path
import skimage.draw as sidraw
import skimage.transform as sitransform
import numpy as np
from scipy import ndimage
from scipy.ndimage.filters import median_filter
from . import cmaps
# setup logging
logger = logging.getLogger(__name__)
logger.addHandler(logging.NullHandler())
# we can't use TK backend, it will crash with python 3.4 on windows:
# https://github.com/ipython/ipython/issues/8921#issuecomment-151046708
# matplotlib.use('TkAgg')
# matplotlib.use('Qt4Agg')
# ----------------------------------------------------------------------------
# Miscellaneous
# ----------------------------------------------------------------------------
Circle = namedtuple('Circle', ['center', 'radius'])
Rectangle = namedtuple('Rectangle', ['corner', 'width', 'height'])
Polygon = namedtuple('Polygon', ['vertices'])
RingSector = namedtuple('RingSector', ['theta1', 'theta2', 'radius',
'width', 'center'])
def handle_close(event):
"""Handle the closing of a figure,
it stops the event loop so the program can continue
"""
fig = event.canvas.figure
logger.debug("stopping blocking event loop")
fig.canvas.stop_event_loop()
def prepare_patter_for_show(img, ulev=None, dlev=None, log=0, med=None,
over=None, neg=False, mag=False, clip=True):
"""prepare pattern for show
Scales the pattern and computes ``ulev`` and ``dlev``
A copy of the pattern is returned.
:param img: the image dictionary
:type img: dict
:param ulev: show the image in certain interval, ulev defines the upper level.
:type ulev: float
:param dlev: defines the down level
:type dlev: float
:param log: show the image in log scale coordinate
:log==0: show it in linear coordinate
:log==1: show it in log() coordinate
:log==2: show it in log(log()) coordinate
:type log: int
:param med: use median filter to estimate ulev, ``3 < med < 15`` otherwise ``med=5``
:type med: float
:param over: overestimation of the scales
:type over: float
:param neg: show the negative side of the image
:type neg: bool
:param mag: show magnitude of image
:type mag: bool
:param clip: clip negative values
:type clip: bool
:return: scaled pattern, ulev, dlev
:rtype: pattern dict, float, float
"""
img = deepcopy(img)
if mag:
img['map'] = np.absolute(img['map'])
if neg:
mask = img['map'] <= 0.0
img['map'] *= mask
img['map'] *= -1.0
if clip:
img['map'] = img['map'] * (img['map'] >= 0.0)
if log == 0:
logger.info("The image is shown in the linear coordinates")
if ulev is None:
if med is not None:
if not 3 < med < 15:
med = 5
ulev = ndimage.median_filter(img['map'], med).max()
logger.debug("ulev is None: estimated with median %g linear as %g" %(med, ulev))
else:
ulev = img['map'].max()
logger.debug("ulev is None: estimated directly as %g" %ulev)
logger.debug("linear ulev = %g" %ulev)
else:
logger.debug("ulev set by user as %g" %ulev)
if dlev is None:
dlev = img['map'].min()
logger.debug("dlev is None: estimated as %g" %dlev)
else:
logger.debug("dlev set as: %g" %dlev)
elif log == 1:
img['map'] = np.log(img['map']+1.0)
if ulev is None:
logger.debug("estimating ulev")
ulev = (img['map']+1.0).max()
dlev = (img['map']+1.0).min()
logger.debug("log scale used: dlev = %g, ulev = %g" % (dlev, ulev))
elif log == 2:
img['map'] = np.log(np.log(img['map']+1.0)+1.0)
if ulev is None:
ulev = (img['map']+1.0).max()
dlev = (img['map']+1.0).min()
logger.debug("double log scale used: dlev = %g, ulev = %g" % (dlev, ulev))
if over is not None:
ulev /= over
logger.info("overestimated ulev corrected to %g" % ulev)
return img, ulev, dlev
# ----------------------------------------------------------------------------
# Interactive functions
# ----------------------------------------------------------------------------
def show(img, ulev=None, dlev=None, log=0, med=None, win=None, block=False, show=True,
cmap='viridis', over=None, neg=False, mag=False, clip=True, scalefig=1.2):
""" show the image under different conditions
.. note:: This function can not show the positive and negative value
in one image except we use the absolute value to show all the
values in one image.
:param img: the image dictionary
:type img: dict
:param ulev: show the image in certain interval, ulev defines the upper level.
:type ulev: float
:param dlev: defines the down level
:type dlev: float
:param log: show the image in log scale coordinate
:log==0: show it in linear coordinate
:log==1: show it in log() coordinate
:log==2: show it in log(log()) coordinate
:type log: int
:param med: use median filter to estimate ulev, ``3 < med < 15`` otherwise ``med=5``
:type med: float
:param win:
:type win: matplotlib window, int
:param block: show the image in the interactive way and block the command line
:type block: bool
:param show: show the figure
:type show: bool
:param cmap: colormap to be passed to ``imshow``, delauft ``ipychord3.cmaps.lut05()``
:type cmap: matplotlib.colors.Colormap or string
:param over: overestimation of the scales
:type over: float
:param neg: show the negative side of the image
:type neg: bool
:param mag: show magnitude of image
:type mag: bool
:param clip: clip negative values
:type clip: bool
:param float scalefig: scale the figure by factor
:return: figure
:rtype: matplotlib figure object
"""
# protect the virgin img
kwargs_for_prepare = {'ulev': ulev, 'dlev': dlev, 'log': log, 'med': med,
'over': over, 'neg': neg, 'mag': mag, 'clip': clip}
img, ulev, dlev = prepare_patter_for_show(img, **kwargs_for_prepare)
# create figure
w, h = figaspect(img['map'])
if win is None:
fig = plt.figure(figsize=(scalefig*w, scalefig*h))
else:
fig = plt.figure(win, figsize=(scalefig*w, scalefig*h))
logger.info("dlev = %g ulev = %g" % (dlev, ulev))
# create the axis and show the image
ax = plt.Axes(fig, [0., 0., 1., 1.])
fig.add_axes(ax)
ax.imshow(img['map'], interpolation='nearest', vmin=dlev, vmax=ulev, cmap=cmap, origin='upper')
ax.set_aspect('equal')
ax.set_axis_off()
if 'filename' in img:
fig.canvas.set_window_title(img['filename']+'_sf_show')
elif 'title' in img:
fig.canvas.set_window_title(img['title'])
else:
fig.canvas.set_window_title('sf.show pattern')
fig._sf_kwargs_for_prepare = kwargs_for_prepare
if not show:
return fig
elif block:
# now we start an extra event loop for this figure
# it will block the program until fig.canvas.stop_event_loop() is called
fig.canvas.mpl_connect('close_event', handle_close)
fig.show()
logger.debug("starting blocking event loop")
fig.canvas.start_event_loop(timeout=-1)
else:
fig.show()
logger.debug("show non-blocking figure: starting event loop to force drawing of figure")
fig.canvas.start_event_loop(timeout=.01) # start extra event loop for a short time to
# force drawing of the figure
logger.debug("show non-blocking figure: event loop exited")
return fig
def killcircle(img, fig={}):
"""Select circles in figure and mask them in the pattern
:param img: pattern dict
:param fig: a dictionary with keyword arguments for ``sf.show``
or a matplotlib figure
.. note:: If you use ``sf.show`` the figure must be created using ``block=False``.
If a dict is passed ``block`` will be set to ``False``.
:returns: masked pattern, mask, circles
:raises RuntimeError: if no circles have been drawn
.. hint::
:Draw circle: left mouse button to set center, set radius by clicking left button again
:Modify circle:
use +/- keys to increase/decrease radius by 1 px
use arrow-keys to move center
:Delete circle: backspace
:Select circle: use "ctrl+[0..6]" to select one of the first 7 circles
"""
if isinstance(fig, dict):
logger.debug('creating figure')
fig['block'] = False
fig = show(img, **fig)
selector = SelectCircles(fig)
circles = selector.circles
imgmask, mask = mask_circles(img, circles)
return imgmask, mask, circles
def killbox(img, fig={}):
"""Select rectangles in figure and mask the pattern
:param img: pattern dict
:param fig: a dictionary with keyword arguments for ``sf.show``
or a matplotlib figure
.. note:: If you use ``sf.show`` the figure must be created using ``block=False``.
If a dict is passed ``block`` will be set to ``False``.
:returns: masked pattern, mask, rectangles
:raises RuntimeError: if no rectangles have been drawn
.. hint::
:Draw rectangle: left mouse button to set corner, set other corner by clicking left button again
:Modify circle:
use +/-/*/_ keys to increase/decrease x/y by 1 px
use arrow-keys to first corner
:Delete rectangle: backspace
"""
if isinstance(fig, dict):
logger.debug('creating figure')
fig['block'] = False
fig = show(img, **fig)
selector = SelectRectangles(fig)
rectangles = selector.rectangles
imgmask, mask = mask_rectangles(img, rectangles)
return imgmask, mask, rectangles
def killpoly(img, fig={}):
"""Select polygons in figure and mask them in the pattern
:param img: pattern dict
:param fig: a dictionary with keyword arguments for ``sf.show``
or a matplotlib figure
.. note:: If you use ``sf.show`` the figure must be created using ``block=False``.
If a dict is passed ``block`` will be set to ``False``.
:returns: masked pattern, mask, polygons
:raises RuntimeError: if no polygons have been drawn
.. hint::
:Draw polygon: left mouse button to set vertices, set last vertex with right mouse button
:Modify polygon:
use `shift-backspace` to delete a vertex
:Delete polygon: backspace
"""
if isinstance(fig, dict):
logger.debug('creating figure')
fig['block'] = False
fig = show(img, **fig)
selector = SelectPolygons(fig)
polygons = selector.polygons
imgmask, mask = mask_polygons(img, polygons)
return imgmask, mask, polygons
def kill_ringsector(img, fig={}, center=None):
"""Select ring sectors in figure and mask them in the pattern
:param img: pattern dict
:param fig: a dictionary with keyword arguments for ``sf.show``
or a matplotlib figure
.. note:: If you use ``sf.show`` the figure must be created using ``block=False``.
If a dict is passed ``block`` will be set to ``False``.
:returns: masked pattern, mask, masks, sectors
:raises RuntimeError: if no sectors have been drawn
.. hint::
:Draw sector: left mouse button to set vertices, adjust position with keyboard (see ctrl-h), press space to draw new sector
:Delete sector: backspace
"""
if isinstance(fig, dict):
logger.debug('creating figure')
fig['block'] = False
fig = show(img, **fig)
selector = SelectRingSectors(fig, center=center)
sectors = selector.sectors
imgmask, mask, masks = mask_ring_sectors(img, sectors)
return imgmask, mask, masks, sectors
def create_peak_masks(img, fig={}, center=None):
"""Select ring sectors in figure to select peaks and a corresponding reference.
This function returns a stacked list of masks [peak_mask, reference_mask]
:param img: pattern dict
:param fig: a dictionary with keyword arguments for ``sf.show``
or a matplotlib figure
.. note:: If you use ``sf.show`` the figure must be created using ``block=False``.
If a dict is passed ``block`` will be set to ``False``.
:returns: masks, sectors
:raises RuntimeError: if no sectors have been drawn
.. hint::
:Draw sector: left mouse button to set vertices, adjust position with keyboard (see ctrl-h), press space to draw new sector.
:Delete sector: backspace
"""
if isinstance(fig, dict):
logger.debug('creating figure')
fig['block'] = False
fig = show(img, **fig)
selector = SelectTwoRingSectors(fig, center=center)
sectors = selector.sectors
mask = make_peak_mask(img, sectors)
return mask, sectors
def rotate_pattern(img, fig={}, angle=None):
""" Rotates the pattern by interactively by 0.3° / 1° or non-interactive by ``angle``
:param img: pattern dict
:param fig: a dictionary with keyword arguments for ``sf.show``
or a matplotlib figure
.. note:: If you use ``sf.show`` the figure must be created using ``block=False``.
If a dict is passed ``block`` will be set to ``False``.
:param angle: if not ``None`` rotate pattern by ``angle`` without opening a figure window
:returns: rotated pattern, angle
.. hint::
:rotate clockwise: ``r``: 0.3° ``R``: 1°
:rotate anticlockwise: ``a``: 0.3° ``A``: 1°
"""
img = deepcopy(img)
if angle is not None:
img['map'] = ndimage.rotate(img['map'], angle, mode='constant', cval=0.0)
img['beam_position'] = midpnt(img)
else:
if isinstance(fig, dict):
logger.debug('creating figure')
fig['block'] = False
fig = show(img, **fig)
rot = RotatePattern(fig, img)
img = rot.img
angle = rot.angle
return img, angle
def debye(img, fig, center=None):
"""Draw the Debye-Scherrer rings, calculates diameter and center of each
and returns the mean center for mirroring
:param fig: a dictionary with keyword arguments for ``sf.show``
or a matplotlib figure
.. note:: If you use ``sf.show`` the figure must be created using ``block=False``.
If a dict is passed ``block`` will be set to ``False``.
:param center: set the beam position (x, y)
:returns: ``[center x, center y, circles]``
:raises RuntimeError: if no circles have been drawn
"""
if isinstance(fig, dict):
logger.debug('creating figure')
fig['block'] = False
fig = show(img, **fig)
print('Draw circles in Debye-Scherrer rings to calculate their diameter \
and center.')
selector = SelectCirclesSameCenter(fig, center)
centers = []
circles = selector.circles
if not circles:
raise RuntimeError("You have to create at least one circle")
logger.debug("length of circles = %d" % len(circles))
for i, circle in enumerate(circles):
d = 2 * circle.radius
center = circle.center
centers.append(center)
print("Circle %d: (%.4f, %.4f)@%.4f" % (i + 1, center[0], center[1], d))
return circles[0].center[0], circles[0].center[1], circles
# ----------------------------------------------------------------------------
# Modifier functions
# ----------------------------------------------------------------------------
def mask_circles(img, circles):
"""mask ``circle`` in ``img``
:param img: pattern dict
:param circles: list of ``sf.Circle``'s
:returns: masked image, mask
"""
imgmask = deepcopy(img)
mask = np.ones_like(imgmask['map'], dtype=np.uint8)
for circle in circles:
temp_mask = np.ones_like(imgmask['map'], dtype=np.uint8)
x, y = circle.center
rr, cc = sidraw.circle(y, x, circle.radius, shape=imgmask['map'].shape)
temp_mask[rr, cc] = 0
mask *= temp_mask
imgmask['map'] = mask * imgmask['map']
return imgmask, mask
def mask_rectangles(img, rectangles):
"""mask ``rectangles`` in ``img``
:param img: pattern dict
:param rectangles: list of ``sf.Rectangle``'s
:returns: masked image, mask
"""
imgmask = deepcopy(img)
mask = np.ones_like(imgmask['map'], dtype=np.uint8)
for rectangle in rectangles:
temp_mask = np.ones_like(imgmask['map'], dtype=np.uint8)
corner = rectangle.corner
width = rectangle.width
height = rectangle.height
c = np.array([corner[0], corner[0] + width, corner[0] + width, corner[0]])
r = np.array([corner[1], corner[1], corner[1] + height, corner[1] + height])
rr, cc = sidraw.polygon(r, c, shape=imgmask['map'].shape)
temp_mask[rr, cc] = 0
mask *= temp_mask
imgmask['map'] = imgmask['map'] * mask
return imgmask, mask
def mask_polygons(img, polygons):
"""mask ``polygons`` in ``img``
:param img: pattern dict
:param polygons: list of ``sf.Polygon``'s
:returns: masked image, mask
"""
imgmask = deepcopy(img)
mask = np.ones_like(imgmask['map'], dtype=np.uint8)
for polygon in polygons:
temp_mask = np.ones_like(imgmask['map'], dtype=np.uint8)
xy = polygon.vertices
c = xy[:, 0]
r = xy[:, 1]
rr, cc = sidraw.polygon(r, c, shape=imgmask['map'].shape)
temp_mask[rr, cc] = 0
mask *= temp_mask
imgmask['map'] = imgmask['map'] * mask
return imgmask, mask
def mask_ring_sectors(img, sectors):
"""mask ``sectors`` in ``img``
:param img: pattern dict
:param sectors: list of ``sf.RingSector``'s
:returns: masked image, mask, masks
"""
imgmask = deepcopy(img)
mask = np.ones_like(imgmask['map'], dtype=np.uint8)
masks = []
for sector in sectors:
temp_mask = np.ones_like(imgmask['map'], dtype=np.uint8)
xy = SelectRingSectors.compute_path(sector)
c = xy[:, 0]
r = xy[:, 1]
rr, cc = sidraw.polygon(r, c, shape=imgmask['map'].shape)
temp_mask[rr, cc] = 0
mask *= temp_mask
masks.append(temp_mask)
imgmask['map'] = imgmask['map'] * mask
return imgmask, mask, masks
def make_peak_mask(img, peak_sectors):
"""mask ``peak_sectors`` in ``img``
``peak_sectors`` is a stacked list of sectors for the peak and the reference.
This function returns a stacked list of masks [peak_mask, reference_mask]
:param img: pattern dict
:param peak_sectors: stacked list of ``sf.RingSector``'s
:returns: masks
"""
masks = []
for sectors in peak_sectors:
mask0 = np.zeros_like(img['map'], dtype=np.uint8)
xy = SelectRingSectors.compute_path(sectors[0])
c = xy[:, 0]
r = xy[:, 1]
rr, cc = sidraw.polygon(r, c, shape=img['map'].shape)
mask0[rr, cc] = 1
mask1 = np.zeros_like(img['map'], dtype=np.uint8)
xy = SelectRingSectors.compute_path(sectors[1])
c = xy[:, 0]
r = xy[:, 1]
rr, cc = sidraw.polygon(r, c, shape=img['map'].shape)
mask1[rr, cc] = 1
masks.append([mask0, mask1])
return masks
def midpnt(img):
""" compute the midpoint pixel of an image
The pixel coordinates in dimension (``dim``) are computed as
:if ``dim`` is odd: ``(dim - 1)/2``
:if ``dim`` is even: ``dim/2``
:param img: pattern
:return: midpoint pixel in image coordinates
"""
shape = np.asarray(img['map'].shape, dtype=np.int)
midp = np.zeros_like(shape)
for i, item in enumerate(shape):
midp[i] = item - 1 if item % 2 else item
midp = midp[::-1]
return midp // 2
def extend_image(img, center):
"""extend the pattern such that the midpoint is the center of the image
the shape of the extended image is always odd
:param img: pattern
:param center: center
:return: extended pattern
"""
array_mid = np.asarray(list(reversed(center)), dtype=np.int)
map_size = np.asarray(img['map'].shape, dtype=np.int)
map_mid = midpnt(img)[::-1]
delta_midp = map_mid - array_mid
ext_y = np.abs(2*array_mid[0] + 1 - map_size[0])
if delta_midp[0] > 0:
new_map = np.vstack((np.zeros((ext_y, map_size[1])), img['map']))
else:
new_map = np.vstack((img['map'], np.zeros((ext_y, map_size[1]))))
ext_x = np.abs(2*array_mid[1] + 1 - map_size[1])
if delta_midp[1] > 0:
new_map = np.hstack((np.zeros((new_map.shape[0], ext_x)), new_map))
else:
new_map = np.hstack((new_map, np.zeros((new_map.shape[0], ext_x))))
new_img = deepcopy(img)
new_img['map'] = new_map
return new_img
def harmonize_image(img):
"""harmonize the image"""
new_map = img['map']
map_size = np.asarray(img['map'].shape, dtype=np.int)
if not any(map_size % 2):
raise ValueError('The shape of the pattern must be odd.')
map_mid = midpnt(img)[::-1]
lower_left = new_map[0:map_mid[0]+1, 0:map_mid[1]+1]
lower_right = new_map[0:map_mid[0]+1, map_mid[1]:]
lower_right = np.fliplr(lower_right)
upper_left = new_map[map_mid[0]:, 0:map_mid[1]+1]
upper_left = np.flipud(upper_left)
upper_right = new_map[map_mid[0]:, map_mid[1]:]
upper_right = np.flipud(np.fliplr(upper_right))
all_sum = np.zeros_like(lower_left)
count = np.zeros_like(lower_left)
for i in [lower_left, lower_right, upper_left, upper_right]:
all_sum += i
count += i > 0
count[count == 0] = 1
final_map = all_sum / count
# we have to crop the parts as the row and column containing
# the midpoint would otherwise appear four times in the final pattern
ll = final_map
lr = np.fliplr(ll)[:, 1:]
ul = np.flipud(ll)[1:, :]
ur = np.flipud(np.fliplr(ll))[1:, 1:]
l = np.hstack((ll, lr))
u = np.hstack((ul, ur))
f = np.vstack((l, u))
new_img = deepcopy(img)
new_img['map'] = f
return new_img
def harmonize_image_2(img):
"""harmonize the pattern, assumeing 180° symmetry"""
new_map = img['map']
map_size = np.asarray(img['map'].shape, dtype=np.int)
if not any(map_size % 2):
raise ValueError('The shape of the pattern must be odd.')
map_mid = midpnt(img)[::-1]
lower = new_map[0:map_mid[0]+1, :]
lower = np.flipud(np.fliplr(lower))
upper = new_map[map_mid[0]:, :]
all_sum = np.zeros_like(lower)
count = np.zeros_like(lower)
for i in [lower, upper]:
all_sum += i
count += i > 0
count[count == 0] = 1
final_map = all_sum / count
# we have to crop the parts as the row containing
# the midpoint would otherwise appear twice in the final pattern
u = final_map[1:, :]
l = np.flipud(np.fliplr(final_map))
f = np.vstack((l, u))
new_img = deepcopy(img)
new_img['map'] = f
return new_img
def harmony(img, center, angle=None):
"""Harmonize the pattern by exploiting symmetry
If the shape of the pattern is not anymore odd after the rotation has been
performed the pattern is padded with zeros such that its shape is odd.
:param img: pattern
:param center: center coordinates in pattern
:param angle: rotate image by angle, in degrees in counter-clockwise direction
:return: harmonized pattern
"""
if angle is not None:
ext_img = extend_image(img, center)
new_center = midpnt(ext_img)
ext_img['map'] = sitransform.rotate(ext_img['map'], angle,
center=new_center, cval=0,
resize=1, preserve_range=1)
# after rotation the image shape may not be odd anymore so we append zeros
if not ext_img['map'].shape[0] % 2:
fill = np.zeros((1, ext_img['map'].shape[1]))
ext_img['map'] = | np.vstack((fill, ext_img['map'])) | numpy.vstack |
"""
Tests for the particle array module.
"""
# standard imports
import unittest
import numpy
# local imports
from pysph.base import particle_array
from pysph.base import utils
from pyzoltan.core.carray import LongArray, IntArray, DoubleArray
import pickle
import pytest
from pysph.cpy.config import get_config
def check_array(x, y):
"""Check if two arrays are equal with an absolute tolerance of
1e-16."""
return numpy.allclose(x, y, atol=1e-16, rtol=0)
###############################################################################
# `ParticleArrayTest` class.
###############################################################################
class ParticleArrayTest(object):
"""
Tests for the particle array class.
"""
def test_constructor(self):
# Default constructor test.
p = particle_array.ParticleArray(name='test_particle_array',
backend=self.backend)
self.assertEqual(p.name, 'test_particle_array')
self.assertEqual('tag' in p.properties, True)
self.assertEqual(p.properties['tag'].length, 0)
# Constructor with some properties.
x = [1, 2, 3, 4.]
y = [0., 1., 2., 3.]
z = [0., 0., 0., 0.]
m = [1., 1., 1., 1.]
h = [.1, .1, .1, .1]
p = particle_array.ParticleArray(x={'data': x},
y={'data': y},
z={'data': z},
m={'data': m},
h={'data': h},
backend=self.backend)
self.assertEqual(p.name, '')
self.assertEqual('x' in p.properties, True)
self.assertEqual('y' in p.properties, True)
self.assertEqual('z' in p.properties, True)
self.assertEqual('m' in p.properties, True)
self.assertEqual('h' in p.properties, True)
# get the properties are check if they are the same
xarr = p.properties['x'].get_npy_array()
self.assertEqual(check_array(xarr, x), True)
yarr = p.properties['y'].get_npy_array()
self.assertEqual(check_array(yarr, y), True)
zarr = p.properties['z'].get_npy_array()
self.assertEqual(check_array(zarr, z), True)
marr = p.properties['m'].get_npy_array()
self.assertEqual(check_array(marr, m), True)
harr = p.properties['h'].get_npy_array()
self.assertEqual(check_array(harr, h), True)
# check if the 'tag' array was added.
self.assertEqual('tag' in p.properties, True)
self.assertEqual(list(p.properties.values())[0].length == len(x), True)
# Constructor with tags
tags = [0, 1, 0, 1]
p = particle_array.ParticleArray(x={'data': x}, y={'data': y},
z={'data': z},
tag={'data': tags, 'type': 'int'},
backend=self.backend)
self.assertEqual(check_array(p.get('tag', only_real_particles=False),
[0, 0, 1, 1]), True)
self.assertEqual(check_array(p.get('x', only_real_particles=False),
[1, 3, 2, 4]), True)
self.assertEqual(check_array(p.get('y', only_real_particles=False),
[0, 2, 1, 3]), True)
self.assertEqual(check_array(p.get('z', only_real_particles=False),
[0, 0, 0, 0]), True)
# trying to create particle array without any values but some
# properties.
p = particle_array.ParticleArray(x={}, y={}, z={}, h={},
backend=self.backend)
self.assertEqual(p.get_number_of_particles(), 0)
self.assertEqual('x' in p.properties, True)
self.assertEqual('y' in p.properties, True)
self.assertEqual('z' in p.properties, True)
self.assertEqual('tag' in p.properties, True)
# now trying to supply some properties with values and others without
p = particle_array.ParticleArray(
x={'default': 10.0}, y={'data': [1.0, 2.0]},
z={}, h={'data': [0.1, 0.1]}, backend=self.backend
)
self.assertEqual(p.get_number_of_particles(), 2)
self.assertEqual(check_array(p.x, [10., 10.]), True)
self.assertEqual(check_array(p.y, [1., 2.]), True)
self.assertEqual(check_array(p.z, [0, 0]), True)
self.assertEqual(check_array(p.h, [0.1, 0.1]), True)
def test_constructor_works_with_strides(self):
# Given
x = [1, 2, 3, 4.]
rho = 10.0
data = numpy.arange(8)
# When
p = particle_array.ParticleArray(
x=x, rho=rho, data={'data': data, 'stride': 2}, name='fluid',
backend=self.backend
)
# Then
self.assertEqual(p.name, 'fluid')
self.assertEqual('x' in p.properties, True)
self.assertEqual('rho' in p.properties, True)
self.assertEqual('data' in p.properties, True)
self.assertEqual('tag' in p.properties, True)
self.assertEqual('pid' in p.properties, True)
self.assertEqual('gid' in p.properties, True)
# get the properties are check if they are the same
self.assertEqual(check_array(p.x, x), True)
self.assertEqual(check_array(p.rho, numpy.ones(4) * rho), True)
self.assertEqual(check_array(p.data, numpy.ravel(data)), True)
def test_constructor_works_with_simple_props(self):
# Given
x = [1, 2, 3, 4.]
y = [0., 1., 2., 3.]
rho = 10.0
data = numpy.diag((2, 2))
# When
p = particle_array.ParticleArray(
x=x, y=y, rho=rho, data=data, name='fluid',
backend=self.backend
)
# Then
self.assertEqual(p.name, 'fluid')
self.assertEqual('x' in p.properties, True)
self.assertEqual('y' in p.properties, True)
self.assertEqual('rho' in p.properties, True)
self.assertEqual('data' in p.properties, True)
self.assertEqual('tag' in p.properties, True)
self.assertEqual('pid' in p.properties, True)
self.assertEqual('gid' in p.properties, True)
# get the properties are check if they are the same
self.assertEqual(check_array(p.x, x), True)
self.assertEqual(check_array(p.y, y), True)
self.assertEqual(check_array(p.rho, numpy.ones(4) * rho), True)
self.assertEqual(check_array(p.data, numpy.ravel(data)), True)
def test_get_number_of_particles(self):
x = [1, 2, 3, 4.]
y = [0., 1., 2., 3.]
z = [0., 0., 0., 0.]
m = [1., 1., 1., 1.]
h = [.1, .1, .1, .1]
A = numpy.arange(12)
p = particle_array.ParticleArray(
x={'data': x}, y={'data': y},
z={'data': z}, m={'data': m},
h={'data': h}, A={'data': A, 'stride': 3},
backend=self.backend
)
self.assertEqual(p.get_number_of_particles(), 4)
def test_get(self):
x = [1, 2, 3, 4.]
y = [0., 1., 2., 3.]
z = [0., 0., 0., 0.]
m = [1., 1., 1., 1.]
h = [.1, .1, .1, .1]
A = numpy.arange(12)
p = particle_array.ParticleArray(
x={'data': x}, y={'data': y},
z={'data': z}, m={'data': m},
h={'data': h}, A={'data': A, 'stride': 3},
backend=self.backend
)
self.assertEqual(check_array(x, p.get('x')), True)
self.assertEqual(check_array(y, p.get('y')), True)
self.assertEqual(check_array(z, p.get('z')), True)
self.assertEqual(check_array(m, p.get('m')), True)
self.assertEqual(check_array(h, p.get('h')), True)
self.assertEqual(check_array(A.ravel(), p.get('A')), True)
def test_clear(self):
x = [1, 2, 3, 4.]
y = [0., 1., 2., 3.]
z = [0., 0., 0., 0.]
m = [1., 1., 1., 1.]
h = [.1, .1, .1, .1]
p = particle_array.ParticleArray(x={'data': x}, y={'data': y},
z={'data': z}, m={'data': m},
h={'data': h}, backend=self.backend)
p.clear()
self.assertEqual(len(p.properties), 3)
self.assertEqual('tag' in p.properties, True)
self.assertEqual(p.properties['tag'].length, 0)
self.assertEqual('pid' in p.properties, True)
self.assertEqual(p.properties['pid'].length, 0)
self.assertEqual('gid' in p.properties, True)
self.assertEqual(p.properties['gid'].length, 0)
def test_getattr(self):
x = [1, 2, 3, 4.]
y = [0., 1., 2., 3.]
z = [0., 0., 0., 0.]
m = [1., 1., 1., 1.]
h = [.1, .1, .1, .1]
A = numpy.arange(12)
p = particle_array.ParticleArray(
x={'data': x}, y={'data': y},
z={'data': z}, m={'data': m},
h={'data': h}, A={'data': A, 'stride': 3},
backend=self.backend
)
self.assertEqual(check_array(x, p.x), True)
self.assertEqual(check_array(y, p.y), True)
self.assertEqual(check_array(z, p.z), True)
self.assertEqual(check_array(m, p.m), True)
self.assertEqual(check_array(h, p.h), True)
self.assertEqual(check_array(A.ravel(), p.get('A')), True)
# try getting an non-existant attribute
self.assertRaises(AttributeError, p.__getattr__, 'a')
def test_setattr(self):
x = [1, 2, 3, 4.]
y = [0., 1., 2., 3.]
z = [0., 0., 0., 0.]
m = [1., 1., 1., 1.]
h = [.1, .1, .1, .1]
A = numpy.arange(12)
p = particle_array.ParticleArray(
x={'data': x}, y={'data': y},
z={'data': z}, m={'data': m},
h={'data': h}, A={'data': A, 'stride': 3},
backend=self.backend
)
p.x = p.x * 2.0
self.assertEqual(check_array(p.get('x'), [2., 4, 6, 8]), True)
p.x = p.x + 3.0 * p.x
self.assertEqual(check_array(p.get('x'), [8., 16., 24., 32.]), True)
p.A = p.A*2
self.assertEqual(check_array(p.get('A').ravel(), A*2), True)
def test_remove_particles(self):
x = [1, 2, 3, 4.]
y = [0., 1., 2., 3.]
z = [0., 0., 0., 0.]
m = [1., 1., 1., 1.]
h = [.1, .1, .1, .1]
A = numpy.arange(12)
p = particle_array.ParticleArray(
x={'data': x}, y={'data': y},
z={'data': z}, m={'data': m},
h={'data': h}, A={'data': A, 'stride': 3},
backend=self.backend
)
remove_arr = LongArray(0)
remove_arr.append(0)
remove_arr.append(1)
p.remove_particles(remove_arr)
self.pull(p)
self.assertEqual(p.get_number_of_particles(), 2)
self.assertEqual(check_array(p.x, [3., 4.]), True)
self.assertEqual(check_array(p.y, [2., 3.]), True)
self.assertEqual(check_array(p.z, [0., 0.]), True)
self.assertEqual(check_array(p.m, [1., 1.]), True)
self.assertEqual(check_array(p.h, [.1, .1]), True)
self.assertEqual(check_array(p.A, numpy.arange(6, 12)), True)
# now try invalid operations to make sure errors are raised.
remove_arr.resize(10)
self.assertRaises(ValueError, p.remove_particles, remove_arr)
# now try to remove a particle with index more that particle
# length.
remove_arr = [2]
p.remove_particles(remove_arr)
self.pull(p)
# make sure no change occurred.
self.assertEqual(p.get_number_of_particles(), 2)
self.assertEqual(check_array(p.x, [3., 4.]), True)
self.assertEqual(check_array(p.y, [2., 3.]), True)
self.assertEqual(check_array(p.z, [0., 0.]), True)
self.assertEqual(check_array(p.m, [1., 1.]), True)
self.assertEqual(check_array(p.h, [.1, .1]), True)
self.assertEqual(check_array(p.A, numpy.arange(6, 12)), True)
def test_add_particles(self):
x = [1, 2, 3, 4.]
y = [0., 1., 2., 3.]
z = [0., 0., 0., 0.]
m = [1., 1., 1., 1.]
h = [.1, .1, .1, .1]
A = numpy.arange(12)
p = particle_array.ParticleArray(
x={'data': x}, y={'data': y},
z={'data': z}, m={'data': m},
h={'data': h}, A=dict(data=A, stride=3),
backend=self.backend
)
new_particles = {}
new_particles['x'] = numpy.array([5., 6, 7], dtype=numpy.float32)
new_particles['y'] = numpy.array([4., 5, 6], dtype=numpy.float32)
new_particles['z'] = numpy.array([0., 0, 0], dtype=numpy.float32)
p.add_particles(**new_particles)
self.pull(p)
self.assertEqual(p.get_number_of_particles(), 7)
self.assertEqual(check_array(p.x, [1., 2, 3, 4, 5, 6, 7]), True)
self.assertEqual(check_array(p.y, [0., 1, 2, 3, 4, 5, 6]), True)
self.assertEqual(check_array(p.z, [0., 0, 0, 0, 0, 0, 0]), True)
expect = numpy.zeros(21, dtype=A.dtype)
expect[:12] = A
numpy.testing.assert_array_equal(p.A, expect)
# make sure the other arrays were resized
self.assertEqual(len(p.h), 7)
self.assertEqual(len(p.m), 7)
# try adding an empty particle list
p.add_particles(**{})
self.pull(p)
self.assertEqual(p.get_number_of_particles(), 7)
self.assertEqual(check_array(p.x, [1., 2, 3, 4, 5, 6, 7]), True)
self.assertEqual(check_array(p.y, [0., 1, 2, 3, 4, 5, 6]), True)
self.assertEqual(check_array(p.z, [0., 0, 0, 0, 0, 0, 0]), True)
self.assertEqual(check_array(p.A, expect), True)
# make sure the other arrays were resized
self.assertEqual(len(p.h), 7)
self.assertEqual(len(p.m), 7)
# adding particles with tags
p = particle_array.ParticleArray(x={'data': x}, y={'data': y},
z={'data': z}, m={'data': m},
h={'data': h},
backend=self.backend)
p.add_particles(x=[5, 6, 7, 8], tag=[1, 1, 0, 0])
self.pull(p)
self.assertEqual(p.get_number_of_particles(), 8)
self.assertEqual(check_array(p.x, [1, 2, 3, 4, 7, 8]), True)
self.assertEqual(check_array(p.y, [0, 1, 2, 3, 0, 0]), True)
self.assertEqual(check_array(p.z, [0, 0, 0, 0, 0, 0]), True)
def test_remove_tagged_particles(self):
x = [1, 2, 3, 4.]
y = [0., 1., 2., 3.]
z = [0., 0., 0., 0.]
m = [1., 1., 1., 1.]
h = [.1, .1, .1, .1]
A = numpy.arange(12)
tag = [1, 1, 1, 0]
p = particle_array.ParticleArray(
x={'data': x}, y={'data': y},
z={'data': z}, m={'data': m},
h={'data': h}, tag={'data': tag}, A={'data': A, 'stride': 3},
backend=self.backend
)
numpy.testing.assert_array_equal(
p.get('A'), numpy.arange(9, 12)
)
p.remove_tagged_particles(0)
self.pull(p)
self.assertEqual(p.get_number_of_particles(), 3)
self.assertEqual(
check_array(
numpy.sort(p.get('x', only_real_particles=False)),
[1., 2., 3.]),
True
)
self.assertEqual(
check_array(
numpy.sort(p.get('y', only_real_particles=False)),
[0., 1., 2.]
), True
)
self.assertEqual(
check_array(
numpy.sort(p.get('z', only_real_particles=False)),
[0., 0, 0]
), True
)
self.assertEqual(
check_array(
numpy.sort(p.get('h', only_real_particles=False)),
[0.1, 0.1, 0.1]
), True
)
self.assertEqual(
check_array(p.get('m', only_real_particles=False), [1., 1., 1.]),
True
)
if p.gpu is None:
numpy.testing.assert_array_equal(
p.get('A', only_real_particles=False),
| numpy.arange(9) | numpy.arange |
import numpy as np
from astropy.io import fits
import os
import re
import glob
import copy
from vorbin.voronoi_2d_binning import voronoi_2d_binning
import matplotlib.pyplot as plt
from scipy import interpolate, stats, optimize
import gc
from matplotlib import gridspec, animation
try:
import tqdm
except:
tqdm = None
from joblib import Parallel, delayed
plt.style.use('dark_background')
def read_muse_ifu(fits_file,z=0):
"""
Read in a MUSE-formatted IFU cube
:param fits_file: str
File path to the FITS IFU cube
:param z: float, optional
The redshift of the spectrum, since MUSE cubes often do not provide this information
:return nx: int
x-dimension (horizontal axis) of the cube
:return ny: int
y-dimension (vertical axis) of the cube
:return nz: int
z-dimension (wavelength axis) of the cube
:return ra: float
Right ascension
:return dec: float
Declination
:return museid: str
The MUSE ID of the observation
:return wave: array
1-D Wavelength array with dimension (nz,)
:return flux: array
3-D flux array with dimensions (nz, ny, nx)
:return ivar: array
3-D inverse variance array with dimensions (nz, ny, nx)
:return specres: array
1-D spectral resolution ("R") array with dimension (nz,)
:return mask: array
3-D mask array with dimensions (nz, ny, nx)
:return object_name: str
The name of the object, if provided in the FITS header
"""
# Load the file
# https://www.eso.org/rm/api/v1/public/releaseDescriptions/78
with fits.open(fits_file) as hdu:
# First axis is wavelength, then 2nd and 3rd are image x/y
try:
nx, ny, nz = hdu[1].header['NAXIS1'], hdu[1].header['NAXIS2'], hdu[1].header['NAXIS3']
ra = hdu[0].header['RA']
dec = hdu[0].header['DEC']
except:
# ra = hdu[0].header['ESO ADA GUID RA']
# dec = hdu[0].header['ESO ADA GUID DEC']
nx, ny, nz = hdu[0].header['NAXIS1'], hdu[0].header['NAXIS2'], hdu[0].header['NAXIS3']
ra = hdu[0].header['CRVAL1']
dec = hdu[0].header['CRVAL2']
primary = hdu[0].header
try:
object_name = primary['OBJECT']
except:
object_name = None
i = 1
museid = []
while True:
try:
museid.append(primary['OBID'+str(i)])
i += 1
except:
break
# Get unit of flux, assuming 10^-x erg/s/cm2/Angstrom/spaxel
# unit = hdu[0].header['BUNIT']
# power = int(re.search('10\*\*(\(?)(.+?)(\))?\s', unit).group(2))
# scale = 10**(-17) / 10**power
try:
# 3d rectified cube in units of 10(-20) erg/s/cm2/Angstrom/spaxel [NX x NY x NWAVE], convert to 10(-17)
flux = hdu[1].data
# Variance (sigma2) for the above [NX x NY x NWAVE], convert to 10(-17)
var = hdu[2].data
# Wavelength vector must be reconstructed, convert from nm to angstroms
header = hdu[1].header
wave = np.array(header['CRVAL3'] + header['CD3_3']*np.arange(header['NAXIS3']))
# wave = np.linspace(primary['WAVELMIN'], primary['WAVELMAX'], nz) * 10
# Median spectral resolution at (wavelmin + wavelmax)/2
# dlambda = cwave / primary['SPEC_RES']
# specres = wave / dlambda
# Default behavior for MUSE data cubes using https://www.aanda.org/articles/aa/pdf/2017/12/aa30833-17.pdf equation 7
dlambda = 5.835e-8 * wave**2 - 9.080e-4 * wave + 5.983
specres = wave / dlambda
# Scale by the measured spec_res at the central wavelength
spec_cent = primary['SPEC_RES']
cwave = np.nanmedian(wave)
c_dlambda = 5.835e-8 * cwave**2 - 9.080e-4 * cwave + 5.983
scale = 1 + (spec_cent - cwave/c_dlambda) / spec_cent
specres *= scale
except:
flux = hdu[0].data
var = (0.1 * flux)**2
wave = np.arange(primary['CRVAL3'], primary['CRVAL3']+primary['CDELT3']*(nz-1), primary['CDELT3'])
# specres = wave / 2.6
dlambda = 5.835e-8 * wave**2 - 9.080e-4 * wave + 5.983
specres = wave / dlambda
ivar = 1/var
mask = np.zeros_like(flux)
return nx,ny,nz,ra,dec,museid,wave,flux,ivar,specres,mask,object_name
def read_manga_ifu(fits_file,z=0):
"""
Read in a MANGA-formatted IFU cube
:param fits_file: str
File path to the FITS IFU cube
:param z: float, optional
The redshift of the spectrum, this is unused.
:return nx: int
x-dimension (horizontal axis) of the cube
:return ny: int
y-dimension (vertical axis) of the cube
:return nz: int
z-dimension (wavelength axis) of the cube
:return ra: float
Right ascension
:return dec: float
Declination
:return mangaid: str
The MANGA ID of the observation
:return wave: array
1-D Wavelength array with dimension (nz,)
:return flux: array
3-D flux array with dimensions (nz, ny, nx)
:return ivar: array
3-D inverse variance array with dimensions (nz, ny, nx)
:return specres: array
1-D spectral resolution ("R") array with dimension (nz,)
:return mask: array
3-D mask array with dimensions (nz, ny, nx)
:return None:
To mirror the output length of read_muse_ifu
"""
# Load the file
# https://data.sdss.org/datamodel/files/MANGA_SPECTRO_REDUX/DRPVER/PLATE4/stack/manga-CUBE.html#hdu1
with fits.open(fits_file) as hdu:
# First axis is wavelength, then 2nd and 3rd are image x/y
nx, ny, nz = hdu[1].header['NAXIS1'], hdu[1].header['NAXIS2'], hdu[1].header['NAXIS3']
try:
ra = hdu[0].header['OBJRA']
dec = hdu[0].header['OBJDEC']
except:
ra = hdu[1].header['IFURA']
dec = hdu[1].header['IFUDEC']
primary = hdu[0].header
ebv = primary['EBVGAL']
mangaid = primary['MANGAID']
# 3d rectified cube in units of 10(-17) erg/s/cm2/Angstrom/spaxel [NX x NY x NWAVE]
flux = hdu[1].data
# Inverse variance (1/sigma2) for the above [NX x NY x NWAVE]
ivar = hdu[2].data
# Pixel mask [NX x NY x NWAVE]. Defined values are set in sdssMaskbits.par
mask = hdu[3].data
# Wavelength vector [NWAVE]
wave = hdu[6].data
# Median spectral resolution as a function of wavelength for the fibers in this IFU [NWAVE]
specres = hdu[7].data
# ebv = hdu[0].header['EBVGAL']
return nx,ny,nz,ra,dec,mangaid,wave,flux,ivar,specres,mask,None
def prepare_ifu(fits_file,z,format,aperture=None,voronoi_binning=True,fixed_binning=False,targetsn=None,cvt=True,voronoi_plot=True,quiet=True,wvt=False,
maxbins=800,snr_threshold=0.5,fixed_bin_size=10,use_and_mask=True,nx=None,ny=None,nz=None,ra=None,dec=None,dataid=None,wave=None,flux=None,ivar=None,
specres=None,mask=None,objname=None):
"""
Deconstruct an IFU cube into individual spaxel files for fitting with BADASS
:param fits_file: str
The file path to the IFU FITS file; if format == 'user', this field may be left as None, '', or any other filler value
:param z: float
The redshift of the spectrum
:param aperture: array, optional
The lower-left and upper-right corners of a square aperture, formatted as [y0, y1, x0, x1]
:param voronoi_binning: bool
Whether or not to bin spaxels using the voronoi method (grouping to read a certain SNR threshold). Default True.
Mutually exclusive with fixed_binning.
:param fixed_binning: bool
Whether or not to bin spaxels using a fixed size. Default False.
Mutually exclusive with voronoi_binning.
:param targetsn: float, optional
The target SNR to bin by, if using voronoi binning.
:param cvt: bool
Vorbin CVT option (see the vorbin package docs). Default True.
:param voronoi_plot: bool
Whether or not to plot the voronoi bin structure. Default True.
:param quiet: bool
Vorbin quiet option (see the vorbin package docs). Default True.
:param wvt: bool
Vorbin wvt option (see the vorbin package docs). Default False.
:param maxbins: int
If no target SNR is provided for voronoi binning, maxbins may be specified, which will automatically calculate
the target SNR required to reach the number of bins desired. Default 800.
:param snr_threshold: float
Minimum SNR threshold, below which spaxel data will be removed and not fit.
:param fixed_bin_size: int
If using fixed binning, this is the side length of the square bins, in units of spaxels.
:param use_and_mask: bool
Whether or not to save the and_mask data.
:param nx: int, optional
x-dimension of the cube, only required if format == 'user'
:param ny: int, optional
y-dimension of the cube, only required if format == 'user'
:param nz: int, optional
z-dimension of the cube, only required if format == 'user'
:param ra: float, optional
Right ascension of the cube, only required if format == 'user'
:param dec: float, optional
Declination of the cube, only required if format == 'user'
:param dataid: str, optional
ID of the cube, only required if format == 'user'
:param wave: array, optional
1-D wavelength array with shape (nz,), only required if format == 'user'
:param flux: array, optional
3-D flux array with shape (nz, ny, nx), only required if format == 'user'
:param ivar: array, optional
3-D inverse variance array with shape (nz, ny, nx), only required if format == 'user'
:param specres: array, optional
1-D spectral resolution ("R") array with shape (nz,), only required if format == 'user'
:param mask: array, optional
3-D mask array with shape (nz, ny, nx), only required if format == 'user'
:param objname: str, optional
The name of the object, only required if format == 'user'
:return wave: array
1-D wavelength array with shape (nz,)
:return flux: array
3-D masked flux array with shape (nz, ny, nx)
:return ivar: array
3-D masked inverse variance array with shape (nz, ny, nx)
:return mask: array
3-D mask array with shape (nz, ny, nx)
:return fwhm_res: array
1-D FWHM resolution array with shape (nz,)
:return binnum: array
Bin number array that specifies which spaxels are in each bin (see the vorbin docs)
:return npixels: array
Number of spaxels in each bin (see the vorbin docs)
:return xpixbin: array
The x positions of spaxels in each bin
:return ypixbin: array
The y positions of spaxels in each bin
:return z: float
The redshift
:return dataid: str
The data ID
:return objname: str
The object name
"""
assert format in ('manga', 'muse', 'user'), "format must be either 'manga' or 'muse'; no others currently supported!"
# Read the FITS file using the appropriate parsing function
# no more eval 🥲
if format == 'manga':
nx,ny,nz,ra,dec,dataid,wave,flux,ivar,specres,mask,objname = read_manga_ifu(fits_file,z)
elif format == 'muse':
nx,ny,nz,ra,dec,dataid,wave,flux,ivar,specres,mask,objname = read_muse_ifu(fits_file,z)
else:
# wave array shape = (nz,)
# flux, ivar array shape = (nz, ny, nx)
# specres can be a single value or an array of shape (nz,)
# VALIDATE THAT USER INPUTS ARE IN THE CORRECT FORMAT
for value in (nx, ny, nz, ra, dec, wave, flux, specres):
assert value is not None, "For user spec, all of (nx, ny, nz, ra, dec, wave, flux, specres) must be specified!"
if ivar is None:
print("WARNING: No ivar was input. Defaulting to sqrt(flux).")
ivar = np.sqrt(flux)
if mask is None:
mask = np.zeros(flux.shape, dtype=int)
assert wave.shape == (nz,), "Wave array shape should be (nz,)"
assert flux.shape == (nz, ny, nx), "Flux array shape should be (nz, ny, nx)"
assert ivar.shape == (nz, ny, nx), "Ivar array shape should be (nz, ny, nx)"
assert mask.shape == (nz, ny, nx), "Mask array shape should be (nz, ny, nx)"
assert (type(specres) in (int, float, np.int_, np.float_)) or (specres.shape == (nz,)), "Specres should be a float or an array of shape (nz,)"
loglam = np.log10(wave)
# FWHM Resolution in angstroms:
fwhm_res = wave / specres # dlambda = lambda / R; R = lambda / dlambda
if not use_and_mask:
mask = np.zeros(flux.shape, dtype=int)
# Converting to wdisp -- so that 2.355*wdisp*dlam_gal = fwhm_res
# if format == 'manga':
# c = 299792.458 # speed of light in km/s
# frac = wave[1]/wave[0] # Constant lambda fraction per pixel
# dlam_gal = (frac-1)*wave # Size of every pixel in Angstrom
# vdisp = c / (2.355*specres) # delta v = c / R in km/s
# velscale = np.log(frac) * c # Constant velocity scale in km/s per pixel
# wdisp = vdisp / velscale # Intrinsic dispersion of every pixel, in pixels units
minx, maxx = 0, nx
miny, maxy = 0, ny
if aperture:
miny, maxy, minx, maxx = aperture
maxy += 1
maxx += 1
x = np.arange(minx, maxx, 1)
y = np.arange(miny, maxy, 1)
# Create x/y grid for the voronoi binning
X, Y = np.meshgrid(x, y)
_x, _y = X.ravel(), Y.ravel()
if voronoi_binning:
# Average along the wavelength axis so each spaxel has one s/n value
# Note to self: Y AXIS IS ALWAYS FIRST ON NUMPY ARRAYS
signal = np.nanmean(flux[:, miny:maxy, minx:maxx], axis=0)
noise = np.sqrt(1 / np.nanmean(ivar[:, miny:maxy, minx:maxx], axis=0))
sr = signal.ravel()
nr = noise.ravel()
good = np.where(np.isfinite(sr) & np.isfinite(nr) & (sr > 0) & (nr > 0))[0]
# Target S/N ratio to bin for. If none, defaults to value such that the highest pixel isnt binned
# In general this isn't a great choice. Should want to maximize resolution without sacrificing too much
# computation time.
if not targetsn:
# binnum = np.array([maxbins+1])
targetsn0 = np.max([np.sort((sr / nr)[good], kind='quicksort')[-1] / 16, 10])
def objective(targetsn, return_data=False):
vplot = voronoi_plot if return_data else False
qt = quiet if return_data else True
try:
binnum, xbin, ybin, xbar, ybar, sn, npixels, scale = voronoi_2d_binning(_x[good], _y[good], sr[good], nr[good],
targetsn, cvt=cvt, pixelsize=1, plot=vplot,
quiet=qt, wvt=wvt)
except ValueError:
return np.inf
if return_data:
return binnum, xbin, ybin, xbar, ybar, sn, npixels, scale
return (np.max(binnum)+1 - maxbins)**2
print(f'Performing S/N optimization to reach {maxbins} bins. This may take a while...')
soln = optimize.minimize(objective, [targetsn0], method='Nelder-Mead', bounds=[(1, X.size)])
targetsn = soln.x[0]
binnum, xbin, ybin, xbar, ybar, SNR, npixels, scale = objective(targetsn, return_data=True)
else:
binnum, xbin, ybin, xbar, ybar, SNR, npixels, scale = voronoi_2d_binning(_x[good], _y[good], sr[good], nr[good],
targetsn, cvt=cvt, pixelsize=1, plot=voronoi_plot,
quiet=quiet, wvt=wvt)
print(f'Voronoi binning successful with target S/N = {targetsn}! Created {np.max(binnum)+1} bins.')
if voronoi_plot:
# For some reason voronoi makes the plot but doesnt save it or anything
filename = os.path.join(os.path.dirname(fits_file), 'voronoi_binning.pdf')
plt.savefig(filename, bbox_inches='tight', dpi=300)
plt.close()
_x = _x[good]
_y = _y[good]
# Create output arrays for flux, ivar, mask
out_flux = np.zeros((flux.shape[0], np.nanmax(binnum)+1))
out_ivar = np.zeros((ivar.shape[0], np.nanmax(binnum)+1))
out_mask = np.zeros((mask.shape[0], np.nanmax(binnum)+1))
xpixbin = np.full(np.nanmax(binnum)+1, fill_value=np.nan, dtype=object)
ypixbin = np.full(np.nanmax(binnum)+1, fill_value=np.nan, dtype=object)
for j in range(xpixbin.size):
xpixbin[j] = []
ypixbin[j] = []
# Average flux/ivar in each bin
for i, bin in enumerate(binnum):
# there is probably a better way to do this, but I'm lazy
xi, yi = _x[i], _y[i]
out_flux[:, bin] += flux[:, yi, xi]
out_ivar[:, bin] += ivar[:, yi, xi]
out_mask[:, bin] += mask[:, yi, xi]
xpixbin[bin].append(xi)
ypixbin[bin].append(yi)
out_flux /= npixels
out_ivar /= npixels
irange = np.nanmax(binnum)+1
for bin in binnum:
if SNR[bin] < snr_threshold:
flux[:, | np.asarray(ypixbin[bin]) | numpy.asarray |
# Copyright 2019 <NAME> & <NAME>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import numba
import numpy as np
from sklearn.metrics import pairwise_distances
SMOOTH_K_TOLERANCE = 1e-5
MIN_K_DIST_SCALE = 1e-3
NPY_INFINITY = np.inf
@numba.njit(parallel=True, cache=True)
def parallel_adaptive_knn_indices(X, n_neighbors):
"""This handles the case of multiple farthest neighbors that all have an
equal distance to the center.
Parameters
----------
X: array of shape (n_samples, n_samples) or tuple with shape.
A pairwise distance matrix.
n_neighbors: int
The number of neighbors to compute distances for.
Larger numbers induce more global estimates of the manifold that can
miss finer detail, while smaller values will focus on fine manifold
structure to the detriment of the larger picture.
Returns
-------
knn_indices: array of shape (X[0], n_neighbors + e) where `e` is either 0 or
the number of identical farthest neighbors - 1.
The indices of the k-nearest neighbors.
knn_mask: array of shape (X[0], n_neighbors + e) where `e` is either 0 or
the number of identical farthest neighbors - 1.
A boolean mask that masks indices in knn_indices for points that do not
have multiple farthest neighbors (for which `e=0`).
"""
# We do not know `e` yet, so we have to assume the full shape
knn_indices = np.empty(X.shape, dtype=np.int64)
knn_mask = np.zeros_like(X, dtype=np.bool_)
# Per point farthest neighbor index
max_knn_indices = | np.empty(X.shape[0], dtype=np.int64) | numpy.empty |
"""Test distributed mulit-host device mesh."""
import os
import unittest
from flax import linen as nn
from flax import optim
import jax
import jax.numpy as jnp
from jax.interpreters import pxla
import numpy as np
import ray
from alpa import DeviceCluster, parallelize, set_parallelize_options, testing, DistributedArray
from alpa.testing import assert_allclose
class DeviceMeshTest(unittest.TestCase):
def setUp(self):
os.environ["XLA_PYTHON_CLIENT_ALLOCATOR"] = "platform"
ray.init(address="auto", ignore_reinit_error=True)
def tearDown(self):
ray.shutdown()
def test_add_one(self):
# Launch a multi-host device mesh
device_cluster = DeviceCluster(use_cpu_on_driver=False)
physical_mesh = device_cluster.get_physical_mesh()
num_devices = len(
physical_mesh.host_ids) * physical_mesh.num_devices_per_host
logical_mesh = physical_mesh.get_logical_mesh([1, num_devices])
set_parallelize_options(devices=logical_mesh)
@parallelize
def add_one(x):
return x + 1
@parallelize
def multiply_two(x):
return x * 2
# Run computation
a = jnp.ones((512, 512))
out = add_one(a)
out = multiply_two(out)
# Check results
assert_allclose(out._value, ( | np.ones_like(a) | numpy.ones_like |
import numpy as np
import os
import time
import pytest
import ray
from ray.cluster_utils import Cluster, cluster_not_supported
from ray.internal.internal_api import memory_summary
# RayConfig to enable recording call sites during ObjectRej creations.
ray_config = {"record_ref_creation_sites": True}
# Unique strings.
DRIVER_PID = "Driver"
WORKER_PID = "Worker"
UNKNOWN_SIZE = " ? "
# Reference status.
PINNED_IN_MEMORY = "PINNED_IN_MEMORY"
LOCAL_REF = "LOCAL_REFERENCE"
USED_BY_PENDING_TASK = "USED_BY_PENDING_TASK"
CAPTURED_IN_OBJECT = "CAPTURED_IN_OBJECT"
ACTOR_HANDLE = "ACTOR_HANDLE"
# Call sites.
PUT_OBJ = "(put object)"
TASK_CALL_OBJ = "(task call)"
ACTOR_TASK_CALL_OBJ = "(actor call)"
DESER_TASK_ARG = "(deserialize task arg)"
# Only 22 characters can be matched because longer strings are wrapped around.
DESER_ACTOR_TASK_ARG = "(deserialize actor tas"
# Group by and sort by parameters.
NODE_ADDRESS = "node address"
STACK_TRACE = "stack trace"
PID = "pid"
OBJECT_SIZE = "object size"
REFERENCE_TYPE = "reference type"
def data_lines(memory_str):
for line in memory_str.split("\n"):
if (
PINNED_IN_MEMORY in line
or LOCAL_REF in line
or USED_BY_PENDING_TASK in line
or CAPTURED_IN_OBJECT in line
or ACTOR_HANDLE in line
):
yield line
else:
continue
def num_objects(memory_str):
n = 0
for line in data_lines(memory_str):
n += 1
return n
def count(memory_str, substr):
substr = substr[:42]
n = 0
for line in memory_str.split("\n"):
if substr in line:
n += 1
return n
@pytest.mark.parametrize(
"ray_start_regular", [{"_system_config": ray_config}], indirect=True
)
def test_driver_put_ref(ray_start_regular):
address = ray_start_regular["address"]
info = memory_summary(address)
assert num_objects(info) == 0, info
x_id = ray.put("HI")
info = memory_summary(address)
print(info)
assert num_objects(info) == 1, info
assert count(info, DRIVER_PID) == 1, info
assert count(info, WORKER_PID) == 0, info
del x_id
info = memory_summary(address)
assert num_objects(info) == 0, info
@pytest.mark.parametrize(
"ray_start_regular", [{"_system_config": ray_config}], indirect=True
)
def test_worker_task_refs(ray_start_regular):
address = ray_start_regular["address"]
@ray.remote
def f(y):
from ray.internal.internal_api import memory_summary
x_id = ray.put("HI")
info = memory_summary(address)
del x_id
return info
x_id = f.remote(np.zeros(100000))
info = ray.get(x_id)
print(info)
assert num_objects(info) == 4, info
# Task argument plus task return ids.
assert count(info, TASK_CALL_OBJ) == 2, info
assert count(info, DRIVER_PID) == 2, info
assert count(info, WORKER_PID) == 2, info
assert count(info, LOCAL_REF) == 2, info
assert count(info, PINNED_IN_MEMORY) == 1, info
assert count(info, PUT_OBJ) == 1, info
assert count(info, DESER_TASK_ARG) == 1, info
assert count(info, UNKNOWN_SIZE) == 1, info
print(ray_start_regular)
info = memory_summary(address)
print(info)
assert num_objects(info) == 1, info
assert count(info, DRIVER_PID) == 1, info
assert count(info, TASK_CALL_OBJ) == 1, info
assert count(info, UNKNOWN_SIZE) == 0, info
assert count(info, x_id.hex()) == 1, info
del x_id
info = memory_summary(address)
assert num_objects(info) == 0, info
@pytest.mark.parametrize(
"ray_start_regular", [{"_system_config": ray_config}], indirect=True
)
def test_actor_task_refs(ray_start_regular):
address = ray_start_regular["address"]
@ray.remote
class Actor:
def __init__(self):
self.refs = []
def f(self, x):
from ray.internal.internal_api import memory_summary
self.refs.append(x)
return memory_summary(address)
def make_actor():
return Actor.remote()
actor = make_actor()
x_id = actor.f.remote(np.zeros(100000))
info = ray.get(x_id)
print(info)
# Note, the actor will always hold a handle to the actor itself.
assert num_objects(info) == 5, info
# Actor handle, task argument id, task return id.
assert count(info, ACTOR_TASK_CALL_OBJ) == 3, info
assert count(info, DRIVER_PID) == 3, info
assert count(info, WORKER_PID) == 2, info
assert count(info, LOCAL_REF) == 1, info
assert count(info, PINNED_IN_MEMORY) == 1, info
assert count(info, USED_BY_PENDING_TASK) == 1, info
assert count(info, ACTOR_HANDLE) == 2, info
assert count(info, DESER_ACTOR_TASK_ARG) == 1, info
del x_id
# These should accumulate in the actor.
for _ in range(5):
ray.get(actor.f.remote([ray.put(np.zeros(100000))]))
info = memory_summary(address)
print(info)
assert count(info, DESER_ACTOR_TASK_ARG) == 5, info
assert count(info, ACTOR_TASK_CALL_OBJ) == 1, info
# Cleanup.
del actor
time.sleep(1)
info = memory_summary(address)
assert num_objects(info) == 0, info
@pytest.mark.parametrize(
"ray_start_regular", [{"_system_config": ray_config}], indirect=True
)
def test_nested_object_refs(ray_start_regular):
address = ray_start_regular["address"]
x_id = ray.put(np.zeros(100000))
y_id = ray.put([x_id])
z_id = ray.put([y_id])
del x_id, y_id
info = memory_summary(address)
print(info)
assert num_objects(info) == 3, info
assert count(info, LOCAL_REF) == 1, info
assert count(info, CAPTURED_IN_OBJECT) == 2, info
del z_id
@pytest.mark.parametrize(
"ray_start_regular", [{"_system_config": ray_config}], indirect=True
)
def test_pinned_object_call_site(ray_start_regular):
address = ray_start_regular["address"]
# Local ref only.
x_id = ray.put( | np.zeros(100000) | numpy.zeros |
# This must be done BEFORE importing numpy or anything else.
# Therefore it must be in your main script.
import os
os.environ["MKL_NUM_THREADS"] = "1"
os.environ["NUMEXPR_NUM_THREADS"] = "1"
os.environ["OMP_NUM_THREADS"] = "1"
import sys
import numpy as np
import pyqmc.testwf as testwf
def test_wfs():
"""
Ensure that the wave function objects are consistent in several situations.
"""
from pyscf import lib, gto, scf
from pyqmc.slateruhf import PySCFSlaterUHF
from pyqmc.jastrowspin import JastrowSpin
from pyqmc.multiplywf import MultiplyWF
from pyqmc.coord import OpenConfigs
from pyqmc.manybody_jastrow import J3
import pyqmc
mol = gto.M(atom="Li 0. 0. 0.; H 0. 0. 1.5", basis="cc-pvtz", unit="bohr")
mf = scf.RHF(mol).run()
mf_rohf = scf.ROHF(mol).run()
mf_uhf = scf.UHF(mol).run()
epsilon = 1e-4
nconf = 10
epos = pyqmc.initial_guess(mol, nconf)
for wf in [
J3(mol),
#JastrowSpin(mol),
#MultiplyWF(PySCFSlaterUHF(mol, mf), JastrowSpin(mol)),
#PySCFSlaterUHF(mol, mf_uhf),
#PySCFSlaterUHF(mol, mf),
#PySCFSlaterUHF(mol, mf_rohf),
]:
for k in wf.parameters:
if k != "mo_coeff":
wf.parameters[k] = | np.random.rand(*wf.parameters[k].shape) | numpy.random.rand |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
import numpy as np
import ubelt as ub # NOQA
def argsubmax(ydata, xdata=None):
"""
Finds a single submaximum value to subindex accuracy.
If xdata is not specified, submax_x is a fractional index.
Otherwise, submax_x is sub-xdata (essentially doing the index interpolation
for you)
Example:
>>> ydata = [ 0, 1, 2, 1.5, 0]
>>> xdata = [00, 10, 20, 30, 40]
>>> result1 = argsubmax(ydata, xdata=None)
>>> result2 = argsubmax(ydata, xdata=xdata)
>>> result = ub.repr2([result1, result2], precision=4, nl=1, nobr=True)
>>> print(result)
(2.1667, 2.0208),
(21.6667, 2.0208),
Example:
>>> hist_ = np.array([0, 1, 2, 3, 4])
>>> centers = None
>>> maxima_thresh=None
>>> argsubmax(hist_)
(4.0, 4.0)
"""
if len(ydata) == 0:
raise IndexError('zero length array')
ydata = np.asarray(ydata)
xdata = None if xdata is None else np.asarray(xdata)
submaxima_x, submaxima_y = argsubmaxima(ydata, centers=xdata)
idx = submaxima_y.argmax()
submax_y = submaxima_y[idx]
submax_x = submaxima_x[idx]
return submax_x, submax_y
def argsubmaxima(hist, centers=None, maxima_thresh=None, _debug=False):
r"""
Determines approximate maxima values to subindex accuracy.
Args:
hist_ (ndarray): ydata, histogram frequencies
centers (ndarray): xdata, histogram labels
maxima_thresh (float): cutoff point for labeing a value as a maxima
Returns:
tuple: (submaxima_x, submaxima_y)
Example:
>>> maxima_thresh = .8
>>> hist = np.array([6.73, 8.69, 0.00, 0.00, 34.62, 29.16, 0.00, 0.00, 6.73, 8.69])
>>> centers = np.array([-0.39, 0.39, 1.18, 1.96, 2.75, 3.53, 4.32, 5.11, 5.89, 6.68])
>>> (submaxima_x, submaxima_y) = argsubmaxima(hist, centers, maxima_thresh)
>>> result = str((submaxima_x, submaxima_y))
>>> print(result)
>>> # xdoc: +REQUIRES(--show)
>>> import plottool as pt
>>> pt.draw_hist_subbin_maxima(hist, centers)
>>> pt.show_if_requested()
(array([ 3.0318792]), array([ 37.19208239]))
"""
maxima_x, maxima_y, argmaxima = _hist_argmaxima(hist, centers, maxima_thresh=maxima_thresh)
argmaxima = np.asarray(argmaxima)
if _debug:
print('Argmaxima: ')
print(' * maxima_x = %r' % (maxima_x))
print(' * maxima_y = %r' % (maxima_y))
print(' * argmaxima = %r' % (argmaxima))
flags = (argmaxima == 0) | (argmaxima == len(hist) - 1)
argmaxima_ = argmaxima[~flags]
submaxima_x_, submaxima_y_ = _interpolate_submaxima(argmaxima_, hist, centers)
if np.any(flags):
endpts = argmaxima[flags]
submaxima_x = (np.hstack([submaxima_x_, centers[endpts]])
if centers is not None else
np.hstack([submaxima_x_, endpts]))
submaxima_y = | np.hstack([submaxima_y_, hist[endpts]]) | numpy.hstack |
# Copyright (c) 2018, Lehrstuhl für Angewandte Mechanik, Technische Universität München.
#
# Distributed under BSD-3-Clause License. See LICENSE-File for more information
#
#
from unittest import TestCase
import numpy as np
from scipy.linalg import qr, lu_factor, lu_solve
from scipy.sparse import csr_matrix
from scipy.sparse.linalg import LinearOperator
from numpy.testing import assert_allclose, assert_array_almost_equal
from amfe.structural_dynamics import *
class TestStructuralDynamicsToolsMAC(TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def test_mac_diag_ones(self):
"""
Test mac criterion for getting ones on the diagonal, if the same matrix is
given.
"""
N = 100
n = 10
A = | np.random.rand(N, n) | numpy.random.rand |
'''
construct shading using sh basis
'''
import numpy as np
def SH_basis(normal):
'''
get SH basis based on normal
normal is a Nx3 matrix
return a Nx9 matrix
The order of SH here is:
1, Y, Z, X, YX, YZ, 3Z^2-1, XZ, X^2-y^2
'''
numElem = normal.shape[0]
norm_X = normal[:,0]
norm_Y = normal[:,1]
norm_Z = normal[:,2]
sh_basis = np.zeros((numElem, 9))
att= np.pi*np.array([1, 2.0/3.0, 1/4.0])
sh_basis[:,0] = 0.5/np.sqrt(np.pi)*att[0]
sh_basis[:,1] = np.sqrt(3)/2/np.sqrt(np.pi)*norm_Y*att[1]
sh_basis[:,2] = np.sqrt(3)/2/np.sqrt(np.pi)*norm_Z*att[1]
sh_basis[:,3] = np.sqrt(3)/2/np.sqrt(np.pi)*norm_X*att[1]
sh_basis[:,4] = np.sqrt(15)/2/np.sqrt(np.pi)*norm_Y*norm_X*att[2]
sh_basis[:,5] = np.sqrt(15)/2/np.sqrt(np.pi)*norm_Y*norm_Z*att[2]
sh_basis[:,6] = np.sqrt(5)/4/np.sqrt(np.pi)*(3*norm_Z**2-1)*att[2]
sh_basis[:,7] = np.sqrt(15)/2/np.sqrt(np.pi)*norm_X*norm_Z*att[2]
sh_basis[:,8] = np.sqrt(15)/4/np.sqrt(np.pi)*(norm_X**2-norm_Y**2)*att[2]
return sh_basis
def SH_basis_noAtt(normal):
'''
get SH basis based on normal
normal is a Nx3 matrix
return a Nx9 matrix
The order of SH here is:
1, Y, Z, X, YX, YZ, 3Z^2-1, XZ, X^2-y^2
'''
numElem = normal.shape[0]
norm_X = normal[:,0]
norm_Y = normal[:,1]
norm_Z = normal[:,2]
sh_basis = np.zeros((numElem, 9))
sh_basis[:,0] = 0.5/np.sqrt(np.pi)
sh_basis[:,1] = np.sqrt(3)/2/np.sqrt(np.pi)*norm_Y
sh_basis[:,2] = np.sqrt(3)/2/np.sqrt(np.pi)*norm_Z
sh_basis[:,3] = np.sqrt(3)/2/np.sqrt(np.pi)*norm_X
sh_basis[:,4] = np.sqrt(15)/2/np.sqrt(np.pi)*norm_Y*norm_X
sh_basis[:,5] = np.sqrt(15)/2/np.sqrt(np.pi)*norm_Y*norm_Z
sh_basis[:,6] = np.sqrt(5)/4/np.sqrt(np.pi)*(3*norm_Z**2-1)
sh_basis[:,7] = np.sqrt(15)/2/np.sqrt(np.pi)*norm_X*norm_Z
sh_basis[:,8] = np.sqrt(15)/4/ | np.sqrt(np.pi) | numpy.sqrt |
# Copyright 2021 DeepMind Technologies Limited. 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.
#
# WikiGraphs is licensed under the terms of the Creative Commons
# Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.
#
# WikiText-103 data (unchanged) is licensed by Salesforce.com, Inc. under the
# terms of the Creative Commons Attribution-ShareAlike 4.0 International
# (CC BY-SA 4.0) license. You can find details about CC BY-SA 4.0 at:
#
# https://creativecommons.org/licenses/by-sa/4.0/legalcode
#
# Freebase data is licensed by Google LLC under the terms of the Creative
# Commons CC BY 4.0 license. You may obtain a copy of the License at:
#
# https://creativecommons.org/licenses/by/4.0/legalcode
#
# ==============================================================================
"""Tests for wikigraphs.model.transformer."""
from absl import logging
from absl.testing import absltest
import haiku as hk
import jax
import jax.numpy as jnp
import jraph
import numpy as np
import optax
from wikigraphs.model import embedding
from wikigraphs.model import transformer as models
def tree_size(nest):
return sum(x.size for x in jax.tree_util.tree_leaves(nest))
class TransformerXlTest(absltest.TestCase):
def test_transformer_param_count(self):
seqs = np.array([[1, 2, 3, 0, 0],
[3, 3, 5, 1, 2]], dtype=np.int32)
x = seqs[:, :-1]
y = seqs[:, 1:]
vocab_size = 267_735
def forward(inputs, labels):
input_mask = (labels != 0).astype(jnp.float32)
model = models.TransformerXL(
vocab_size=vocab_size,
emb_dim=210,
num_layers=2,
num_heads=10,
dropout_prob=0.0,
dropout_attn_prob=0.0,
self_att_init_scale=0.02,
dense_init_scale=0.02,
dense_dim=2100,
cutoffs=(20000, 40000, 200000), # WikiText-103
relative_pos_clamp_len=None,
)
return model.loss(inputs, labels, mask=input_mask, cache_steps=2)
init_fn, apply_fn = hk.transform_with_state(forward)
key = hk.PRNGSequence(8)
params, state = init_fn(next(key), x, y)
out, _ = apply_fn(params, state, next(key), x, y)
loss, metrics = out
logging.info('loss: %g', loss)
logging.info('metrics: %r', metrics)
param_count = tree_size(params)
self.assertEqual(param_count, 58_704_438)
def test_transformer_with_extra_runs(self):
extra = np.array([[1, 1, 0, 0],
[2, 2, 2, 2],
[3, 3, 3, 0]], dtype=np.int32)
seqs = np.array([[1, 2, 3, 0, 0],
[2, 4, 5, 6, 0],
[3, 3, 5, 1, 2]], dtype=np.int32)
x = seqs[:, :-1]
y = seqs[:, 1:]
vocab_size = seqs.max() + 1
extra_vocab_size = extra.max() + 1
def forward(inputs, labels, extra):
input_mask = (labels != 0).astype(jnp.float32)
extra_mask = (extra != 0).astype(jnp.float32)
extra = hk.Embed(vocab_size=extra_vocab_size, embed_dim=16)(extra)
model = models.TransformerXL(
vocab_size=vocab_size,
emb_dim=16,
num_layers=2,
num_heads=4,
cutoffs=[],
)
return model.loss(inputs, labels, mask=input_mask,
extra=extra, extra_mask=extra_mask)
init_fn, apply_fn = hk.transform_with_state(forward)
key = hk.PRNGSequence(8)
params, state = init_fn(next(key), x, y, extra)
out, _ = apply_fn(params, state, next(key), x, y, extra)
loss, metrics = out
logging.info('loss: %g', loss)
logging.info('metrics: %r', metrics)
def test_graph_embedding_model_runs(self):
graph = jraph.GraphsTuple(
nodes=np.array([[0, 1, 1],
[1, 2, 0],
[0, 3, 0],
[0, 4, 4]], dtype=np.float32),
edges=np.array([[1, 1],
[2, 2],
[3, 3]], dtype=np.float32),
senders=np.array([0, 1, 2], dtype=np.int32),
receivers=np.array([1, 2, 3], dtype=np.int32),
n_node=np.array([4], dtype=np.int32),
n_edge=np.array([3], dtype=np.int32),
globals=None)
embed_dim = 3
def forward(graph):
return embedding.GraphEmbeddingModel(embed_dim=3, num_layers=2)(graph)
init_fn, apply_fn = hk.without_apply_rng(hk.transform(forward))
key = hk.PRNGSequence(8)
params = init_fn(next(key), graph)
out = apply_fn(params, graph)
self.assertEqual(out.nodes.shape, (graph.nodes.shape[0], embed_dim))
self.assertEqual(out.edges.shape, (graph.edges.shape[0], embed_dim))
np.testing.assert_array_equal(out.senders, graph.senders)
np.testing.assert_array_equal(out.receivers, graph.receivers)
np.testing.assert_array_equal(out.n_node, graph.n_node)
def test_unpack_and_pad(self):
x = np.array([1, 1, 2, 2, 2, 3, 4, 4], dtype=np.float32)
s = np.array([2, 3, 1, 2], dtype=np.int32)
tensors, mask = models.unpack_and_pad(x, s, pad_size=s.max(), pad_value=0)
np.testing.assert_array_equal(
tensors,
[[1, 1, 0],
[2, 2, 2],
[3, 0, 0],
[4, 4, 0]])
np.testing.assert_array_equal(
mask,
[[1, 1, 0],
[1, 1, 1],
[1, 0, 0],
[1, 1, 0]])
# [n, 1] tensor
x = np.array([1, 1, 2, 2, 2, 3, 4, 4], dtype=np.float32)[:, None]
s = | np.array([2, 3, 1, 2], dtype=np.int32) | numpy.array |
from joblib import Parallel, delayed
from numba import jit
import numpy as np
import openturns as ot
from anastruct.fem.system import SystemElements, Vertex
from scipy.interpolate import CubicSpline
N = ot.Normal(2, 1)
pts_normal_reversed = np.arange(2, 0, -1*(2/50))
pts_normal = np.array(list(map(N.computeCDF, pts_normal_reversed)))
l_0 = pts_normal.sum()
pts_normal = (pts_normal/l_0)
vertices_half = np.concatenate([np.array([0]), np.array(pts_normal*500)])
vertices = np.concatenate([vertices_half, vertices_half[::-1]])
for i in range(vertices.shape[0]-1):
vertices[i+1] = vertices[i+1] + vertices[i]
vertices = np.unique(vertices)
vertex_list = [Vertex(vertices[i], 0) for i in range(101)]
print('len vertices is:', len(vertex_list))
X = np.arange(0, 1000+1, 10) # to include also 1000
elem_coords = (X[1:]+X[:-1])/2
def experience_mod(young_modulus, diameter, position_force, norm_force,
vertices=vertices, vertex_list=vertex_list,
elem_coords=elem_coords):
cs_young_modulus = CubicSpline(elem_coords, young_modulus)
cs_diameter = CubicSpline(elem_coords, diameter)
# now we calculate the value of the young modulus and diameter at each element
young_modu_new = np.divide(
np.add(cs_young_modulus(vertices[1:]), cs_young_modulus(vertices[:-1])), 2)
diameter_new = np.divide(np.add(cs_diameter(vertices[1:]), cs_diameter(vertices[:-1])), 2)
#Here we clip the values to not have negative young moduli or diameter
young_modu_new = np.clip(a=young_modu_new, a_min=1000, a_max=None)
diameter_new = | np.clip(a=diameter_new, a_min=.1, a_max=None) | numpy.clip |
import os
import os.path
import argparse
import logging
import numpy as np
from datetime import datetime
from oncodrivefm import VERSION
from bgcore import tsv
from oncodrivefm.mapping import MatrixMapping
_LOG_LEVELS = {
"debug" : logging.DEBUG,
"info" : logging.INFO,
"warn" : logging.WARN,
"error" : logging.ERROR,
"critical" : logging.CRITICAL,
"notset" : logging.NOTSET }
class Command(object):
def __init__(self, prog=None, desc=""):
parser = argparse.ArgumentParser(prog=prog, description=desc)
self._add_arguments(parser)
parser.add_argument("-j", "--cores", dest="num_cores", type=int, metavar="CORES",
help="Number of cores to use for calculations. Default is 0 that means all the available cores")
parser.add_argument("-D", dest="defines", metavar="KEY=VALUE", action="append",
help="Define external parameters to be saved in the results")
parser.add_argument("-L", "--log-level", dest="log_level", metavar="LEVEL", default=None,
choices=["debug", "info", "warn", "error", "critical", "notset"],
help="Define log level: debug, info, warn, error, critical, notset")
self.args = parser.parse_args()
logging.basicConfig(
format = "%(asctime)s %(name)s %(levelname)-5s : %(message)s",
datefmt = "%Y-%m-%d %H:%M:%S")
if self.args.log_level is None:
self.args.log_level = "info"
else:
self.args.log_level = self.args.log_level.lower()
logging.getLogger("oncodrivefm").setLevel(_LOG_LEVELS[self.args.log_level])
self.log = logging.getLogger("oncodrivefm")
self._arg_errors = []
def _add_arguments(self, parser):
parser.add_argument("-o", "--output-path", dest="output_path", metavar="PATH",
help="Directory where output files will be written")
parser.add_argument("-n", dest="analysis_name", metavar="NAME",
help="Analysis name")
parser.add_argument("--output-format", dest="output_format", metavar="FORMAT",
choices=["tsv", "tsv.gz", "tsv.bz2"], default="tsv",
help="The FORMAT for the output file")
def _check_args(self):
if self.args.output_path is None:
self.args.output_path = os.getcwd()
def _error(self, msg):
self._arg_errors += [msg]
def load_mapping(self, matrix, path, filt=None):
map = {}
if path is None:
return map
with open(path) as f:
for line in f:
line = line.rstrip()
if len(line) == 0 or line.startswith("#"):
continue
fields = line.split('\t')
if len(fields) < 2:
continue
gene, pathway = fields[0:2]
if filt is None or filt.valid(gene):
if pathway in map:
map[pathway].add(gene)
else:
map[pathway] = set([gene])
for pathway, genes in map.items():
map[pathway] = sorted(genes)
return MatrixMapping(matrix, map)
def save_splited_results(self, output_path, analysis_name, output_format,
matrix, mapping, method, results, slices, suffix=""):
if len(suffix) > 0:
suffix = "-{0}".format(suffix)
for slice_results_index, slice in enumerate(slices):
slice_name = matrix.slice_names[slice]
path = os.path.join(output_path, "{0}{1}-{2}.{3}".format(
analysis_name, suffix, slice_name, output_format))
self.log.debug(" > {0}".format(path))
with tsv.open(path, 'w') as f:
tsv.write_line(f, "## version={0}".format(VERSION))
tsv.write_line(f, "## slice={0}".format(slice_name))
tsv.write_line(f, "## method={0}".format(method.name))
tsv.write_line(f, "## date={0}".format(datetime.now().strftime("%Y-%m-%d %H:%M:%S")))
for key, value in self.parameters:
tsv.write_line(f, "## {0}={1}".format(key, value))
tsv.write_line(f, "ID", *method.results_columns)
for row_index, row_name in enumerate(mapping.group_names):
value = results[slice_results_index, row_index]
if not | np.isnan(value) | numpy.isnan |
import numpy as np
import pandas as pd
from os.path import join
import glob
import tensorflow as tf
import tensorflow_datasets as tfds
from hps.common.Common import Common
from hps.dataset.DatasetAbstract import DatasetAbstract
class CICIDSDataset(DatasetAbstract):
LOGGER = Common.LOGGER.getLogger()
@classmethod
def get_dataset(cls):
data, label = cls.load_data()
#cls.LOGGER.info("label_count : {}".format(label.value_counts()))
balanced_data, balanced_label = cls.balancing_data(data, label)
normalized_data = cls.normalize(balanced_data)
cls.LOGGER.info("nan_count : {}".format(np.isnan(normalized_data).sum()))
train, test,train_label, test_label = cls.split_data(normalized_data, balanced_label)
ds_train, ds_test, label_train, label_test = cls.make_dataset(train,test, train_label, test_label)
cls.LOGGER.info("spec of train:{}, test:{}, train_label:{}, test_label:{}".format(np.shape(ds_train),np.shape(ds_test),np.shape(label_train),np.shape(label_test)))
return ds_train, label_train, ds_test, label_test
@classmethod
def load_data(cls)-> (pd.DataFrame, pd.DataFrame):
filenames = [i for i in glob.glob(join("/../../../../cicids", "*.pcap_ISCX.csv"))]
combined_csv = pd.concat([pd.read_csv(f,dtype=object,skipinitialspace=True) for f in filenames],sort=False,)
data = combined_csv.rename(columns=lambda x: x.strip()) #strip() : delete \n & space
#data.replace([np.inf, -np.inf], 0)
cls.LOGGER.info("{}".format(data['Label'].value_counts()))
#if data["Label"] == 1. :
# data["Label"] = 1
#else :
# data["Label"] = 0
label = data["Label"]
#cls.LOGGER.info("label count: {}".format(label.value_counts()))
# encoded_label = cls.encode_label(label.values)
encoded_label, num = cls.label_encoder(data)
data.replace('Infinity',0.0, inplace=True)
data = data.astype(float).apply(pd.to_numeric)
#encoded_label = cls.ont_hot_encoder(encoded_label, num)
data.drop("Label", inplace=True, axis=1)
#data = data.astype(float).apply(pd.to_numeric)
data.fillna(0, inplace=True)
cls.LOGGER.info("data : {}".format(data))
encoded_label = encoded_label.astype("float")
#cls.LOGGER.info("label : {}".format(encoded_label))
# data["Label"]=encoded_label
#cls.LOGGER.info("label : {}".format(encoded_label.unique()))
data = data.values
#encoded_label = cls.ont_hot_encoder(encoded_label, num)
return data, encoded_label
@classmethod
def make_dataset(cls, train:np.ndarray, test:np.ndarray, train_label:np.ndarray, test_label:np.ndarray)->(list, list):
cls.LOGGER.info("train :{}".format(train.shape))
cls.LOGGER.info("train_label :{}".format(train_label.shape))
ds_train_list = train.tolist()
ds_test_list = test.tolist()
label_train_list = train_label.tolist()
label_test_list = test_label.tolist()
return ds_train_list, ds_test_list, label_train_list, label_test_list
@classmethod
def split_data(cls, dataset:np.ndarray, label:np.ndarray) -> (np.ndarray, np.ndarray, np.ndarray, np.ndarray):
data_size = int(len(label))
train_size = int(0.65 * data_size)
split_data= np.split(dataset,[train_size, data_size])
split_label= np.split(label, [train_size, data_size])
return split_data[0], split_data[1], split_label[0], split_label[1]
@classmethod
def encode_label(cls, y_str):
labels_d = cls.make_lut(np.unique(y_str))
y = [labels_d[y_str_i] for y_str_i in y_str]
return | np.array(y) | numpy.array |
from unittest import TestCase
import numpy as np
from astropy.cosmology import Planck13
import astropy.units as u
from physics_functions import comoving_distance
class TestComovingDistance(TestCase):
def test_fast_comoving_distance(self):
z_params = {'z_start': 1.8, 'z_end': 3.7, 'z_step': 0.001}
cd = comoving_distance.ComovingDistance(**z_params)
ar_z = np.arange(1.952, 3.6, 0.132)
ar_dist = cd.fast_comoving_distance(ar_z)
ar_dist_reference = Planck13.comoving_transverse_distance(ar_z) / u.Mpc
print(ar_dist - ar_dist_reference)
self.assertTrue( | np.allclose(ar_dist, ar_dist_reference) | numpy.allclose |
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import numpy as np
from hyperemble.utils import corr, table_int, table_obj
def test_corr():
a = np.array([1, 2, 3])
b = np.array([2, 3, 4])
c = np.array([2, 3, 5])
d = corr(a, b)
e = corr(a, c)
assert type(d) is np.float64
assert type(e) is np.float64
assert np.isclose(d, 1.)
assert np.isclose(e, 0.98198050606196585)
def test_table_int():
x = np.array([1, 1, 1, 1, 2, 2, 2, 3])
res = table_int(x)
assert type(res) is dict
assert len(res) == 3
assert res == {1: 4, 2: 3, 3: 1}
def test_table_obj():
x = | np.array(["a", "a", "b", "c"]) | numpy.array |
import warnings
warnings.simplefilter("ignore", category=FutureWarning)
from pmaf.biome.essentials._metakit import (
EssentialFeatureMetabase,
EssentialSampleMetabase,
)
from pmaf.biome.essentials._base import EssentialBackboneBase
from collections import defaultdict
from os import path
import pandas as pd
import numpy as np
import biom
from typing import Union, Sequence, Tuple, Callable, Any, Optional
from pmaf.internal._typing import AnyGenericIdentifier, Mapper
class FrequencyTable(
EssentialBackboneBase, EssentialFeatureMetabase, EssentialSampleMetabase
):
"""An essential class for handling frequency data."""
def __init__(
self,
frequency: Union[pd.DataFrame, str],
skipcols: Union[Sequence[Union[str, int]], str, int] = None,
allow_nan: bool = False,
**kwargs
):
"""Constructor for :class:`.FrequencyTable`
Parameters
----------
frequency
Data containing frequency data.
skipcols
Columns to skip when processing data.
allow_nan
Allow NA/NaN values or raise an error.
kwargs
Remaining parameters passed to :func:`~pandas.read_csv` or :mod:`biom` loader
"""
self.__internal_frequency = None
tmp_skipcols = np.asarray([])
tmp_metadata = kwargs.pop("metadata", {})
if skipcols is not None:
if isinstance(skipcols, (str, int)):
tmp_skipcols = np.asarray([skipcols])
elif isinstance(skipcols, (list, tuple)):
if not isinstance(skipcols[0], (str, int)):
tmp_skipcols = np.asarray(skipcols)
else:
raise TypeError(
"`skipcols` can be int/str or list-like of int/str."
)
else:
raise TypeError("`skipcols` can be int/str or list-like of int/str.")
if isinstance(frequency, pd.DataFrame):
if all(frequency.shape):
tmp_frequency = frequency
else:
raise ValueError("Provided `frequency` Datafame is invalid.")
elif isinstance(frequency, str):
if not path.isfile(frequency):
raise FileNotFoundError("Provided `frequency` file path is invalid.")
file_extension = path.splitext(frequency)[-1].lower()
if file_extension in [".csv", ".tsv"]:
tmp_frequency = pd.read_csv(frequency, **kwargs)
elif file_extension in [".biom", ".biome"]:
tmp_frequency, new_metadata = self.__load_biom(frequency, **kwargs)
tmp_metadata.update({"biom": new_metadata})
else:
raise NotImplementedError("File type is not supported.")
else:
raise TypeError("Provided `frequency` has invalid type.")
if skipcols is not None:
if np.issubdtype(tmp_skipcols.dtype, np.number):
if tmp_frequency.columns.isin(tmp_skipcols).any():
tmp_frequency.drop(columns=tmp_skipcols, inplace=True)
else:
tmp_frequency.drop(
columns=tmp_frequency.columns[tmp_skipcols], inplace=True
)
else:
tmp_frequency.drop(columns=tmp_skipcols, inplace=True)
tmp_dtypes = list(set(tmp_frequency.dtypes.values))
if len(tmp_dtypes) == 1 and pd.api.types.is_numeric_dtype(tmp_dtypes[0]):
self.__init_frequency_table(tmp_frequency)
else:
if not allow_nan:
raise ValueError(
"Provided `frequency` must have numeric dtypes. "
"Use `allow_nan` to allow missing values."
)
if len(tmp_dtypes) == 1 and pd.api.types.is_numeric_dtype(tmp_dtypes[0]):
self.__init_frequency_table(tmp_frequency)
elif len(tmp_dtypes) == 2:
tmp_dtypes_cond = [
(dt == object) or (pd.api.types.is_numeric_dtype(dt))
for dt in tmp_dtypes
]
if all(tmp_dtypes_cond) and tmp_frequency.isnull().values.any():
self.__init_frequency_table(tmp_frequency)
else:
raise ValueError(
"Provided `frequency` may contain numeric values or NAs."
)
else:
raise ValueError("Provided `frequency` has zero or too many dtypes.")
super().__init__(metadata=tmp_metadata, **kwargs)
@classmethod
def from_biom(cls, filepath: str, **kwargs) -> "FrequencyTable":
"""Factory method to construct a :class:`.FrequencyTable` from
:mod:`biom` file.
Parameters
----------
filepath
Path to :mod:`biom` file
kwargs
Compatibility
Returns
-------
Instance of class:`.FrequencyTable`
"""
frequency_frame, new_metadata = cls.__load_biom(filepath, **kwargs)
tmp_metadata = kwargs.pop("metadata", {})
tmp_metadata.update({"biom": new_metadata})
return cls(frequency=frequency_frame, metadata=tmp_metadata, **kwargs)
@classmethod
def from_csv(cls, filepath: str, **kwargs) -> "FrequencyTable":
"""Factory method to construct a :class:`.FrequencyTable` from CSV
file.
Parameters
----------
filepath
Path to .csv file.
kwargs
Compatibility
Returns
-------
Instance of class:`.FrequencyTable`
"""
tmp_frequency = pd.read_csv(filepath, **kwargs)
tmp_metadata = kwargs.pop("metadata", {})
tmp_metadata.update({"filepath": path.abspath(filepath)})
return cls(frequency=tmp_frequency, metadata=tmp_metadata, **kwargs)
@classmethod
def __load_biom(cls, filepath: str, **kwargs) -> Tuple[pd.DataFrame, dict]:
"""Actual private method to process :mod:`biom` file.
Parameters
----------
filepath
:mod:`biom` file path.
kwargs
Compatibility
"""
biom_file = biom.load_table(filepath)
return biom_file.to_dataframe(dense=True), {}
def _rename_samples_by_map(
self, map_like: Mapper, **kwargs
) -> Union[None, Mapper, dict]:
"""Rename sample names by map and ratify action.
Parameters
----------
map_like
Mapper to use for renaming
kwargs
Compatibility
"""
self.__internal_frequency.rename(mapper=map_like, axis=1, inplace=True)
return self._ratify_action("_rename_samples_by_map", map_like, **kwargs)
def _remove_features_by_id(
self, ids: AnyGenericIdentifier, **kwargs
) -> Union[None, AnyGenericIdentifier, dict]:
"""Remove feature by id and ratify action.
Parameters
----------
ids
Feature identifiers.
kwargs
Compatibility
"""
tmp_ids = np.asarray(ids, dtype=self.__internal_frequency.index.dtype)
if len(tmp_ids) > 0:
self.__internal_frequency.drop(index=tmp_ids, inplace=True)
return self._ratify_action("_remove_features_by_id", ids, **kwargs)
def _merge_features_by_map(
self, map_dict: Mapper, aggfunc: Union[str, Callable] = "sum", **kwargs
) -> Union[None, Mapper]:
"""Merge features by map with aggfunc and ratify action.
Parameters
----------
map_dict
Feature-wise map to use for merging
aggfunc
Aggregation function
kwargs
Compatibility
"""
tmp_agg_dict = defaultdict(list)
for new_id, group in map_dict.items():
tmp_agg_dict[new_id] = (
self.__internal_frequency.loc[group, :].agg(func=aggfunc, axis=0).values
)
tmp_freq_table = pd.DataFrame.from_dict(
tmp_agg_dict, orient="index", columns=self.__internal_frequency.columns
)
self.__init_frequency_table(tmp_freq_table)
return self._ratify_action(
"_merge_features_by_map", map_dict, aggfunc=aggfunc, **kwargs
)
def _remove_samples_by_id(
self, ids: AnyGenericIdentifier, **kwargs
) -> Union[None, AnyGenericIdentifier, dict]:
"""Remove samples by id and ratify action.
Parameters
----------
ids
Feature identifiers
kwargs
Compatibility
"""
tmp_ids = np.asarray(ids, dtype=self.__internal_frequency.columns.dtype)
if len(tmp_ids) > 0:
self.__internal_frequency.drop(columns=tmp_ids, inplace=True)
return self._ratify_action("_remove_samples_by_id", ids, **kwargs)
def _merge_samples_by_map(
self, map_dict: Mapper, aggfunc: Union[str, Callable] = "mean", **kwargs
) -> Optional[Mapper]:
"""Merge samples by map with aggfunc and ratify action.
Parameters
----------
map_dict
Sample-wise map to use for merging
aggfunc
Aggregation function
kwargs
Compatibility
"""
tmp_agg_dict = defaultdict(list)
for new_id, group in map_dict.items():
tmp_agg_dict[new_id] = (
self.__internal_frequency.loc[:, group]
.agg(func=aggfunc, axis=1)
.to_dict()
)
tmp_freq_table = pd.DataFrame.from_dict(tmp_agg_dict, orient="columns")
self.__init_frequency_table(tmp_freq_table)
return self._ratify_action(
"_merge_samples_by_map", map_dict, aggfunc=aggfunc, **kwargs
)
def transform_to_relative_abundance(self):
"""Transform absolute counts to relative."""
self.__internal_frequency = self.__internal_frequency.div(
self.__internal_frequency.sum(axis=0), axis=1
)
def replace_nan_with(self, value: Any) -> None:
"""Replace NaN values with `value`.
Parameters
----------
value
Value to replace NaN's
"""
self.__internal_frequency.fillna(value, inplace=True)
def drop_features_by_id(self, ids: AnyGenericIdentifier) -> Union[None, np.ndarray]:
"""Drop features by `ids`
Parameters
----------
ids
Feature identifiers
"""
target_ids = np.asarray(ids)
if self.__internal_frequency.index.isin(target_ids).sum() == len(target_ids):
self._remove_features_by_id(target_ids)
if self.is_buckled:
return target_ids
else:
raise ValueError("Invalid _feature ids are provided.")
def rename_samples(self, mapper: Mapper) -> None:
"""Rename sample names.
Parameters
----------
mapper
Rename samples by map
"""
if isinstance(mapper, dict) or callable(mapper):
if isinstance(mapper, dict):
if self.__internal_frequency.columns.isin(
list(mapper.keys())
).sum() == len(mapper):
self._rename_samples_by_map(mapper)
else:
raise ValueError("Invalid sample ids are provided.")
else:
self._rename_samples_by_map(mapper)
else:
raise TypeError("Invalid `mapper` type.")
def drop_features_without_counts(self) -> Optional[np.ndarray]:
"""Drop features that has no counts.
Typically required after dropping samples.
"""
target_ids = self.__internal_frequency.index[
self.__internal_frequency.sum(axis=1) == 0
].values
self._remove_features_by_id(target_ids)
if self.is_buckled:
return target_ids
def drop_samples_by_id(self, ids: AnyGenericIdentifier) -> Optional[np.ndarray]:
"""Drop samples by `ids`
Parameters
----------
ids
Sample identifiers
"""
target_ids = np.asarray(ids)
if self.__internal_frequency.columns.isin(target_ids).sum() == len(target_ids):
self._remove_samples_by_id(target_ids)
if self.is_buckled:
return target_ids
else:
raise ValueError("Invalid _sample ids are provided.")
def __init_frequency_table(self, freq_table: pd.DataFrame) -> None:
"""Initiate the frequency table."""
self.__internal_frequency = freq_table
def merge_features_by_map(
self, mapping: Mapper, aggfunc: Union[str, Callable] = "sum", **kwargs
) -> Optional[Mapper]:
"""Merge features by `mapping`
Parameters
----------
mapping
Map with values as feature identifiers to be aggregated.
aggfunc
Aggregation function to apply
kwargs
Compatibility
"""
if isinstance(mapping, (dict, pd.Series)):
tmp_ids = sorted(
{x for _, v in mapping.items() for x in v}
) # FIXME: Uncool behavior make it better and follow the usage.
if self.__internal_frequency.index.isin(tmp_ids).sum() == len(tmp_ids):
return self._merge_features_by_map(mapping, aggfunc, **kwargs)
else:
raise ValueError("Invalid feature ids were found.")
else:
raise TypeError("`mapping` can be `dict` or `pd.Series`")
def merge_samples_by_map(
self, mapping: Mapper, aggfunc: Union[str, Callable] = "mean", **kwargs
) -> Optional[Mapper]:
"""Merge samples by `mapping`
Parameters
----------
mapping
Map with values as sample identifiers to be aggregated.
aggfunc
Aggregation function to apply
kwargs
Compatibility
"""
if isinstance(mapping, (dict, pd.Series)):
tmp_ids = sorted(
{x for _, v in mapping.items() for x in v}
) # FIXME: Uncool. See above.
if self.__internal_frequency.columns.isin(tmp_ids).sum() == len(tmp_ids):
return self._merge_samples_by_map(mapping, aggfunc, **kwargs)
else:
raise ValueError("Invalid sample ids were found.")
else:
raise TypeError("`mapping` can be `dict` or `pd.Series`")
def copy(self) -> "FrequencyTable":
"""Copy of the instance."""
return type(self)(
frequency=self.__internal_frequency.copy(), metadata=self.metadata, name=self.name
)
def get_subset(
self,
rids: Optional[AnyGenericIdentifier] = None,
sids: Optional[AnyGenericIdentifier] = None,
*args,
**kwargs
) -> "FrequencyTable":
"""Get subset of the :class:`.FrequencyTable`.
Parameters
----------
rids
Feature Identifiers
sids
Sample Identifiers
args
Compatibility
kwargs
Compatibility
Returns
-------
Instance of class:`.FrequencyTable`.
"""
if rids is None:
target_rids = self.xrid
else:
target_rids = | np.asarray(rids) | numpy.asarray |
from __future__ import print_function
import os
import shutil
import warnings
import tempfile
import pickle
import numpy
import scipy.linalg as linalg
from galpy.util.config import __config__
_SHOW_WARNINGS= __config__.getboolean('warnings','verbose')
class galpyWarning(Warning):
pass
# galpy warnings only shown if verbose = True in the configuration
class galpyWarningVerbose(galpyWarning):
pass
def _warning(
message,
category=galpyWarning,
filename='',
lineno=-1,
file=None,
line=None):
if issubclass(category,galpyWarning):
if not issubclass(category,galpyWarningVerbose) or _SHOW_WARNINGS:
print("galpyWarning: "+str(message))
else:
print(warnings.formatwarning(message,category,filename,lineno))
warnings.showwarning = _warning
def save_pickles(savefilename,*args,**kwargs):
"""
NAME:
save_pickles
PURPOSE:
relatively safely save things to a pickle
INPUT:
savefilename - name of the file to save to; actual save operation will be performed on a temporary file and then that file will be shell mv'ed to savefilename
+things to pickle (as many as you want!)
OUTPUT:
none
HISTORY:
2010-? - Written - Bovy (NYU)
2011-08-23 - generalized and added to galpy.util - Bovy (NYU)
"""
saving= True
interrupted= False
file, tmp_savefilename= tempfile.mkstemp() #savefilename+'.tmp'
os.close(file) #Easier this way
while saving:
try:
savefile= open(tmp_savefilename,'wb')
file_open= True
if kwargs.get('testKeyboardInterrupt',False) and not interrupted:
raise KeyboardInterrupt
for f in args:
pickle.dump(f,savefile,pickle.HIGHEST_PROTOCOL)
savefile.close()
file_open= False
shutil.move(tmp_savefilename,savefilename)
saving= False
if interrupted:
raise KeyboardInterrupt
except KeyboardInterrupt:
if not saving:
raise
print("KeyboardInterrupt ignored while saving pickle ...")
interrupted= True
finally:
if file_open:
savefile.close()
def logsumexp(arr,axis=0):
"""Faster logsumexp?"""
minarr= numpy.amax(arr,axis=axis)
if axis == 1:
minarr= numpy.reshape(minarr,(arr.shape[0],1))
if axis == 0:
minminarr= numpy.tile(minarr,(arr.shape[0],1))
elif axis == 1:
minminarr= numpy.tile(minarr,(1,arr.shape[1]))
elif axis == None:
minminarr= | numpy.tile(minarr,arr.shape) | numpy.tile |
# -*- coding: utf-8 -*-
"""
Created on Wed Dec 4 22:45:19 2019
@author: Pavan
"""
import numpy as np
import scipy.stats as sc
import math
################################################################################################
# Helper Functions
def column_wise(fun,*args):
return np.apply_along_axis(fun,0,*args)
def rolling_window(a, shape): # rolling window for 2D array
s = (a.shape[0] - shape[0] + 1,) + (a.shape[1] - shape[1] + 1,) + shape
strides = a.strides + a.strides
return np.lib.stride_tricks.as_strided(a, shape=s, strides=strides)
def fisher_helper_ema(array,alpha,window):
def numpy_ewma(a, alpha, windowSize):
# a=a.flatten()
wghts = (1-alpha)**np.arange(windowSize)
# wghts /= wghts.sum()
out = np.convolve(a,wghts)
out[:windowSize-1] = np.nan
return out[:a.size]
return column_wise(numpy_ewma,array,alpha,window)
################################################################################################
# A. Mathematical Functions
# Rolling Median
def median(a,window):
me = np.empty_like(a)
me[:window-1,:]=np.nan
me[window-1:,:]= np.squeeze(np.median(rolling_window(a,(window,a.shape[1])),axis=2),axis=1)
return me
# Rolling Mean
def mean(a,window):
me = np.empty_like(a)
me[:window-1,:]=np.nan
me[window-1:,:]= np.squeeze(np.mean(rolling_window(a,(window,a.shape[1])),axis=2),axis=1)
return me
#Rolling Standard Deviation
def stdev(a,window):
std = np.empty_like(a)
std[:window-1,:]=np.nan
std[window-1:,:]= np.squeeze(np.std(rolling_window(a,(window,a.shape[1])),axis=2),axis=1)
return std
#Rolling Product
def product(a,window):
prod = np.empty_like(a)
prod[:window-1,:]=np.nan
prod[window-1:,:]= np.squeeze(np.prod(rolling_window(a,(window,a.shape[1])),axis=2),axis=1)
return prod
#Rolling Summation
def summation(a,window):
summ = np.empty_like(a)
summ[:window-1,:]=np.nan
summ[window-1:,:]= np.squeeze(np.sum(rolling_window(a,(window,a.shape[1])),axis=2),axis=1)
return summ
#Rolling Nan Product. Treats nan values as 1
def nanprod(a,window):
nanprod = np.empty_like(a)
nanprod[:window-1,:]=np.nan
nanprod[window-1:,:]= np.squeeze(np.nanprod(rolling_window(a,(window,a.shape[1])),axis=2),axis=1)
return nanprod
#Rolling Nan Summation. Treats nan values as 0
def nansum(a,window):
summ = np.empty_like(a)
summ[:window-1,:]=np.nan
summ[window-1:,:]= np.squeeze(np.nansum(rolling_window(a,(window,a.shape[1])),axis=2),axis=1)
return summ
#Rolling Cummulative Product
def cumproduct(a,window):
prod = np.empty_like(a)
prod[:window-1,:]=np.nan
prod[window-1:,:]= np.squeeze(np.cumprod(rolling_window(a,(window,a.shape[1])),axis=2),axis=1)
return prod
#Rolling Summation
def cumsummation(a,window):
summ = np.empty_like(a)
summ[:window-1,:]=np.nan
summ[window-1:,:]= np.squeeze(np.cumsum(rolling_window(a,(window,a.shape[1])),axis=2),axis=1)
return summ
#Rolling nan Cummulative Product. Treats nan as 1
def nancumproduct(a,window):
prod = np.empty_like(a)
prod[:window-1,:]=np.nan
prod[window-1:,:]= np.squeeze(np.nancumprod(rolling_window(a,(window,a.shape[1])),axis=2),axis=1)
return prod
#Rolling nan Cummulative Summation. Treats nan as 0
def nancumsummation(a,window):
summ = np.empty_like(a)
summ[:window-1,:]=np.nan
summ[window-1:,:]= np.squeeze(np.nancumsum(rolling_window(a,(window,a.shape[1])),axis=2),axis=1)
return summ
#backward difference: a[n]=b[n]-b[n-(window-1)]
def back_diff(a,window):
back= np.empty_like(a)
back[:window-1,:]=np.nan
back[window-1:,:]=a[window-1:,:]-a[:-(window-1),:]
return back
# rolling integration
def integrate(a,window):
inte= np.empty_like(a)
inte[:window-1,:]=np.nan
inte[window-1:,:]=np.squeeze(np.trapz(rolling_window(a,(window,a.shape[1])),axis=2),axis=1)
return inte
# rolling integration
def integrate_along_x(y,x,window):
inte= np.empty_like(y)
inte[:window-1,:]=np.nan
inte[window-1:,:]=np.squeeze(np.trapz(rolling_window(y,(window,y.shape[1])),rolling_window(x,(window,x.shape[1])),axis=2),axis=1)
return inte
#Centers Value by subtracting its median over the TimePeriod.
#Using the median instead of the mean reduces the effect of outliers.
def center(a,window):
cen = np.empty_like(a)
cen[:window-1,:]=np.nan
cen[window-1:,:]= a[window-1:,:]-np.squeeze(np.median(rolling_window(a,(window,a.shape[1])),axis=2),axis=1)
return cen
#Compresses Value to the -100...+100 range. For this, Value is divided by its interquartile range
# - the difference of the 75th and 25th percentile - taken over TimePeriod, and
# then compressed by a cdf function. Works best when Value is an oscillator that crosses
# the zero line. Formula: 200 * cdf(0.25*Value/(P75-P25)) - 100.
def compress(a,window):
from scipy.stats import norm
com = np.empty_like(a)
com[:window-1,:]=np.nan
value = a[window-1:,:]
q25 = np.squeeze(np.quantile(rolling_window(a,(window,a.shape[1])),0.25,axis=2),axis=1)
q75 = np.squeeze(np.quantile(rolling_window(a,(window,a.shape[1])),0.75,axis=2),axis=1)
com[window-1:,:] = 200*(norm.cdf((0.25*value/(q75-q25))))-100
return com
#Centers and compresses Value to the -100...+100 scale.
#The deviation of Value from its median is divided by its interquartile range and then
#compressed by a cdf function. Formula: 200 * cdf(0.5*(Value-Median)/(P75-P25)) - 100.
def scale(a,window):
from scipy.stats import norm
scale = np.empty_like(a)
scale[:window-1,:]=np.nan
value = a[window-1:,:]
median = np.squeeze(np.median(rolling_window(a,(window,a.shape[1])),axis=2),axis=1)
q25 = np.squeeze(np.quantile(rolling_window(a,(window,a.shape[1])),0.25,axis=2),axis=1)
q75 = np.squeeze(np.quantile(rolling_window(a,(window,a.shape[1])),0.75,axis=2),axis=1)
scale[window-1:,:] = 200*(norm.cdf((0.25*(value-median)/(q75-q25))))-100
return scale
#Normalizes Value to the -100...+100 range through subtracting its minimum and dividing
#by its range over TimePeriod. Formula: 200 * (Value-Min)/(Max-Min) - 100 .
#For a 0..100 oscillator, multiply the returned value with 0.5 and add 50.
def normalize(a,window):
norm = np.empty_like(a)
norm[:window-1,:]=np.nan
value = a[window-1:,:]
minimum = np.squeeze(rolling_window(a,(window,a.shape[1])).min(axis=2),axis=1)
maximum = np.squeeze(rolling_window(a,(window,a.shape[1])).max(axis=2),axis=1)
norm[window-1:,:] = 200*((value-minimum)/(maximum-minimum))-100
return norm
def normalize_o(a,window):
norm = np.empty_like(a)
norm[:window-1,:]=np.nan
value = a[window-1:,:]
minimum = np.squeeze(rolling_window(a,(window,a.shape[1])).min(axis=2),axis=1)
maximum = np.squeeze(rolling_window(a,(window,a.shape[1])).max(axis=2),axis=1)
norm[window-1:,:] = 2*((value-minimum)/(maximum-minimum))-1
return norm
#Calculates the Z-score of the Value. The Z-score is the deviation from
# the mean over the TimePeriod, divided by the standard deviation.
# Formula: (Value-Mean)/StdDev.
def zscore(a,window):
z = np.empty_like(a)
z[:window-1,:]=np.nan
value = a[window-1:,:]
mean =np.squeeze(np.mean(rolling_window(a,(window,a.shape[1])),axis=2),axis=1)
stddev = np.squeeze(np.std(rolling_window(a,(window,a.shape[1])),axis=2),axis=1)
z[window-1:,:] = (value-mean)/stddev
return z
#### Mathematical functions
def absolute(a):
return np.absolute(a)
def sin(a):
return np.sin(a)
def cos(a):
return np.cos(a)
def tan(a):
return np.tan(a)
def asin(a):
return np.arcsin(a)
def acos(a):
return np.arccos(a)
def atan(a):
return np.arctan(a)
def sinh(a):
return np.sinh(a)
def cosh(a):
return np.cosh(a)
def tanh(a):
return np.tanh(a)
def asinh(a):
return np.arcsinh(a)
def acosh(a):
return np.arccosh(a)
def atanh(a):
return np.arctanh(a)
def floor(a):
return np.floor(a)
def ceil(a):
return np.ceil(a)
def clamp(a,minimum,maximum):
return np.clip(a,minimum,maximum)
def around(a,decimals=0):
return np.around(a,decimals)
def round_(a,decimals=0):
return np.round_(a,decimals)
def rint(a):
return np.rint(a)
def fix(a):
return np.fix(a)
def trunc(a):
return np.trunc(a)
def pdf(a):
from scipy.stats import norm
return norm.pdf(a)
def logpdf(a):
from scipy.stats import norm
return norm.logpdf(a)
def cdf(a):
from scipy.stats import norm
return norm.cdf(a)
def logcdf(a):
from scipy.stats import norm
return norm.logcdf(a)
def qnorm(a):
from scipy.stats import norm
return norm.ppf(a)
def survival(a):
from scipy.stats import norm
return norm.sf(a)
def inv_survival(a):
from scipy.stats import norm
return norm.isf(a)
def errorf(a):
from scipy.special import erf
return erf(a)
def errorfc(a):
from scipy.special import erfc
return erfc(a)
def exp(a):
return np.exp(a)
def exp1(a):
return np.exp1(a)
def exp2(a):
return np.exp2(a)
def log(a):
return np.log(a)
def log10(a):
return np.log10(a)
def log2(a):
return np.log2(a)
def log1p(a):
return np.log1p(a)
def add(a,b):
return np.add(a,b)
def receiprocal(a):
return np.reciprocal(a)
def negative(a):
return np.negative(a)
def multiply(a,b):
return np.multiply(a,b)
def divide(a,b):
return np.divide(a,b)
def power(a,b):
return np.power(a,b)
def subtract(a,b):
return np.subtract(a,b)
def true_divide(a,b):
return np.true_divide(a,b)
def remainder(a,b):
return np.remainder(a,b)
def sqrt(a):
return np.sqrt(a)
def square(a):
return np.square(a)
def sign(a):
return np.sign(a)
def maximum(a,b):
return np.maximum(a,b)
def minimum(a,b):
return np.minimum(a,b)
def nan_to_num(a):
return np.nan_to_num(a)
############################################################################################
### Time Series properties, transformations and statistics
#Rolling Pearson Correlation
def corr(a,b,window):
from skimage.util import view_as_windows
A = view_as_windows(a,(window,1))[...,0]
B = view_as_windows(b,(window,1))[...,0]
A_mA = A - A.mean(-1, keepdims=True)
B_mB = B - B.mean(-1, keepdims=True)
# ## Sum of squares across rows
# ssA = (A_mA**2).sum(-1) # or better : np.einsum('ijk,ijk->ij',A_mA,A_mA)
# ssB = (B_mB**2).sum(-1) # or better : np.einsum('ijk,ijk->ij',B_mB,B_mB)
ssA = np.einsum('ijk,ijk->ij',A_mA,A_mA)
ssB = np.einsum('ijk,ijk->ij',B_mB,B_mB)
## Finally get corr coeff
out = np.full(a.shape, np.nan)
out[window-1:] = np.einsum('ijk,ijk->ij',A_mA,B_mB)/np.sqrt(ssA*ssB)
return out
# Rolling Covariance
def covariance(a,b,window):
from skimage.util import view_as_windows
A = view_as_windows(a,(window,1))[...,0]
B = view_as_windows(b,(window,1))[...,0]
A_mA = A - A.mean(-1, keepdims=True)
B_mB = B - B.mean(-1, keepdims=True)
out = np.full(a.shape, np.nan)
out[window-1:] = np.einsum('ijk,ijk->ij',A_mA,B_mB)
return out
## Fisher transformation
#Fisher Transform; transforms a normalized Data series to a normal distributed range.
# The return value has no theoretical limit, but most values are between -1 .. +1.
# All Data values must be in the -1 .. +1 range f.i. by normalizing with
# the AGC, Normalize, or cdf function. The minimum Data length is 1.
def fisher(a):
tran = np.clip(a,-0.998,0.998)
return 0.5*np.log((1+tran)/(1-tran))
def invfisher(a):
return (np.exp(2*a)-1)/(np.exp(2*a)+1)
# Simple Moving average
def sma(array,window):
def sma_array(array,window):
weights = np.ones(window)/window
ma = np.full_like(array,np.nan)
ma[window-1:] = np.convolve(array, weights, 'valid')
return ma
return column_wise(sma_array,array,window)
def ema_v1(array,alpha,window):
def numpy_ewma(a, alpha, windowSize):
wghts = (1-alpha)**np.arange(windowSize)
wghts /= wghts.sum()
out = np.convolve(a,wghts)
out[:windowSize-1] = np.nan
return out[:a.size]
return column_wise(numpy_ewma,array,alpha,window)
def ema(array,window):
def ExpMovingAverage(values, window):
alpha = 2/(1.0+window)
weights = (1-alpha)**np.arange(window)
weights /= weights.sum()
a = np.convolve(values, weights, mode='full')[:len(values)]
a[:window-1] = np.nan
return a
return column_wise(ExpMovingAverage,array,window)
### Check this AGAIN. this involves ema with 0.67 and 0.33 as weights
def fisher_norm(a,window):
return fisher_helper_ema(fisher(ema(normalize_o(a,window),2)),2/3,2)
#Highest value over a specified period.
def maxval(a,window):
z = np.full_like(a,np.nan)
z[window-1:,:] = np.squeeze(rolling_window(a,(window,a.shape[1]))).max(axis=1)
return z
#Lowest value over a specified period.
def minval(a,window):
z = np.full_like(a,np.nan)
z[window-1:,:] = np.squeeze(rolling_window(a,(window,a.shape[1]))).min(axis=1)
return z
#Index of highest value over a specified period. 0 = highest value is at
#current bar, 1 = at one bar ago, and so on.
def max_index(a,window):
z = np.full_like(a,np.nan)
z[window-1:,:] = window-np.argmax(np.squeeze(rolling_window(a,(window,a.shape[1]))),axis=1)
return z
#Index of lowest value over a specified period. 0 = lowest value is at
#current bar, 1 = at one bar ago, and so on.
def min_index(a,window):
z = np.full_like(a,np.nan)
z[window-1:,:] = window-np.argmin(np.squeeze(rolling_window(a,(window,a.shape[1]))),axis=1)
return z
#Fractal dimension of the Data series; normally 1..2.
#Smaller values mean more 'jaggies'. Can be used to detect the current market regime or
#to adapt moving averages to the fluctuations of a price series.
#Requires a lookback period of twice the TimePeriod.
def fractal_d(a,window):
def fractal_d_helper_max(a,window):
first = np.full_like(a,np.nan)
second = np.full_like(a,np.nan)
br = int(max(1,window/2))
strides = np.squeeze(rolling_window(a,(window,a.shape[1])))
first_half = strides[:,:br,:]
second_half = strides[:,br:,:]
first[window-1:,:]= first_half.max(axis=1)
second[window-1:,:]= second_half.max(axis=1)
return first,second
def fractal_d_helper_min(a,window):
first = np.full_like(a,np.nan)
second = np.full_like(a,np.nan)
br = int(max(1,window/2))
strides = np.squeeze(rolling_window(a,(window,a.shape[1])))
first_half = strides[:,:br,:]
second_half = strides[:,br:,:]
first[window-1:,:]= first_half.min(axis=1)
second[window-1:,:]= second_half.min(axis=1)
return first,second
if window%2==0:
period1 = int(max(1,window/2))
period2 = int(max(1,window-period1))
max_first,max_second = fractal_d_helper_max(a,window)
min_first,min_second = fractal_d_helper_min(a,window)
N1 = (max_first - min_first)/period1
N2 = (max_second - min_second)/period2
N3 = (maxval(a,window)-minval(a,window))/window
nu = N1+N2
nu[nu<=0]=1
N3[N3<=0]=1
return (log(N1+N2)-log(N3))/log(2)
else:
print('Time Period for fractional dimension should be an even number')
#4 pole Gauss Filter, returns a weighted average of the data within the given
#time period, with the weight curve equal to the Gauss Normal Distribution.
#Useful for removing noise by smoothing raw data.
# The minimum length of the Data series is equal to TimePeriod,
# the lag is half the TimePeriod.
def gauss_filter(array,window):
def gauss(a0,window):
# a0=a0.flatten()
N = len(a0)
a0=a0[~np.isnan(a0)]
to_fill = N-len(a0)
poles = 4
PI = math.pi
beta = (1 - math.cos(2 * PI / window)) / (math.pow(2, 1 / poles) - 1)
alpha = -beta + math.sqrt(math.pow(beta, 2) + 2 * beta)
fil = np.zeros(4+len(a0))
coeff = np.array([alpha**4,4*(1-alpha),-6*(1-alpha)**2,4*(1-alpha)**3,-(1-alpha)**4])
for i in range(len(a0)):
val = np.array([np.asscalar(a0[i]),fil[3+i],fil[2+i],fil[1+i],fil[i]])
fil[4+i]=np.dot(coeff,val)
if to_fill!=0:
out = np.insert(fil[4:],0,np.repeat(np.nan,to_fill))
else:
out = fil[4:]
return out
return column_wise(gauss,array,window)
# Ehlers' smoothing filter, 2-pole Butterworth * SMA
def smooth(array,cutoff=10):
def smooth_helper(a0,cutoff=10):
a0=a0.flatten()
N = len(a0)
a0=a0[~np.isnan(a0)]
to_fill = N-len(a0)
PI = math.pi
f = (math.sqrt(2)*PI)/cutoff
a = math.exp(-f)
c2 = 2*a*math.cos(f)
c3 = -a*a
c1 = 1-c2-c3
src = np.insert(a0,0,0)
coeff = np.array([0.5*c1,0.5*c1,c2,c3])
fil = np.zeros(2+len(a0))
for i in range(len(a0)):
val = np.array([np.asscalar(src[i,]),np.asscalar(src[i+1,]),fil[i+1],fil[i]])
fil[2+i]=np.dot(coeff,val)
if to_fill!=0:
out = np.insert(fil[2:],0,np.repeat(np.nan,to_fill))
else:
out = fil[2:]
return out
return column_wise(smooth_helper,array,cutoff)
def hurst_exp(array,window):
window = max(window,20)
hurst = (2.0-fractal_d(array,window))
return clamp(smooth(hurst,int(window/10)),0,1)
#Linear Regression, also known as the "least squares moving average" (LSMA).
#Linear Regression attempts to fit a straight trendline between several data points
# in such a way that the distance between each data point and the trendline
# is minimized. For each point, the straight line over the specified
# previous bar period is determined in terms of y = b + m*x, where
# y is the price and x the bar number starting at TimePeriod bars ago.
# The formula for calculating b and m is then
#
#m = (nΣxy - ΣxΣy) / (nΣx² - (Σx)²)
#b = (Σy - bΣx) / n
#
#where n is the number of data points (TimePeriod) and Σ is the summation operator.
# The LinearReg function returns b+m*(TimePeriod-1), i.e. the y of the current bar.
def linear_reg(a,window):
res = np.full_like(a,np.nan)
Y = np.squeeze(rolling_window(a,(window,a.shape[1])))
X = np.tile(np.linspace(1,window,window)[:,np.newaxis],(Y.shape[0],1,a.shape[1]))
XY = np.multiply(X,Y)
s_XY = np.sum(XY,axis=1)
s_Y = np.sum(Y,axis=1)
s_X = np.sum(X,axis=1)
s_X2 = np.sum(X**2,axis=1)
m = (window*(s_XY)-(s_X*s_Y))/(window*s_X2-(s_X)**2)
b = (s_Y-m*s_X)/window
projected = m*(window+1)+b
res[window-1:,:]=projected
return res
#Forecast of bth bar after window
def linear_reg_forecast(a,window,bar):
res = np.full_like(a,np.nan)
Y = np.squeeze(rolling_window(a,(window,a.shape[1])))
X = np.tile(np.linspace(1,window,window)[:,np.newaxis],(Y.shape[0],1,a.shape[1]))
XY = np.multiply(X,Y)
s_XY = np.sum(XY,axis=1)
s_Y = np.sum(Y,axis=1)
s_X = np.sum(X,axis=1)
s_X2 = np.sum(X**2,axis=1)
m = (window*(s_XY)-(s_X*s_Y))/(window*s_X2-(s_X)**2)
b = (s_Y-m*s_X)/window
projected = m*(window+bar)+b
res[window-1:,:]=projected
return res
def linear_reg_angle(a,window):
res = np.full_like(a,np.nan)
Y = np.squeeze(rolling_window(a,(window,a.shape[1])))
X = np.tile(np.linspace(1,window,window)[:,np.newaxis],(Y.shape[0],1,a.shape[1]))
XY = np.multiply(X,Y)
s_XY = np.sum(XY,axis=1)
s_Y = np.sum(Y,axis=1)
s_X = np.sum(X,axis=1)
s_X2 = np.sum(X**2,axis=1)
m = (window*(s_XY)-(s_X*s_Y))/(window*s_X2-(s_X)**2)
# b = (s_Y-m*s_X)/window
# projected = m*(window+1)+b
res[window-1:,:]=atan(m)
return res
def linear_reg_slope(a,window):
res = np.full_like(a,np.nan)
Y = np.squeeze(rolling_window(a,(window,a.shape[1])))
X = np.tile(np.linspace(1,window,window)[:,np.newaxis],(Y.shape[0],1,a.shape[1]))
XY = np.multiply(X,Y)
s_XY = np.sum(XY,axis=1)
s_Y = | np.sum(Y,axis=1) | numpy.sum |
import numpy as np
from numpy.linalg import eig, norm, pinv
import pinocchio
from crocoddyl import (ActionModelNumDiff, ActuationModelFreeFloating, CallbackDDPLogger, ContactModel3D,
ContactModel6D, ContactModelMultiple, CostModelControl, CostModelForce,
CostModelForceLinearCone, CostModelFrameTranslation, CostModelState, CostModelSum,
DifferentialActionModelFloatingInContact, DifferentialActionModelNumDiff,
IntegratedActionModelEuler, ShootingProblem, SolverDDP, SolverKKT, StatePinocchio, a2m, absmax,
loadTalosArm, m2a)
from crocoddyl.utils import EPS
from pinocchio.utils import rand, zero
from testutils import NUMDIFF_MODIFIER, assertNumDiff, df_dq, df_dx
pinocchio.switchToNumpyMatrix()
# Loading Talos arm with FF TODO use a bided or quadruped
# -----------------------------------------------------------------------------
robot = loadTalosArm(freeFloating=True)
robot.model.armature[6:] = 1.
qmin = robot.model.lowerPositionLimit
qmin[:7] = -1
robot.model.lowerPositionLimit = qmin
qmax = robot.model.upperPositionLimit
qmax[:7] = 1
robot.model.upperPositionLimit = qmax
rmodel = robot.model
rdata = rmodel.createData()
np.set_printoptions(linewidth=400, suppress=True)
contactModel = ContactModel6D(rmodel,
rmodel.getFrameId('gripper_left_fingertip_2_link'),
ref=pinocchio.SE3.Random(),
gains=[4., 4.])
contactData = contactModel.createData(rdata)
q = pinocchio.randomConfiguration(rmodel)
v = rand(rmodel.nv)
x = m2a(np.concatenate([q, v]))
u = m2a(rand(rmodel.nv - 6))
pinocchio.forwardKinematics(rmodel, rdata, q, v, zero(rmodel.nv))
pinocchio.computeJointJacobians(rmodel, rdata)
pinocchio.updateFramePlacements(rmodel, rdata)
pinocchio.computeForwardKinematicsDerivatives(rmodel, rdata, q, v, zero(rmodel.nv))
contactModel.calc(contactData, x)
contactModel.calcDiff(contactData, x)
rdata2 = rmodel.createData()
pinocchio.computeAllTerms(rmodel, rdata2, q, v)
pinocchio.updateFramePlacements(rmodel, rdata2)
contactData2 = contactModel.createData(rdata2)
contactModel.calc(contactData2, x)
assert (norm(contactData.a0 - contactData2.a0) < 1e-9)
assert (norm(contactData.J - contactData2.J) < 1e-9)
def returna_at0(q, v):
x = np.vstack([q, v]).flat
pinocchio.computeAllTerms(rmodel, rdata2, q, v)
pinocchio.updateFramePlacements(rmodel, rdata2)
contactModel.calc(contactData2, x)
return a2m(contactData2.a0) # .copy()
Aq_numdiff = df_dq(rmodel, lambda _q: returna_at0(_q, v), q)
Av_numdiff = df_dx(lambda _v: returna_at0(q, _v), v)
assertNumDiff(contactData.Aq, Aq_numdiff,
NUMDIFF_MODIFIER * np.sqrt(2 * EPS)) # threshold was 1e-4, is now 2.11e-4 (see assertNumDiff.__doc__)
assertNumDiff(contactData.Av, Av_numdiff,
NUMDIFF_MODIFIER * np.sqrt(2 * EPS)) # threshold was 1e-4, is now 2.11e-4 (see assertNumDiff.__doc__)
eps = 1e-8
Aq_numdiff = df_dq(rmodel, lambda _q: returna_at0(_q, v), q, h=eps)
Av_numdiff = df_dx(lambda _v: returna_at0(q, _v), v, h=eps)
assert (np.isclose(contactData.Aq, Aq_numdiff, atol=np.sqrt(eps)).all())
assert (np.isclose(contactData.Av, Av_numdiff, atol=np.sqrt(eps)).all())
contactModel = ContactModel3D(rmodel,
rmodel.getFrameId('gripper_left_fingertip_2_link'),
ref=np.random.rand(3),
gains=[4., 4.])
contactData = contactModel.createData(rdata)
q = pinocchio.randomConfiguration(rmodel)
v = rand(rmodel.nv)
x = m2a(np.concatenate([q, v]))
u = m2a(rand(rmodel.nv - 6))
pinocchio.forwardKinematics(rmodel, rdata, q, v, zero(rmodel.nv))
pinocchio.computeJointJacobians(rmodel, rdata)
pinocchio.updateFramePlacements(rmodel, rdata)
pinocchio.computeForwardKinematicsDerivatives(rmodel, rdata, q, v, zero(rmodel.nv))
contactModel.calc(contactData, x)
contactModel.calcDiff(contactData, x)
rdata2 = rmodel.createData()
pinocchio.computeAllTerms(rmodel, rdata2, q, v)
pinocchio.updateFramePlacements(rmodel, rdata2)
contactData2 = contactModel.createData(rdata2)
contactModel.calc(contactData2, x)
assert (norm(contactData.a0 - contactData2.a0) < 1e-9)
assert (norm(contactData.J - contactData2.J) < 1e-9)
def returna0(q, v):
x = np.vstack([q, v]).flat
pinocchio.computeAllTerms(rmodel, rdata2, q, v)
pinocchio.updateFramePlacements(rmodel, rdata2)
contactModel.calc(contactData2, x)
return a2m(contactData2.a0) # .copy()
Aq_numdiff = df_dq(rmodel, lambda _q: returna0(_q, v), q)
Av_numdiff = df_dx(lambda _v: returna0(q, _v), v)
assertNumDiff(contactData.Aq, Aq_numdiff,
NUMDIFF_MODIFIER * np.sqrt(2 * EPS)) # threshold was 1e-4, is now 2.11e-4 (see assertNumDiff.__doc__)
assertNumDiff(contactData.Av, Av_numdiff,
NUMDIFF_MODIFIER * np.sqrt(2 * EPS)) # threshold was 1e-4, is now 2.11e-4 (see assertNumDiff.__doc__)
Aq_numdiff = df_dq(rmodel, lambda _q: returna0(_q, v), q, h=eps)
Av_numdiff = df_dx(lambda _v: returna0(q, _v), v, h=eps)
assert (np.isclose(contactData.Aq, Aq_numdiff, atol=np.sqrt(eps)).all())
assert (np.isclose(contactData.Av, Av_numdiff, atol=np.sqrt(eps)).all())
q = pinocchio.randomConfiguration(rmodel)
v = rand(rmodel.nv) * 2 - 1
pinocchio.computeJointJacobians(rmodel, rdata, q)
J6 = pinocchio.getJointJacobian(rmodel, rdata, rmodel.joints[-1].id, pinocchio.ReferenceFrame.LOCAL).copy()
J = J6[:3, :]
v -= pinv(J) * J * v
x = np.concatenate([m2a(q), m2a(v)])
u = np.random.rand(rmodel.nv - 6) * 2 - 1
actModel = ActuationModelFreeFloating(rmodel)
contactModel3 = ContactModel3D(rmodel,
rmodel.getFrameId('gripper_left_fingertip_2_link'),
ref= | np.random.rand(3) | numpy.random.rand |
import numpy as np
from active_tester.query_strategy.base import BaseQueryStrategy
from active_tester.query_strategy.random import Random
from active_tester.label_estimation.methods import oracle_one_label, oracle_multiple_labels
from active_tester.util import estimate_expectation, estimate_expectation_fixed, draw_samples
import unittest
from sklearn.metrics import accuracy_score
def compute_uncertainty_distribution(p_classifier, y_noisy, num_classes, unlabeled):
label_probs = np.zeros((len(y_noisy), num_classes))
for i in range(len(y_noisy)):
label_probs[i, y_noisy[i]] = 1.0
measure = np.sum(np.abs(label_probs[unlabeled, :] - p_classifier[unlabeled, :]), axis=1)
measure = measure / np.sum(measure)
return measure
class MCM(BaseQueryStrategy):
def __init__(self, estimation_method, X=None, y_noisy=None, p_classifier=None, option='smoothed'):
"""
Choose items related to the difference between the classifier predictions
and the current ground truth estimates
:param estimation_method: pass None when using the naive estimator
:param X: matrix of features
:param y_noisy: noisy labels
:param p_classifier: classifier predicted probabilities
:param option: Can be greedy, sample, or otherwise defaults to smoothed. Greedy items with the largest
probability. Sample chooses according to the distribution defined by the entropy of the classifier
predicted probabilities. Smoothed combines the above distribution with a uniform distribution.
"""
super().__init__(X, y_noisy, p_classifier)
self.X = X
if X is not None:
sizes = []
for i in range(1, np.ndim(self.X)):
sizes.append( | np.size(self.X, axis=i) | numpy.size |
# Dual annealing unit tests implementation.
# Copyright (c) 2018 <NAME> <<EMAIL>>,
# <NAME> <<EMAIL>>
# Author: <NAME>, PMP S.A.
"""
Unit tests for the dual annealing global optimizer
"""
from scipy.optimize import dual_annealing
from scipy.optimize._dual_annealing import VisitingDistribution
from scipy.optimize._dual_annealing import ObjectiveFunWrapper
from scipy.optimize._dual_annealing import EnergyState
from scipy.optimize._dual_annealing import LocalSearchWrapper
from scipy.optimize import rosen, rosen_der
import numpy as np
from numpy.testing import (assert_equal, TestCase, assert_allclose,
assert_array_less)
from pytest import raises as assert_raises
from scipy._lib._util import check_random_state
class TestDualAnnealing(TestCase):
def setUp(self):
# A function that returns always infinity for initialization tests
self.weirdfunc = lambda x: np.inf
# 2-D bounds for testing function
self.ld_bounds = [(-5.12, 5.12)] * 2
# 4-D bounds for testing function
self.hd_bounds = self.ld_bounds * 4
# Number of values to be generated for testing visit function
self.nbtestvalues = 5000
self.high_temperature = 5230
self.low_temperature = 0.1
self.qv = 2.62
self.seed = 1234
self.rs = check_random_state(self.seed)
self.nb_fun_call = 0
self.ngev = 0
def tearDown(self):
pass
def callback(self, x, f, context):
# For testing callback mechanism. Should stop for e <= 1 as
# the callback function returns True
if f <= 1.0:
return True
def func(self, x, args=()):
# Using Rastrigin function for performing tests
if args:
shift = args
else:
shift = 0
y = np.sum((x - shift) ** 2 - 10 * np.cos(2 * np.pi * (
x - shift))) + 10 * np.size(x) + shift
self.nb_fun_call += 1
return y
def rosen_der_wrapper(self, x, args=()):
self.ngev += 1
return rosen_der(x, *args)
def test_visiting_stepping(self):
lu = list(zip(*self.ld_bounds))
lower = np.array(lu[0])
upper = np.array(lu[1])
dim = lower.size
vd = VisitingDistribution(lower, upper, self.qv, self.rs)
values = np.zeros(dim)
x_step_low = vd.visiting(values, 0, self.high_temperature)
# Make sure that only the first component is changed
assert_equal(np.not_equal(x_step_low, 0), True)
values = np.zeros(dim)
x_step_high = vd.visiting(values, dim, self.high_temperature)
# Make sure that component other than at dim has changed
assert_equal(np.not_equal(x_step_high[0], 0), True)
def test_visiting_dist_high_temperature(self):
lu = list(zip(*self.ld_bounds))
lower = np.array(lu[0])
upper = np.array(lu[1])
vd = VisitingDistribution(lower, upper, self.qv, self.rs)
# values = np.zeros(self.nbtestvalues)
# for i in np.arange(self.nbtestvalues):
# values[i] = vd.visit_fn(self.high_temperature)
values = vd.visit_fn(self.high_temperature, self.nbtestvalues)
# Visiting distribution is a distorted version of Cauchy-Lorentz
# distribution, and as no 1st and higher moments (no mean defined,
# no variance defined).
# Check that big tails values are generated
assert_array_less(np.min(values), 1e-10)
assert_array_less(1e+10, np.max(values))
def test_reset(self):
owf = ObjectiveFunWrapper(self.weirdfunc)
lu = list(zip(*self.ld_bounds))
lower = | np.array(lu[0]) | numpy.array |
import argparse
from pathlib import Path
import numpy as np
import tensorflow as tf
import gym
from tqdm import tqdm
import matplotlib
matplotlib.use('agg')
from matplotlib import pyplot as plt
from imgcat import imgcat
import rospy
from openai_ros.task_envs.turtlebot2 import turtlebot2_maze
# Import my own libraries
import os, sys
sys.path.append(os.path.dirname(os.path.abspath(__file__))+'/learner/baselines/')
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' # Only show ERROR log
from tf_commons.ops import *
class PPO2Agent(object):
def __init__(self, env, env_type, path, stochastic=False, gpu=True):
from baselines.common.policies import build_policy
from baselines.ppo2.model import Model
self.graph = tf.Graph()
if gpu:
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
else:
config = tf.ConfigProto(device_count = {'GPU': 0})
self.sess = tf.Session(graph=self.graph,config=config)
with self.graph.as_default():
with self.sess.as_default():
ob_space = env.observation_space
ac_space = env.action_space
if env_type == 'atari':
policy = build_policy(env,'cnn')
elif env_type == 'mujoco':
policy = build_policy(env,'mlp')
elif env_type == 'gazebo':
policy = build_policy(env, 'mlp')
else:
assert False,' not supported env_type'
make_model = lambda : Model(policy=policy, ob_space=ob_space, ac_space=ac_space, nbatch_act=1, nbatch_train=1,
nsteps=1, ent_coef=0., vf_coef=0.,
max_grad_norm=0.)
self.model = make_model()
self.model_path = path
self.model.load(path)
if env_type == 'mujoco':
with open(path+'.env_stat.pkl', 'rb') as f :
import pickle
s = pickle.load(f)
self.ob_rms = s['ob_rms']
self.ret_rms = s['ret_rms']
self.clipob = 10.
self.epsilon = 1e-8
elif env_type == 'gazebo':
with open(path + '.env_stat.pkl', 'rb') as f:
import pickle
s = pickle.load(f)
self.ob_rms = s['ob_rms']
self.ret_rms = s['ret_rms']
self.clipob = 10.
self.epsilon = 1e-8
else:
self.ob_rms = None
self.stochastic = stochastic
def act(self, obs, reward, done):
if self.ob_rms:
obs = np.clip((obs - self.ob_rms.mean) / np.sqrt(self.ob_rms.var + self.epsilon), -self.clipob, self.clipob)
with self.graph.as_default():
with self.sess.as_default():
if self.stochastic:
a,v,state,neglogp = self.model.step(obs)
else:
a = self.model.act_model.act(obs)
return a
class RandomAgent(object):
"""The world's simplest agent!"""
def __init__(self, action_space):
self.action_space = action_space
self.model_path = 'random_agent'
def act(self, observation, reward, done):
return self.action_space.sample()[None]
class Model(object):
def __init__(self,include_action,ob_dim,ac_dim,batch_size=64,num_layers=2,embedding_dims=256,steps=None):
self.include_action = include_action
in_dims = ob_dim+ac_dim if include_action else ob_dim
self.inp = tf.placeholder(tf.float32,[None,in_dims])
self.x = tf.placeholder(tf.float32,[None,in_dims]) #[B*steps,in_dim]
self.y = tf.placeholder(tf.float32,[None,in_dims])
self.x_split = tf.placeholder(tf.int32,[batch_size]) # B-lengthed vector indicating the size of each steps
self.y_split = tf.placeholder(tf.int32,[batch_size]) # B-lengthed vector indicating the size of each steps
self.l = tf.placeholder(tf.int32,[batch_size]) # [0 when x is better 1 when y is better]
self.l2_reg = tf.placeholder(tf.float32,[]) # [0 when x is better 1 when y is better]
with tf.variable_scope('weights') as param_scope:
self.fcs = []
last_dims = in_dims
for l in range(num_layers):
self.fcs.append(Linear('fc%d'%(l+1),last_dims,embedding_dims)) #(l+1) is gross, but for backward compatibility
last_dims = embedding_dims
self.fcs.append(Linear('fc%d'%(num_layers+1),last_dims,1))
self.param_scope = param_scope
# build graph
def _reward(x):
for fc in self.fcs[:-1]:
x = tf.nn.relu(fc(x))
r = tf.squeeze(self.fcs[-1](x),axis=1)
return x, r
self.fv, self.r = _reward(self.inp)
_, rs_xs = _reward(self.x)
self.v_x = tf.stack([tf.reduce_sum(rs_x) for rs_x in tf.split(rs_xs,self.x_split,axis=0)],axis=0)
_, rs_ys = _reward(self.y)
self.v_y = tf.stack([tf.reduce_sum(rs_y) for rs_y in tf.split(rs_ys,self.y_split,axis=0)],axis=0)
logits = tf.stack([self.v_x,self.v_y],axis=1) #[None,2]
loss = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=logits,labels=self.l)
self.loss = tf.reduce_mean(loss,axis=0)
weight_decay = 0.
for fc in self.fcs:
weight_decay += tf.reduce_sum(fc.w**2)
self.l2_loss = self.l2_reg * weight_decay
pred = tf.cast(tf.greater(self.v_y,self.v_x),tf.int32)
self.acc = tf.reduce_mean(tf.cast(tf.equal(pred,self.l),tf.float32))
self.optim = tf.train.AdamOptimizer(1e-4)
self.update_op = self.optim.minimize(self.loss+self.l2_loss,var_list=self.parameters(train=True))
self.saver = tf.train.Saver(var_list=self.parameters(train=False),max_to_keep=0)
def parameters(self,train=False):
if train:
return tf.trainable_variables(self.param_scope.name)
else:
return tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES,self.param_scope.name)
def train(self,D,batch_size=64,iter=10000,l2_reg=0.01,noise_level=0.1,debug=False):
"""
Training will be early-terminate when validation accuracy becomes large enough..?
args:
D: list of triplets (\sigma^1,\sigma^2,\mu)
while
sigma^{1,2}: shape of [steps,in_dims]
mu : 0 or 1
"""
sess = tf.get_default_session()
idxes = np.random.permutation(len(D))
train_idxes = idxes[:int(len(D)*0.8)]
valid_idxes = idxes[int(len(D)*0.8):]
def _batch(idx_list,add_noise):
batch = []
if len(idx_list) > batch_size:
idxes = np.random.choice(idx_list,batch_size,replace=False)
else:
idxes = idx_list
for i in idxes:
batch.append(D[i])
b_x,b_y,b_l = zip(*batch)
x_split = np.array([len(x) for x in b_x])
y_split = np.array([len(y) for y in b_y])
b_x,b_y,b_l = np.concatenate(b_x,axis=0),np.concatenate(b_y,axis=0),np.array(b_l)
if add_noise:
b_l = (b_l + np.random.binomial(1,noise_level,batch_size)) % 2 #Flip it with probability 0.1
return b_x,b_y,x_split,y_split,b_l
for it in tqdm(range(iter),dynamic_ncols=True):
b_x,b_y,x_split,y_split,b_l = _batch(train_idxes,add_noise=True)
loss,l2_loss,acc,_ = sess.run([self.loss,self.l2_loss,self.acc,self.update_op],feed_dict={
self.x:b_x,
self.y:b_y,
self.x_split:x_split,
self.y_split:y_split,
self.l:b_l,
self.l2_reg:l2_reg,
})
if debug:
if it % 100 == 0 or it < 10:
b_x,b_y,x_split,y_split,b_l = _batch(valid_idxes,add_noise=False)
valid_acc = sess.run(self.acc,feed_dict={
self.x:b_x,
self.y:b_y,
self.x_split:x_split,
self.y_split:y_split,
self.l:b_l
})
tqdm.write(('loss: %f (l2_loss: %f), acc: %f, valid_acc: %f'%(loss,l2_loss,acc,valid_acc)))
#if valid_acc >= 0.95:
# print('loss: %f (l2_loss: %f), acc: %f, valid_acc: %f'%(loss,l2_loss,acc,valid_acc))
# print('early termination@%08d'%it)
# break
def train_with_dataset(self,dataset,batch_size,include_action=False,iter=10000,l2_reg=0.01,debug=False):
sess = tf.get_default_session()
for it in tqdm(range(iter),dynamic_ncols=True):
b_x,b_y,x_split,y_split,b_l = dataset.batch(batch_size=batch_size,include_action=include_action)
loss,l2_loss,acc,_ = sess.run([self.loss,self.l2_loss,self.acc,self.update_op],feed_dict={
self.x:b_x,
self.y:b_y,
self.x_split:x_split,
self.y_split:y_split,
self.l:b_l,
self.l2_reg:l2_reg,
})
if debug:
if it % 100 == 0 or it < 10:
tqdm.write(('loss: %f (l2_loss: %f), acc: %f'%(loss,l2_loss,acc)))
def eval(self,D,batch_size=64):
sess = tf.get_default_session()
b_x,b_y,b_l = zip(*D)
b_x,b_y,b_l = np.array(b_x),np.array(b_y),np.array(b_l)
b_r_x, b_acc = [], 0.
for i in range(0,len(b_x),batch_size):
sum_r_x, acc = sess.run([self.sum_r_x,self.acc],feed_dict={
self.x:b_x[i:i+batch_size],
self.y:b_y[i:i+batch_size],
self.l:b_l[i:i+batch_size]
})
b_r_x.append(sum_r_x)
b_acc += len(sum_r_x)*acc
return np.concatenate(b_r_x,axis=0), b_acc/len(b_x)
def get_reward(self,obs,acs,batch_size=1024):
sess = tf.get_default_session()
if self.include_action:
inp = np.concatenate((obs,acs),axis=1)
else:
inp = obs
b_r = []
for i in range(0,len(obs),batch_size):
r = sess.run(self.r,feed_dict={
self.inp:inp[i:i+batch_size]
})
b_r.append(r)
return np.concatenate(b_r,axis=0)
class GTDataset(object):
def __init__(self,env):
self.env = env
self.unwrapped = env
while hasattr(self.unwrapped,'env'):
self.unwrapped = self.unwrapped.env
def gen_traj(self,agent,min_length):
max_x_pos = -99999
obs, actions, rewards = [self.env.reset()], [], []
while True:
action = agent.act(obs[-1], None, None)
ob, reward, done, _ = self.env.step(action)
if self.unwrapped.sim.data.qpos[0] > max_x_pos:
max_x_pos = self.unwrapped.sim.data.qpos[0]
obs.append(ob)
actions.append(action)
rewards.append(reward)
if done:
if len(obs) < min_length:
obs.pop()
obs.append(self.env.reset())
else:
obs.pop()
break
return (np.stack(obs,axis=0), np.concatenate(actions,axis=0), np.array(rewards)), max_x_pos
def prebuilt(self,agents,min_length):
assert len(agents)>0, 'no agent given'
trajs = []
for agent in tqdm(agents):
traj, max_x_pos = self.gen_traj(agent,min_length)
trajs.append(traj)
tqdm.write('model: %s avg reward: %f max_x_pos: %f'%(agent.model_path,np.sum(traj[2]),max_x_pos))
obs,actions,rewards = zip(*trajs)
self.trajs = (np.concatenate(obs,axis=0),np.concatenate(actions,axis=0),np.concatenate(rewards,axis=0))
print(self.trajs[0].shape,self.trajs[1].shape,self.trajs[2].shape)
def sample(self,num_samples,steps=40,include_action=False):
obs, actions, rewards = self.trajs
D = []
for _ in range(num_samples):
x_ptr = np.random.randint(len(obs)-steps)
y_ptr = np.random.randint(len(obs)-steps)
if include_action:
D.append((np.concatenate((obs[x_ptr:x_ptr+steps],actions[x_ptr:x_ptr+steps]),axis=1),
np.concatenate((obs[y_ptr:y_ptr+steps],actions[y_ptr:y_ptr+steps]),axis=1),
0 if np.sum(rewards[x_ptr:x_ptr+steps]) > np.sum(rewards[y_ptr:y_ptr+steps]) else 1)
)
else:
D.append((obs[x_ptr:x_ptr+steps],
obs[y_ptr:y_ptr+steps],
0 if np.sum(rewards[x_ptr:x_ptr+steps]) > np.sum(rewards[y_ptr:y_ptr+steps]) else 1)
)
return D
class GTTrajLevelDataset(GTDataset):
def __init__(self,env):
super().__init__(env)
def prebuilt(self,agents,min_length):
assert len(agents)>0, 'no agent is given'
trajs = []
for agent_idx,agent in enumerate(tqdm(agents)):
(obs,actions,rewards),_ = self.gen_traj(agent,min_length)
trajs.append((agent_idx,obs,actions,rewards))
self.trajs = trajs
_idxes = np.argsort([np.sum(rewards) for _,_,_,rewards in self.trajs]) # rank 0 is the most bad demo.
self.trajs_rank = np.empty_like(_idxes)
self.trajs_rank[_idxes] = np.arange(len(_idxes))
def sample(self,num_samples,steps=40,include_action=False):
D = []
GT_preference = []
for _ in tqdm(range(num_samples)):
x_idx,y_idx = np.random.choice(len(self.trajs),2,replace=False)
x_traj = self.trajs[x_idx]
y_traj = self.trajs[y_idx]
x_ptr = np.random.randint(len(x_traj[1])-steps)
y_ptr = np.random.randint(len(y_traj[1])-steps)
if include_action:
D.append((np.concatenate((x_traj[1][x_ptr:x_ptr+steps],x_traj[2][x_ptr:x_ptr+steps]),axis=1),
np.concatenate((y_traj[1][y_ptr:y_ptr+steps],y_traj[2][y_ptr:y_ptr+steps]),axis=1),
0 if self.trajs_rank[x_idx] > self.trajs_rank[y_idx] else 1)
)
else:
D.append((x_traj[1][x_ptr:x_ptr+steps],
y_traj[1][y_ptr:y_ptr+steps],
0 if self.trajs_rank[x_idx] > self.trajs_rank[y_idx] else 1)
)
GT_preference.append(0 if np.sum(x_traj[3][x_ptr:x_ptr+steps]) > np.sum(y_traj[3][y_ptr:y_ptr+steps]) else 1)
print('------------------')
_,_,preference = zip(*D)
preference = np.array(preference).astype(np.bool)
GT_preference = np.array(GT_preference).astype(np.bool)
print('Quality of time-indexed preference (0-1):', np.count_nonzero(preference == GT_preference) / len(preference))
print('------------------')
return D
class GTTrajLevelNoStepsDataset(GTTrajLevelDataset):
def __init__(self,env,max_steps):
super().__init__(env)
self.max_steps = max_steps
def prebuilt(self,agents,min_length):
assert len(agents)>0, 'no agent is given'
trajs = []
for agent_idx,agent in enumerate(tqdm(agents)):
agent_trajs = []
while np.sum([len(obs) for obs,_,_ in agent_trajs]) < min_length:
(obs,actions,rewards),_ = self.gen_traj(agent,-1)
agent_trajs.append((obs,actions,rewards))
trajs.append(agent_trajs)
agent_rewards = [np.mean([np.sum(rewards) for _,_,rewards in agent_trajs]) for agent_trajs in trajs]
self.trajs = trajs
_idxes = np.argsort(agent_rewards) # rank 0 is the most bad demo.
self.trajs_rank = np.empty_like(_idxes)
self.trajs_rank[_idxes] = np.arange(len(_idxes))
def sample(self,num_samples,steps=None,include_action=False):
assert steps == None
D = []
GT_preference = []
for _ in tqdm(range(num_samples)):
x_idx,y_idx = np.random.choice(len(self.trajs),2,replace=False)
x_traj = self.trajs[x_idx][np.random.choice(len(self.trajs[x_idx]))]
y_traj = self.trajs[y_idx][np.random.choice(len(self.trajs[y_idx]))]
if len(x_traj[0]) > self.max_steps:
ptr = np.random.randint(len(x_traj[0])-self.max_steps)
x_slice = slice(ptr,ptr+self.max_steps)
else:
x_slice = slice(len(x_traj[1]))
if len(y_traj[0]) > self.max_steps:
ptr = np.random.randint(len(y_traj[0])-self.max_steps)
y_slice = slice(ptr,ptr+self.max_steps)
else:
y_slice = slice(len(y_traj[0]))
if include_action:
D.append((np.concatenate((x_traj[0][x_slice],x_traj[1][x_slice]),axis=1),
np.concatenate((y_traj[0][y_slice],y_traj[1][y_slice]),axis=1),
0 if self.trajs_rank[x_idx] > self.trajs_rank[y_idx] else 1)
)
else:
D.append((x_traj[0][x_slice],
y_traj[0][y_slice],
0 if self.trajs_rank[x_idx] > self.trajs_rank[y_idx] else 1)
)
GT_preference.append(0 if np.sum(x_traj[2][x_slice]) > np.sum(y_traj[2][y_slice]) else 1)
print('------------------')
_,_,preference = zip(*D)
preference = np.array(preference).astype(np.bool)
GT_preference = np.array(GT_preference).astype(np.bool)
print('Quality of time-indexed preference (0-1):', np.count_nonzero(preference == GT_preference) / len(preference))
print('------------------')
return D
class GTTrajLevelNoSteps_Noise_Dataset(GTTrajLevelNoStepsDataset):
def __init__(self,env,max_steps,ranking_noise=0):
super().__init__(env,max_steps)
self.ranking_noise = ranking_noise
def prebuilt(self,agents,min_length):
super().prebuilt(agents,min_length)
original_trajs_rank = self.trajs_rank.copy()
for _ in range(self.ranking_noise):
x = np.random.randint(len(self.trajs)-1)
x_ptr = np.where(self.trajs_rank==x)
y_ptr = np.where(self.trajs_rank==x+1)
self.trajs_rank[x_ptr], self.trajs_rank[y_ptr] = x+1, x
from itertools import combinations
order_correctness = [
(self.trajs_rank[x] < self.trajs_rank[y]) == (original_trajs_rank[x] < original_trajs_rank[y])
for x,y in combinations(range(len(self.trajs)),2)]
print('Total Order Correctness: %f'%(np.count_nonzero(order_correctness)/len(order_correctness)))
class GTTrajLevelNoSteps_N_Mix_Dataset(GTTrajLevelNoStepsDataset):
def __init__(self,env,N,max_steps):
super().__init__(env,max_steps)
self.N = N
self.max_steps = max_steps
def sample(self,*kargs,**kwargs):
return None
def batch(self,batch_size,include_action):
#self.trajs = trajs
#self.trajs_rank = np.argsort([np.sum(rewards) for _,_,_,rewards in self.trajs]) # rank 0 is the most bad demo.
xs = []
ys = []
for _ in range(batch_size):
idxes = np.random.choice(len(self.trajs),2*self.N)
ranks = self.trajs_rank[idxes]
bad_idxes = [idxes[i] for i in np.argsort(ranks)[:self.N]]
good_idxes = [idxes[i] for i in np.argsort(ranks)[self.N:]]
def _pick_and_merge(idxes):
inp = []
for idx in idxes:
obs, acs, rewards = self.trajs[idx][np.random.choice(len(self.trajs[idx]))]
if len(obs) > self.max_steps:
ptr = np.random.randint(len(obs)-self.max_steps)
slc = slice(ptr,ptr+self.max_steps)
else:
slc = slice(len(obs))
if include_action:
inp.append(np.concatenate([obs[slc],acs[slc]],axis=1))
else:
inp.append(obs[slc])
return np.concatenate(inp,axis=0)
x = _pick_and_merge(bad_idxes)
y = _pick_and_merge(good_idxes)
xs.append(x)
ys.append(y)
x_split = np.array([len(x) for x in xs])
y_split = np.array([len(y) for y in ys])
xs = np.concatenate(xs,axis=0)
ys = np.concatenate(ys,axis=0)
return xs, ys, x_split, y_split, np.ones((batch_size,)).astype(np.int32)
class LearnerDataset(GTTrajLevelDataset):
def __init__(self,env,min_margin):
super().__init__(env)
self.min_margin = min_margin
def sample(self,num_samples,steps=40,include_action=False):
D = []
GT_preference = []
for _ in tqdm(range(num_samples)):
x_idx,y_idx = np.random.choice(len(self.trajs),2,replace=False)
while abs(self.trajs[x_idx][0] - self.trajs[y_idx][0]) < self.min_margin:
x_idx,y_idx = np.random.choice(len(self.trajs),2,replace=False)
x_traj = self.trajs[x_idx]
y_traj = self.trajs[y_idx]
x_ptr = np.random.randint(len(x_traj[1])-steps)
y_ptr = np.random.randint(len(y_traj[1])-steps)
if include_action:
D.append((np.concatenate((x_traj[1][x_ptr:x_ptr+steps],x_traj[2][x_ptr:x_ptr+steps]),axis=1),
np.concatenate((y_traj[1][y_ptr:y_ptr+steps],y_traj[2][y_ptr:y_ptr+steps]),axis=1),
0 if x_traj[0] > y_traj[0] else 1)
)
else:
D.append((x_traj[1][x_ptr:x_ptr+steps],
y_traj[1][y_ptr:y_ptr+steps],
0 if x_traj[0] > y_traj[0] else 1)
)
GT_preference.append(0 if np.sum(x_traj[3][x_ptr:x_ptr+steps]) > np.sum(y_traj[3][y_ptr:y_ptr+steps]) else 1)
print('------------------')
_,_,preference = zip(*D)
preference = np.array(preference).astype(np.bool)
GT_preference = np.array(GT_preference).astype(np.bool)
print('Quality of time-indexed preference (0-1):', np.count_nonzero(preference == GT_preference) / len(preference))
print('------------------')
return D
def train(args):
logdir = Path(args.log_dir)
if logdir.exists() :
c = input('log dir is already exist. continue to train a preference model? [Y/etc]? ')
if c in ['YES','yes','Y']:
import shutil
shutil.rmtree(str(logdir))
else:
print('good bye')
return
logdir.mkdir(parents=True)
with open(str(logdir/'args.txt'),'w') as f:
f.write( str(args) )
logdir = str(logdir)
rospy.init_node('turtlebot2_maze',anonymous=True,log_level=rospy.FATAL)
env = gym.make(args.env_id)
train_agents = [RandomAgent(env.action_space)] if args.random_agent else []
models = sorted([p for p in Path(args.learners_path).glob('?????') if int(p.name) <= args.max_chkpt])
for path in models:
agent = PPO2Agent(env,args.env_type,str(path),stochastic=args.stochastic)
train_agents.append(agent)
if args.preference_type == 'gt':
dataset = GTDataset(env)
elif args.preference_type == 'gt_traj':
dataset = GTTrajLevelDataset(env)
elif args.preference_type == 'gt_traj_no_steps':
dataset = GTTrajLevelNoStepsDataset(env,args.max_steps)
elif args.preference_type == 'gt_traj_no_steps_noise':
dataset = GTTrajLevelNoSteps_Noise_Dataset(env,args.max_steps,args.traj_noise)
elif args.preference_type == 'gt_traj_no_steps_n_mix':
dataset = GTTrajLevelNoSteps_N_Mix_Dataset(env,args.N,args.max_steps)
elif args.preference_type == 'time':
dataset = LearnerDataset(env,args.min_margin)
else:
assert False, 'specify prefernce type'
dataset.prebuilt(train_agents,args.min_length)
models = []
for i in range(args.num_models):
with tf.variable_scope('model_%d'%i):
models.append(Model(args.include_action,env.observation_space.shape[0],env.action_space.shape[0],steps=args.steps,num_layers=args.num_layers,embedding_dims=args.embedding_dims))
### Initialize Parameters
init_op = tf.group(tf.global_variables_initializer(),
tf.local_variables_initializer())
# Training configuration
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
sess = tf.InteractiveSession()
sess.run(init_op)
for i,model in enumerate(models):
D = dataset.sample(args.D,args.steps,include_action=args.include_action)
if D is None:
model.train_with_dataset(dataset,64,include_action=args.include_action,debug=True)
else:
model.train(D,l2_reg=args.l2_reg,noise_level=args.noise,debug=True)
model.saver.save(sess,logdir+'/model_%d.ckpt'%(i),write_meta_graph=False)
def eval(args):
logdir = str(Path(args.logbase_path) / args.env_id)
env = gym.make(args.env_id)
valid_agents = []
models = sorted(Path(args.learners_path).glob('?????'))
for path in models:
if path.name > args.max_chkpt:
continue
agent = PPO2Agent(env,args.env_type,str(path),stochastic=args.stochastic)
valid_agents.append(agent)
test_agents = []
for i,path in enumerate(models):
if i % 10 == 0:
agent = PPO2Agent(env,args.env_type,str(path),stochastic=args.stochastic)
test_agents.append(agent)
gt_dataset= GTDataset(env)
gt_dataset.prebuilt(valid_agents,-1)
gt_dataset_test = GTDataset(env)
gt_dataset_test.prebuilt(test_agents,-1)
models = []
for i in range(args.num_models):
with tf.variable_scope('model_%d'%i):
models.append(Model(args.include_action,env.observation_space.shape[0],env.action_space.shape[0],steps=args.steps))
### Initialize Parameters
init_op = tf.group(tf.global_variables_initializer(),
tf.local_variables_initializer())
# Training configuration
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
sess = tf.InteractiveSession()
sess.run(init_op)
for i,model in enumerate(models):
model.saver.restore(sess,logdir+'/model_%d.ckpt'%(i))
print('model %d'%i)
obs, acs, r = gt_dataset.trajs
r_hat = model.get_reward(obs, acs)
obs, acs, r_test = gt_dataset_test.trajs
r_hat_test = model.get_reward(obs, acs)
fig,axes = plt.subplots(1,2)
axes[0].plot(r,r_hat,'o')
axes[1].plot(r_test,r_hat_test,'o')
fig.savefig('model_%d.png'%i)
imgcat(fig)
plt.close(fig)
np.savez('model_%d.npz'%i,r=r,r_hat=r_hat,r_test=r_test,r_hat_test=r_hat_test)
if __name__ == "__main__":
# Required Args (target envs & learners)
parser = argparse.ArgumentParser(description=None)
parser.add_argument('--env_id', default='', help='Select the environment to run')
parser.add_argument('--env_type', default='', help='gazebo')
parser.add_argument('--learners_path', default='', help='path of learning agents')
parser.add_argument('--max_chkpt', default=240, type=int, help='decide upto what learner stage you want to give')
parser.add_argument('--steps', default=None, type=int, help='length of snippets')
parser.add_argument('--max_steps', default=None, type=int, help='length of max snippets (gt_traj_no_steps only)')
parser.add_argument('--traj_noise', default=None, type=int, help='number of adjacent swaps (gt_traj_no_steps_noise only)')
parser.add_argument('--min_length', default=1000,type=int, help='minimum length of trajectory generated by each agent')
parser.add_argument('--num_layers', default=2, type=int, help='number layers of the reward network')
parser.add_argument('--embedding_dims', default=256, type=int, help='embedding dims')
parser.add_argument('--num_models', default=3, type=int, help='number of models to ensemble')
parser.add_argument('--l2_reg', default=0.01, type=float, help='l2 regularization size')
parser.add_argument('--noise', default=0.1, type=float, help='noise level to add on training label')
parser.add_argument('--D', default=1000, type=int, help='|D| in the preference paper')
parser.add_argument('--N', default=10, type=int, help='number of trajactory mix (gt_traj_no_steps_n_mix only)')
parser.add_argument('--log_dir', required=True)
parser.add_argument('--preference_type', help='gt or gt_traj or time or gt_traj_no_steps, gt_traj_no_steps_n_mix; if gt then preference will be given as a GT reward, otherwise, it is given as a time index')
parser.add_argument('--min_margin', default=1, type=int, help='when prefernce type is "time", the minimum margin that we can assure there exist a margin')
parser.add_argument('--include_action', action='store_true', help='whether to include action for the model or not')
parser.add_argument('--stochastic', action='store_true', help='whether want to use stochastic agent or not')
parser.add_argument('--random_agent', action='store_true', help='whether to use default random agent')
parser.add_argument('--eval', action='store_true', help='path to log base (env_id will be concatenated at the end)')
# Args for PPO
parser.add_argument('--rl_runs', default=1, type=int)
parser.add_argument('--ppo_log_path', default='ppo2')
parser.add_argument('--custom_reward', required=True, help='preference or preference_normalized')
parser.add_argument('--ctrl_coeff', default=0.0, type=float)
parser.add_argument('--alive_bonus', default=0.0, type=float)
parser.add_argument('--gamma', default=0.99, type=float)
args = parser.parse_args()
if not args.eval :
# Train a Preference Model
train(args)
# Train an agent
import os, subprocess
openai_logdir = Path(os.path.abspath(os.path.join(args.log_dir,args.ppo_log_path)))
if openai_logdir.exists():
print('openai_logdir is already exist.')
exit()
template = 'python -m baselines.run --alg=ppo2 --env={env} --num_timesteps=1e6 --save_interval=10 --custom_reward {custom_reward} --custom_reward_kwargs="{kwargs}" --gamma {gamma}'
kwargs = {
"num_models":args.num_models,
"include_action":args.include_action,
"model_dir":os.path.abspath(args.log_dir),
"num_layers":args.num_layers,
"embedding_dims":args.embedding_dims,
"ctrl_coeff":args.ctrl_coeff,
"alive_bonus":args.alive_bonus
}
# Write down some log
openai_logdir.mkdir(parents=True)
with open(str(openai_logdir/'args.txt'),'w') as f:
f.write( args.custom_reward + '/')
f.write( str(kwargs) )
cmd = template.format(
env=args.env_id,
custom_reward=args.custom_reward,
gamma=args.gamma,
kwargs=str(kwargs))
procs = []
for i in range(args.rl_runs):
env = os.environ.copy()
env["OPENAI_LOGDIR"] = str(openai_logdir/('run_%d'%i))
if i == 0:
env["OPENAI_LOG_FORMAT"] = 'stdout,log,csv,tensorboard'
p = subprocess.Popen(cmd, cwd='./learner/baselines', stdout=subprocess.PIPE, env=env, shell=True)
else:
env["OPENAI_LOG_FORMAT"] = 'log,csv,tensorboard'
p = subprocess.Popen(cmd, cwd='./learner/baselines', env=env, shell=True)
procs.append(p)
for line in procs[0].stdout:
print(line.decode(),end='')
for p in procs[1:]:
p.wait()
else:
# eval(args)
import os
from performance_checker import gen_traj_dist as get_perf
#from performance_checker import gen_traj_return as get_perf
env = gym.make(args.env_id)
agents_dir = Path(os.path.abspath(os.path.join(args.log_dir,args.ppo_log_path)))
trained_steps = sorted(list(set([path.name for path in agents_dir.glob('run_*/checkpoints/?????')])))
print(trained_steps)
print(str(agents_dir))
for step in trained_steps[::-1]:
perfs = []
for i in range(args.rl_runs):
path = agents_dir/('run_%d'%i)/'checkpoints'/step
if path.exists() == False:
continue
agent = PPO2Agent(env,args.env_type,str(path),stochastic=args.stochastic)
perfs += [
get_perf(env,agent) for _ in range(5)
]
print('[%s-%d] %f %f'%(step,i,np.mean(perfs[-5:]),np.std(perfs[-5:])))
print('[%s] %f %f %f %f'%(step,np.mean(perfs),np.std(perfs),np.max(perfs), | np.min(perfs) | numpy.min |
import math
import numpy as np
import pybullet as p
from gym_pybullet_drones.control.BaseControl import BaseControl
from gym_pybullet_drones.envs.BaseAviary import DroneModel, BaseAviary
from gym_pybullet_drones.utils.utils import nnlsRPM
class SimplePIDControl(BaseControl):
"""Generic PID control class without yaw control.
Based on https://github.com/prfraanje/quadcopter_sim.
"""
################################################################################
def __init__(self,
drone_model: DroneModel,
g: float=9.8
):
"""Common control classes __init__ method.
Parameters
----------
drone_model : DroneModel
The type of drone to control (detailed in an .urdf file in folder `assets`).
g : float, optional
The gravitational acceleration in m/s^2.
"""
super().__init__(drone_model=drone_model, g=g)
if self.DRONE_MODEL not in [DroneModel.HB, DroneModel.ARDRONE2]:
print("[ERROR] in SimplePIDControl.__init__(), SimplePIDControl requires DroneModel.HB")
exit()
self.P_COEFF_FOR = np.array([1, 1, 2])
self.I_COEFF_FOR = np.array([.001, .001, .001])
self.D_COEFF_FOR = np.array([3, 3, 4])
self.P_COEFF_TOR = np.array([3, 3, .5])
self.I_COEFF_TOR = np.array([.001, .001, .001])
self.D_COEFF_TOR = np.array([3, 3, 5])
self.MAX_ROLL_PITCH = np.pi/6
self.L = self._getURDFParameter('arm')
self.THRUST2WEIGHT_RATIO = self._getURDFParameter('thrust2weight')
self.MAX_RPM = np.sqrt((self.THRUST2WEIGHT_RATIO*self.GRAVITY) / (4*self.KF))
self.MAX_THRUST = (4*self.KF*self.MAX_RPM**2)
self.MAX_XY_TORQUE = (self.L*self.KF*self.MAX_RPM**2)
self.MAX_Z_TORQUE = (2*self.KM*self.MAX_RPM**2)
self.A = np.array([ [1, 1, 1, 1], [0, 1, 0, -1], [-1, 0, 1, 0], [-1, 1, -1, 1] ])
self.INV_A = np.linalg.inv(self.A)
self.B_COEFF = np.array([1/self.KF, 1/(self.KF*self.L), 1/(self.KF*self.L), 1/self.KM])
if(self.DRONE_MODEL == DroneModel.ARDRONE2):
sqr2 = np.sqrt(2)
self.A = np.array([ [1, 1, 1, 1], [1/sqr2, 1/sqr2, -1/sqr2, -1/sqr2], [-1/sqr2, 1/sqr2, 1/sqr2, -1/sqr2], [-1, 1, -1, 1]])
self.MAX_XY_TORQUE = (self.L*self.KF*self.MAX_RPM**2 * np.sqrt(2))
self.reset()
################################################################################
def reset(self):
"""Resets the control classes.
The previous step's and integral errors for both position and attitude are set to zero.
"""
super().reset()
#### Initialized PID control variables #####################
self.last_pos_e = np.zeros(3)
self.integral_pos_e = np.zeros(3)
self.last_rpy_e = np.zeros(3)
self.integral_rpy_e = np.zeros(3)
################################################################################
def computeControl(self,
control_timestep,
cur_pos,
cur_quat,
cur_vel,
cur_ang_vel,
target_pos,
target_rpy=np.zeros(3),
target_vel=np.zeros(3),
target_rpy_rates=np.zeros(3)
):
"""Computes the PID control action (as RPMs) for a single drone.
This methods sequentially calls `_simplePIDPositionControl()` and `_simplePIDAttitudeControl()`.
Parameters `cur_ang_vel`, `target_rpy`, `target_vel`, and `target_rpy_rates` are unused.
Parameters
----------
control_timestep : float
The time step at which control is computed.
cur_pos : ndarray
(3,1)-shaped array of floats containing the current position.
cur_quat : ndarray
(4,1)-shaped array of floats containing the current orientation as a quaternion.
cur_vel : ndarray
(3,1)-shaped array of floats containing the current velocity.
cur_ang_vel : ndarray
(3,1)-shaped array of floats containing the current angular velocity.
target_pos : ndarray
(3,1)-shaped array of floats containing the desired position.
target_rpy : ndarray, optional
(3,1)-shaped array of floats containing the desired orientation as roll, pitch, yaw.
target_vel : ndarray, optional
(3,1)-shaped array of floats containing the desired velocity.
target_rpy_rates : ndarray, optional
(3,1)-shaped array of floats containing the the desired roll, pitch, and yaw rates.
Returns
-------
ndarray
(4,1)-shaped array of integers containing the RPMs to apply to each of the 4 motors.
ndarray
(3,1)-shaped array of floats containing the current XYZ position error.
float
The current yaw error.
"""
self.control_counter += 1
if target_rpy[2]!=0:
print("\n[WARNING] ctrl it", self.control_counter, "in SimplePIDControl.computeControl(), desired yaw={:.0f}deg but locked to 0. for DroneModel.HB".format(target_rpy[2]*(180/np.pi)))
thrust, computed_target_rpy, pos_e = self._simplePIDPositionControl(control_timestep,
cur_pos,
cur_quat,
target_pos
)
rpm = self._simplePIDAttitudeControl(control_timestep,
thrust,
cur_quat,
computed_target_rpy
)
cur_rpy = p.getEulerFromQuaternion(cur_quat)
return rpm, pos_e, computed_target_rpy[2] - cur_rpy[2]
################################################################################
def _simplePIDPositionControl(self,
control_timestep,
cur_pos,
cur_quat,
target_pos
):
"""Simple PID position control (with yaw fixed to 0).
Parameters
----------
control_timestep : float
The time step at which control is computed.
cur_pos : ndarray
(3,1)-shaped array of floats containing the current position.
cur_quat : ndarray
(4,1)-shaped array of floats containing the current orientation as a quaternion.
target_pos : ndarray
(3,1)-shaped array of floats containing the desired position.
Returns
-------
float
The target thrust along the drone z-axis.
ndarray
(3,1)-shaped array of floats containing the target roll, pitch, and yaw.
float
The current position error.
"""
pos_e = target_pos - np.array(cur_pos).reshape(3)
d_pos_e = (pos_e - self.last_pos_e) / control_timestep
self.last_pos_e = pos_e
self.integral_pos_e = self.integral_pos_e + pos_e*control_timestep
#### PID target thrust #####################################
target_force = np.array([0, 0, self.GRAVITY]) \
+ np.multiply(self.P_COEFF_FOR, pos_e) \
+ np.multiply(self.I_COEFF_FOR, self.integral_pos_e) \
+ np.multiply(self.D_COEFF_FOR, d_pos_e)
target_rpy = np.zeros(3)
sign_z = np.sign(target_force[2])
if sign_z == 0:
sign_z = 1
#### Target rotation #######################################
target_rpy[0] = np.arcsin(-sign_z*target_force[1] / np.linalg.norm(target_force))
target_rpy[1] = np.arctan2(sign_z*target_force[0], sign_z*target_force[2])
target_rpy[2] = 0.
target_rpy[0] = np.clip(target_rpy[0], -self.MAX_ROLL_PITCH, self.MAX_ROLL_PITCH)
target_rpy[1] = np.clip(target_rpy[1], -self.MAX_ROLL_PITCH, self.MAX_ROLL_PITCH)
cur_rotation = np.array(p.getMatrixFromQuaternion(cur_quat)).reshape(3, 3)
thrust = np.dot(cur_rotation, target_force)
return thrust[2], target_rpy, pos_e
################################################################################
def _simplePIDAttitudeControl(self,
control_timestep,
thrust,
cur_quat,
target_rpy
):
"""Simple PID attitude control (with yaw fixed to 0).
Parameters
----------
control_timestep : float
The time step at which control is computed.
thrust : float
The target thrust along the drone z-axis.
cur_quat : ndarray
(4,1)-shaped array of floats containing the current orientation as a quaternion.
target_rpy : ndarray
(3,1)-shaped array of floats containing the computed the target roll, pitch, and yaw.
Returns
-------
ndarray
(4,1)-shaped array of integers containing the RPMs to apply to each of the 4 motors.
"""
cur_rpy = p.getEulerFromQuaternion(cur_quat)
rpy_e = target_rpy - np.array(cur_rpy).reshape(3,)
if rpy_e[2] > np.pi:
rpy_e[2] = rpy_e[2] - 2*np.pi
if rpy_e[2] < -np.pi:
rpy_e[2] = rpy_e[2] + 2*np.pi
d_rpy_e = (rpy_e - self.last_rpy_e) / control_timestep
self.last_rpy_e = rpy_e
self.integral_rpy_e = self.integral_rpy_e + rpy_e*control_timestep
#### PID target torques ####################################
target_torques = np.multiply(self.P_COEFF_TOR, rpy_e) \
+ | np.multiply(self.I_COEFF_TOR, self.integral_rpy_e) | numpy.multiply |
import numpy as np
import pytest
from muzero.sample_batch import SampleBatch
from muzero.structure_list import ArraySpec
@pytest.fixture(scope='module')
def atari_tensor_spec():
n_channels = 4
frame_shape = (96, 96)
loss_steps = 6
action_count = 4
tensor_spec = (
ArraySpec(frame_shape + (n_channels,), np.float32, SampleBatch.CUR_OBS),
ArraySpec((1,), np.int32, SampleBatch.EPS_ID),
ArraySpec((1,), np.int32, SampleBatch.UNROLL_ID),
ArraySpec((loss_steps,), np.int32, SampleBatch.ACTIONS),
ArraySpec((action_count,), np.float32, 'action_dist_probs'),
ArraySpec((1,), np.float32, SampleBatch.ACTION_PROB),
ArraySpec((1,), np.float32, SampleBatch.ACTION_LOGP),
ArraySpec((1,), np.bool, SampleBatch.DONES),
ArraySpec((1,), np.float32, SampleBatch.REWARDS),
ArraySpec((loss_steps, action_count), np.float32, 'rollout_policies'),
ArraySpec((loss_steps,), np.float32, 'rollout_rewards'),
ArraySpec((loss_steps,), np.float32, 'rollout_values'),
)
return tensor_spec
def random_tensor(spec):
if spec.dtype == np.float32:
return np.random.uniform(size=spec.shape)
elif spec.dtype == np.int32:
return np.random.randint(0, 1 << 24, size=spec.shape)
elif spec.dtype == np.bool:
return np.random.choice(a=[False, True], size=spec.shape)
else:
raise NotImplementedError(f"tensor spec dtype {spec.dtype} not supported")
def random_struct(tensor_spec):
struct = []
for spec in tensor_spec:
struct.append(random_tensor(spec))
return tuple(struct)
def random_batch(tensor_spec, batch_size):
structs = []
for _ in range(batch_size):
structs.append(random_struct(tensor_spec))
batch = []
for i in range(len(tensor_spec)):
batch_tensor = []
for j in range(len(structs)):
batch_tensor.append(structs[j][i])
batch.append(np.array(batch_tensor))
return tuple(batch)
def random_sample_batch(tensor_spec, batch_size):
tensor_batch = random_batch(tensor_spec, batch_size)
batch = {}
for spec, tensor in zip(tensor_spec, tensor_batch):
if spec.name == SampleBatch.EPS_ID:
eps_ids = [np.zeros(batch_size // 2, dtype=np.int32), | np.ones(batch_size // 2, dtype=np.int32) | numpy.ones |
# procedure for existing halos, after the first snapshot was initiated :
import sys
# only input parameter is the numbering of the snapshot. These have to be
#processed in sequence, cannot be done in parallel ... First 1, 2, 3, ...
#ii = int(sys.argv[1])
#print('snapshot' ii)
import time
t0 = time.time()
from multiprocessing import Pool
#p=Pool(12)
import h5py
import os
import glob
import numpy as n
import EmergeStellarMass as sm
model = sm.StellarMass()
import pandas as pd
from astropy.cosmology import FlatLambdaCDM
import astropy.units as u
cosmoMD = FlatLambdaCDM(H0=67.77*u.km/u.s/u.Mpc, Om0=0.307115)#, Ob0=0.048206)
import astropy.constants as constants
# generic functions
# =================
f_loss = lambda t : 0.05*n.log( 1 + t / (1.4*10**6))
t_dyn = lambda rvir, mvir : (rvir**3./(9.797465327217671e-24*mvir))**0.5
def tau_quenching( m_star, tdyn, tau_0=4.282, tau_s=0.363):
out = n.zeros_like(m_star)
case_1 = (m_star < 1e10 )
out[case_1] = tdyn[case_1] * tau_0
case_2 = (case_1==False)
out[case_2] = tdyn[case_2] * tau_0 * (m_star[case_2] * 10.**(-10.))**(tau_s)
return out
def compute_qtys_new_halos_pk(mvir, rvir, redshift, age_yr):
"""
Creates a new galaxy along with the new halo.
Integrates since the start of the Universe.
Updates the initiated quantities with the values of interest.
:param mvir: list of mvir [Msun], length = n.
:param rvir: list of rvir [kpc] , length = n.
:param redshift: redshift of the snapshot replicated n times.
:param age_yr: age of the Universe for the snapshot replicated n times.
Typically inputs should be :
* mvir=self.f1['/halo_properties/mvir'].value[self.mask_f1_new_halos],
* rvir=self.f1['/halo_properties/rvir'].value[self.mask_f1_new_halos],
* age_yr=self.f1.attrs['age_yr']
returns
mvir_dot, rvir_dot, dMdt, dmdt_star, star_formation_rate, stellar_mass
"""
f_b=model.f_b
epsilon = model.epsilon(mvir, redshift )
f_lost = f_loss(age_yr)
# evaluate equation (4)
mvir_dot = mvir / age_yr
# no pseudo evolution correction
dMdt = mvir_dot
# evaluate equation (1)
dmdt_star = f_b * dMdt * epsilon
# evaluate accretion: 0 in this first step
# self.dmdt_star_accretion = n.zeros_like(self.dmdt_star)
# evaluate equation (11)
# equation (12)
# evaluate stellar mass
star_formation_rate = dmdt_star * (1. - f_lost)
return mvir_dot, rvir / age_yr, dMdt, dmdt_star, star_formation_rate, star_formation_rate * age_yr
def compute_qtys_evolving_halos_pk(mvir_f0, mvir_f1, age_f0, age_f1, rvir_f0, rvir_f1, redshift, t_dynamical, rs_f1, mpeak_f1, mpeak_scale_f1, f1_scale, m_icm_f0, stellar_mass_f0, star_formation_rate_f0 ):
"""
update the quantities for evolving halos, present in f0 and f1.
inputs
mvir_f0 [Msun] : self.f0['/halo_properties/mvir'].value[self.mask_f0_evolving_11_halos]
mvir_f1 [Msun] : self.f1['/halo_properties/mvir'].value[self.mask_f1_evolving_11_halos]
age_f0 [yr] : self.f0.attrs['age_yr'] * n.ones_like(self.f1['/halo_properties/mvir'].value[self.mask_f1_evolving_11_halos])
age_f1 [yr] : self.f1.attrs['age_yr'] * n.ones_like(self.f1['/halo_properties/mvir'].value[self.mask_f1_evolving_11_halos])
mvir_f0 [Msun] : self.f0['/halo_properties/rvir'].value[self.mask_f0_evolving_11_halos]
mvir_f1 [Msun] : self.f1['/halo_properties/rvir'].value[self.mask_f1_evolving_11_halos]
redshift : self.f1.attrs['redshift'] * n.ones_like(self.f1['/halo_properties/mvir'].value[self.mask_f1_evolving_11_halos])
t_dynamical : self.t_dynamical[self.mask_f1_evolving_11_halos]
rs_f1 [kpc] : self.f1['/halo_properties/rs'].value[self.mask_f1_evolving_11_halos]
mpeak_f1 [Msun] : self.f1['/halo_properties/Mpeak'].value[self.mask_f1_evolving_11_halos]
mpeak_scale_f1 : self.f1['/halo_properties/Mpeak_scale'].value[self.mask_f1_evolving_11_halos]
f1_scale : float(self.f1_scale)
m_icm_f0 [Msun] : self.f0['/emerge_data/m_icm'].value[self.mask_f0_evolving_11_halos]
stellar_mass_f0 [Msun] : self.f0['/emerge_data/stellar_mass'].value[self.mask_f0_evolving_11_halos]
star_formation_rate_f0 [Msun/yr] : self.f0['/halo_properties/star_formation_rate'].value[self.mask_f0_evolving_11_halos]
masks :
* mask_f1_evolving_11_halos
* mask_f0_evolving_11_halos
subcases :
* quenching : (mvir < Mpeak) & (Mpeak_scale < f1_scale)
* case 1. ( age >= t_mpeak ) & ( age_yr < t_mpeak + t_quench)
* case 2. (age_yr >= t_mpeak + t_quench)
* stripping, case 1 : (dMdt < 0), then all mass goes to ICM, m=0, mdot=0
* stripping, case 2 : after reaching its peak mass, if M < 0.122 * Mpeak, then all mass goes to ICM, m=0, mdot=0
"""
# computing dMdt for the halo
dt = age_f1 - age_f0
mvir_dot = (mvir_f1-mvir_f0) / (dt)
rvir_dot = (rvir_f1-rvir_f0) / (dt)
c = rvir_f1 / rs_f1
rho_nfw = mvir_f1 / (rs_f1**3. * 4. * n.pi * c * (1+c)**2. * (n.log(1.+c)-c/(1.+c)))
pseudo_evolution_correction = 4. * n.pi * rvir_f1 * rvir_f1 * rvir_dot * rho_nfw
dMdt = mvir_dot - pseudo_evolution_correction
# initialize the ICM mass to the previous value
m_icm = m_icm_f0
# Direct estimates of stellar mass and SFR
dmdt_star = model.f_b * dMdt * model.epsilon(mvir_f1, redshift)
# evaluate accretion: 0 in this first step
# dmdt_star_accretion = n.zeros_like(dmdt_star)
# evaluate equation (11)
f_lost = f_loss(dt)
# evaluate stellar mass
star_formation_rate = dmdt_star * (1. - f_lost)
stellar_mass = star_formation_rate * dt + stellar_mass_f0
# Variations due to stripping, merging and quenching
# quenching
quenching = (mvir_f1 < mpeak_f1) & (mpeak_scale_f1 < f1_scale)
#t_quench = tau_quenching( stellar_mass_f0, t_dynamical )
if stellar_mass_f0 < 1e10 :
t_quench = t_dynamical * 4.282
else :
t_quench = t_dynamical * 4.282 * (stellar_mass_f0 * 10.**(-10.))**(0.363)
t_mpeak = cosmoMD.age( 1. / mpeak_scale_f1 - 1. ).to(u.yr).value
# case 1. mdot = mdot at tpeak
quench_1 = (quenching) & (age_f1 >= t_mpeak ) & ( age_f1 < t_mpeak + t_quench)
if quench_1 :
star_formation_rate = n.ones_like(star_formation_rate)*star_formation_rate_f0
stellar_mass = star_formation_rate * dt + stellar_mass_f0
# case 2. m dot =0
quench_2 = (quenching) &(age_f1 >= t_mpeak + t_quench )
if quench_2:
star_formation_rate = n.zeros_like(star_formation_rate)
stellar_mass = stellar_mass_f0
# stripping, case 1
# negative growth value self.dMdt => 0
stripping_1 = (dMdt < 0)
# stripping, case 2
# after reaching its peak mass,
# if M < 0.122 * Mpeak, all mass goes to ICM, m=0, mdot=0
stripping_2 = (mvir_f1 < 0.122*mpeak_f1) & (mpeak_scale_f1 < f1_scale)
# both cases together
stripping = (stripping_1) | (stripping_1)
if stripping :
m_icm += stellar_mass_f0
stellar_mass = n.zeros_like(stellar_mass)
star_formation_rate = n.zeros_like(star_formation_rate)
return mvir_dot, rvir_dot, dMdt, dmdt_star, star_formation_rate, stellar_mass, m_icm
def merge_system(mvir_f0, mvir_f1, age_f0, age_f1, rvir_f0, rvir_f1, redshift, t_dynamical, rs_f1, mpeak_f1, mpeak_scale_f1, f1_scale, m_icm_f0, stellar_mass_f0, star_formation_rate_f0, sum_stellar_mass_guests):
"""
given f1_host, f0_host and f0 guests,
creates the right quantities, stellar mass and so on...
# m_star_sat x f_esc => m_host_ICM
# m_star_sat x (1-f_esc) => m_star_host
# f_esc = 0.388
#Time_to_future_merger: Time (in Gyr) until the given halo merges into a larger halo. (-1 if no future merger happens)
#Future_merger_MMP_ID: most-massive progenitor of the halo into which the given halo merges. (-1 if the main progenitor of the future merger halo does not exist at the given scale factor.)
"""
# evolution of the host
dt = age_f1 - age_f0
mvir_dot = (mvir_f1-mvir_f0) / (dt)
rvir_dot = (rvir_f1-rvir_f0) / (dt)
c = rvir_f1 / rs_f1
rho_nfw = mvir_f1 / (rs_f1**3. * 4. * n.pi * c * (1+c)**2. * (n.log(1.+c)-c/(1.+c)))
pseudo_evolution_correction = 4. * n.pi * rvir_f1 * rvir_f1 * rvir_dot * rho_nfw
dMdt = mvir_dot - pseudo_evolution_correction
m_icm = m_icm_f0
dmdt_star = model.f_b * dMdt * model.epsilon(mvir_f1, redshift)
f_lost = f_loss(dt)
star_formation_rate = dmdt_star * (1. - f_lost)
stellar_mass = star_formation_rate * dt + stellar_mass_f0
# merging the sub systems, i.e. adding stellar mass
stellar_mass += (1.-0.388)*sum_stellar_mass_guests
m_icm += 0.388*sum_stellar_mass_guests
return mvir_dot, rvir_dot, dMdt, dmdt_star, stellar_mass, star_formation_rate, m_icm
class EmergeIterate():
"""
Loads iterates one step with the Emerge model.
:param ii: index of the snapshot of interest
:param env: environment variable of the box. In this dir must be a sub dir
'h5' with the 'hlist_?.?????_emerge.hdf5' data files in it
:param L_box: length of the box in Mpc/h
Running the iteration
---------------------
ipython3
import EmergeIterate
iterate = EmergeIterate.EmergeIterate(12, 'MD10')
iterate.open_snapshots()
iterate.map_halos_between_snapshots()
iterate.init_new_quantities()
if len((iterate.mask_f1_new_halos).nonzero()[0]) > 0 :
iterate.compute_qtys_new_halos()
if len((iterate.mask_f0_evolving_11_halos).nonzero()[0]) > 0 :
iterate.compute_qtys_evolving_halos()
if len(self.mask_f1_in_a_merging.nonzero()[0]) > 0 :
iterate.compute_qtys_merging_halos()
self.write_results()
"""
def __init__(self, ii, env, L_box=1000.0 ):
self.ii = ii
self.env = env
self.L_box = L_box # box length
def open_snapshots(self):
"""
Opens the files into the class as f0 and f1
"""
h5_dir = os.path.join(os.environ[self.env], 'h5' )
input_list = n.array(glob.glob(os.path.join(h5_dir, "hlist_?.?????_emerge.hdf5")))
input_list.sort()
file_0 = input_list[self.ii-1]
file_1 = input_list[self.ii]
self.f0 = h5py.File(file_0, "r")
self.f0_scale = os.path.basename(file_0).split('_')[1]
self.positions_f0 = n.arange(len(self.f0['/halo_properties/id'].value))
self.f1 = h5py.File(file_1, "r+")
self.f1_scale = os.path.basename(file_1).split('_')[1]
self.positions_f1 = n.arange(len(self.f1['/halo_properties/id'].value))
def map_halos_between_snapshots(self):
"""
id mapping for halos present in the previous snapshot
Creates 6 arrays to do the mapping in the different cases
* mask_f1_new_halos
* mask_f0_evolving_11_halos
* mask_f1_evolving_11_halos
* f1_id_with_multiple_progenitors
* mask_f1_in_a_merging
* mask_f0_in_a_merging
"""
#f0_desc_id_unique_list_all_descendents = n.unique(self.f0['/halo_properties/desc_id'].value)
f1_id_unique_list_descendents_detected_at_next_scale = n.intersect1d(n.unique(self.f0['/halo_properties/desc_id'].value), self.f1['/halo_properties/id'].value)
mask_f0_to_propagate = n.in1d(self.f0['/halo_properties/desc_id'].value, f1_id_unique_list_descendents_detected_at_next_scale)
# mask_f0_lost = (mask_f0_to_propagate == False )
# evolving halos are given after applying this boolean mask to a f1 quantity :
mask_f1_evolved_from_previous = n.in1d( self.f1['/halo_properties/id'].value, f1_id_unique_list_descendents_detected_at_next_scale )
# new halos are given after applying this boolean mask to a f1 quantity
# new halos in f1, not present in f0
self.mask_f1_new_halos = (mask_f1_evolved_from_previous==False)
print('new halos', len(self.mask_f1_new_halos.nonzero()[0]))
# halos descending :
# mask_f0_to_propagate
# mask_f1_evolved_from_previous
s = pd.Series(self.f0['/halo_properties/desc_id'].value[mask_f0_to_propagate])
self.f1_id_with_multiple_progenitors = s[s.duplicated()].get_values()
# also = f0_desc_id merging into 1 halo in f1
# merging systems [many halos in f0 into a single f1 halo]
self.mask_f1_in_a_merging = n.in1d( self.f1['/halo_properties/id'].value, self.f1_id_with_multiple_progenitors )
self.mask_f0_in_a_merging = n.in1d( self.f0['/halo_properties/desc_id'].value, self.f1_id_with_multiple_progenitors )
# halos mapped fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b between snapshots
self.mask_f0_evolving_11_halos = ( mask_f0_to_propagate ) & ( self.mask_f0_in_a_merging == False )
self.mask_f1_evolving_11_halos = ( mask_f1_evolved_from_previous ) & ( self.mask_f1_in_a_merging == False )
print('11 mapping', len(self.mask_f0_evolving_11_halos.nonzero()[0]), len(self.mask_f1_evolving_11_halos.nonzero()[0]))
print('merging systems', len(self.f1_id_with_multiple_progenitors))
#for dede in self.f1_id_with_multiple_progenitors :
#sel = self.f0['/halo_properties/desc_id'].value == dede
#print( dede )
#print('desc id', self.f0['/halo_properties/desc_id'].value[sel])
#print('id', self.f0['/halo_properties/id'].value[sel])
#print('pid', self.f0['/halo_properties/pid'].value[sel])
#print('mvir', self.f0['/halo_properties/mvir'].value[sel])
#print('futur merger mmpid', self.f0['/halo_properties/Future_merger_MMP_ID'].value[sel])
#print('time to future merger', self.f0['/halo_properties/Time_to_future_merger'].value[sel])
#print('Ms', self.f0['/emerge_data/stellar_mass'].value[sel])
#print('SFR',self.f0['/emerge_data/star_formation_rate'].value[sel])
#print('mCIM',self.f0['/emerge_data/m_icm'].value[sel])
#print('=================================')
def init_new_quantities(self):
"""
Quantities computed for every halos are initialized to 0
* mvir_dot
* rvir_dot
* dMdt
* dmdt_star
* dmdt_star_accretion
* stellar_mass
* star_formation_rate
* m_icm
* t_dynamical [in years]
Along with the iteration, these quantities will be updated accordingly
"""
self.mvir_dot = n.zeros_like(self.f1['/halo_properties/mvir'].value)
self.rvir_dot = | n.zeros_like(self.f1['/halo_properties/mvir'].value) | numpy.zeros_like |
import os
import json
from copy import copy
from subprocess import call, Popen, PIPE, STDOUT
import time
import numpy as np
import pandas as pd
from pyproj import Transformer
import rasterio
import fiona
from affine import Affine
from shapely.geometry import shape
from scipy.ndimage.morphology import binary_erosion
from pandas.plotting import register_matplotlib_converters
import matplotlib
import matplotlib.pyplot as plt
import flopy
from flopy.utils import GridIntersect
import richdem as rd
from gsflow.builder import GenerateFishnet, FlowAccumulation, PrmsBuilder, ControlFileBuilder
from gsflow.builder.builder_defaults import ControlFileDefaults
from gsflow.builder import builder_utils as bu
from gsflow.prms.prms_parameter import ParameterRecord
from gsflow.prms import PrmsData, PrmsParameters
from gsflow.control import ControlFile
from gsflow.output import StatVar
from model_config import PRMSConfig
from gsflow_prep import PRMS_NOT_REQ
from datafile import write_basin_datafile
register_matplotlib_converters()
pd.options.mode.chained_assignment = None
# RichDEM flow-direction coordinate system:
# 234
# 105
# 876
d8_map = {5: 1, 6: 2, 7: 4, 8: 8, 1: 16, 2: 32, 3: 64, 4: 128}
class StandardPrmsBuild(object):
def __init__(self, config):
self.cfg = PRMSConfig(config)
self.res = float(self.cfg.hru_cellsize)
self.proj_name_res = '{}_{}'.format(self.cfg.project_name,
self.cfg.hru_cellsize)
for folder in ['hru_folder', 'parameter_folder', 'control_folder', 'data_folder', 'output_folder']:
folder_path = os.path.join(self.cfg.project_folder,
self.proj_name_res,
getattr(self.cfg, folder))
setattr(self.cfg, folder, folder_path)
if not os.path.isdir(folder_path):
os.makedirs(folder_path, exist_ok=True)
self.parameters = None
self.control = None
self.data = None
self.zeros = None
with fiona.open(self.cfg.study_area_path, 'r') as src:
self.raster_meta = src.meta
self.basin_geo = [shape(f['geometry']) for f in src][0]
self.prj = self.cfg.study_area_path.replace('.shp', '.prj')
self.control_file = os.path.join(self.cfg.control_folder,
'{}.control'.format(self.proj_name_res))
self.parameter_file = os.path.join(self.cfg.parameter_folder,
'{}.params'.format(self.proj_name_res))
self.data_file = os.path.join(self.cfg.data_folder, '{}.data'.format(self.proj_name_res))
def write_parameter_file(self):
builder = PrmsBuilder(
self.streams,
self.cascades,
self.modelgrid,
self.dem.ravel(),
hru_type=self.hru_lakeless.ravel(),
hru_subbasin=self.hru_lakeless.ravel())
self.parameters = builder.build()
self.parameters.hru_lat = self.lat
self.parameters.hru_lon = self.lon
self.parameters.add_record_object(ParameterRecord('hru_x',
np.array(self.modelgrid.xcellcenters.ravel(),
dtype=float).ravel(),
dimensions=[['nhru', len(self.lon)]],
datatype=2))
self.parameters.add_record_object(ParameterRecord('hru_y',
np.array(self.modelgrid.ycellcenters.ravel(),
dtype=float).ravel(),
dimensions=[['nhru', len(self.lat)]],
datatype=2))
areas = np.ones_like(self.lat) * self.hru_area
self.parameters.add_record_object(ParameterRecord('hru_area',
np.array(areas, dtype=float).ravel(),
dimensions=[['nhru', len(self.lat)]],
datatype=2))
# self.build_lakes()
self._build_veg_params()
self._build_soil_params()
[self.parameters.add_record_object(rec) for rec in self.data_params]
[self.parameters.remove_record(rec) for rec in PRMS_NOT_REQ]
self.parameters.write(self.parameter_file)
def write_control_file(self):
controlbuild = ControlFileBuilder(ControlFileDefaults())
self.control = controlbuild.build(name='{}.control'.format(self.proj_name_res),
parameter_obj=self.parameters)
self.control.model_mode = ['PRMS']
self.control.executable_desc = ['PRMS Model']
self.control.executable_model = [self.cfg.prms_exe]
self.control.cascadegw_flag = [0]
self.control.et_module = ['potet_jh']
self.control.precip_module = ['xyz_dist']
self.control.temp_module = ['xyz_dist']
self.control.solrad_module = ['ccsolrad']
self.control.rpt_days = [7]
self.control.snarea_curve_flag = [0]
self.control.soilzone_aet_flag = [0]
self.control.srunoff_module = ['srunoff_smidx']
# 0: standard; 1: SI/metric
units = 0
self.control.add_record('elev_units', [units])
self.control.add_record('precip_units', [units])
self.control.add_record('temp_units', [units])
self.control.add_record('runoff_units', [units])
self.control.start_time = [int(d) for d in self.cfg.start_time.split(',')] + [0, 0, 0]
self.control.subbasin_flag = [0]
self.control.transp_module = ['transp_tindex']
self.control.csv_output_file = [os.path.join(self.cfg.output_folder, 'output.csv')]
self.control.param_file = [self.parameter_file]
self.control.subbasin_flag = [0, ]
self.control.parameter_check_flag = [0, ]
self.control.add_record('end_time', [int(d) for d in self.cfg.end_time.split(',')] + [0, 0, 0])
self.control.add_record('model_output_file', [os.path.join(self.cfg.output_folder, 'output.model')],
datatype=4)
self.control.add_record('var_init_file', [os.path.join(self.cfg.output_folder, 'init.csv')],
datatype=4)
self.control.add_record('data_file', [self.data_file], datatype=4)
stat_vars = ['runoff',
'basin_tmin',
'basin_tmax',
'basin_ppt',
'basin_rain',
'basin_snow',
'basin_potsw',
'basin_potet',
'basin_net_ppt',
'basin_intcp_stor',
'basin_pweqv',
'basin_snowmelt',
'basin_snowcov',
'basin_sroff',
'basin_hortonian',
'basin_infil',
'basin_soil_moist',
'basin_recharge',
'basin_actet',
'basin_gwstor',
'basin_gwflow',
'basin_gwsink',
'basin_cfs',
'basin_ssflow',
'basin_imperv_stor',
'basin_lake_stor',
'basin_ssstor']
self.control.add_record('statsON_OFF', values=[1], datatype=1)
self.control.add_record('nstatVars', values=[len(stat_vars)], datatype=1)
self.control.add_record('statVar_element', values=['1' for _ in stat_vars], datatype=4)
self.control.add_record('statVar_names', values=stat_vars, datatype=4)
self.control.add_record('stat_var_file', [os.path.join(self.cfg.output_folder, 'statvar.out')],
datatype=4)
disp_vars = [('basin_cfs', '1'),
('runoff', '1'),
('basin_gwflow', '2'),
('basin_sroff', '2'),
('basin_ssflow', '2'),
('basin_actet', '3'),
('basin_potet', '3'),
('basin_perv_et', '3'),
('basin_pweqv', '4'),
('basin_snow', '4'),
('basin_snowdepth', '4'),
('basin_snowmelt', '4')]
self.control.add_record('dispVar_plot', values=[e[1] for e in disp_vars], datatype=4)
self.control.add_record('statVar_names', values=stat_vars, datatype=4)
self.control.add_record('dispVar_element', values=['1' for _ in disp_vars], datatype=4)
self.control.add_record('gwr_swale_flag', [1])
# remove gsflow control objects
self.control.remove_record('gsflow_output_file')
self.control.write(self.control_file)
def write_datafile(self, units='metric'):
self.nmonths = 12
ghcn = self.cfg.prms_data_ghcn
stations = self.cfg.prms_data_stations
gages = self.cfg.prms_data_gages
with open(stations, 'r') as js:
sta_meta = json.load(js)
sta_iter = sorted([(v['zone'], v) for k, v in sta_meta.items()], key=lambda x: x[0])
tsta_elev, tsta_nuse, tsta_x, tsta_y, psta_elev = [], [], [], [], []
for _, val in sta_iter:
if units != 'metric':
elev = val['elev'] / 0.3048
else:
elev = val['elev']
tsta_elev.append(elev)
tsta_nuse.append(1)
tsta_x.append(val['proj_coords'][1])
tsta_y.append(val['proj_coords'][0])
psta_elev.append(elev)
self.data_params = [ParameterRecord('nrain', values=[len(tsta_x)], datatype=1),
ParameterRecord('ntemp', values=[len(tsta_x)], datatype=1),
ParameterRecord('psta_elev', np.array(psta_elev, dtype=float).ravel(),
dimensions=[['nrain', len(psta_elev)]], datatype=2),
ParameterRecord('psta_nuse', np.array(tsta_nuse, dtype=int).ravel(),
dimensions=[['nrain', len(tsta_nuse)]], datatype=1),
ParameterRecord(name='ndist_psta', values=[len(tsta_nuse), ], datatype=1),
ParameterRecord('psta_x', np.array(tsta_x, dtype=float).ravel(),
dimensions=[['nrain', len(tsta_x)]], datatype=2),
ParameterRecord('psta_y', np.array(tsta_y, dtype=float).ravel(),
dimensions=[['nrain', len(tsta_y)]], datatype=2),
ParameterRecord('tsta_elev', np.array(tsta_elev, dtype=float).ravel(),
dimensions=[['ntemp', len(tsta_elev)]], datatype=2),
ParameterRecord('tsta_nuse', | np.array(tsta_nuse, dtype=int) | numpy.array |
# Copyright (c) 2019 - The Procedural Generation for Gazebo authors
# For information on the respective copyright owner see the NOTICE file
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import numpy as np
import trimesh
from multiprocessing.pool import Pool
from shapely.geometry import MultiPoint, Polygon, MultiPolygon, Point
from shapely.ops import triangulate, unary_union
from time import time
from ..log import PCG_ROOT_LOGGER
from ..visualization import create_scene
from ..simulation import SimulationModel, ModelGroup
from time import time
def _get_model_limits(model, mesh_type='collision'):
x_limits = None
y_limits = None
z_limits = None
meshes = list()
if isinstance(model, SimulationModel) or isinstance(model, ModelGroup):
PCG_ROOT_LOGGER.info('Processing the bounds of simulation model={}'.format(model.name))
meshes = model.get_meshes(mesh_type)
elif isinstance(model, trimesh.Trimesh):
meshes = [model]
else:
msg = 'Input is neither of SimulationModel or Trimesh type, provided={}'.format()
PCG_ROOT_LOGGER.error(msg)
raise ValueError(msg)
for mesh in meshes:
bounds = mesh.bounds
if x_limits is None:
x_limits = bounds[:, 0].flatten()
else:
x_limits[0] = min(x_limits[0], bounds[0, 0])
x_limits[1] = max(x_limits[1], bounds[1, 0])
if y_limits is None:
y_limits = bounds[:, 1].flatten()
else:
y_limits[0] = min(y_limits[0], bounds[0, 1])
y_limits[1] = max(y_limits[1], bounds[1, 1])
if z_limits is None:
z_limits = bounds[:, 2].flatten()
else:
z_limits[0] = min(z_limits[0], bounds[0, 2])
z_limits[1] = max(z_limits[1], bounds[1, 2])
return x_limits, y_limits, z_limits
def get_footprint(model, step_x=0.001, step_y=0.001, x_limits=None,
y_limits=None, z_limits=None, mesh_type='collision'):
if x_limits is None or y_limits is None or z_limits is None:
model_x_limits, model_y_limits, model_z_limits = _get_model_limits(model)
if x_limits is None:
x_limits = model_x_limits
else:
x_limits = np.array(x_limits).flatten()
if x_limits.size != 2:
PCG_ROOT_LOGGER.error('Input x_limits must have two elements, provided={}'.format(x_limits.size))
return None
if x_limits[0] >= x_limits[1]:
PCG_ROOT_LOGGER.error('Input x_limits[0] must be smaller than x_limits[1], provided={}'.format(z_limits))
return None
if y_limits is None:
y_limits = model_y_limits
else:
y_limits = np.array(y_limits).flatten()
if y_limits.size != 2:
PCG_ROOT_LOGGER.error('Input y_limits must have two elements, provided={}'.format(x_limits.size))
return None
if y_limits[0] >= y_limits[1]:
PCG_ROOT_LOGGER.error('Input y_limits[0] must be smaller than y_limits[1], provided={}'.format(z_limits))
return None
if z_limits is None:
z_limits = model_z_limits
else:
z_limits = np.array(z_limits).flatten()
if z_limits.size != 2:
PCG_ROOT_LOGGER.error('Input z_limits must have two elements, provided={}'.format(z_limits.size))
return None
if z_limits[0] >= z_limits[1]:
PCG_ROOT_LOGGER.error('Input z_limits[0] must be smaller than z_limits[1], provided={}'.format(z_limits))
return None
x_samples = np.arange(x_limits[0] - step_x, x_limits[1] + step_x, step_x)
y_samples = np.arange(y_limits[0] - step_y, y_limits[1] + step_y, step_y)
x, y = np.meshgrid(x_samples, y_samples)
ray_origins = np.vstack((
x.flatten(),
y.flatten(),
| np.max(z_limits) | numpy.max |
import os
import sys
import csv
import pickle
import numpy as np
import argparse
import colorsys
from tqdm import tqdm
import gdal
import matplotlib
matplotlib.use('tkagg')
import h5py
from monte_carlo_simulation import monte_carlo_simulation, monte_carlo_ml
import block_surface_fraction as bsf
import rosel_alg
sys.path.append('/Users/nicholas/Documents/Dartmouth/Github/OSSP')
import preprocess as pp
from hist_test import plot_histograms
sys.path.append('/Users/nicholas/Documents/Dartmouth/Projects/modis_unmixing/ANN/artificial_tds/')
from load_data import load_tds_file
def block_albedo(optic_img, clsf_image, factor, pmean=None):
# Given an input image, this function divides it into blocks based on factor,
# and calculates the average surface color within each block
nbands, ydim, xdim = np.shape(optic_img)
ice_albedo = np.zeros((nbands, int(ydim / factor), int(xdim / factor)))
pnd_albedo = np.zeros((nbands, int(ydim / factor), int(xdim / factor)))
ocn_albedo = np.zeros((nbands, int(ydim / factor), int(xdim / factor)))
pratio_list = []
total_albedo = np.zeros((nbands, int(ydim / factor), int(xdim / factor)))
for y in range(0, ydim, factor):
for x in range(0, xdim, factor):
for b in range(nbands):
ice_sum, pnd_sum, ocn_sum = 0, 0, 0
num_light_ponds, num_dark_ponds = 0, 0
# Slice the input data block and calculate the surface histogram
ih, ph, oh = bsf.surface_histograms(optic_img[b, y:y + factor, x:x + factor],
clsf_image[y:y + factor, x:x + factor],
factor, factor)
# Find Average from histogram
# Multiply bin number (i:pixel value) times the bin count (hist[i])
# and sum these to get the total sum from that category
for i in range(len(ih)):
ice_sum += ih[i] * i
pnd_sum += ph[i] * i
ocn_sum += oh[i] * i
# Count the total number of pond pixels that are above and below the image mean
if pmean is not None and b == 2:
if i > pmean:
num_light_ponds += ph[i]
else: # i < pmean
num_dark_ponds += ph[i]
if pmean is not None and b == 2:
pratio = num_light_ponds / (num_dark_ponds + 1)
pratio_list.append(pratio)
if (np.sum(ih) + np.sum(ph) + np.sum(oh)) < factor*factor*.25:
continue
else:
total_albedo[b, int(y / factor), int(x / factor)] = ((ice_sum + pnd_sum + ocn_sum)
/ (np.sum(ih) + np.sum(ph) + np.sum(oh)))
# Divide the sum by the total number of pixels (sum of bin counts)
if np.sum(ih) > factor*factor*.05:
ice_average = ice_sum / (np.sum(ih))
else:
ice_average = find_default('ice', b) * 255
if np.sum(ph) > factor*factor*.05:
pnd_average = pnd_sum / (np.sum(ph))
else:
pnd_average = find_default('pnd', b) * 255
if np.sum(oh) > factor*factor*.05:
ocn_average = ocn_sum / (np.sum(oh))
else:
ocn_average = find_default('ocn', b) * 255
# Convert to float from uint8
ice_albedo[b, int(y / factor), int(x / factor)] = ice_average / 255.
pnd_albedo[b, int(y / factor), int(x / factor)] = pnd_average / 255.
ocn_albedo[b, int(y / factor), int(x / factor)] = ocn_average / 255.
# if b == 2:
# print(ice_average, pnd_average, ocn_average)
# print(pmean)
# avgs = [ice_average, pmean, ocn_average]
# plot_histograms(range(256), ih, ph, oh, avgs)
# a = input("Cont?")
# if str(a) == 'n':
# quit()
return ice_albedo, pnd_albedo, ocn_albedo, total_albedo, pratio_list
def block_classification(clsf_image, factor):
ydim, xdim = np.shape(clsf_image)
blk_fractions = np.zeros((int(ydim/factor), int(xdim/factor), 3))
for y in range(0, ydim, factor):
for x in range(0, xdim, factor):
fs, fp, fo = bsf.block_surface_fraction(clsf_image[y:y+factor, x:x+factor], factor, factor)
blk_fractions[int(y/factor), int(x/factor), :] = [fs, fp, fo]
return blk_fractions
def find_image_pmean(src_ds, clsf_ds, dark_ref, white_pt):
y_dim = src_ds.RasterYSize
x_dim = src_ds.RasterXSize
block_size = 2500
y_blocks = range(0, y_dim, block_size)
x_blocks = range(0, x_dim, block_size)
ice_sum = [0 for _ in range(8)]
pnd_sum = [0 for _ in range(8)]
ocn_sum = [0 for _ in range(8)]
ice_count = [0 for _ in range(8)]
pnd_count = [0 for _ in range(8)]
ocn_count = [0 for _ in range(8)]
pbar = tqdm(total=len(y_blocks)*len(x_blocks), unit='blocks')
for y in y_blocks:
for x in x_blocks:
read_size_y = check_read_size(y, block_size, y_dim)
read_size_x = check_read_size(x, block_size, x_dim)
if read_size_y != block_size or read_size_x != block_size:
continue
optic_data = src_ds.ReadAsArray(x, y, read_size_x, read_size_y)
clsf_data = clsf_ds.ReadAsArray(x, y, read_size_x, read_size_y)
for b in range(8):
if not valid_block(optic_data):
continue
# Apply a dark point reference based on the image histogram (skip band 8)
if b != 7:
optic_data[b, :, :] = pp.rescale_band(optic_data[b, :, :], dark_ref[b], white_pt)
ih, ph, oh = bsf.surface_histograms(optic_data[b, :, :], clsf_data, block_size, block_size)
# Find Average from histogram
# Multiply bin number (i:pixel value) times the bin count (hist[i])
# and sum these to get the total sum from that category
for i in range(len(ih)):
ice_sum[b] += ih[i] * i
pnd_sum[b] += ph[i] * i
ocn_sum[b] += oh[i] * i
# Record the total number of pixels in the pond category
ice_count[b] += np.sum(ih)
pnd_count[b] += np.sum(ph)
ocn_count[b] += np.sum(oh)
pbar.update()
pbar.close()
ice_albedo = np.divide(ice_sum, ice_count)
pnd_albedo = np.divide(pnd_sum, pnd_count)
ocn_albedo = np.divide(ocn_sum, ocn_count)
# quit()
srm = [[ocn_albedo[4]/255, pnd_albedo[4]/255, ice_albedo[4]/255],
[ocn_albedo[6]/255, pnd_albedo[6]/255, ice_albedo[6]/255],
[ocn_albedo[1]/255, pnd_albedo[1]/255, ice_albedo[1]/255],
[1, 1, 1]]
# Divide the sum by the count to get mean
return (pnd_sum[2] / pnd_count[2]), np.array(srm)
def analyze_imagery(optic_image, clsf_image, ds_clsf_data, f, pmean=None):
'''
Reads through the input imagery to extract the variables needed for later processing
'''
# Output variables
srm_list = []
refl_list = []
pond_hsv_list = []
ocean_hsv_list = []
true_fraction_list = []
pond_ocean_diff_list = []
# Find the average reflectance of each surface within the chosen block size.
ice_albedo, pnd_albedo, ocn_albedo, total_albedo, pratio = block_albedo(optic_image, clsf_image, f, pmean=pmean)
# Change all of the nan values back to 0
ice_albedo = np.nan_to_num(ice_albedo)
pnd_albedo = np.nan_to_num(pnd_albedo)
ocn_albedo = np.nan_to_num(ocn_albedo)
# Loop through each pseudo_modis pixel
for i in range(np.shape(total_albedo)[1]):
for j in range(np.shape(total_albedo)[2]):
# Store the true fraction for this pseudo modis pixel
if np.sum(ds_clsf_data[i, j]) == 0:
continue
true_fraction_list.append(ds_clsf_data[i, j])
## Calculate the best spectral reflectance matrix for the current pixel
srm = [[ocn_albedo[4, i, j], pnd_albedo[4, i, j], ice_albedo[4, i, j]],
[ocn_albedo[6, i, j], pnd_albedo[6, i, j], ice_albedo[6, i, j]],
[ocn_albedo[1, i, j], pnd_albedo[1, i, j], ice_albedo[1, i, j]],
[1, 1, 1]]
# srm = assert_defaults(srm)
## Find the reflectance of the current pixel
# refl = [total_albedo[4, i, j], total_albedo[6, i, j], total_albedo[1, i, j]]
refl = total_albedo[:, i, j] # ML needs the full array
refl = np.divide(refl, 255.)
# Store the srm and reflectance for output
srm_list.append(srm)
refl_list.append(refl)
## Save the color of ponds and ocean as HSV
pond_hsv = colorsys.rgb_to_hsv(pnd_albedo[6, i, j], pnd_albedo[4, i, j], pnd_albedo[2, i, j])
ocean_hsv = colorsys.rgb_to_hsv(ocn_albedo[6, i, j], ocn_albedo[4, i, j], ocn_albedo[2, i, j])
pond_ocean_diff = np.sqrt((pnd_albedo[6, i, j] - ocn_albedo[6, i, j]) ** 2 +
(pnd_albedo[4, i, j] - ocn_albedo[4, i, j]) ** 2 +
(pnd_albedo[2, i, j] - ocn_albedo[2, i, j]) ** 2)
pond_hsv_list.append(pond_hsv)
ocean_hsv_list.append(ocean_hsv)
pond_ocean_diff_list.append(pond_ocean_diff)
# Convert these lists to numpy arrays
srm_list = np.array(srm_list)
refl_list = np.array(refl_list)
pond_hsv_list = np.array(pond_hsv_list)
ocean_hsv_list = np.array(ocean_hsv_list)
true_fraction_list = np.array(true_fraction_list)
return srm_list, refl_list, pond_hsv_list, ocean_hsv_list, true_fraction_list, pond_ocean_diff_list, pratio
def stage_one_unmixing(refl_list, srm_list, true_list):
'''
Perform stage 1 unmixing, where each entry in reflectance list is unmixed by
a unique spectral reflectance matrix
:param refl_list: List of pixel reflectance triplets
:param srm_list: SRM for each associated reflectance triplet
:return unmix_fraction: Unmixed fraction for each entry in refl_list
:return unmix_error: Montecarlo error approx for each unmix attempt
'''
# Output data
unmix_fraction = []
unmix_error = []
num_obs = len(refl_list)
# Unmix each reflectance value with its associated srm
for i in range(num_obs):
refl = refl_list[i]
srm = srm_list[i]
# refl might be more than 3 entries if we stored extras for the ML process
if len(refl) != 3:
refl = [refl[4], refl[6], refl[1]]
## Approximate the surface distribution with unmixing
unmix_fraction_i = rosel_alg.spec_unmix(refl, 1, srm)
unmix_fraction_i = np.flip(unmix_fraction_i)
unmix_fraction.append(np.divide(unmix_fraction_i, 1000.))
# Apply a MonteCarlo error propagation
mc_errors = monte_carlo_simulation(refl, srm)
unmix_error.append(np.mean(mc_errors))
return np.array(unmix_fraction), np.array(unmix_error)
def stage_two_unmixing(refl_list, srm):
'''
Perform stage 2 unmixing, where each entry in reflectance list is unmixed by
the same spectral reflectance matrix
:param refl_list: List of pixel reflectance triplets
:param srm_list: Single (average) SRM
:return unmix_fraction: Unmixed fraction for each entry in refl_list
:return unmix_error: Montecarlo error approx for each unmix attempt
'''
# Output data
unmix_fraction = []
unmix_error = []
i = 0
# Unmix each reflectance value with its associated srm
for refl in refl_list:
# refl might be more than 3 entries if we stored extras for the ML process
if len(refl) != 3:
refl = [refl[4], refl[6], refl[1]]
## Approximate the surface distribution with unmixing
unmix_fraction_i = rosel_alg.spec_unmix(refl, 1, srm)
unmix_fraction_i = np.flip(unmix_fraction_i)
unmix_fraction.append(np.divide(unmix_fraction_i, 1000.))
if i == 0:
print("Stage2 SRM:")
print_srm(srm)
i+=1
# Apply a MonteCarlo error propagation
mc_errors = monte_carlo_simulation(refl, srm)
unmix_error.append(np.mean(mc_errors))
return np.array(unmix_fraction), np.array(unmix_error)
def stage_three_unmixing(refl_list, srm):
# Output data
unmix_fraction = []
unmix_error = []
# Unmix each reflectance value with its associated srm
for refl in refl_list:
# refl might be more than 3 entries if we stored extras for the ML process
if len(refl) != 3:
refl = [refl[4], refl[6], refl[1]]
## Approximate the surface distribution with unmixing
unmix_fraction_i = rosel_alg.spec_unmix(refl, 1, srm)
unmix_fraction_i = np.flip(unmix_fraction_i)
unmix_fraction.append(np.divide(unmix_fraction_i, 1000.))
# Apply a MonteCarlo error propagation
mc_errors = monte_carlo_simulation(refl, srm)
unmix_error.append(np.mean(mc_errors))
return np.array(unmix_fraction), | np.array(unmix_error) | numpy.array |
"""
Module to construct pseudo-Stokes (I,Q,U,V) visibilities from miriad files or UVData objects
"""
import numpy as np, os
import pyuvdata
import copy
from collections import OrderedDict as odict
import argparse
from . import version
# Weights used in forming Stokes visibilities.
# See pyuvdata.utils.polstr2num for conversion between polarization string
# and polarization integer. Ex. {'XX': -5, ...}
pol_weights = {
1: odict([(-5, 1.), (-6, 1.)]),
2: odict([(-5, 1.), (-6, -1.)]),
3: odict([(-7, 1.), (-8, 1.)]),
4: odict([(-7, -1.j), (-8, 1.j)])
}
def miriad2pyuvdata(dset, antenna_nums=None, bls=None, polarizations=None,
ant_str=None, time_range=None):
"""
Reads-in a Miriad filepath to a UVData object
Parameters
----------
dset : str
Miriad file to convert to UVData object containing visibilities and
corresponding metadata
antenna_nums: integer list
The antennas numbers to read into the object.
bls: list of tuples
A list of antenna number tuples (e.g. [(0,1), (3,2)])
specifying baselines to read into the object. Ordering of the
numbers within the tuple does not matter. A single antenna iterable
e.g. (1,) is interpreted as all visibilities with that antenna.
ant_str: str
A string containing information about what kinds of visibility data
to read-in. Can be 'auto', 'cross', 'all'. Cannot provide ant_str if
antenna_nums and/or bls is not None.
polarizations: integer or string list
List of polarization integers or strings to read-in.
Ex: ['xx', 'yy', ...]
time_range: float list
len-2 list containing min and max range of times (Julian Date) to read-in.
Ex: [2458115.20, 2458115.40]
Returns
-------
uvd : pyuvdata.UVData object
"""
uvd = pyuvdata.UVData()
uvd.read_miriad(dset, antenna_nums=antenna_nums, bls=bls,
polarizations=polarizations, ant_str=ant_str,
time_range=time_range)
return uvd
def _combine_pol(uvd1, uvd2, pol1, pol2, pstokes='pI', x_orientation=None):
"""
Combines UVData visibilities to form the desired pseudo-stokes visibilities.
It returns UVData object containing the pseudo-stokes visibilities
Parameters
----------
uvd1 : UVData object
First UVData object containing data that is used to
form Stokes visibilities
uvd2 : UVData oject
Second UVData objects containing data that is used to
form Stokes visibilities
pol1 : Polarization, type: str
Polarization of the first UVData object to use in constructing
pStokes visibility.
pol2 : Polarization, type: str
Polarization of the second UVData object to use in constructing
pStokes visibility.
pstokes: Pseudo-stokes polarization to form, type: str
Pseudo stokes polarization to form, can be 'pI' or 'pQ' or 'pU' or 'pV'.
Default: pI
x_orientation: str, optional
Orientation in cardinal direction east or north of X dipole.
Default keeps polarization in X and Y basis.
Returns
-------
uvdS : UVData object
"""
assert isinstance(uvd1, pyuvdata.UVData), \
"uvd1 must be a pyuvdata.UVData instance"
assert isinstance(uvd2, pyuvdata.UVData), \
"uvd2 must be a pyuvdata.UVData instance"
# convert pol1 and/or pol2 to integer if fed as a string
if isinstance(pol1, (str, np.str)):
pol1 = pyuvdata.utils.polstr2num(pol1, x_orientation=x_orientation)
if isinstance(pol2, (str, np.str)):
pol2 = pyuvdata.utils.polstr2num(pol2, x_orientation=x_orientation)
# extracting data array from the UVData objects
data1 = uvd1.data_array
data2 = uvd2.data_array
# extracting flag array from the UVdata objects
flag1 = uvd1.flag_array
flag2 = uvd2.flag_array
# constructing flags (boolean)
flag = np.logical_or(flag1, flag2)
# convert pStokes to polarization integer if a string
if isinstance(pstokes, (str, np.str)):
pstokes = pyuvdata.utils.polstr2num(pstokes, x_orientation=x_orientation)
# get string form of polarizations
pol1_str = pyuvdata.utils.polnum2str(pol1)
pol2_str = pyuvdata.utils.polnum2str(pol2)
pstokes_str = pyuvdata.utils.polnum2str(pstokes)
# assert pstokes in pol_weights, and pol1 and pol2 in pol_weights[pstokes]
assert pstokes in pol_weights, \
"unrecognized pstokes parameter {}".format(pstokes_str)
assert pol1 in pol_weights[pstokes], \
"pol1 {} not used in constructing pstokes {}".format(pol1_str, pstokes_str)
assert pol2 in pol_weights[pstokes], \
"pol2 {} not used in constructing pstokes {}".format(pol2_str, pstokes_str)
# constructing Stokes visibilities
stdata = 0.5 * (pol_weights[pstokes][pol1]*data1 + pol_weights[pstokes][pol2]*data2)
# assigning and writing data, flags and metadata to UVData object
uvdS = copy.deepcopy(uvd1)
uvdS.data_array = stdata # pseudo-stokes data
uvdS.flag_array = flag # flag array
uvdS.polarization_array = np.array([pstokes], dtype=np.int) # polarization number
uvdS.nsample_array = uvd1.nsample_array + uvd2.nsample_array # nsamples
uvdS.history = "Merged into pseudo-stokes vis with hera_pspec version {} Git hash {}\n{}" \
"{}{}{}{}\n".format(version.version, version.git_hash, "-"*20+'\n',
'dset1 history:\n', uvd1.history, '\n'+'-'*20+'\ndset2 history:\n',
uvd2.history)
return uvdS
def construct_pstokes(dset1, dset2, pstokes='pI', run_check=True, antenna_nums=None,
bls=None, polarizations=None, ant_str=None, time_range=None,
history=''):
"""
Validates datasets required to construct desired visibilities and
constructs desired pseudo-Stokes visibilities. These are formed
via the following expression
( V_pI ) ( 1 0 0 1 ) ( V_XX )
| V_pQ | | 1 0 0 -1 | | V_XY |
| V_pU | = 0.5 * | 0 1 1 0 | * | V_YX |
( V_pV ) ( 0 -i i 0 ) ( V_YY )
In constructing a given pseudo-Stokes visibilities, the XX or XY polarization is
taken from dset1, and the YX or YY pol is taken from dset2.
Parameters
----------
dset1 : UVData object or Miriad file
First UVData object or Miriad file containing data that is used to
form Stokes visibilities
dset2 : UVData oject or Miriad file
Second UVData object or Miriad file containing data that is used to
form Stokes visibilities
pstokes: Stokes polarization, type: str
Pseudo stokes polarization to form, can be 'pI' or 'pQ' or 'pU' or 'pV'.
Default: pI
run_check: boolean
Option to check for the existence and proper shapes of
parameters after downselecting data on this object. Default is True.
antenna_nums: integer list
The antennas numbers to read into the object.
bls: list of tuples
A list of antenna number tuples (e.g. [(0,1), (3,2)])
specifying baselines to read into the object. Ordering of the
numbers within the tuple does not matter. A single antenna iterable
e.g. (1,) is interpreted as all visibilities with that antenna.
ant_str: str
A string containing information about what kinds of visibility data
to read-in. Can be 'auto', 'cross', 'all'. Cannot provide ant_str if
antenna_nums and/or bls is not None.
polarizations: integer or string list
List of polarization integers or strings to read-in.
Ex: ['xx', 'yy', ...]
time_range: float list
len-2 list containing min and max range of times (Julian Date) to
read-in. Ex: [2458115.20, 2458115.40]
history : str
Extra history string to add to concatenated pseudo-Stokes visibility.
Returns
-------
uvdS : UVData object with pseudo-Stokes visibility
"""
# convert dset1 and dset2 to UVData objects if they are miriad files
if isinstance(dset1, pyuvdata.UVData) == False:
assert isinstance(dset1, (str, np.str)), \
"dset1 must be fed as a string or UVData object"
uvd1 = miriad2pyuvdata(dset1, antenna_nums=antenna_nums, bls=bls,
polarizations=polarizations, ant_str=ant_str,
time_range=time_range)
else:
uvd1 = dset1
if isinstance(dset2, pyuvdata.UVData) == False:
assert isinstance(dset2, (str, np.str)), \
"dset2 must be fed as a string or UVData object"
uvd2 = miriad2pyuvdata(dset2, antenna_nums=antenna_nums, bls=bls,
polarizations=polarizations, ant_str=ant_str,
time_range=time_range)
else:
uvd2 = dset2
# convert pstokes to integer if fed as a string
if isinstance(pstokes, (str, np.str)):
pstokes = pyuvdata.utils.polstr2num(pstokes, x_orientation=dset1.x_orientation)
# check if dset1 and dset2 habe the same spectral window
spw1 = uvd1.spw_array
spw2 = uvd2.spw_array
assert (spw1 == spw2), "dset1 and dset2 must have the same spectral windows."
# check if dset1 and dset2 have the same frequencies
freqs1 = uvd1.freq_array
freqs2 = uvd2.freq_array
if | np.array_equal(freqs1, freqs2) | numpy.array_equal |
from __future__ import print_function
'''
This module should be organized as follows:
Main function:
chi_estimate() = returns chi_n, chi_b
- calls:
wealth.get_wealth_data() - returns data moments on wealth distribution
labor.labor_data_moments() - returns data moments on labor supply
minstat() - returns min of statistical objective function
model_moments() - returns model moments
SS.run_SS() - return SS distributions
'''
'''
------------------------------------------------------------------------
Last updated: 7/27/2016
Uses a simulated method of moments to calibrate the chi_n adn chi_b
parameters of OG-USA.
This py-file calls the following other file(s):
wealth.get_wealth_data()
labor.labor_data_moments()
SS.run_SS
This py-file creates the following other file(s): None
------------------------------------------------------------------------
'''
import numpy as np
import scipy.optimize as opt
import pandas as pd
import os
try:
import cPickle as pickle
except ImportError:
import pickle
from . import wealth
from . import labor
from . import SS
from . import utils
from ogusa import aggregates as aggr
from ogusa import SS
def chi_n_func(s, a0, a1, a2, a3, a4):
chi_n = a0 + a1 * s + a2 * s ** 2 + a3 * s ** 3 + a4 * s ** 4
return chi_n
def chebyshev_func(x, a0, a1, a2, a3, a4):
func = np.polynomial.chebyshev.chebval(x, [a0, a1, a2, a3, a4])
return func
def chi_estimate(p, client=None):
'''
--------------------------------------------------------------------
This function calls others to obtain the data momements and then
runs the simulated method of moments estimation by calling the
minimization routine.
INPUTS:
income_tax_parameters = length 4 tuple, (analytical_mtrs, etr_params, mtrx_params, mtry_params)
ss_parameters = length 21 tuple, (J, S, T, BW, beta, sigma, alpha, Z, delta, ltilde, nu, g_y,\
g_n_ss, tau_payroll, retire, mean_income_data,\
h_wealth, p_wealth, m_wealth, b_ellipse, upsilon)
iterative_params = [2,] vector, vector with max iterations and tolerance
for SS solution
chi_guesses = [J+S,] vector, initial guesses of chi_b and chi_n stacked together
baseline_dir = string, path where baseline results located
OTHER FUNCTIONS AND FILES CALLED BY THIS FUNCTION:
wealth.compute_wealth_moments()
labor.labor_data_moments()
minstat()
OBJECTS CREATED WITHIN FUNCTION:
wealth_moments = [J+2,] array, wealth moments from data
labor_moments = [S,] array, labor moments from data
data_moments = [J+2+S,] array, wealth and labor moments stacked
bnds = [S+J,] array, bounds for parameter estimates
chi_guesses_flat = [J+S,] vector, initial guesses of chi_b and chi_n stacked
min_arg = length 6 tuple, variables needed for minimizer
est_output = dictionary, output from minimizer
chi_params = [J+S,] vector, parameters estimates for chi_b and chi_n stacked
objective_func_min = scalar, minimum of statistical objective function
OUTPUT:
./baseline_dir/Calibration/chi_estimation.pkl
RETURNS: chi_params
--------------------------------------------------------------------
'''
baseline_dir="./OUTPUT"
#chi_b_guess = np.ones(80)
# a0 = 5.38312524e+01
# a1 = -1.55746248e+00
# a2 = 1.77689237e-02
# a3 = -8.04751667e-06
# a4 = 5.65432019e-08
""" Kei's Vals
a0 = 170
a1 = -2.19154735e+00
a2 = -2.22817460e-02
a3 = 4.49993507e-04
a4 = -1.34197054e-06
"""
""" Adam's Vals 1
a0 = 2.59572155e+02
a1 = -2.35122641e+01
a2 = 4.27581467e-01
a3 = -3.40808933e-03
a4 = 1.00404321e-05
"""
a0 = 1.10807470e+03#5.19144310e+02
#a0 = 1.10807470e+03#5.19144310e+02
a1 = -1.05805189e+02#-4.70245283e+01
a2 = 1.92411660e+00#8.55162933e-01
a3 = -1.53364020e-02#-6.81617866e-03
a4 = 4.51819445e-05#2.00808642e-05
# a0 = 2.07381e+02
# a1 = -1.03143105e+01
# a2 = 1.42760562e-01
# a3 = -8.41089078e-04
# a4 = 1.85173227e-06
# sixty_plus_chi = 300
params_init = np.array([a0, a1, a2, a3, a4])
# Generate labor data moments
labor_hours = np.array([167, 165, 165, 165, 165, 166, 165, 165, 164])#, 166, 164])
labor_part_rate = np.array([0.69, 0.849, 0.849, 0.847, 0.847, 0.859, 0.859, 0.709, 0.709])#, 0.212, 0.212])
employ_rate = np.array([0.937, 0.954, 0.954, 0.966, 0.966, 0.97, 0.97, 0.968, 0.968])#, 0.978, 0.978])
labor_hours_adj = labor_hours * labor_part_rate * employ_rate
# get fraction of time endowment worked (assume time
# endowment is 24 hours minus required time to sleep 6.5 hours)
labor_moments = labor_hours_adj * 12 / (365 * 17.5)
#labor_moments[9] = 0.1
#labor_moments[10] = 0.1
# combine moments
data_moments = np.array(list(labor_moments.flatten()))
# weighting matrix
W = np.identity(p.J+2+p.S)
W = np.identity(9)
ages = np.linspace(20, 65, p.S // 2 + 5)
#ages = np.linspace(20, 100, p.S)
est_output = opt.minimize(minstat_init_calibrate, params_init,\
args=(p, client, data_moments, W, ages),\
method="L-BFGS-B",\
tol=1e-15, options={'eps': 0.1})
a0, a1, a2, a3, a4 = est_output.x
#chi_n = chebyshev_func(ages, a0, a1, a2, a3, a4)
chi_n = np.ones(p.S)
#ages_full = np.linspace(20, 100, p.S)
#chi_n = chebyshev_func(ages_full, a0, a1, a2, a3, a4)
chi_n[:p.S // 2 + 5] = chebyshev_func(ages, a0, a1, a2, a3, a4)
slope = 1500#chi_n[p.S // 2 + 5 - 1] - chi_n[p.S // 2 + 5 - 2]
chi_n[p.S // 2 + 5 - 1:] = (np.linspace(65, 100, 36) - 65) * slope + chi_n[p.S // 2 + 5 - 1]
chi_n[chi_n < 0.5] = 0.5
p.chi_n = chi_n
print('PARAMS for Chebyshev:', est_output.x)
with open("output.txt", "a") as text_file:
text_file.write('\nPARAMS for Chebyshev: ' + str(est_output.x) + '\n')
pickle.dump(chi_n, open("chi_n.p", "wb"))
ss_output = SS.run_SS(p)
return ss_output
def minstat_init_calibrate(params, *args):
a0, a1, a2, a3, a4 = params
p, client, data_moments, W, ages = args
chi_n = np.ones(p.S)
chi_n[:p.S // 2 + 5] = chebyshev_func(ages, a0, a1, a2, a3, a4)
slope = chi_n[p.S // 2 + 5 - 1] - chi_n[p.S // 2 + 5 - 2]
chi_n[p.S // 2 + 5 - 1:] = (np.linspace(65, 100, 36) - 65) * slope + chi_n[p.S // 2 + 5 - 1]
chi_n[chi_n < 0.5] = 0.5
p.chi_n = chi_n
print("-----------------------------------------------------")
print('PARAMS AT START' + str(params))
print("-----------------------------------------------------")
b_guess = np.ones((p.S, p.J)) * 0.07
n_guess = np.ones((p.S, p.J)) * .4 * p.ltilde
rguess = 0.09
T_Hguess = 0.12
factorguess = 7.7 #70000 # Modified
BQguess = aggr.get_BQ(rguess, b_guess, None, p, 'SS', False)
exit_early = [0, 2] # 2nd value gives number of valid labor moments to consider before exiting SS_fsolve
ss_params_baseline = (b_guess, n_guess, None, None, p, client, exit_early)
guesses = [rguess] + list(BQguess) + [T_Hguess, factorguess]
[solutions_fsolve, infodict, ier, message] =\
opt.fsolve(SS.SS_fsolve, guesses, args=ss_params_baseline,
xtol=p.mindist_SS, full_output=True)
rss = solutions_fsolve[0]
BQss = solutions_fsolve[1:-2]
T_Hss = solutions_fsolve[-2]
factor_ss = solutions_fsolve[-1]
Yss = T_Hss/p.alpha_T[-1]
fsolve_flag = True
try:
output = SS.SS_solver(b_guess, n_guess, rss, BQss, T_Hss,
factor_ss, Yss, p, client, fsolve_flag)
except:
print('RuntimeError: Steady state aggregate resource constraint not satisfied')
print('Luckily we caught the error, so minstat_init_calibrate will continue')
return 1e10
model_moments = calc_moments(output, p.omega_SS, p.lambdas, p.S, p.J)
print('Model moments:', model_moments)
print("-----------------------------------------------------")
distance = np.dot(np.dot((np.array(model_moments[:9]) - np.array(data_moments)).T,W),
np.array(model_moments[:9]) - np.array(data_moments))
print('DATA and MODEL DISTANCE: ', distance)
return distance
def minstat(params, *args):
'''
--------------------------------------------------------------------
This function generates the weighted sum of squared differences
between the model and data moments.
INPUTS:
chi_guesses = [J+S,] vector, initial guesses of chi_b and chi_n stacked together
arg = length 6 tuple, variables needed for minimizer
OTHER FUNCTIONS AND FILES CALLED BY THIS FUNCTION:
SS.run_SS()
calc_moments()
OBJECTS CREATED WITHIN FUNCTION:
ss_output = dictionary, variables from SS of model
model_moments = [J+2+S,] array, moments from the model solution
distance = scalar, weighted, squared deviation between data and model moments
RETURNS: distance
--------------------------------------------------------------------
'''
a0, a1, a2, a3, a4 = params
p, client, data_moments, W, ages = args
chi_n = np.ones(p.S)
#chi_n = chebyshev_func(ages, a0, a1, a2, a3, a4)
chi_n[:p.S // 2 + 5] = chebyshev_func(ages, a0, a1, a2, a3, a4)
#chi_n[p.S // 2 + 5:] = sixty_plus_chi
slope = chi_n[p.S // 2 + 5 - 1] - chi_n[p.S // 2 + 5 - 2]
chi_n[p.S // 2 + 5 - 1:] = (np.linspace(65, 100, 36) - 65) * slope + chi_n[p.S // 2 + 5 - 1]
chi_n[chi_n < 0.5] = 0.5
p.chi_n = chi_n
#print(chi_n)
#with open("output.txt", "a") as text_file:
# text_file.write('\nPARAMS AT START\n' + str(params) + '\n')
print("-----------------------------------------------------")
print('PARAMS AT START' + str(params))
print("-----------------------------------------------------")
try:
ss_output = SS.run_SS(p, client)
except:
#with open("output.txt", "a") as text_file:
# text_file.write('\nSteady state not found\n' + str(params) + '\n')
print("-----------------------------------------------------")
print("Steady state not found")
print("-----------------------------------------------------")
return 1e100
#with open("output.txt", "a") as text_file:
# text_file.write('\nPARAMS AT END\n' + str(params) + '\n')
print("-----------------------------------------------------")
print('PARAMS AT END', params)
print("-----------------------------------------------------")
model_moments = calc_moments(ss_output, p.omega_SS, p.lambdas, p.S, p.J)
#with open("output.txt", "a") as text_file:
# text_file.write('\nModel moments:\n' + str(model_moments) + '\n')
print('Model moments:', model_moments)
print("-----------------------------------------------------")
# distance with levels
distance = np.dot(np.dot((np.array(model_moments[:9]) - | np.array(data_moments) | numpy.array |
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import numpy as np
import time, re
import pandas as pd
import csv, math
from matplotlib import rc
import matplotlib.ticker as ticker
import matplotlib.pyplot as plt
from astropy.io import ascii
from scipy.optimize import curve_fit
from scipy.optimize import least_squares
from astropy.modeling import models, fitting
from astropy.stats import sigma_clip
from astropy.io import fits
from astropy.convolution import convolve, Gaussian1DKernel, Box1DKernel
from astropy.stats import LombScargle
from scipy.signal import savgol_filter as savgol
import matplotlib.gridspec as gridspec
from astropy.stats import mad_std
from scipy.stats import gaussian_kde
from mpl_toolkits.axes_grid1.axes_divider import make_axes_locatable
sample='astero'
if sample=='astero':
start=6135
if sample=='pande':
start=0
whitenoise=np.loadtxt('/Users/maryumsayeed/Desktop/HuberNess/mlearning/hrdmachine/whitenoisevalues.txt',skiprows=1,delimiter=',')
kpfile ='/Users/maryumsayeed/Desktop/HuberNess/mlearning/hrdmachine/KIC_Kepmag_Berger2018.csv'
df =pd.read_csv(kpfile,usecols=['KIC','kic_kepmag'])
kp_kics =list(df['KIC'])
allkps =list(df['kic_kepmag'])
def sigclip(x,y,subs,sig):
keep = np.zeros_like(x)
start=0
end=subs
nsubs=int((len(x)/subs)+1)
for i in range(0,nsubs):
me=np.mean(y[start:end])
sd=np.std(y[start:end])
good=np.where((y[start:end] > me-sig*sd) & (y[start:end] < me+sig*sd))[0]
keep[start:end][good]=1
start=start+subs
end=end+subs
return keep
def getclosest(num,collection):
'''Given a number and a list, get closest number in the list to number given.'''
return min(collection,key=lambda x:abs(x-num))
def getkp(file):
kic=re.search('kplr(.*)-', file).group(1)
kic=int(kic.lstrip('0'))
kp=allkps[kp_kics.index(kic)]
if kp in whitenoise[:,0]:
idx=np.where(whitenoise[:,0]==kp)[0]
closestkp=whitenoise[idx,0][0]
wnoise=whitenoise[idx,1][0]
#print(closestkp,wnoise)
else:
closestkp=getclosest(kp,whitenoise[:,0])
idx=np.where(whitenoise[:,0]==closestkp)[0]
wnoise=whitenoise[idx,1][0]
#print(closestkp,wnoise)
return wnoise
def getps(file,day):
data=fits.open(file)
head=data[0].data
dat=data[1].data
time=dat['TIME']
qual=dat['SAP_QUALITY']
flux=dat['PDCSAP_FLUX']
good=np.where(qual == 0)[0]
time=time[good]
flux=flux[good]
ndays=(time[-1]-time[0])/1.
time_1=time
flux_1=flux
#third=time[0]+ndays
#idx=np.where(time<third)[0]
#time=time[idx]
#flux=flux[idx]
#time_1=time
#flux_1=flux
# Duty cycle:
total_obs_time=ndays*24.*60 #mins
cadence =30. #mins
expected_points=total_obs_time/cadence
observed_points=len(flux)
# Only analyze stars with light curve duty cycle > 60%:
# if observed_points/expected_points<0.5:
# continue
res =sigclip(time,flux,50,3)
good=np.where(res == 1)[0]
time=time[good]
flux=flux[good]
time_2=time
flux_2=flux
width=day
boxsize=width/(30./60./24.)
box_kernel = Box1DKernel(boxsize)
smoothed_flux = savgol(flux,int(boxsize)-1,1,mode='mirror')
flux=flux/(smoothed_flux)
time_3=time
flux_3=smoothed_flux
# Remove data points > 3*sigma:
std=mad_std(flux,ignore_nan=True)
med=np.median(flux)
#idx =np.where(abs(flux-med)<3.*std)[0]
#time=time[idx]
#flux=flux[idx]
# now let's calculate the fourier transform. the nyquist frequency is:
nyq=1./(30./60./24.)
fres=1./90./0.0864
fres_cd=0.001
fres_mhz=fres_cd/0.0864
freq = np.arange(0.001, 24., 0.001)
#pdb.set_trace()
# FT magic
#freq, amp = LombScargle(time,flux).autopower(method='fast',samples_per_peak=10,maximum_frequency=nyq)
amp = LombScargle(time,flux).power(freq)
# unit conversions
freq = 1000.*freq/86.4
bin = freq[1]-freq[0]
amp = 2.*amp*np.var(flux*1e6)/(np.sum(amp)*bin)
# White noise correction:
wnoise=getkp(file)
amp1=np.zeros(len(amp))
for p in range(0,len(amp)):
a=amp[p]
if a-wnoise < 0.:
amp1[p]=amp[p]
if a-wnoise > 0.:
amp1[p]=a-wnoise
# smooth by 2 muHz
n=np.int(2./fres_mhz)
n_wnoise=np.int(2./fres_mhz)
gauss_kernel = Gaussian1DKernel(n)
gk_wnoise=Gaussian1DKernel(n_wnoise)
pssm = convolve(amp, gauss_kernel)
pssm_wnoise = convolve(amp1, gk_wnoise)
timeseries=[time_1,flux_1,time_2,flux_2,time_3,flux_3]
return timeseries,time,flux,freq,amp1,pssm,pssm_wnoise,wnoise
def gettraindata(text_files,pickle_files):
trainlabels=[]
alldata=[]
allpickledata=[]
allfiles=[]
star_count=0
data_lengths=[]
for i in range(0,len(text_files)):
print(i,'getting data from:',pickle_files[i])
labels=np.loadtxt(text_files[i],delimiter=' ',usecols=[1])
files=np.loadtxt(text_files[i],delimiter=' ',usecols=[0],dtype=str)
stars= len(labels)
data = np.memmap(pickle_files[i],dtype=np.float32,mode='r',shape=(21000,stars,3))
trainlabels.append(labels)
traindata=data[:,:,1].transpose()
alldata.append(traindata)
allfiles.append(files)
# data_lengths.append(stars)
star_count+=stars
print('Concatenating data...')
s1=time.time()
alldata=list(alldata[0])+list(alldata[1])+list(alldata[2])+list(alldata[3])+list(alldata[4])+list(alldata[5])+list(alldata[6])
labels=np.concatenate((trainlabels),axis=0)
allfiles=np.concatenate((allfiles),axis=0)
print(' ',time.time()-s1)
total_stars=star_count
return labels,alldata,total_stars,allfiles
def get_idx(files):
if sample=='astero':
fname='Astero_Catalogue.txt'
if sample=='pande':
fname='Pande_Catalogue.txt'
df=pd.read_csv(fname,index_col=False,delimiter=';')
df=df[df['Outlier']==0]
kics=np.array(df['KICID'])
true=np.array(df['True_Logg'])
pred=np.array(df['Inferred_Logg'])
rad=np.array(df['Radius'])
teff=np.array(df['Teff'])
# Get index of good stars using catalogue KICIDs:
good_index=[]
for i in range(len(files)):
file=files[i]
kic=re.search('kplr(.*)-', file).group(1)
kic=int(kic.lstrip('0'))
if kic in kics: # if kic in catalogue:
good_index.append(i)
print(len(kics),len(good_index))
return good_index
dirr='/Users/maryumsayeed/Desktop/HuberNess/mlearning/powerspectrum/jan2020_{}_sample/'.format(sample)
average=np.load(dirr+'average.npy')
end=len(average)
testlabels=np.load(dirr+'testlabels.npy')[start:]
print(len(testlabels))
labels_m1 =np.load(dirr+'labels_m1.npy')
labels_m2 =np.load(dirr+'labels_m2.npy')
spectra_m1=np.load(dirr+'spectra_m1.npy')
chi2_vals =np.load(dirr+'min_chi2.npy')
print('Size of saved data:',len(testlabels),len(average),len(labels_m1),len(labels_m2),len(spectra_m1))
dp='jan2020_pande_sample/'
da='jan2020_astero_sample/'
train_file_names =[dp+'pande_pickle_1',dp+'pande_pickle_2',dp+'pande_pickle_3',da+'astero_final_sample_1',da+'astero_final_sample_2',da+'astero_final_sample_3',da+'astero_final_sample_4']
train_file_pickle=[i+'_memmap.pickle' for i in train_file_names]
train_file_txt =[i+'.txt' for i in train_file_names]
print('Getting training data...')
all_labels,all_data,total_stars,all_files=gettraindata(train_file_txt,train_file_pickle)
all_labels,all_data,all_files=all_labels[start:start+end],all_data[start:start+end],all_files[start:start+end]
keep=get_idx(all_files)
true,labelm1,models,alldata,allfiles=testlabels,labels_m1,spectra_m1,all_data,all_files
print('Loading in data...')
alldata=np.array(alldata)[keep]
models=models[keep]
savedir='/Users/maryumsayeed/LLR_updates/Aug3/stars_with_high_radii/'
check_kics=pd.read_csv(savedir+'kics_with_high_radii.txt',names=['KIC'],skiprows=1)
check_kics=np.array(check_kics['KIC'])
if sample=='astero':
fname='Astero_Catalogue.txt'
if sample=='pande':
fname='Pande_Catalogue.txt'
df=pd.read_csv(fname,index_col=False,delimiter=';')
#df=df[df['Outlier']==0]
raw_kics=[]
raw_kics_idx=[]
for i in range(0,len(keep)):
file=allfiles[keep][i][0:-3]
kic=file.split('/')[-1].split('-')[0].split('kplr')[-1]
kic=int(kic.lstrip('0'))
if kic in check_kics:
raw_kics.append(kic)
raw_kics_idx.append(i)
print(len(raw_kics))
print(len(raw_kics_idx))
print(len(keep))
all_teffs=np.array(df['Teff'])
all_rads=np.array(df['Radius'])
all_lums=all_rads**2.*(all_teffs/5777.)**4.
wnoise_values=np.loadtxt('/Users/maryumsayeed/Desktop/HuberNess/mlearning/hrdmachine/whitenoisevalues.txt',skiprows=1,delimiter=',')
wnoise_kics=np.array(wnoise_values[:,0])
wnoise_values
for star in raw_kics_idx[0:200]:
file=allfiles[keep][star][0:-3]
timeseries,time,flux,f,amp,pssm,pssm_wnoise,wn=getps(file,1)
time_1,flux_1,time_2,flux_2,time_3,flux_3=timeseries
kic=file.split('/')[-1].split('-')[0].split('kplr')[-1]
kic=int(kic.lstrip('0'))
print(star,kic)
idx=np.where(df['KICID']==kic)[0]
t =np.array(df['Teff'])[idx][0]
r =np.array(df['Radius'])[idx][0]
l =r**2.*(t/5777.)**4.
kp= | np.array(df['Kp']) | numpy.array |
import pickle
import os
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
import math
from scipy import signal
objectRep = open("C:\\Users\\asus\\OneDrive\\BSC_brain_math\\year_c\\Yearly\\BCI\\bci4als\\recordings\\adi\\9\\trials.pickle", "rb")
file = pickle.load(objectRep)
all_data = np.zeros([len(file), 1230, 13])
sampling_rate = 125
fig, ax = plt.subplots(2,1, figsize=(16,4), sharey=True)
eeg = file[0]['C3']
time = np.arange(len(file[0]['C3']))/ sampling_rate
ax[0].plot(time, eeg, lw=1)
ax[0].set_xlabel('Time (sec)'), ax[0].set_ylabel('Voltage ($\mu$Volts)')
ax[0].set_xticks(np.arange(0, 10, 0.5))
ax[1].plot(time, eeg, lw=1, color='k')
ax[1].set_xlim(4.25,4.5)
#ax[1].set_xlim(12,14.5)
ax[1].set_xticks(np.arange(4.3,4.5,0.1))
ax[1].set_xlabel('Time (sec)')
FourierCoeff = | np.fft.fft(eeg) | numpy.fft.fft |
import math
import numpy as np
class Transform:
"""This class represents an 2D rotation, scaling, and translation."""
def __init__(self):
self.set_rotation(0.0)
self.set_translation(0.0, 0.0)
self.set_scale(1.0)
def set_rotation(self, rotation):
"""Calculate rotation matrix"""
self.rotation = rotation
cr = math.cos(self.rotation)
sr = math.sin(self.rotation)
self.rot_mat = np.array([[cr, -sr], [sr, cr]])
def set_translation(self, tx, ty):
self.translation = (tx, ty)
self.t_vec = np.array([[self.translation[0]], [self.translation[1]]])
def set_scale(self, scale):
self.scale = scale
def transform_point(self, p):
vec = np.array([[p[0]], [p[1]]])
transformed = (self.rot_mat @ vec) * self.scale + self.t_vec
return ( | np.asscalar(transformed[0]) | numpy.asscalar |
"""
Unit tests for meta/train/env.py.
"""
from itertools import product
from typing import Dict, List, Any, Tuple
import numpy as np
import torch
from meta.utils.storage import RolloutStorage
from meta.train.env import (
get_env,
get_base_env,
get_metaworld_ml_benchmark_names,
get_metaworld_benchmark_names,
)
from tests.helpers import get_policy, DEFAULT_SETTINGS
METAWORLD_OBS_GOAL_POS = 39
ROLLOUT_LENGTH = 128
TIME_LIMIT = 4
PROCESS_EPISODES = 5
TASK_EPISODES = 3
ENOUGH_THRESHOLD = 0.5
SINGLE_ENV_NAME = "reach-v2"
def test_collect_rollout_MT1_single() -> None:
"""
Test the values of the returned RolloutStorage objects collected from a rollout on
the MetaWorld MT1 benchmark, to ensure that the task indices are returned correctly
and goals are resampled correctly, with a single process.
"""
settings = dict(DEFAULT_SETTINGS)
settings["env_name"] = "MT1_%s" % SINGLE_ENV_NAME
settings["num_processes"] = 1
settings["rollout_length"] = ROLLOUT_LENGTH
settings["time_limit"] = TIME_LIMIT
settings["normalize_transition"] = False
settings["normalize_first_n"] = None
settings["same_np_seed"] = True
settings["save_memory"] = False
check_metaworld_rollout(settings)
def test_collect_rollout_MT1_single_normalize() -> None:
"""
Test the values of the returned RolloutStorage objects collected from a rollout on
the MetaWorld MT1 benchmark, to ensure that the task indices are returned correctly
and goals are resampled correctly, with a single process and observation
normalization.
"""
settings = dict(DEFAULT_SETTINGS)
settings["env_name"] = "MT1_%s" % SINGLE_ENV_NAME
settings["num_processes"] = 1
settings["rollout_length"] = ROLLOUT_LENGTH
settings["time_limit"] = TIME_LIMIT
settings["normalize_transition"] = True
settings["normalize_first_n"] = METAWORLD_OBS_GOAL_POS
settings["same_np_seed"] = True
settings["save_memory"] = False
check_metaworld_rollout(settings)
def test_collect_rollout_MT1_multi() -> None:
"""
Test the values of the returned RolloutStorage objects collected from a rollout on
the MetaWorld MT1 benchmark, to ensure that the task indices are returned correctly
and goals are resampled correctly, when running a multi-process environment.
"""
settings = dict(DEFAULT_SETTINGS)
settings["env_name"] = "MT1_%s" % SINGLE_ENV_NAME
settings["num_processes"] = 4
settings["rollout_length"] = ROLLOUT_LENGTH
settings["time_limit"] = TIME_LIMIT
settings["normalize_transition"] = False
settings["normalize_first_n"] = None
settings["same_np_seed"] = True
settings["save_memory"] = False
check_metaworld_rollout(settings)
def test_collect_rollout_MT1_multi_normalize() -> None:
"""
Test the values of the returned RolloutStorage objects collected from a rollout on
the MetaWorld MT1 benchmark, to ensure that the task indices are returned correctly
and goals are resampled correctly, when running a multi-process environment and
observation normalization.
"""
settings = dict(DEFAULT_SETTINGS)
settings["env_name"] = "MT1_%s" % SINGLE_ENV_NAME
settings["num_processes"] = 4
settings["rollout_length"] = ROLLOUT_LENGTH
settings["time_limit"] = TIME_LIMIT
settings["normalize_transition"] = True
settings["normalize_first_n"] = METAWORLD_OBS_GOAL_POS
settings["same_np_seed"] = True
settings["save_memory"] = False
check_metaworld_rollout(settings)
def test_collect_rollout_MT10_single() -> None:
"""
Test the values of the returned RolloutStorage objects collected from a rollout on
the MetaWorld MT10 benchmark, to ensure that the task indices are returned correctly
and tasks/goals are resampled correctly, with a single process.
"""
settings = dict(DEFAULT_SETTINGS)
settings["env_name"] = "MT10"
settings["num_processes"] = 1
settings["rollout_length"] = ROLLOUT_LENGTH
settings["time_limit"] = TIME_LIMIT
settings["normalize_transition"] = False
settings["normalize_first_n"] = None
settings["same_np_seed"] = True
settings["save_memory"] = False
check_metaworld_rollout(settings)
def test_collect_rollout_MT10_single_normalize() -> None:
"""
Test the values of the returned RolloutStorage objects collected from a rollout on
the MetaWorld MT10 benchmark, to ensure that the task indices are returned correctly
and tasks/goals are resampled correctly, with a single process and observation
normalization.
"""
settings = dict(DEFAULT_SETTINGS)
settings["env_name"] = "MT10"
settings["num_processes"] = 1
settings["rollout_length"] = ROLLOUT_LENGTH
settings["time_limit"] = TIME_LIMIT
settings["normalize_transition"] = True
settings["normalize_first_n"] = METAWORLD_OBS_GOAL_POS
settings["same_np_seed"] = True
settings["save_memory"] = False
check_metaworld_rollout(settings)
def test_collect_rollout_MT10_multi() -> None:
"""
Test the values of the returned RolloutStorage objects collected from a rollout on
the MetaWorld MT10 benchmark, to ensure that the task indices are returned correctly
and tasks/goals are resampled correctly, when running a multi-process environment.
"""
settings = dict(DEFAULT_SETTINGS)
settings["env_name"] = "MT10"
settings["num_processes"] = 4
settings["rollout_length"] = ROLLOUT_LENGTH
settings["time_limit"] = TIME_LIMIT
settings["normalize_transition"] = False
settings["normalize_first_n"] = None
settings["same_np_seed"] = True
settings["save_memory"] = False
check_metaworld_rollout(settings)
def test_collect_rollout_MT10_multi_normalize() -> None:
"""
Test the values of the returned RolloutStorage objects collected from a rollout on
the MetaWorld MT10 benchmark, to ensure that the task indices are returned correctly
and tasks/goals are resampled correctly, when running a multi-process environment
and observation normalization.
"""
settings = dict(DEFAULT_SETTINGS)
settings["env_name"] = "MT10"
settings["num_processes"] = 4
settings["rollout_length"] = ROLLOUT_LENGTH
settings["time_limit"] = TIME_LIMIT
settings["normalize_transition"] = True
settings["normalize_first_n"] = METAWORLD_OBS_GOAL_POS
settings["same_np_seed"] = True
settings["save_memory"] = False
check_metaworld_rollout(settings)
def test_collect_rollout_MT10_multi_save_memory() -> None:
"""
Test the values of the returned RolloutStorage objects collected from a rollout on
the MetaWorld MT10 benchmark, to ensure that the task indices are returned correctly
and tasks/goals are resampled correctly, when running a multi-process environment
with the `save_memory` option enabled.
"""
settings = dict(DEFAULT_SETTINGS)
settings["env_name"] = "MT10"
settings["num_processes"] = 4
settings["rollout_length"] = ROLLOUT_LENGTH
settings["time_limit"] = TIME_LIMIT
settings["normalize_transition"] = False
settings["normalize_first_n"] = None
settings["same_np_seed"] = True
settings["save_memory"] = True
check_metaworld_rollout(settings)
def test_collect_rollout_MT50_multi() -> None:
"""
Test the values of the returned RolloutStorage objects collected from a rollout on
the MetaWorld MT50 benchmark, to ensure that the task indices are returned correctly
and tasks/goals are resampled correctly, when running a multi-process environment.
"""
settings = dict(DEFAULT_SETTINGS)
settings["env_name"] = "MT50"
settings["num_processes"] = 4
settings["rollout_length"] = 8 * ROLLOUT_LENGTH
settings["time_limit"] = TIME_LIMIT
settings["normalize_transition"] = False
settings["normalize_first_n"] = None
settings["same_np_seed"] = True
settings["save_memory"] = False
check_metaworld_rollout(settings)
def test_collect_rollout_MT50_multi_save_memory() -> None:
"""
Test the values of the returned RolloutStorage objects collected from a rollout on
the MetaWorld MT50 benchmark, to ensure that the task indices are returned correctly
and tasks/goals are resampled correctly, when running a multi-process environment
with the `save_memory` option enabled.
"""
settings = dict(DEFAULT_SETTINGS)
settings["env_name"] = "MT50"
settings["num_processes"] = 4
settings["rollout_length"] = 8 * ROLLOUT_LENGTH
settings["time_limit"] = TIME_LIMIT
settings["normalize_transition"] = False
settings["normalize_first_n"] = None
settings["same_np_seed"] = True
settings["save_memory"] = True
check_metaworld_rollout(settings)
def test_collect_rollout_ML1_train_single() -> None:
"""
Test the values of the returned RolloutStorage objects collected from a rollout on
the MetaWorld ML1_train benchmark, to ensure that the task indices are returned
correctly and goals are resampled correctly, with a single process.
"""
settings = dict(DEFAULT_SETTINGS)
settings["env_name"] = "ML1_train_%s" % SINGLE_ENV_NAME
settings["num_processes"] = 1
settings["rollout_length"] = ROLLOUT_LENGTH
settings["time_limit"] = TIME_LIMIT
settings["normalize_transition"] = False
settings["normalize_first_n"] = None
settings["same_np_seed"] = False
settings["save_memory"] = False
check_metaworld_rollout(settings)
def test_collect_rollout_ML1_train_single_normalize() -> None:
"""
Test the values of the returned RolloutStorage objects collected from a rollout on
the MetaWorld ML1_train benchmark, to ensure that the task indices are returned
correctly and goals are resampled correctly, with a single process and observation
normalization.
"""
settings = dict(DEFAULT_SETTINGS)
settings["env_name"] = "ML1_train_%s" % SINGLE_ENV_NAME
settings["num_processes"] = 1
settings["rollout_length"] = ROLLOUT_LENGTH
settings["time_limit"] = TIME_LIMIT
settings["normalize_transition"] = True
settings["normalize_first_n"] = METAWORLD_OBS_GOAL_POS
settings["same_np_seed"] = False
settings["save_memory"] = False
check_metaworld_rollout(settings)
def test_collect_rollout_ML1_train_multi() -> None:
"""
Test the values of the returned RolloutStorage objects collected from a rollout on
the MetaWorld ML1_train benchmark, to ensure that the task indices are returned
correctly and goals are resampled correctly, when running a multi-process
environment.
"""
settings = dict(DEFAULT_SETTINGS)
settings["env_name"] = "ML1_train_%s" % SINGLE_ENV_NAME
settings["num_processes"] = 4
settings["rollout_length"] = ROLLOUT_LENGTH
settings["time_limit"] = TIME_LIMIT
settings["normalize_transition"] = False
settings["normalize_first_n"] = None
settings["same_np_seed"] = False
settings["save_memory"] = False
check_metaworld_rollout(settings)
def test_collect_rollout_ML1_train_multi_normalize() -> None:
"""
Test the values of the returned RolloutStorage objects collected from a rollout on
the MetaWorld ML1_train benchmark, to ensure that the task indices are returned
correctly and goals are resampled correctly, when running a multi-process
environment and observation normalization.
"""
settings = dict(DEFAULT_SETTINGS)
settings["env_name"] = "ML1_train_%s" % SINGLE_ENV_NAME
settings["num_processes"] = 4
settings["rollout_length"] = ROLLOUT_LENGTH
settings["time_limit"] = TIME_LIMIT
settings["normalize_transition"] = True
settings["normalize_first_n"] = METAWORLD_OBS_GOAL_POS
settings["same_np_seed"] = False
settings["save_memory"] = False
check_metaworld_rollout(settings)
def test_collect_rollout_ML1_test_single() -> None:
"""
Test the values of the returned RolloutStorage objects collected from a rollout on
the MetaWorld ML1_test benchmark, to ensure that the task indices are returned
correctly and goals are resampled correctly, with a single process.
"""
settings = dict(DEFAULT_SETTINGS)
settings["env_name"] = "ML1_test_%s" % SINGLE_ENV_NAME
settings["num_processes"] = 1
settings["rollout_length"] = ROLLOUT_LENGTH
settings["time_limit"] = TIME_LIMIT
settings["normalize_transition"] = False
settings["normalize_first_n"] = None
settings["same_np_seed"] = False
settings["save_memory"] = False
check_metaworld_rollout(settings)
def test_collect_rollout_ML1_test_single_normalize() -> None:
"""
Test the values of the returned RolloutStorage objects collected from a rollout on
the MetaWorld ML1_test benchmark, to ensure that the task indices are returned
correctly and goals are resampled correctly, with a single process and observation
normalization.
"""
settings = dict(DEFAULT_SETTINGS)
settings["env_name"] = "ML1_test_%s" % SINGLE_ENV_NAME
settings["num_processes"] = 1
settings["rollout_length"] = ROLLOUT_LENGTH
settings["time_limit"] = TIME_LIMIT
settings["normalize_transition"] = True
settings["normalize_first_n"] = METAWORLD_OBS_GOAL_POS
settings["same_np_seed"] = False
settings["save_memory"] = False
check_metaworld_rollout(settings)
def test_collect_rollout_ML1_test_multi() -> None:
"""
Test the values of the returned RolloutStorage objects collected from a rollout on
the MetaWorld ML1_test benchmark, to ensure that the task indices are returned
correctly and goals are resampled correctly, when running a multi-process
environment.
"""
settings = dict(DEFAULT_SETTINGS)
settings["env_name"] = "ML1_test_%s" % SINGLE_ENV_NAME
settings["num_processes"] = 4
settings["rollout_length"] = ROLLOUT_LENGTH
settings["time_limit"] = TIME_LIMIT
settings["normalize_transition"] = False
settings["normalize_first_n"] = None
settings["same_np_seed"] = False
settings["save_memory"] = False
check_metaworld_rollout(settings)
def test_collect_rollout_ML1_test_multi_normalize() -> None:
"""
Test the values of the returned RolloutStorage objects collected from a rollout on
the MetaWorld ML1_test benchmark, to ensure that the task indices are returned
correctly and goals are resampled correctly, when running a multi-process
environment and observation normalization.
"""
settings = dict(DEFAULT_SETTINGS)
settings["env_name"] = "ML1_test_%s" % SINGLE_ENV_NAME
settings["num_processes"] = 4
settings["rollout_length"] = ROLLOUT_LENGTH
settings["time_limit"] = TIME_LIMIT
settings["normalize_transition"] = True
settings["normalize_first_n"] = METAWORLD_OBS_GOAL_POS
settings["same_np_seed"] = False
settings["save_memory"] = False
check_metaworld_rollout(settings)
def test_collect_rollout_ML10_train_single() -> None:
"""
Test the values of the returned RolloutStorage objects collected from a rollout on
the MetaWorld ML10_train benchmark, to ensure that the task indices are returned
correctly and goals are resampled correctly, with a single process.
"""
settings = dict(DEFAULT_SETTINGS)
settings["env_name"] = "ML10_train"
settings["num_processes"] = 1
settings["rollout_length"] = ROLLOUT_LENGTH
settings["time_limit"] = TIME_LIMIT
settings["normalize_transition"] = False
settings["normalize_first_n"] = None
settings["same_np_seed"] = False
settings["save_memory"] = False
check_metaworld_rollout(settings)
def test_collect_rollout_ML10_train_single_normalize() -> None:
"""
Test the values of the returned RolloutStorage objects collected from a rollout on
the MetaWorld ML10_train benchmark, to ensure that the task indices are returned
correctly and goals are resampled correctly, with a single process and observation
normalization.
"""
settings = dict(DEFAULT_SETTINGS)
settings["env_name"] = "ML10_train"
settings["num_processes"] = 1
settings["rollout_length"] = ROLLOUT_LENGTH
settings["time_limit"] = TIME_LIMIT
settings["normalize_transition"] = True
settings["normalize_first_n"] = METAWORLD_OBS_GOAL_POS
settings["same_np_seed"] = False
settings["save_memory"] = False
check_metaworld_rollout(settings)
def test_collect_rollout_ML10_train_multi() -> None:
"""
Test the values of the returned RolloutStorage objects collected from a rollout on
the MetaWorld ML10_train benchmark, to ensure that the task indices are returned
correctly and goals are resampled correctly, when running a multi-process
environment.
"""
settings = dict(DEFAULT_SETTINGS)
settings["env_name"] = "ML10_train"
settings["num_processes"] = 4
settings["rollout_length"] = ROLLOUT_LENGTH
settings["time_limit"] = TIME_LIMIT
settings["normalize_transition"] = False
settings["normalize_first_n"] = None
settings["same_np_seed"] = False
settings["save_memory"] = False
check_metaworld_rollout(settings)
def test_collect_rollout_ML10_train_multi_normalize() -> None:
"""
Test the values of the returned RolloutStorage objects collected from a rollout on
the MetaWorld ML10_train benchmark, to ensure that the task indices are returned
correctly and goals are resampled correctly, when running a multi-process
environment and observation normalization.
"""
settings = dict(DEFAULT_SETTINGS)
settings["env_name"] = "ML10_train"
settings["num_processes"] = 4
settings["rollout_length"] = ROLLOUT_LENGTH
settings["time_limit"] = TIME_LIMIT
settings["normalize_transition"] = True
settings["normalize_first_n"] = METAWORLD_OBS_GOAL_POS
settings["same_np_seed"] = False
settings["save_memory"] = False
check_metaworld_rollout(settings)
def test_collect_rollout_ML10_test_single() -> None:
"""
Test the values of the returned RolloutStorage objects collected from a rollout on
the MetaWorld ML10_test benchmark, to ensure that the task indices are returned
correctly and goals are resampled correctly, with a single process.
"""
settings = dict(DEFAULT_SETTINGS)
settings["env_name"] = "ML10_test"
settings["num_processes"] = 1
settings["rollout_length"] = ROLLOUT_LENGTH
settings["time_limit"] = TIME_LIMIT
settings["normalize_transition"] = False
settings["normalize_first_n"] = None
settings["same_np_seed"] = False
settings["save_memory"] = False
check_metaworld_rollout(settings)
def test_collect_rollout_ML10_test_single_normalize() -> None:
"""
Test the values of the returned RolloutStorage objects collected from a rollout on
the MetaWorld ML10_test benchmark, to ensure that the task indices are returned
correctly and goals are resampled correctly, with a single process and observation
normalization.
"""
settings = dict(DEFAULT_SETTINGS)
settings["env_name"] = "ML10_test"
settings["num_processes"] = 1
settings["rollout_length"] = ROLLOUT_LENGTH
settings["time_limit"] = TIME_LIMIT
settings["normalize_transition"] = True
settings["normalize_first_n"] = METAWORLD_OBS_GOAL_POS
settings["same_np_seed"] = False
settings["save_memory"] = False
check_metaworld_rollout(settings)
def test_collect_rollout_ML10_test_multi() -> None:
"""
Test the values of the returned RolloutStorage objects collected from a rollout on
the MetaWorld ML10_test benchmark, to ensure that the task indices are returned
correctly and goals are resampled correctly, when running a multi-process
environment.
"""
settings = dict(DEFAULT_SETTINGS)
settings["env_name"] = "ML10_test"
settings["num_processes"] = 4
settings["rollout_length"] = ROLLOUT_LENGTH
settings["time_limit"] = TIME_LIMIT
settings["normalize_transition"] = False
settings["normalize_first_n"] = None
settings["same_np_seed"] = False
settings["save_memory"] = False
check_metaworld_rollout(settings)
def test_collect_rollout_ML10_test_multi_normalize() -> None:
"""
Test the values of the returned RolloutStorage objects collected from a rollout on
the MetaWorld ML10_test benchmark, to ensure that the task indices are returned
correctly and goals are resampled correctly, when running a multi-process
environment and observation normalization.
"""
settings = dict(DEFAULT_SETTINGS)
settings["env_name"] = "ML10_test"
settings["num_processes"] = 4
settings["rollout_length"] = ROLLOUT_LENGTH
settings["time_limit"] = TIME_LIMIT
settings["normalize_transition"] = True
settings["normalize_first_n"] = METAWORLD_OBS_GOAL_POS
settings["same_np_seed"] = False
settings["save_memory"] = False
check_metaworld_rollout(settings)
def test_collect_rollout_ML45_train_multi() -> None:
"""
Test the values of the returned RolloutStorage objects collected from a rollout on
the MetaWorld ML45_train benchmark, to ensure that the task indices are returned
correctly and goals are resampled correctly, when running a multi-process
environment.
"""
settings = dict(DEFAULT_SETTINGS)
settings["env_name"] = "ML45_train"
settings["num_processes"] = 4
settings["rollout_length"] = 8 * ROLLOUT_LENGTH
settings["time_limit"] = TIME_LIMIT
settings["normalize_transition"] = False
settings["normalize_first_n"] = None
settings["same_np_seed"] = False
settings["save_memory"] = False
check_metaworld_rollout(settings)
def test_collect_rollout_ML45_train_multi_save_memory() -> None:
"""
Test the values of the returned RolloutStorage objects collected from a rollout on
the MetaWorld ML45_train benchmark, to ensure that the task indices are returned
correctly and goals are resampled correctly, when running a multi-process
environment and with the `save_memory` option enabled.
"""
settings = dict(DEFAULT_SETTINGS)
settings["env_name"] = "ML45_train"
settings["num_processes"] = 4
settings["rollout_length"] = 8 * ROLLOUT_LENGTH
settings["time_limit"] = TIME_LIMIT
settings["normalize_transition"] = False
settings["normalize_first_n"] = None
settings["same_np_seed"] = False
settings["save_memory"] = True
check_metaworld_rollout(settings)
def test_collect_rollout_ML45_test_multi() -> None:
"""
Test the values of the returned RolloutStorage objects collected from a rollout on
the MetaWorld ML45_train benchmark, to ensure that the task indices are returned
correctly and goals are resampled correctly, when running a multi-process
environment.
"""
settings = dict(DEFAULT_SETTINGS)
settings["env_name"] = "ML45_test"
settings["num_processes"] = 4
settings["rollout_length"] = ROLLOUT_LENGTH
settings["time_limit"] = TIME_LIMIT
settings["normalize_transition"] = False
settings["normalize_first_n"] = None
settings["same_np_seed"] = False
settings["save_memory"] = False
check_metaworld_rollout(settings)
def test_collect_rollout_ML45_test_multi_save_memory() -> None:
"""
Test the values of the returned RolloutStorage objects collected from a rollout on
the MetaWorld ML45_train benchmark, to ensure that the task indices are returned
correctly and goals are resampled correctly, when running a multi-process
environment and with the `save_memory` option enabled.
"""
settings = dict(DEFAULT_SETTINGS)
settings["env_name"] = "ML45_test"
settings["num_processes"] = 4
settings["rollout_length"] = ROLLOUT_LENGTH
settings["time_limit"] = TIME_LIMIT
settings["normalize_transition"] = False
settings["normalize_first_n"] = None
settings["same_np_seed"] = False
settings["save_memory"] = True
check_metaworld_rollout(settings)
def check_metaworld_rollout(settings: Dict[str, Any]) -> None:
"""
Verify that rollouts on MetaWorld benchmarks satisfy a few assumptions:
- If running a multi-task benchmark, each observation is a vector with length at
least 39, and the elements after 39 form a one-hot vector with length equal to the
number of tasks denoting the task index. The task denoted by the one-hot vector
changes when we encounter a done=True, and only then. Also, each process should
resample tasks each episode, and the sequence of tasks sampled by each process
should be different.
- Goals for a single task are fixed within episodes and either resampled each
episode (meta learning benchmarks) or fixed across episodes (multi task learning
benchmarks). Also, the initial placement of objects is fixed across episodes
(multi task learning benchmarks) or resampled each episode (meta learning
benchmarks).
- Initial hand positions are identical between episodes from the same task.
"""
# Check if we are running a multi-task benchmark.
mt_benchmarks = get_metaworld_benchmark_names()
multitask = settings["env_name"] in mt_benchmarks
# Determine whether or not goals should be resampled.
ml_benchmarks = get_metaworld_ml_benchmark_names()
resample_goals = settings["env_name"] in ml_benchmarks or settings[
"env_name"
].startswith("ML1_")
settings["add_observability"] = resample_goals
# Perform rollout.
rollout = get_metaworld_rollout(settings)
# Check task indices and task resampling, if necessary.
if multitask:
task_check(rollout)
# Check goal resampling and initial observations, if necessary. We don't check this
# in the case that observations are normalized, because in this case the same
# goal/observation will look different on separate transitions due to varying
# normalization statistics.
check_goals = not settings["normalize_transition"]
if check_goals:
goal_check(rollout, resample_goals, multitask)
initial_hand_check(rollout, multitask)
def get_metaworld_rollout(
settings: Dict[str, Any]
) -> Tuple[RolloutStorage, np.ndarray]:
"""
Execute and return a single rollout over a MetaWorld environment using configuration
in `settings`.
"""
# Construct environment and policy.
env = get_env(
settings["env_name"],
num_processes=settings["num_processes"],
seed=settings["seed"],
time_limit=settings["time_limit"],
normalize_transition=settings["normalize_transition"],
normalize_first_n=settings["normalize_first_n"],
allow_early_resets=True,
same_np_seed=settings["same_np_seed"],
add_observability=settings["add_observability"],
save_memory=settings["save_memory"],
)
policy = get_policy(env, settings)
rollout = RolloutStorage(
rollout_length=settings["rollout_length"],
observation_space=env.observation_space,
action_space=env.action_space,
num_processes=settings["num_processes"],
hidden_state_size=1,
device=settings["device"],
)
rollout.set_initial_obs(env.reset())
# Collect rollout.
for rollout_step in range(rollout.rollout_length):
# Sample actions.
with torch.no_grad():
values, actions, action_log_probs, hidden_states = policy.act(
rollout.obs[rollout_step],
rollout.hidden_states[rollout_step],
rollout.dones[rollout_step],
)
# Perform step and record in ``rollout``.
obs, rewards, dones, infos = env.step(actions)
rollout.add_step(
obs, actions, dones, action_log_probs, values, rewards, hidden_states
)
env.close()
return rollout
def task_check(rollout: RolloutStorage) -> None:
"""
Given a rollout, checks that task indices are returned from observations correctly
and that tasks are resampled correctly within and between processes.
"""
# Get initial task indices.
task_indices = get_task_indices(rollout.obs[0])
episode_tasks = {
process: [task_indices[process]] for process in range(rollout.num_processes)
}
# Check if rollout satisfies conditions at each step.
for step in range(rollout.rollout_step):
# Get information from step.
obs = rollout.obs[step]
dones = rollout.dones[step]
assert len(obs) == len(dones)
new_task_indices = get_task_indices(obs)
# Make sure that task indices are the same if we haven't reached a done,
# otherwise set new task indices. Also track tasks attempted for each process.
for process in range(len(obs)):
done = dones[process]
if done:
task_indices[process] = new_task_indices[process]
episode_tasks[process].append(task_indices[process])
else:
assert task_indices[process] == new_task_indices[process]
# Check that each process is resampling tasks.
enough_ratio = sum(
len(tasks) >= PROCESS_EPISODES for tasks in episode_tasks.values()
) / len(episode_tasks)
if enough_ratio < ENOUGH_THRESHOLD:
raise ValueError(
"Less than %d episodes ran for more than half of processes, which is the"
" minimum amount needed for testing. Try increasing rollout length."
% (PROCESS_EPISODES)
)
for process, tasks in episode_tasks.items():
if len(tasks) >= PROCESS_EPISODES:
num_unique_tasks = len(set(tasks))
assert num_unique_tasks > 1
# Check that each process has distinct sequences of tasks.
for p1, p2 in product(range(rollout.num_processes), range(rollout.num_processes)):
if p1 == p2:
continue
assert episode_tasks[p1] != episode_tasks[p2]
print("\nTasks for each process: %s" % episode_tasks)
def goal_check(rollout: RolloutStorage, resample_goals: bool, multitask: bool) -> None:
"""
Given a rollout, checks that goals and initial object positions are resampled
correctly within and between processes.
"""
# Get initial goals.
task_indices = (
get_task_indices(rollout.obs[0]) if multitask else [0] * rollout.num_processes
)
goals = get_goals(rollout.obs[0])
episode_goals = {
task_indices[process]: [goals[process]]
for process in range(rollout.num_processes)
}
# Get initial object placements.
object_pos = get_object_pos(rollout.obs[0])
episode_object_pos = {
task_indices[process]: [object_pos[process]]
for process in range(rollout.num_processes)
}
# Check if rollout satisfies conditions at each step.
for step in range(rollout.rollout_step):
# Get information from step.
obs = rollout.obs[step]
dones = rollout.dones[step]
assert len(obs) == len(dones)
task_indices = (
get_task_indices(obs) if multitask else [0] * rollout.num_processes
)
new_goals = get_goals(obs)
new_object_pos = get_object_pos(obs)
# Make sure that goal is the same if we haven't reached a done or if goal should
# remain fixed across episodes, otherwise set new goal.
for process in range(len(obs)):
done = dones[process]
if done and (resample_goals or multitask):
goals[process] = new_goals[process]
else:
assert (goals[process] == new_goals[process]).all()
# Track goals and initial object positions from each task.
if done:
task = task_indices[process]
if task not in episode_goals:
episode_goals[task] = []
episode_goals[task].append(goals[process])
if task not in episode_object_pos:
episode_object_pos[task] = []
episode_object_pos[task].append(new_object_pos[process])
# Check that each task is resampling goals and initial object positions, if
# necessary.
enough_ratio = sum(
len(task_goals) >= TASK_EPISODES for task_goals in episode_goals.values()
) / len(episode_goals)
if enough_ratio < ENOUGH_THRESHOLD:
raise ValueError(
"Less than %d episodes ran for more than half of tasks, which is the"
"minimum amount needed for testing. Try increasing rollout length."
% (TASK_EPISODES)
)
for task, task_goals in episode_goals.items():
if len(task_goals) >= TASK_EPISODES:
goals_arr = np.array([g.numpy() for g in task_goals])
num_unique_goals = len(np.unique(goals_arr, axis=0))
if resample_goals:
assert num_unique_goals > 1
else:
assert num_unique_goals == 1
for task, task_object_pos in episode_object_pos.items():
if len(task_object_pos) >= TASK_EPISODES:
object_pos_arr = np.array([p.numpy() for p in task_object_pos])
num_unique_pos = len( | np.unique(object_pos_arr, axis=0) | numpy.unique |
# This module has been generated automatically from space group information
# obtained from the Computational Crystallography Toolbox
#
"""
Space groups
This module contains a list of all the 230 space groups that can occur in
a crystal. The variable space_groups contains a dictionary that maps
space group numbers and space group names to the corresponding space
group objects.
.. moduleauthor:: <NAME> <<EMAIL>>
"""
#-----------------------------------------------------------------------------
# Copyright (C) 2013 The Mosaic Development Team
#
# Distributed under the terms of the BSD License. The full license is in
# the file LICENSE.txt, distributed as part of this software.
#-----------------------------------------------------------------------------
import numpy as N
class SpaceGroup(object):
"""
Space group
All possible space group objects are created in this module. Other
modules should access these objects through the dictionary
space_groups rather than create their own space group objects.
"""
def __init__(self, number, symbol, transformations):
"""
:param number: the number assigned to the space group by
international convention
:type number: int
:param symbol: the Hermann-Mauguin space-group symbol as used
in PDB and mmCIF files
:type symbol: str
:param transformations: a list of space group transformations,
each consisting of a tuple of three
integer arrays (rot, tn, td), where
rot is the rotation matrix and tn/td
are the numerator and denominator of the
translation vector. The transformations
are defined in fractional coordinates.
:type transformations: list
"""
self.number = number
self.symbol = symbol
self.transformations = transformations
self.transposed_rotations = N.array([N.transpose(t[0])
for t in transformations])
self.phase_factors = N.exp(N.array([(-2j*N.pi*t[1])/t[2]
for t in transformations]))
def __repr__(self):
return "SpaceGroup(%d, %s)" % (self.number, repr(self.symbol))
def __len__(self):
"""
:return: the number of space group transformations
:rtype: int
"""
return len(self.transformations)
def symmetryEquivalentMillerIndices(self, hkl):
"""
:param hkl: a set of Miller indices
:type hkl: Scientific.N.array_type
:return: a tuple (miller_indices, phase_factor) of two arrays
of length equal to the number of space group
transformations. miller_indices contains the Miller
indices of each reflection equivalent by symmetry to the
reflection hkl (including hkl itself as the first element).
phase_factor contains the phase factors that must be applied
to the structure factor of reflection hkl to obtain the
structure factor of the symmetry equivalent reflection.
:rtype: tuple
"""
hkls = N.dot(self.transposed_rotations, hkl)
p = N.multiply.reduce(self.phase_factors**hkl, -1)
return hkls, p
space_groups = {}
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(1, 'P 1', transformations)
space_groups[1] = sg
space_groups['P 1'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(2, 'P -1', transformations)
space_groups[2] = sg
space_groups['P -1'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(3, 'P 1 2 1', transformations)
space_groups[3] = sg
space_groups['P 1 2 1'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(4, 'P 1 21 1', transformations)
space_groups[4] = sg
space_groups['P 1 21 1'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(5, 'C 1 2 1', transformations)
space_groups[5] = sg
space_groups['C 1 2 1'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(6, 'P 1 m 1', transformations)
space_groups[6] = sg
space_groups['P 1 m 1'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(7, 'P 1 c 1', transformations)
space_groups[7] = sg
space_groups['P 1 c 1'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(8, 'C 1 m 1', transformations)
space_groups[8] = sg
space_groups['C 1 m 1'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(9, 'C 1 c 1', transformations)
space_groups[9] = sg
space_groups['C 1 c 1'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(10, 'P 1 2/m 1', transformations)
space_groups[10] = sg
space_groups['P 1 2/m 1'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(11, 'P 1 21/m 1', transformations)
space_groups[11] = sg
space_groups['P 1 21/m 1'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(12, 'C 1 2/m 1', transformations)
space_groups[12] = sg
space_groups['C 1 2/m 1'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(13, 'P 1 2/c 1', transformations)
space_groups[13] = sg
space_groups['P 1 2/c 1'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(14, 'P 1 21/c 1', transformations)
space_groups[14] = sg
space_groups['P 1 21/c 1'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(15, 'C 1 2/c 1', transformations)
space_groups[15] = sg
space_groups['C 1 2/c 1'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(16, 'P 2 2 2', transformations)
space_groups[16] = sg
space_groups['P 2 2 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(17, 'P 2 2 21', transformations)
space_groups[17] = sg
space_groups['P 2 2 21'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(18, 'P 21 21 2', transformations)
space_groups[18] = sg
space_groups['P 21 21 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(19, 'P 21 21 21', transformations)
space_groups[19] = sg
space_groups['P 21 21 21'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(20, 'C 2 2 21', transformations)
space_groups[20] = sg
space_groups['C 2 2 21'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(21, 'C 2 2 2', transformations)
space_groups[21] = sg
space_groups['C 2 2 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(22, 'F 2 2 2', transformations)
space_groups[22] = sg
space_groups['F 2 2 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(23, 'I 2 2 2', transformations)
space_groups[23] = sg
space_groups['I 2 2 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(24, 'I 21 21 21', transformations)
space_groups[24] = sg
space_groups['I 21 21 21'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(25, 'P m m 2', transformations)
space_groups[25] = sg
space_groups['P m m 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(26, 'P m c 21', transformations)
space_groups[26] = sg
space_groups['P m c 21'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(27, 'P c c 2', transformations)
space_groups[27] = sg
space_groups['P c c 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(28, 'P m a 2', transformations)
space_groups[28] = sg
space_groups['P m a 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(29, 'P c a 21', transformations)
space_groups[29] = sg
space_groups['P c a 21'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(30, 'P n c 2', transformations)
space_groups[30] = sg
space_groups['P n c 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(31, 'P m n 21', transformations)
space_groups[31] = sg
space_groups['P m n 21'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(32, 'P b a 2', transformations)
space_groups[32] = sg
space_groups['P b a 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(33, 'P n a 21', transformations)
space_groups[33] = sg
space_groups['P n a 21'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(34, 'P n n 2', transformations)
space_groups[34] = sg
space_groups['P n n 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(35, 'C m m 2', transformations)
space_groups[35] = sg
space_groups['C m m 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(36, 'C m c 21', transformations)
space_groups[36] = sg
space_groups['C m c 21'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(37, 'C c c 2', transformations)
space_groups[37] = sg
space_groups['C c c 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(38, 'A m m 2', transformations)
space_groups[38] = sg
space_groups['A m m 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(39, 'A b m 2', transformations)
space_groups[39] = sg
space_groups['A b m 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(40, 'A m a 2', transformations)
space_groups[40] = sg
space_groups['A m a 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(41, 'A b a 2', transformations)
space_groups[41] = sg
space_groups['A b a 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(42, 'F m m 2', transformations)
space_groups[42] = sg
space_groups['F m m 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([3,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([3,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([3,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([3,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(43, 'F d d 2', transformations)
space_groups[43] = sg
space_groups['F d d 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(44, 'I m m 2', transformations)
space_groups[44] = sg
space_groups['I m m 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(45, 'I b a 2', transformations)
space_groups[45] = sg
space_groups['I b a 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(46, 'I m a 2', transformations)
space_groups[46] = sg
space_groups['I m a 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(47, 'P m m m', transformations)
space_groups[47] = sg
space_groups['P m m m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(48, 'P n n n :2', transformations)
space_groups[48] = sg
space_groups['P n n n :2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(49, 'P c c m', transformations)
space_groups[49] = sg
space_groups['P c c m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(50, 'P b a n :2', transformations)
space_groups[50] = sg
space_groups['P b a n :2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(51, 'P m m a', transformations)
space_groups[51] = sg
space_groups['P m m a'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(52, 'P n n a', transformations)
space_groups[52] = sg
space_groups['P n n a'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(53, 'P m n a', transformations)
space_groups[53] = sg
space_groups['P m n a'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(54, 'P c c a', transformations)
space_groups[54] = sg
space_groups['P c c a'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(55, 'P b a m', transformations)
space_groups[55] = sg
space_groups['P b a m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(56, 'P c c n', transformations)
space_groups[56] = sg
space_groups['P c c n'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(57, 'P b c m', transformations)
space_groups[57] = sg
space_groups['P b c m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(58, 'P n n m', transformations)
space_groups[58] = sg
space_groups['P n n m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(59, 'P m m n :2', transformations)
space_groups[59] = sg
space_groups['P m m n :2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(60, 'P b c n', transformations)
space_groups[60] = sg
space_groups['P b c n'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(61, 'P b c a', transformations)
space_groups[61] = sg
space_groups['P b c a'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(62, 'P n m a', transformations)
space_groups[62] = sg
space_groups['P n m a'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(63, 'C m c m', transformations)
space_groups[63] = sg
space_groups['C m c m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(64, 'C m c a', transformations)
space_groups[64] = sg
space_groups['C m c a'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(65, 'C m m m', transformations)
space_groups[65] = sg
space_groups['C m m m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(66, 'C c c m', transformations)
space_groups[66] = sg
space_groups['C c c m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(67, 'C m m a', transformations)
space_groups[67] = sg
space_groups['C m m a'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(68, 'C c c a :2', transformations)
space_groups[68] = sg
space_groups['C c c a :2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(69, 'F m m m', transformations)
space_groups[69] = sg
space_groups['F m m m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([4,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([4,4,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([4,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([4,4,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,3,3])
trans_den = N.array([1,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([4,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,3,1])
trans_den = N.array([4,4,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,1,1])
trans_den = N.array([4,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,1,1])
trans_den = N.array([4,4,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([2,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([3,0,3])
trans_den = N.array([4,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([3,1,1])
trans_den = N.array([4,4,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,-1,1])
trans_den = N.array([2,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([4,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,-1,1])
trans_den = N.array([4,4,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,3,1])
trans_den = N.array([2,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([3,1,1])
trans_den = N.array([4,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([3,3,0])
trans_den = N.array([4,4,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,-1])
trans_den = N.array([2,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,-1])
trans_den = N.array([4,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([4,4,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(70, 'F d d d :2', transformations)
space_groups[70] = sg
space_groups['F d d d :2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(71, 'I m m m', transformations)
space_groups[71] = sg
space_groups['I m m m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(72, 'I b a m', transformations)
space_groups[72] = sg
space_groups['I b a m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(73, 'I b c a', transformations)
space_groups[73] = sg
space_groups['I b c a'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(74, 'I m m a', transformations)
space_groups[74] = sg
space_groups['I m m a'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(75, 'P 4', transformations)
space_groups[75] = sg
space_groups['P 4'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,3])
trans_den = N.array([1,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(76, 'P 41', transformations)
space_groups[76] = sg
space_groups['P 41'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(77, 'P 42', transformations)
space_groups[77] = sg
space_groups['P 42'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,3])
trans_den = N.array([1,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(78, 'P 43', transformations)
space_groups[78] = sg
space_groups['P 43'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(79, 'I 4', transformations)
space_groups[79] = sg
space_groups['I 4'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,3])
trans_den = N.array([2,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,3])
trans_den = N.array([2,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,5])
trans_den = N.array([1,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,5])
trans_den = N.array([1,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(80, 'I 41', transformations)
space_groups[80] = sg
space_groups['I 41'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(81, 'P -4', transformations)
space_groups[81] = sg
space_groups['P -4'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(82, 'I -4', transformations)
space_groups[82] = sg
space_groups['I -4'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(83, 'P 4/m', transformations)
space_groups[83] = sg
space_groups['P 4/m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(84, 'P 42/m', transformations)
space_groups[84] = sg
space_groups['P 42/m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(85, 'P 4/n :2', transformations)
space_groups[85] = sg
space_groups['P 4/n :2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(86, 'P 42/n :2', transformations)
space_groups[86] = sg
space_groups['P 42/n :2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(87, 'I 4/m', transformations)
space_groups[87] = sg
space_groups['I 4/m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-3,-3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([3,5,5])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([3,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,-1,-1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(88, 'I 41/a :2', transformations)
space_groups[88] = sg
space_groups['I 41/a :2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(89, 'P 4 2 2', transformations)
space_groups[89] = sg
space_groups['P 4 2 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(90, 'P 4 21 2', transformations)
space_groups[90] = sg
space_groups['P 4 21 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,3])
trans_den = N.array([1,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,3])
trans_den = N.array([1,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,4])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(91, 'P 41 2 2', transformations)
space_groups[91] = sg
space_groups['P 41 2 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([2,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([2,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(92, 'P 41 21 2', transformations)
space_groups[92] = sg
space_groups['P 41 21 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(93, 'P 42 2 2', transformations)
space_groups[93] = sg
space_groups['P 42 2 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(94, 'P 42 21 2', transformations)
space_groups[94] = sg
space_groups['P 42 21 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,3])
trans_den = N.array([1,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,3])
trans_den = N.array([1,1,4])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(95, 'P 43 2 2', transformations)
space_groups[95] = sg
space_groups['P 43 2 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([2,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([2,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(96, 'P 43 21 2', transformations)
space_groups[96] = sg
space_groups['P 43 21 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(97, 'I 4 2 2', transformations)
space_groups[97] = sg
space_groups['I 4 2 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,3])
trans_den = N.array([2,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,3])
trans_den = N.array([2,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,3])
trans_den = N.array([2,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,3])
trans_den = N.array([2,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,5])
trans_den = N.array([1,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,5])
trans_den = N.array([1,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,5])
trans_den = N.array([1,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,5])
trans_den = N.array([1,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(98, 'I 41 2 2', transformations)
space_groups[98] = sg
space_groups['I 41 2 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(99, 'P 4 m m', transformations)
space_groups[99] = sg
space_groups['P 4 m m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(100, 'P 4 b m', transformations)
space_groups[100] = sg
space_groups['P 4 b m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(101, 'P 42 c m', transformations)
space_groups[101] = sg
space_groups['P 42 c m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(102, 'P 42 n m', transformations)
space_groups[102] = sg
space_groups['P 42 n m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(103, 'P 4 c c', transformations)
space_groups[103] = sg
space_groups['P 4 c c'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(104, 'P 4 n c', transformations)
space_groups[104] = sg
space_groups['P 4 n c'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(105, 'P 42 m c', transformations)
space_groups[105] = sg
space_groups['P 42 m c'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(106, 'P 42 b c', transformations)
space_groups[106] = sg
space_groups['P 42 b c'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(107, 'I 4 m m', transformations)
space_groups[107] = sg
space_groups['I 4 m m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(108, 'I 4 c m', transformations)
space_groups[108] = sg
space_groups['I 4 c m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,3])
trans_den = N.array([2,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,3])
trans_den = N.array([2,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,3])
trans_den = N.array([2,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,3])
trans_den = N.array([2,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,5])
trans_den = N.array([1,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,5])
trans_den = N.array([1,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,5])
trans_den = N.array([1,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,5])
trans_den = N.array([1,2,4])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(109, 'I 41 m d', transformations)
space_groups[109] = sg
space_groups['I 41 m d'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,3])
trans_den = N.array([2,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,3])
trans_den = N.array([2,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,5])
trans_den = N.array([1,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,5])
trans_den = N.array([1,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([1,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([1,2,4])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(110, 'I 41 c d', transformations)
space_groups[110] = sg
space_groups['I 41 c d'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(111, 'P -4 2 m', transformations)
space_groups[111] = sg
space_groups['P -4 2 m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(112, 'P -4 2 c', transformations)
space_groups[112] = sg
space_groups['P -4 2 c'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(113, 'P -4 21 m', transformations)
space_groups[113] = sg
space_groups['P -4 21 m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(114, 'P -4 21 c', transformations)
space_groups[114] = sg
space_groups['P -4 21 c'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(115, 'P -4 m 2', transformations)
space_groups[115] = sg
space_groups['P -4 m 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(116, 'P -4 c 2', transformations)
space_groups[116] = sg
space_groups['P -4 c 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(117, 'P -4 b 2', transformations)
space_groups[117] = sg
space_groups['P -4 b 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(118, 'P -4 n 2', transformations)
space_groups[118] = sg
space_groups['P -4 n 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(119, 'I -4 m 2', transformations)
space_groups[119] = sg
space_groups['I -4 m 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(120, 'I -4 c 2', transformations)
space_groups[120] = sg
space_groups['I -4 c 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(121, 'I -4 2 m', transformations)
space_groups[121] = sg
space_groups['I -4 2 m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,3])
trans_den = N.array([2,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,3])
trans_den = N.array([2,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,3])
trans_den = N.array([2,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,3])
trans_den = N.array([2,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,5])
trans_den = N.array([1,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,5])
trans_den = N.array([1,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,5])
trans_den = N.array([1,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,5])
trans_den = N.array([1,2,4])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(122, 'I -4 2 d', transformations)
space_groups[122] = sg
space_groups['I -4 2 d'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(123, 'P 4/m m m', transformations)
space_groups[123] = sg
space_groups['P 4/m m m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(124, 'P 4/m c c', transformations)
space_groups[124] = sg
space_groups['P 4/m c c'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(125, 'P 4/n b m :2', transformations)
space_groups[125] = sg
space_groups['P 4/n b m :2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(126, 'P 4/n n c :2', transformations)
space_groups[126] = sg
space_groups['P 4/n n c :2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(127, 'P 4/m b m', transformations)
space_groups[127] = sg
space_groups['P 4/m b m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(128, 'P 4/m n c', transformations)
space_groups[128] = sg
space_groups['P 4/m n c'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(129, 'P 4/n m m :2', transformations)
space_groups[129] = sg
space_groups['P 4/n m m :2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(130, 'P 4/n c c :2', transformations)
space_groups[130] = sg
space_groups['P 4/n c c :2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(131, 'P 42/m m c', transformations)
space_groups[131] = sg
space_groups['P 42/m m c'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(132, 'P 42/m c m', transformations)
space_groups[132] = sg
space_groups['P 42/m c m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(133, 'P 42/n b c :2', transformations)
space_groups[133] = sg
space_groups['P 42/n b c :2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(134, 'P 42/n n m :2', transformations)
space_groups[134] = sg
space_groups['P 42/n n m :2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(135, 'P 42/m b c', transformations)
space_groups[135] = sg
space_groups['P 42/m b c'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(136, 'P 42/m n m', transformations)
space_groups[136] = sg
space_groups['P 42/m n m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(137, 'P 42/n m c :2', transformations)
space_groups[137] = sg
space_groups['P 42/n m c :2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(138, 'P 42/n c m :2', transformations)
space_groups[138] = sg
space_groups['P 42/n c m :2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(139, 'I 4/m m m', transformations)
space_groups[139] = sg
space_groups['I 4/m m m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(140, 'I 4/m c m', transformations)
space_groups[140] = sg
space_groups['I 4/m c m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-3,-1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-3,-1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([3,5,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([3,3,5])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([3,5,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([3,3,5])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,-1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,-1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,-1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,-1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(141, 'I 41/a m d :2', transformations)
space_groups[141] = sg
space_groups['I 41/a m d :2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-3,-1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-3,-3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([3,5,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([3,3,5])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([3,5,5])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([3,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,-1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,-1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,-1,-1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(142, 'I 41/a c d :2', transformations)
space_groups[142] = sg
space_groups['I 41/a c d :2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(143, 'P 3', transformations)
space_groups[143] = sg
space_groups['P 3'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(144, 'P 31', transformations)
space_groups[144] = sg
space_groups['P 31'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(145, 'P 32', transformations)
space_groups[145] = sg
space_groups['P 32'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(146, 'R 3 :H', transformations)
space_groups[146] = sg
space_groups['R 3 :H'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(147, 'P -3', transformations)
space_groups[147] = sg
space_groups['P -3'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(148, 'R -3 :H', transformations)
space_groups[148] = sg
space_groups['R -3 :H'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(149, 'P 3 1 2', transformations)
space_groups[149] = sg
space_groups['P 3 1 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(150, 'P 3 2 1', transformations)
space_groups[150] = sg
space_groups['P 3 2 1'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(151, 'P 31 1 2', transformations)
space_groups[151] = sg
space_groups['P 31 1 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(152, 'P 31 2 1', transformations)
space_groups[152] = sg
space_groups['P 31 2 1'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(153, 'P 32 1 2', transformations)
space_groups[153] = sg
space_groups['P 32 1 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(154, 'P 32 2 1', transformations)
space_groups[154] = sg
space_groups['P 32 2 1'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(155, 'R 3 2 :H', transformations)
space_groups[155] = sg
space_groups['R 3 2 :H'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(156, 'P 3 m 1', transformations)
space_groups[156] = sg
space_groups['P 3 m 1'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(157, 'P 3 1 m', transformations)
space_groups[157] = sg
space_groups['P 3 1 m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(158, 'P 3 c 1', transformations)
space_groups[158] = sg
space_groups['P 3 c 1'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(159, 'P 3 1 c', transformations)
space_groups[159] = sg
space_groups['P 3 1 c'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(160, 'R 3 m :H', transformations)
space_groups[160] = sg
space_groups['R 3 m :H'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,7])
trans_den = N.array([3,3,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,7])
trans_den = N.array([3,3,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,7])
trans_den = N.array([3,3,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,5])
trans_den = N.array([3,3,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,5])
trans_den = N.array([3,3,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,5])
trans_den = N.array([3,3,6])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(161, 'R 3 c :H', transformations)
space_groups[161] = sg
space_groups['R 3 c :H'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(162, 'P -3 1 m', transformations)
space_groups[162] = sg
space_groups['P -3 1 m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(163, 'P -3 1 c', transformations)
space_groups[163] = sg
space_groups['P -3 1 c'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(164, 'P -3 m 1', transformations)
space_groups[164] = sg
space_groups['P -3 m 1'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(165, 'P -3 c 1', transformations)
space_groups[165] = sg
space_groups['P -3 c 1'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(166, 'R -3 m :H', transformations)
space_groups[166] = sg
space_groups['R -3 m :H'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,2,7])
trans_den = N.array([3,3,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,2,7])
trans_den = N.array([3,3,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,2,7])
trans_den = N.array([3,3,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,1])
trans_den = N.array([3,3,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,1])
trans_den = N.array([3,3,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,1])
trans_den = N.array([3,3,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([2,1,5])
trans_den = N.array([3,3,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([2,1,5])
trans_den = N.array([3,3,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([2,1,5])
trans_den = N.array([3,3,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,-1])
trans_den = N.array([3,3,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,-1])
trans_den = N.array([3,3,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,-1])
trans_den = N.array([3,3,6])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(167, 'R -3 c :H', transformations)
space_groups[167] = sg
space_groups['R -3 c :H'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(168, 'P 6', transformations)
space_groups[168] = sg
space_groups['P 6'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,5])
trans_den = N.array([1,1,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(169, 'P 61', transformations)
space_groups[169] = sg
space_groups['P 61'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,5])
trans_den = N.array([1,1,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(170, 'P 65', transformations)
space_groups[170] = sg
space_groups['P 65'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(171, 'P 62', transformations)
space_groups[171] = sg
space_groups['P 62'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(172, 'P 64', transformations)
space_groups[172] = sg
space_groups['P 64'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(173, 'P 63', transformations)
space_groups[173] = sg
space_groups['P 63'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(174, 'P -6', transformations)
space_groups[174] = sg
space_groups['P -6'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(175, 'P 6/m', transformations)
space_groups[175] = sg
space_groups['P 6/m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(176, 'P 63/m', transformations)
space_groups[176] = sg
space_groups['P 63/m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(177, 'P 6 2 2', transformations)
space_groups[177] = sg
space_groups['P 6 2 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,5])
trans_den = N.array([1,1,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,5])
trans_den = N.array([1,1,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,6])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(178, 'P 61 2 2', transformations)
space_groups[178] = sg
space_groups['P 61 2 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,5])
trans_den = N.array([1,1,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,5])
trans_den = N.array([1,1,6])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(179, 'P 65 2 2', transformations)
space_groups[179] = sg
space_groups['P 65 2 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(180, 'P 62 2 2', transformations)
space_groups[180] = sg
space_groups['P 62 2 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(181, 'P 64 2 2', transformations)
space_groups[181] = sg
space_groups['P 64 2 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(182, 'P 63 2 2', transformations)
space_groups[182] = sg
space_groups['P 63 2 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(183, 'P 6 m m', transformations)
space_groups[183] = sg
space_groups['P 6 m m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(184, 'P 6 c c', transformations)
space_groups[184] = sg
space_groups['P 6 c c'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(185, 'P 63 c m', transformations)
space_groups[185] = sg
space_groups['P 63 c m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(186, 'P 63 m c', transformations)
space_groups[186] = sg
space_groups['P 63 m c'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(187, 'P -6 m 2', transformations)
space_groups[187] = sg
space_groups['P -6 m 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(188, 'P -6 c 2', transformations)
space_groups[188] = sg
space_groups['P -6 c 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(189, 'P -6 2 m', transformations)
space_groups[189] = sg
space_groups['P -6 2 m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(190, 'P -6 2 c', transformations)
space_groups[190] = sg
space_groups['P -6 2 c'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(191, 'P 6/m m m', transformations)
space_groups[191] = sg
space_groups['P 6/m m m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(192, 'P 6/m c c', transformations)
space_groups[192] = sg
space_groups['P 6/m c c'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(193, 'P 63/m c m', transformations)
space_groups[193] = sg
space_groups['P 63/m c m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(194, 'P 63/m m c', transformations)
space_groups[194] = sg
space_groups['P 63/m m c'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(195, 'P 2 3', transformations)
space_groups[195] = sg
space_groups['P 2 3'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(196, 'F 2 3', transformations)
space_groups[196] = sg
space_groups['F 2 3'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(197, 'I 2 3', transformations)
space_groups[197] = sg
space_groups['I 2 3'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(198, 'P 21 3', transformations)
space_groups[198] = sg
space_groups['P 21 3'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(199, 'I 21 3', transformations)
space_groups[199] = sg
space_groups['I 21 3'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(200, 'P m -3', transformations)
space_groups[200] = sg
space_groups['P m -3'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(201, 'P n -3 :2', transformations)
space_groups[201] = sg
space_groups['P n -3 :2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(202, 'F m -3', transformations)
space_groups[202] = sg
space_groups['F m -3'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([4,4,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([4,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([4,4,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([4,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([4,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([4,4,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([4,4,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([4,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([4,4,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([4,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([4,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([4,4,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,1])
trans_den = N.array([4,4,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,3,3])
trans_den = N.array([1,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([4,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,1])
trans_den = N.array([4,4,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([4,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,3,3])
trans_den = N.array([1,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,3,3])
trans_den = N.array([1,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([4,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,3,1])
trans_den = N.array([4,4,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([-1,1,1])
trans_den = N.array([4,4,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([-1,1,1])
trans_den = N.array([4,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([-1,1,1])
trans_den = N.array([4,4,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([-1,1,1])
trans_den = N.array([4,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,1,1])
trans_den = N.array([4,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,1,1])
trans_den = N.array([4,4,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([3,1,1])
trans_den = N.array([4,4,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([2,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([3,0,3])
trans_den = N.array([4,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([3,1,1])
trans_den = N.array([4,4,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([3,0,3])
trans_den = N.array([4,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([2,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([2,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([3,0,3])
trans_den = N.array([4,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([3,1,1])
trans_den = N.array([4,4,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,-1,1])
trans_den = N.array([4,4,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,-1,1])
trans_den = N.array([2,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([4,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,-1,1])
trans_den = N.array([4,4,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([4,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,-1,1])
trans_den = N.array([2,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,-1,1])
trans_den = N.array([2,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([4,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,-1,1])
trans_den = N.array([4,4,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([3,3,0])
trans_den = N.array([4,4,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,1])
trans_den = N.array([2,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([3,1,1])
trans_den = N.array([4,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([3,3,0])
trans_den = N.array([4,4,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([3,1,1])
trans_den = N.array([4,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,1])
trans_den = N.array([2,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,3,1])
trans_den = N.array([2,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([3,1,1])
trans_den = N.array([4,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([3,3,0])
trans_den = N.array([4,4,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([4,4,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,-1])
trans_den = N.array([2,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,-1])
trans_den = N.array([4,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([4,4,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,-1])
trans_den = N.array([4,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,-1])
trans_den = N.array([2,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,-1])
trans_den = N.array([2,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,-1])
trans_den = N.array([4,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([4,4,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(203, 'F d -3 :2', transformations)
space_groups[203] = sg
space_groups['F d -3 :2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(204, 'I m -3', transformations)
space_groups[204] = sg
space_groups['I m -3'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(205, 'P a -3', transformations)
space_groups[205] = sg
space_groups['P a -3'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(206, 'I a -3', transformations)
space_groups[206] = sg
space_groups['I a -3'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(207, 'P 4 3 2', transformations)
space_groups[207] = sg
space_groups['P 4 3 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(208, 'P 42 3 2', transformations)
space_groups[208] = sg
space_groups['P 42 3 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(209, 'F 4 3 2', transformations)
space_groups[209] = sg
space_groups['F 4 3 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([3,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([3,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([3,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([3,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([3,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([3,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([3,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([3,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([3,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([3,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([3,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([3,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([3,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([3,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([3,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([3,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([3,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([3,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([3,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([3,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([3,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([3,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([3,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([3,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(210, 'F 41 3 2', transformations)
space_groups[210] = sg
space_groups['F 41 3 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(211, 'I 4 3 2', transformations)
space_groups[211] = sg
space_groups['I 4 3 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([3,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([3,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([3,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([3,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([3,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([3,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(212, 'P 43 3 2', transformations)
space_groups[212] = sg
space_groups['P 43 3 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([3,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([3,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([3,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([3,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([3,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([3,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(213, 'P 41 3 2', transformations)
space_groups[213] = sg
space_groups['P 41 3 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([3,3,5])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([3,5,5])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([3,5,5])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([3,5,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([3,5,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([3,3,5])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([3,5,5])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([3,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([3,3,5])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([3,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([3,5,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([3,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(214, 'I 41 3 2', transformations)
space_groups[214] = sg
space_groups['I 41 3 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(215, 'P -4 3 m', transformations)
space_groups[215] = sg
space_groups['P -4 3 m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(216, 'F -4 3 m', transformations)
space_groups[216] = sg
space_groups['F -4 3 m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(217, 'I -4 3 m', transformations)
space_groups[217] = sg
space_groups['I -4 3 m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(218, 'P -4 3 n', transformations)
space_groups[218] = sg
space_groups['P -4 3 n'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(219, 'F -4 3 c', transformations)
space_groups[219] = sg
space_groups['F -4 3 c'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([3,3,5])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([3,5,5])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([3,5,5])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([3,5,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([3,5,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([3,3,5])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([3,5,5])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([3,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([3,3,5])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([3,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([3,5,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([3,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(220, 'I -4 3 d', transformations)
space_groups[220] = sg
space_groups['I -4 3 d'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(221, 'P m -3 m', transformations)
space_groups[221] = sg
space_groups['P m -3 m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(222, 'P n -3 n :2', transformations)
space_groups[222] = sg
space_groups['P n -3 n :2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(223, 'P m -3 n', transformations)
space_groups[223] = sg
space_groups['P m -3 n'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = | N.array([1,1,1]) | numpy.array |
#!/usr/bin/python
########################################################################################################################
#
# Copyright (c) 2014, Regents of the University of California
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
# following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following
# disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
# following disclaimer in the documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
# INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
########################################################################################################################
"""ADC library
"""
import laygo
import numpy as np
from math import log
import yaml
import os
import laygo.GridLayoutGeneratorHelper as laygenhelper #utility functions
#import logging;logging.basicConfig(level=logging.DEBUG)
def generate_boundary(laygen, objectname_pfix, placement_grid,
devname_bottom, devname_top, devname_left, devname_right,
shape_bottom=None, shape_top=None, shape_left=None, shape_right=None,
transform_bottom=None, transform_top=None, transform_left=None, transform_right=None,
origin=np.array([0, 0])):
# generate a boundary structure to resolve boundary design rules
pg = placement_grid
# parameters
if shape_bottom == None:
shape_bottom = [np.array([1, 1]) for d in devname_bottom]
if shape_top == None:
shape_top = [np.array([1, 1]) for d in devname_top]
if shape_left == None:
shape_left = [np.array([1, 1]) for d in devname_left]
if shape_right == None:
shape_right = [np.array([1, 1]) for d in devname_right]
if transform_bottom == None:
transform_bottom = ['R0' for d in devname_bottom]
if transform_top == None:
transform_top = ['R0' for d in devname_top]
if transform_left == None:
transform_left = ['R0' for d in devname_left]
if transform_right == None:
transform_right = ['R0' for d in devname_right]
# bottom
dev_bottom = []
dev_bottom.append(laygen.place("I" + objectname_pfix + 'BNDBTM0', devname_bottom[0], pg, xy=origin,
shape=shape_bottom[0], transform=transform_bottom[0]))
for i, d in enumerate(devname_bottom[1:]):
dev_bottom.append(
laygen.relplace(name="I" + objectname_pfix + 'BNDBTM' + str(i + 1), templatename=d, gridname=pg,
refinstname=dev_bottom[-1].name,
shape=shape_bottom[i + 1], transform=transform_bottom[i + 1]))
dev_left = []
dev_left.append(laygen.relplace(name="I" + objectname_pfix + 'BNDLFT0', templatename=devname_left[0], gridname=pg,
refinstname=dev_bottom[0].name, direction='top',
shape=shape_left[0], transform=transform_left[0]))
for i, d in enumerate(devname_left[1:]):
dev_left.append(laygen.relplace(name="I" + objectname_pfix + 'BNDLFT' + str(i + 1), templatename=d, gridname=pg,
refinstname=dev_left[-1].name, direction='top',
shape=shape_left[i + 1], transform=transform_left[i + 1]))
dev_right = []
dev_right.append(laygen.relplace(name="I" + objectname_pfix + 'BNDRHT0', templatename=devname_right[0], gridname=pg,
refinstname=dev_bottom[-1].name, direction='top',
shape=shape_right[0], transform=transform_right[0]))
for i, d in enumerate(devname_right[1:]):
dev_right.append(
laygen.relplace(name="I" + objectname_pfix + 'BNDRHT' + str(i + 1), templatename=d, gridname=pg,
refinstname=dev_right[-1].name, direction='top',
shape=shape_right[i + 1], transform=transform_right[i + 1]))
dev_top = []
dev_top.append(laygen.relplace(name="I" + objectname_pfix + 'BNDTOP0', templatename=devname_top[0], gridname=pg,
refinstname=dev_left[-1].name, direction='top',
shape=shape_top[0], transform=transform_top[0]))
for i, d in enumerate(devname_top[1:]):
dev_top.append(laygen.relplace(name="I" + objectname_pfix + 'BNDTOP' + str(i + 1), templatename=d, gridname=pg,
refinstname=dev_top[-1].name,
shape=shape_top[i + 1], transform=transform_top[i + 1]))
dev_right = []
return [dev_bottom, dev_top, dev_left, dev_right]
def create_power_pin_from_inst(laygen, layer, gridname, inst_left, inst_right):
"""create power pin"""
rvdd0_pin_xy = laygen.get_inst_pin_xy(inst_left.name, 'VDD', gridname, sort=True)
rvdd1_pin_xy = laygen.get_inst_pin_xy(inst_right.name, 'VDD', gridname, sort=True)
rvss0_pin_xy = laygen.get_inst_pin_xy(inst_left.name, 'VSS', gridname, sort=True)
rvss1_pin_xy = laygen.get_inst_pin_xy(inst_right.name, 'VSS', gridname, sort=True)
laygen.pin(name='VDD', layer=layer, xy=np.vstack((rvdd0_pin_xy[0], rvdd1_pin_xy[1])), gridname=gridname)
laygen.pin(name='VSS', layer=layer, xy=np.vstack((rvss0_pin_xy[0], rvss1_pin_xy[1])), gridname=gridname)
def generate_latch_ckb(laygen, objectname_pfix, templib_logic, placement_grid, routing_grid_m3m4,
m=2, origin=np.array([0, 0])):
"""generate clock delay """
pg = placement_grid
rg_m3m4 = routing_grid_m3m4
inv_name = 'inv_1x'
latch_name = 'latch_2ck_' + str(m) + 'x'
# placement
iinv0 = laygen.place(name="I" + objectname_pfix + 'IINV0', templatename=inv_name,
gridname=pg, xy=origin, template_libname=templib_logic)
ilatch0 = laygen.relplace(name="I" + objectname_pfix + 'ILATCH0', templatename=latch_name,
gridname=pg, refinstname=iinv0.name, template_libname=templib_logic)
# internal pins
pdict = laygen.get_inst_pin_xy(None, None, rg_m3m4)
# internal routes
x0 = laygen.get_inst_xy(name=iinv0.name, gridname=rg_m3m4)[0] + 1
y0 = pdict[iinv0.name]['I'][0][1] + 0
# route-clk
rv0, rclk0 = laygen.route_vh(laygen.layers['metal'][3], laygen.layers['metal'][4], pdict[iinv0.name]['O'][0],
pdict[ilatch0.name]['CLK'][0], rg_m3m4)
# np.array([x0, y0 + 3]), rg_m3m4)
# route-clkb
rv0, rclkb0 = laygen.route_vh(laygen.layers['metal'][3], laygen.layers['metal'][4], pdict[iinv0.name]['I'][0],
pdict[ilatch0.name]['CLKB'][0], rg_m3m4)
print('test:', pdict[iinv0.name]['I'][0])
# pins
x1 = laygen.get_inst_pin_xy(ilatch0.name, 'O', rg_m3m4)[1][0]
rh0, rout0 = laygen.route_hv(laygen.layers['metal'][4], laygen.layers['metal'][3], pdict[ilatch0.name]['O'][0],
np.array([x1, y0 + 4]), rg_m3m4)
laygen.boundary_pin_from_rect(rout0, rg_m3m4, "O", laygen.layers['pin'][3], size=4, direction='top')
in_xy = laygen.get_inst_pin_xy(ilatch0.name, 'I', rg_m3m4)
laygen.pin(name='I', layer=laygen.layers['pin'][3], xy=in_xy, gridname=rg_m3m4)
laygen.pin_from_rect('CLKB', laygen.layers['pin'][4], rclkb0, rg_m3m4)
# power pin
create_power_pin_from_inst(laygen, layer=laygen.layers['pin'][2], gridname=rg_m1m2, inst_left=iinv0,
inst_right=ilatch0)
def generate_retimer_slice(laygen, objectname_pfix, templib_logic, placement_grid, routing_grid_m3m4,
rg_m3m4_basic_thick, rg_m4m5_thick, num_bits=9, origin=np.array([0, 0])):
"""generate clock delay """
pg = placement_grid
rg_m3m4 = routing_grid_m3m4
tap_name='tap'
#Calculate layout size
x0=laygen.templates.get_template('sar_wsamp_bb_doubleSA', workinglib).xy[1][0]
tap_origin = origin
array_origin = origin + np.array([laygen.get_template_xy(name=tap_name, gridname=pg, libname=templib_logic)[0], 0])
tapr_origin = np.array([laygen.get_template_xy(name='sar_wsamp_bb_doubleSA', gridname=pg, libname=workinglib)[0], 0]) \
- np.array([laygen.get_template_xy(name=tap_name, gridname=pg, libname=templib_logic)[0], 0])
#Space calculation
inv_name = 'inv_1x'
latch_name = 'latch_ckb'
space_name = 'space_1x'
space4x_name = 'space_4x'
space_width = laygen.get_template_xy(name = space_name, gridname = pg, libname = templib_logic)[0]
space4_width = laygen.get_template_xy(name = space4x_name, gridname = pg, libname = templib_logic)[0]
latch_array_width = num_bits*laygen.get_template_xy(name = latch_name, gridname = pg, libname = workinglib)[0]
blank_width = tapr_origin[0] - array_origin[0] - latch_array_width
m_space4 = int(blank_width / space4_width)
m_space1 = int((blank_width-m_space4*space4_width)/space_width)
# placement: first row
# iinv0 = laygen.place(name="I" + objectname_pfix + 'IINV0', templatename=inv_name,
# gridname=pg, xy=origin, template_libname=templib_logic)
itapl2 = laygen.relplace(name="I" + objectname_pfix + 'ITAPL2', templatename=tap_name,
gridname=pg, refinstname=None, xy=tap_origin, template_libname=templib_logic)
itapr2 = laygen.relplace(name="I" + objectname_pfix + 'ITAPR2', templatename=tap_name,
gridname = pg, refinstname = None, xy = tapr_origin, template_libname = templib_logic)
ilatch2 = laygen.relplace(name="I" + objectname_pfix + 'ILATCH2', templatename=latch_name, shape=[num_bits,1],
gridname=pg, refinstname=itapl2.name, template_libname=workinglib)
ispace4x2 = laygen.relplace(name="I" + objectname_pfix + 'ISP4x2', templatename=space4x_name, shape=[m_space4,1],
gridname=pg, refinstname=ilatch2.name, template_libname=templib_logic)
if m_space4 == 0:
ispace1x2 = laygen.relplace(name="I" + objectname_pfix + 'ISP1x2', templatename=space_name, shape=[m_space1, 1],
gridname=pg, refinstname=ilatch2.name, template_libname=templib_logic)
else:
ispace1x2 = laygen.relplace(name="I" + objectname_pfix + 'ISP1x2', templatename=space_name, shape=[m_space1,1],
gridname=pg, refinstname=ispace4x2.name, template_libname=templib_logic)
#second row
itapl1 = laygen.relplace(name="I" + objectname_pfix + 'ITAPL1', templatename=tap_name, transform='MX',
gridname=pg, refinstname=itapl2.name, direction='top', template_libname=templib_logic)
itapr1 = laygen.relplace(name="I" + objectname_pfix + 'ITAPR1', templatename=tap_name, transform='MX',
gridname=pg, refinstname=itapr2.name, direction='top', template_libname=templib_logic)
ilatch1 = laygen.relplace(name="I" + objectname_pfix + 'ILATCH1', templatename=latch_name, shape=[num_bits, 1], transform='MX',
gridname=pg, refinstname=itapl1.name, template_libname=workinglib)
ispace4x1 = laygen.relplace(name="I" + objectname_pfix + 'ISP4x1', templatename=space4x_name,
shape=[m_space4, 1], transform='MX',
gridname=pg, refinstname=ilatch1.name, template_libname=templib_logic)
if m_space4 == 0:
ispace1x1 = laygen.relplace(name="I" + objectname_pfix + 'ISP1x1', templatename=space_name,
shape=[m_space1, 1], transform='MX',
gridname=pg, refinstname=ilatch1.name, template_libname=templib_logic)
else:
ispace1x1 = laygen.relplace(name="I" + objectname_pfix + 'ISP1x1', templatename=space_name,
shape=[m_space1, 1], transform='MX',
gridname=pg, refinstname=ispace4x1.name, template_libname=templib_logic)
# second row
itapl0 = laygen.relplace(name="I" + objectname_pfix + 'ITAPL0', templatename=tap_name,
gridname=pg, refinstname=itapl1.name, direction='top', template_libname=templib_logic)
itapr0 = laygen.relplace(name="I" + objectname_pfix + 'ITAPR0', templatename=tap_name,
gridname=pg, refinstname=itapr1.name, direction='top', template_libname=templib_logic)
ilatch0 = laygen.relplace(name="I" + objectname_pfix + 'ILATCH0', templatename=latch_name, shape=[num_bits, 1],
gridname=pg, refinstname=itapl0.name, template_libname=workinglib)
ispace4x0 = laygen.relplace(name="I" + objectname_pfix + 'ISP4x0', templatename=space4x_name,
shape=[m_space4, 1],
gridname=pg, refinstname=ilatch0.name, template_libname=templib_logic)
if m_space4 == 0:
ispace1x0 = laygen.relplace(name="I" + objectname_pfix + 'ISP1x0', templatename=space_name,
shape=[m_space1, 1],
gridname=pg, refinstname=ilatch0.name, template_libname=templib_logic)
else:
ispace1x0 = laygen.relplace(name="I" + objectname_pfix + 'ISP1x0', templatename=space_name,
shape=[m_space1, 1],
gridname=pg, refinstname=ispace4x0.name, template_libname=templib_logic)
# internal pins
pdict = laygen.get_inst_pin_xy(None, None, rg_m3m4)
# # internal routes
# x0 = laygen.get_inst_xy(name=iinv0.name, gridname=rg_m3m4)[0] + 1
# y0 = pdict[iinv0.name]['I'][0][1] + 0
#
# route-clkb
rclkb0 = laygen.route(None, laygen.layers['metal'][4], xy0=laygen.get_inst_pin_xy(ilatch0.name, 'CLKB', rg_m3m4, index=[0, 0])[0],
xy1=laygen.get_inst_pin_xy(ilatch0.name, 'CLKB', rg_m3m4, index=[num_bits-1, 0])[0], gridname0=rg_m3m4)
rclkb1 = laygen.route(None, laygen.layers['metal'][4], xy0=laygen.get_inst_pin_xy(ilatch1.name, 'CLKB', rg_m3m4, index=[0, 0])[0],
xy1=laygen.get_inst_pin_xy(ilatch1.name, 'CLKB', rg_m3m4, index=[num_bits-1, 0])[0], gridname0=rg_m3m4)
rclkb2 = laygen.route(None, laygen.layers['metal'][4], xy0=laygen.get_inst_pin_xy(ilatch2.name, 'CLKB', rg_m3m4, index=[0, 0])[0],
xy1=laygen.get_inst_pin_xy(ilatch2.name, 'CLKB', rg_m3m4, index=[num_bits-1, 0])[0], gridname0=rg_m3m4)
# route-internal signals
for i in range(num_bits):
[rv0, rh0, rv1] = laygen.route_vhv(laygen.layers['metal'][3], laygen.layers['metal'][4],
laygen.get_inst_pin_xy(ilatch0.name, 'O', rg_m3m4, index=[i, 0])[0],
laygen.get_inst_pin_xy(ilatch1.name, 'I', rg_m3m4, index=[i, 0])[0],
laygen.get_inst_pin_xy(ilatch0.name, 'O', rg_m3m4, index=[i, 0])[0][1] - 4, rg_m3m4)
[rv0, rh0, rv1] = laygen.route_vhv(laygen.layers['metal'][3], laygen.layers['metal'][4],
laygen.get_inst_pin_xy(ilatch1.name, 'O', rg_m3m4, index=[i, 0])[0],
laygen.get_inst_pin_xy(ilatch2.name, 'I', rg_m3m4, index=[i, 0])[0],
laygen.get_inst_pin_xy(ilatch1.name, 'O', rg_m3m4, index=[i, 0])[0][1] - 5, rg_m3m4)
# pins
laygen.pin_from_rect('clkb0', laygen.layers['pin'][4], rclkb0, rg_m3m4)
laygen.pin_from_rect('clkb1', laygen.layers['pin'][4], rclkb1, rg_m3m4)
laygen.pin_from_rect('clkb2', laygen.layers['pin'][4], rclkb2, rg_m3m4)
for i in range(num_bits):
in_xy = laygen.get_inst_pin_xy(ilatch0.name, 'I', rg_m3m4, index=[i,0])
laygen.pin(name='in<%d>'%i, layer=laygen.layers['pin'][3], xy=in_xy, gridname=rg_m3m4)
out_xy = laygen.get_inst_pin_xy(ilatch2.name, 'O', rg_m3m4, index=[i,0])
laygen.pin(name='out<%d>'%i, layer=laygen.layers['pin'][3], xy=out_xy, gridname=rg_m3m4)
# power pin
pwr_dim=laygen.get_template_xy(name=itapl0.cellname, gridname=rg_m2m3, libname=itapl0.libname)
rvddl = []
rvssl = []
rvddr = []
rvssr = []
for i in range(0, int(pwr_dim[0]/2)):
rvddl.append(laygen.route(None, laygen.layers['metal'][3], xy0=np.array([2*i+1, 0]), xy1=np.array([2*i+1, 0]), gridname0=rg_m2m3,
refinstname0=itapl2.name, refpinname0='VSS', refinstindex0=np.array([0, 0]),
refinstname1=itapl0.name, refpinname1='VDD', refinstindex1=np.array([0, 0])))
rvssl.append(laygen.route(None, laygen.layers['metal'][3], xy0=np.array([2*i+2, 0]), xy1=np.array([2*i+2, 0]), gridname0=rg_m2m3,
refinstname0=itapl2.name, refpinname0='VSS', refinstindex0=np.array([0, 0]),
refinstname1=itapl0.name, refpinname1='VDD', refinstindex1=np.array([0, 0])))
laygen.via(None, xy=np.array([2*i+1, 0]), gridname=rg_m2m3, refinstname=itapl0.name, refpinname='VDD')
laygen.via(None, xy=np.array([2*i+1, 0]), gridname=rg_m2m3, refinstname=itapl1.name, refpinname='VDD')
laygen.via(None, xy=np.array([2*i+1, 0]), gridname=rg_m2m3, refinstname=itapl2.name, refpinname='VDD')
laygen.via(None, xy=np.array([2 * i + 2, 0]), gridname=rg_m2m3, refinstname=itapl0.name, refpinname='VSS')
laygen.via(None, xy=np.array([2 * i + 2, 0]), gridname=rg_m2m3, refinstname=itapl1.name, refpinname='VSS')
laygen.via(None, xy=np.array([2 * i + 2, 0]), gridname=rg_m2m3, refinstname=itapl2.name, refpinname='VSS')
laygen.pin(name = 'VDDL'+str(i), layer = laygen.layers['pin'][3], refobj = rvddl[-1], gridname=rg_m2m3, netname='VDD')
laygen.pin(name = 'VSSL'+str(i), layer = laygen.layers['pin'][3], refobj = rvssl[-1], gridname=rg_m2m3, netname='VSS')
rvddr.append(laygen.route(None, laygen.layers['metal'][3], xy0=np.array([2*i+2, 0]), xy1=np.array([2*i+2, 0]), gridname0=rg_m2m3,
refinstname0=itapr2.name, refpinname0='VSS', refinstindex0=np.array([0, 0]),
refinstname1=itapr0.name, refpinname1='VDD', refinstindex1=np.array([0, 0])))
rvssr.append(laygen.route(None, laygen.layers['metal'][3], xy0=np.array([2*i+1, 0]), xy1=np.array([2*i+1, 0]), gridname0=rg_m2m3,
refinstname0=itapr2.name, refpinname0='VSS', refinstindex0=np.array([0, 0]),
refinstname1=itapr0.name, refpinname1='VDD', refinstindex1=np.array([0, 0])))
laygen.via(None, xy=np.array([2 * i + 2, 0]), gridname=rg_m2m3, refinstname=itapr0.name, refpinname='VDD')
laygen.via(None, xy=np.array([2 * i + 2, 0]), gridname=rg_m2m3, refinstname=itapr1.name, refpinname='VDD')
laygen.via(None, xy=np.array([2 * i + 2, 0]), gridname=rg_m2m3, refinstname=itapr2.name, refpinname='VDD')
laygen.via(None, xy=np.array([2 * i + 1, 0]), gridname=rg_m2m3, refinstname=itapr0.name, refpinname='VSS')
laygen.via(None, xy= | np.array([2 * i + 1, 0]) | numpy.array |
import numpy as np
import matplotlib.pyplot as plt
class jFoil:
""" Joukowsky foil creator.
Parameters:
a - Radius of the pre-transformation cilinder. Approximately 1/4 of the final chord length.
relThickness - Proportional to the thickness of the airfoil. Must be between 0 and 1. For airfoils, it is generally close to 0.9.
beta - Curvature of the foil in degrees.
[n] - number of samples that make the foil. Default 100. """
def __init__(self, a, relThickness, beta, n=100):
if relThickness < 0 or relThickness > 1:
raise ValueError(
"Bad value of airfoil thickness (relative thickness must be between 0 and 1)")
self.a = a
self.relThickness = relThickness
self.beta = np.deg2rad(beta)
self._theta = | np.linspace(0, 2*np.pi, n) | numpy.linspace |
#!/usr/bin/env python
import math
import numpy as np
import signal
import scipy.ndimage as ndimage
import pdb
"""
This file contains scripts to filter ALOS data.
"""
def enhanced_lee_filter(img, window_size = 5, n_looks = 16):
'''
Filters a masked array with the enhanced lee filter.
Based on formulation here: http://www.pcigeomatics.com/geomatica-help/concepts/orthoengine_c/Chapter_825.html
Args:
img: A masked array
window_size: Must be an odd number. Defaults to 7, which appears to give the best results.
n_looks: Equivalent number of looks. Defaults to 16, equivalent to native ENL of ALOS mosaic data.
Returns:
A masked array with a filtered verison of img
'''
assert type(window_size == int), "Window size must be an integer. You input the value: %s"%str(window_size)
assert (window_size % 2) == 1, "Window size must be an odd number. You input the value: %s"%str(window_size)
assert window_size >= 3, "Window size must be at least 3. You input the value: %s"%str(window_size)
# Inner function to calculate mean with a moving window and a masked array
def _window_mean(img, window_size = 3):
'''
Based on https://stackoverflow.com/questions/18419871/improving-code-efficiency-standard-deviation-on-sliding-windows
'''
from scipy import signal
c1 = signal.convolve2d(img, np.ones((window_size, window_size)) / (window_size ** 2), boundary = 'symm')
border = math.floor(window_size / 2)
return c1[border:-border, border:-border]
# Inner function to calculate standard deviation with a moving window and a masked array
def _window_stdev(img, window_size = 3):
'''
Based on https://stackoverflow.com/questions/18419871/improving-code-efficiency-standard-deviation-on-sliding-windows
and http://nickc1.github.io/python,/matlab/2016/05/17/Standard-Deviation-(Filters)-in-Matlab-and-Python.html
'''
from scipy import signal
c1 = signal.convolve2d(img, np.ones((window_size, window_size)) / (window_size ** 2), boundary = 'symm')
c2 = signal.convolve2d(img*img, np.ones((window_size, window_size)) / (window_size ** 2), boundary = 'symm')
border = math.floor(window_size / 2)
variance = c2 - c1 * c1
variance[variance < 0] += 0.01 # Prevents divide by zero errors.
return np.sqrt(variance)[border:-border, border:-border]
# Damping factor, set to 1 which is adequate for most SAR images
k = 1
cu = (1./n_looks) ** 0.5
cmax = (1 + (2./n_looks)) ** 0.5
# Interpolate across nodata areas. No standard Python filters understand nodata values; this is a simplification
indices = ndimage.distance_transform_edt(img.mask, return_distances = False, return_indices = True)
data = img.data[tuple(indices)]
img_mean = _window_mean(data, window_size = window_size)
img_std = _window_stdev(data, window_size = window_size)
ci = img_std / img_mean
ci[np.isfinite(ci) == False] = 0.
W = np.zeros_like(ci)
# There are three conditions in the enhanced lee filter
W[ci <= cu] = 1.
W[ci >= cmax] = 0.
sel = np.logical_and(ci > cu, ci < cmax)
W[sel] = np.exp((-k * (ci[sel] - cu)) / (cmax - ci[sel]))
img_filtered = (img_mean * W) + (data * (1. - W))
img_filtered = np.ma.array(img_filtered, mask = np.logical_or( | np.isnan(img_filtered) | numpy.isnan |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
plt.style.use('ggplot')
from mpl_toolkits import mplot3d
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
import matplotlib.ticker as mtick
import BS
import bootstrapping
######################################################################### Training loss
#Plot loss for each epoch
def plotEpochLoss(lossSerie):
fig = plt.figure(figsize=(20,10))
ax = fig.gca()
ax.plot(lossSerie , "-", color="black")
ax.set_xlabel("Epoch number", fontsize=18, labelpad=20)
ax.set_ylabel("Logarithmic Loss", fontsize=18, labelpad=20)
ax.set_title("Training Loss evolution", fontsize=24)
ax.tick_params(labelsize=16)
ax.set_facecolor('white')
plt.show()
return
######################################################################### Plotting smiles
#Plot a surface as a superposition of curves
def plotMultipleCurve(data,
Title = 'True Price Surface',
yMin = 0,
yMax = 1,
zAsPercent = False):
dataCurve = data[(data.index.get_level_values("Strike") <= yMax) * (data.index.get_level_values("Strike") >= yMin)]
fig = plt.figure(figsize=(20,10))
ax = fig.gca()
for t in np.linspace(0,0.8,9) :
k = dataCurve[dataCurve.index.get_level_values("Maturity") >= t].index.get_level_values("Maturity").unique().min()
curveK = dataCurve[dataCurve.index.get_level_values("Maturity")==k]
dataSerie = pd.Series(curveK.values * (100 if zAsPercent else 1) ,
index = curveK.index.get_level_values("Strike"))
ax.plot(dataSerie , "--+", label=str(k))
ax.legend()
ax.set_xlabel(data.index.names[0], fontsize=18, labelpad=20)
ax.set_ylabel(data.name, fontsize=18, labelpad=20)
if zAsPercent :
ax.yaxis.set_major_formatter(mtick.PercentFormatter())
ax.set_title(Title, fontsize=24)
ax.tick_params(labelsize=16)
ax.set_facecolor('white')
plt.show()
return
######################################################################### Plot surface
#Plotting function for surface
#xTitle : title for x axis
#yTitle : title for y axis
#zTitle : title for z axis
#Title : plot title
#az : azimuth i.e. angle of view for surface
#yMin : minimum value for y axis
#yMax : maximum value for y axis
#zAsPercent : boolean, if true format zaxis as percentage
def plot2GridCustom(coordinates, zValue,
coordinates2, zValue2,
xTitle = "Maturity",
yTitle = "Strike",
zTitle = "Price",
Title = 'True Price Surface',
az=320,
yMin = 0,
yMax = 1,
zAsPercent = False):
y = coordinates[:,0]
filteredValue = (y > yMin) & (y < yMax)
x = coordinates[:,1][filteredValue]
y = coordinates[:,0][filteredValue]
z = zValue[filteredValue].flatten()
y2 = coordinates2[:,0]
filteredValue2 = (y2 > yMin) & (y2 < yMax)
x2 = coordinates2[:,1][filteredValue2]
y2 = coordinates2[:,0][filteredValue2]
z2 = zValue2[filteredValue2].flatten()
fig = plt.figure(figsize=(20,10))
ax = fig.gca(projection='3d')
ax.set_xlabel(xTitle, fontsize=18, labelpad=20)
ax.set_ylabel(yTitle, fontsize=18, labelpad=20)
ax.set_zlabel(zTitle, fontsize=18, labelpad=10)
cmap=plt.get_cmap("inferno")
colors=cmap(z * 100 if zAsPercent else z)[np.newaxis, :, :3]
ax.scatter(x2, y2, z2, marker='o', color="r", alpha=1, s=40)
ax.scatter(x, y, z, marker='o', color="b", alpha=1, s=40)
#surf = ax.plot_trisurf(x, y,
# z * 100 if zAsPercent else z ,
# linewidth=1.0,
# antialiased=True,
# cmap = cmap,
# color=(0,0,0,0))
#scaleEdgeValue = surf.to_rgba(surf.get_array())
#surf.set_edgecolors(scaleEdgeValue)
#surf.set_alpha(0)
if zAsPercent :
ax.zaxis.set_major_formatter(mtick.PercentFormatter())
ax.view_init(elev=10., azim=az)
#ax.set_title(Title, fontsize=24)
ax.set_facecolor('white')
plt.tick_params(labelsize=16)
plt.show()
return
#Plotting function from a pandas series
def plot2Series(data,
data2,
Title = 'True Price Surface',
az=320,
yMin = 0,
yMax = 1,
zAsPercent = False):
plot2GridCustom(data.index.to_frame().values,
data.values,
data2.index.to_frame().values,
data2.values,
xTitle = data.index.names[1],
yTitle = data.index.names[0],
zTitle = data.name,
Title = Title,
az=az,
yMin = yMin,
yMax = yMax,
zAsPercent = zAsPercent)
return
def convertToLogMoneyness(formerSerie, S0):
maturity = formerSerie.index.get_level_values("Maturity")
logMoneyness = np.log(S0 / formerSerie.index.get_level_values("Strike"))
newIndex = pd.MultiIndex.from_arrays([np.array(logMoneyness.values), np.array(maturity.values)],
names=('LogMoneyness', 'Maturity'))
if type(formerSerie) == type(pd.Series()) :
return pd.Series(formerSerie.values , index=newIndex)
return pd.DataFrame(formerSerie.values, index = newIndex, columns= formerSerie.columns)
#Plotting function for surface
#xTitle : title for x axis
#yTitle : title for y axis
#zTitle : title for z axis
#Title : plot title
#az : azimuth i.e. angle of view for surface
#yMin : minimum value for y axis
#yMax : maximum value for y axis
#zAsPercent : boolean, if true format zaxis as percentage
def plotGridCustom(coordinates, zValue,
xTitle = "Maturity",
yTitle = "Strike",
zTitle = "Price",
Title = 'True Price Surface',
az=320,
yMin = 0,
yMax = 1,
zAsPercent = False):
y = coordinates[:,0]
filteredValue = (y > yMin) & (y < yMax)
x = coordinates[:,1][filteredValue]
y = coordinates[:,0][filteredValue]
z = zValue[filteredValue].flatten()
fig = plt.figure(figsize=(15,9))
ax = fig.gca(projection='3d')
fontsize = 15
pad = 20
ax.set_xlabel(xTitle, color = "k", fontsize=fontsize, labelpad=pad * 1.0)
ax.set_ylabel(yTitle, color = "k", fontsize=fontsize, labelpad=pad * 1.0)
ax.set_zlabel(zTitle, color = "k", fontsize=fontsize, labelpad=pad * 1.0)
cmap=plt.get_cmap("jet")#("inferno")
colors=cmap(z * 100 if zAsPercent else z)[np.newaxis, :, :3]
surf = ax.plot_trisurf(x, y,
z * 100 if zAsPercent else z ,
linewidth=1.0,
antialiased=True,
cmap = cmap,
color=(0,0,0,0))
scaleEdgeValue = surf.to_rgba(surf.get_array())
surf.set_edgecolors(scaleEdgeValue)
surf.set_alpha(0)
if zAsPercent :
ax.zaxis.set_major_formatter(mtick.PercentFormatter())
ax.view_init(elev=40., azim=az)
ax.set_ylim(np.amax(y), np.amin(y))
ax.set_title(Title, fontsize=fontsize * 1.2)#, rotation='vertical', x=0.1, y=0.8)
ax.set_facecolor('white')
plt.tick_params(axis = "y", labelsize=fontsize * 0.9, pad = pad * 0.4, color = [1,0,0,1])
plt.tick_params(axis = "z", labelsize=fontsize * 0.9, pad = pad * 0.5, color = [1,0,0,1])
plt.tick_params(axis = "x", labelsize=fontsize * 0.9, pad = pad * 0.05, color = [1,0,0,1])
plt.tight_layout()
plt.show()
return
#Plotting function from a dataframe
def plotSurface(data,
zName,
Title = 'True Price Surface',
az=320,
yMin = 0,
yMax = 1,
zAsPercent = False):
plotGridCustom(dataSet.index.to_frame().values,
data[zName].values,
xTitle = dataSet.index.names[1],
yTitle = dataSet.index.names[0],
zTitle = zName,
Title = Title,
az=az,
yMin = yMin,
yMax = yMax,
zAsPercent=zAsPercent)
return
#Plotting function from a pandas series
def plotSerie(data,
Title = 'True Price Surface',
az=320,
yMin = 0,
yMax = 1,
zAsPercent = False):
plotGridCustom(data.index.to_frame().values,
data.values,
xTitle = data.index.names[1],
yTitle = data.index.names[0],
zTitle = data.name,
Title = Title,
az=az,
yMin = yMin,
yMax = yMax,
zAsPercent = zAsPercent)
return
######################################################################### Training Diagnostic
def selectIndex(df, indexToKeep):
return df.loc[indexToKeep][ ~df.loc[indexToKeep].index.duplicated(keep='first') ]
#Plot predicted value, benchmark value, absoluate error and relative error
#It also compute RMSE between predValue and refValue
#predValue : approximated value
#refValue : benchamrk value
#quantityName : name for approximated quantity
#az : azimuth i.e. angle of view for surface
#yMin : minimum value for y axis
#yMax : maximum value for y axis
def predictionDiagnosis(predValue,
refValue,
quantityName,
az=320,
yMin = 0,
yMax = 1,
threshold = None):
if threshold is not None :
filterIndex = refValue[refValue >= threshold].index
predictionDiagnosis(selectIndex(predValue, filterIndex),
selectIndex(refValue, filterIndex),
quantityName,
az=az,
yMin = yMin,
yMax = yMax,
threshold = None)
return
predValueFiltered = predValue[predValue.index.get_level_values("Maturity") > 0.001]
refValueFiltered = refValue[refValue.index.get_level_values("Maturity") > 0.001]
title = "Predicted " + quantityName + " surface"
plotSerie(predValueFiltered.rename(quantityName),
Title = title,
az=az,
yMin = yMin,
yMax = yMax)
title = "True " + quantityName + " surface"
plotSerie(refValueFiltered.rename(quantityName),
Title = title,
az=az,
yMin = yMin,
yMax = yMax)
title = quantityName + " surface error"
absoluteError = np.abs(predValueFiltered - refValueFiltered)
plotSerie(absoluteError.rename(quantityName + " Absolute Error"),
Title = title,
az=az,
yMin = yMin,
yMax = yMax)
title = quantityName + " surface error"
relativeError = np.abs(predValueFiltered - refValueFiltered) / refValueFiltered
plotSerie(relativeError.rename(quantityName + " Relative Error (%)"),
Title = title,
az=az,
yMin = yMin,
yMax = yMax,
zAsPercent = True)
print("RMSE : ", np.sqrt(np.mean(np.square(absoluteError))) )
print("RMSE Relative: ", np.sqrt(np.mean( | np.square(relativeError) | numpy.square |
# Distributed under the MIT License.
# See LICENSE.txt for details.
import numpy as np
def strain_curved(deriv_displacement, metric, deriv_metric,
christoffel_first_kind, displacement):
deriv_displacement_lo = (
np.einsum('jk,ik->ij', metric, deriv_displacement) +
| np.einsum('k,ijk->ij', displacement, deriv_metric) | numpy.einsum |
import cv2 as cv
import re
import numpy as np
from time import time
import os
import pickle
import image_utils as imutils
from sklearn import tree
from sklearn.model_selection import train_test_split
from sklearn.externals import joblib
import logging
from skimage.exposure import rescale_intensity
from sklearn.naive_bayes import GaussianNB
from sklearn.neural_network import MLPClassifier
from skimage.segmentation import slic
from skimage.segmentation import mark_boundaries
from skimage.util import img_as_float
model_dir = "model/"
#model_dir = "."
covs_path = model_dir+"conv_em.dat"
means_path = model_dir+"mean_em.dat"
class EMsegmentation:
def __init__(self):
self.means = pickle.load( open( means_path, "rb" ) )
self.covs = pickle.load( open( covs_path, "rb" ) )
#self.kernel = cv.getStructuringElement(cv.MORPH_ELLIPSE,(3,3))
self.kernel = cv.getStructuringElement(cv.MORPH_RECT,(3,3))
self.no_of_clusters = 2
def segment(self, img):
hsv = cv.cvtColor(img, cv.COLOR_BGR2HSV)
output = hsv.copy()
colors = np.array([[255, 255, 255], [0, 0, 0]])
x, y, z = img.shape
distance = [0] * self.no_of_clusters
t0 = time()
for i in range(x):
for j in range(y):
for k in range(self.no_of_clusters):
diff = hsv[i, j] - self.means[k]
distance[k] = abs(np.dot(np.dot(diff, self.covs[k]), diff.T))
output[i][j] = colors[distance.index(max(distance))]
#print("Segmentation done in %0.3fs" % (time() - t0))
output = cv.cvtColor(output, cv.COLOR_BGR2GRAY)
output = cv.morphologyEx(output, cv.MORPH_OPEN, self.kernel)
output = cv.morphologyEx(output, cv.MORPH_CLOSE, self.kernel)
output = cv.dilate(output,self.kernel,iterations = 1)
roi = cv.cvtColor(output,cv.COLOR_GRAY2BGR)
return roi
class BackPropagationSegmentation:
def __init__(self):
#self.disc = cv.getStructuringElement(cv.MORPH_ELLIPSE,(5,5))
self.kernel = cv.getStructuringElement(cv.MORPH_RECT,(3,3))
#initialize the kernel to use in the morphological operations
self.kernel = np.ones((5,5),np.uint8)
def segment(self, roi):
#get roi dimensions
roi_height, roi_width, roi_channels = roi.shape
#print(roi_width,roi_height)
#get center point
centerx = int(roi_width/2)
centery = int(roi_height/2)
#print(centerx,centery)
#get a square of 50x50 centered in the center point
#square roi points
sqrt_x = centerx - 25
sqrt_y = centery - 25
sqrt_w = 50
sqrt_h = 50
#get the square roi from the image
sqrt_roi = roi[sqrt_y:sqrt_y+sqrt_h, sqrt_x:sqrt_x+sqrt_w]
#cv.rectangle(img,(x,y),(x+w,y+h),(0,0,255),2)
#cv.imshow("square_roi", sqrt_roi)
hsv = cv.cvtColor(sqrt_roi,cv.COLOR_BGR2HSV)
hsvt = cv.cvtColor(roi,cv.COLOR_BGR2HSV)
# calculating object histogram
roihist = cv.calcHist([hsv],[0, 1], None, [180, 256], [0, 180, 0, 256] )
# normalize histogram and apply backprojection
cv.normalize(roihist,roihist,0,255,cv.NORM_MINMAX)
disc = cv.getStructuringElement(cv.MORPH_ELLIPSE,(5,5))
kernel = np.ones((5,5),np.uint8)
dst = cv.calcBackProject([hsvt],[0,1],roihist,[0,180,0,256],1)
cv.filter2D(dst,-1,disc,dst)
# threshold and binary AND
ret,thresh = cv.threshold(dst,50,255,0)
thresh = cv.merge((thresh,thresh,thresh))
res = cv.bitwise_and(roi,thresh)
#res = np.vstack((target,thresh,res))
#res = cv.morphologyEx(res, cv.MORPH_OPEN, kernel)
#res = cv.morphologyEx(res, cv.MORPH_CLOSE, kernel)
#res = cv.morphologyEx(res, cv.MORPH_CLOSE, kernel)
#drawCross(res,[centerx,centery],(255, 0, 255), 2)
#cv.rectangle(res,(sqrt_x,sqrt_y),(sqrt_x+sqrt_w,sqrt_y+sqrt_h),(0,0,255),2)
thresh = cv.cvtColor(thresh, cv.COLOR_BGR2GRAY)
thresh = cv.morphologyEx(thresh, cv.MORPH_OPEN, self.kernel)
thresh = cv.morphologyEx(thresh, cv.MORPH_CLOSE, self.kernel)
thresh = cv.dilate(thresh,self.kernel,iterations = 1)
thresh = cv.cvtColor(thresh,cv.COLOR_GRAY2BGR)
thresh = cv.blur(thresh,(5,5))
return thresh
class StaticColorSegmentation:
def __init__(self):
# Constants for finding range of skin color in YCrCb
self.min_YCrCb = np.array([0,133,77],np.uint8)
self.max_YCrCb = np.array([255,173,127],np.uint8)
self.kernel = cv.getStructuringElement(cv.MORPH_RECT,(3,3))
def segment(self, roi):
t0 = time()
# Convert image to YCrCb
imageYCrCb = cv.cvtColor(roi,cv.COLOR_BGR2YCR_CB)
# Find region with skin tone in YCrCb image
skinRegion = cv.inRange(imageYCrCb,self.min_YCrCb,self.max_YCrCb)
#area,roi,x,y,w,h = imutils.FindBiggestContour(skinRegion)
t1 = (time())-t0
fps = 1/t1
skinRegion = cv.morphologyEx(skinRegion, cv.MORPH_OPEN, self.kernel)
skinRegion = cv.morphologyEx(skinRegion, cv.MORPH_CLOSE, self.kernel)
#skinRegion = cv.blur(skinRegion,(3,3))
roi = cv.cvtColor(skinRegion,cv.COLOR_GRAY2BGR)
#print("roi processed in: ", t1, "s")
#print("Theoretical fps: ", fps)
return roi
class BGSegmentation:
def __init__(self):
self.bgSubThreshold = 50
self.learningRate = 0
self.kernel = np.ones((3, 3), np.uint8)
self.bgModel = cv.createBackgroundSubtractorMOG2(0, self.bgSubThreshold)
def segment(self, frame):
fgmask = self.bgModel.apply(frame,learningRate=self.learningRate)
fgmask = cv.erode(fgmask, self.kernel, iterations=1)
res = cv.bitwise_and(frame, frame, mask=fgmask)
return res
class TreeSegmentation:
def __init__(self):
self.model_path = "models/tree_skin.mod"
self.clf = joblib.load(self.model_path)
def ReadData(self):
#Data in format [B G R Label] from
data = np.genfromtxt('skin_nskin.txt', dtype=np.int32)
labels= data[:,3]
data= data[:,0:3]
return data, labels
def BGR2HSV(self, bgr):
bgr= np.reshape(bgr,(bgr.shape[0],1,3))
hsv= cv.cvtColor( | np.uint8(bgr) | numpy.uint8 |
""" Module for loading PypeIt files
"""
import os
import warnings
import numpy as np
from astropy import units
from astropy.time import Time
from astropy.io import fits
from astropy.table import Table
from linetools.spectra.xspectrum1d import XSpectrum1D
from linetools.spectra.utils import collate
import linetools.utils
from pypeit import msgs
from IPython import embed
from pypeit.core import parse
# TODO I don't think we need this routine
def load_ext_to_array(hdulist, ext_id, ex_value='OPT', flux_value=True, nmaskedge=None):
'''
It will be called by load_1dspec_to_array.
Load one-d spectra from ext_id in the hdulist
Args:
hdulist: FITS HDU list
ext_id: extension name, i.e., 'SPAT1073-SLIT0001-DET03', 'OBJID0001-ORDER0003', 'OBJID0001-ORDER0002-DET01'
ex_value: 'OPT' or 'BOX'
flux_value: if True load fluxed data, else load unfluxed data
Returns:
tuple: Returns wave, flux, ivar, mask
'''
if (ex_value != 'OPT') and (ex_value != 'BOX'):
msgs.error('{:} is not recognized. Please change to either BOX or OPT.'.format(ex_value))
# get the order/slit information
ntrace0 = np.size(hdulist)-1
idx_names = []
for ii in range(ntrace0):
idx_names.append(hdulist[ii+1].name) # idx name
# Initialize ext
ext = None
for indx in (idx_names):
if ext_id in indx:
ext = indx
if ext is None:
msgs.error('Can not find extension {:}.'.format(ext_id))
else:
hdu_iexp = hdulist[ext]
wave = hdu_iexp.data['{:}_WAVE'.format(ex_value)]
mask = hdu_iexp.data['{:}_MASK'.format(ex_value)]
# Mask Edges
if nmaskedge is not None:
mask[:int(nmaskedge)] = False
mask[-int(nmaskedge):] = False
if flux_value:
flux = hdu_iexp.data['{:}_FLAM'.format(ex_value)]
ivar = hdu_iexp.data['{:}_FLAM_IVAR'.format(ex_value)]
else:
msgs.warn('Loading unfluxed spectra')
flux = hdu_iexp.data['{:}_COUNTS'.format(ex_value)]
ivar = hdu_iexp.data['{:}_COUNTS_IVAR'.format(ex_value)]
return wave, flux, ivar, mask
# TODO merge this with unpack orders
def load_1dspec_to_array(fnames, gdobj=None, order=None, ex_value='OPT', flux_value=True, nmaskedge=None):
'''
Load the spectra from the 1d fits file into arrays.
If Echelle, you need to specify which order you want to load.
It can NOT load all orders for Echelle data.
Args:
fnames (list): 1D spectra fits file(s)
gdobj (list): extension name (longslit/multislit) or objID (Echelle)
order (None or int): order number
ex_value (str): 'OPT' or 'BOX'
flux_value (bool): if True it will load fluxed spectra, otherwise load counts
Returns:
tuple: Returns the following:
- waves (ndarray): wavelength array of your spectra, see
below for the shape information of this array.
- fluxes (ndarray): flux array of your spectra
- ivars (ndarray): ivars of your spectra
- masks (ndarray, bool): mask array of your spectra
The shapes of all returns are exactly the same.
- Case 1: np.size(fnames)=np.size(gdobj)=1, order=None for
Longslit or order=N (an int number) for Echelle
Longslit/single order for a single fits file, they are 1D
arrays with the size equal to Nspec
- Case 2: np.size(fnames)=np.size(gdobj)>1, order=None for
Longslit or order=N (an int number) for Echelle
Longslit/single order for a list of fits files, 2D array,
the shapes are Nspec by Nexp
- Case 3: np.size(fnames)=np.size(gdobj)=1, order=None All
Echelle orders for a single fits file, 2D array, the
shapes are Nspec by Norders
- Case 4: np.size(fnames)=np.size(gdobj)>1, order=None All
Echelle orders for a list of fits files, 3D array, the
shapres are Nspec by Norders by Nexp
'''
# read in the first fits file
if isinstance(fnames, (list, np.ndarray)):
nexp = np.size(fnames)
fname0 = fnames[0]
elif isinstance(fnames, str):
nexp = 1
fname0 = fnames
hdulist = fits.open(fname0)
header = hdulist[0].header
npix = header['NPIX']
pypeline = header['PYPELINE']
# get the order/slit information
ntrace0 = np.size(hdulist)-1
idx_orders = []
for ii in range(ntrace0):
idx_orders.append(int(hdulist[ii+1].name.split('-')[1][5:])) # slit ID or order ID
if pypeline == "Echelle":
## np.unique automatically sort the returned array which is not what I want!!!
## order_vec = np.unique(idx_orders)
dum, order_vec_idx = np.unique(idx_orders, return_index=True)
order_vec = np.array(idx_orders)[np.sort(order_vec_idx)]
norder = np.size(order_vec)
else:
norder = 1
#TODO This is unneccessarily complicated. The nexp=1 case does the same operations as the nexp > 1 case. Refactor
# this so that it just does the same set of operations once and then reshapes the array at the end to give you what
# you want. Let's merge this with unpack orders
## Loading data from a single fits file
if nexp == 1:
# initialize arrays
if (order is None) and (pypeline == "Echelle"):
waves = np.zeros((npix, norder,nexp))
fluxes = np.zeros_like(waves)
ivars = np.zeros_like(waves)
masks = np.zeros_like(waves, dtype=bool)
for ii, iord in enumerate(order_vec):
ext_id = gdobj[0]+'-ORDER{:04d}'.format(iord)
wave_iord, flux_iord, ivar_iord, mask_iord = load_ext_to_array(hdulist, ext_id, ex_value=ex_value,
flux_value=flux_value, nmaskedge=nmaskedge)
waves[:,ii,0] = wave_iord
fluxes[:,ii,0] = flux_iord
ivars[:,ii,0] = ivar_iord
masks[:,ii,0] = mask_iord
else:
if pypeline == "Echelle":
ext_id = gdobj[0]+'-ORDER{:04d}'.format(order)
else:
ext_id = gdobj[0]
waves, fluxes, ivars, masks = load_ext_to_array(hdulist, ext_id, ex_value=ex_value, flux_value=flux_value,
nmaskedge=nmaskedge)
## Loading data from a list of fits files
else:
# initialize arrays
if (order is None) and (pypeline == "Echelle"):
# store all orders into one single array
waves = np.zeros((npix, norder, nexp))
else:
# store a specific order or longslit
waves = | np.zeros((npix, nexp)) | numpy.zeros |
import os
import numpy as np
import cv2
import math
import argparse
def DCmakedir(path):
if os.path.exists(path):
return
else:
os.mkdir(path)
def imageRotate(img,theta):
rows,cols = img.shape[0:2]
angle = -theta*math.pi/180
a = math.sin(angle)
b = math.cos(angle)
width = int(cols * math.fabs(b) + rows * math.fabs(a))
heigth = int(rows * math.fabs(b) + cols * math.fabs(a))
M = cv2.getRotationMatrix2D((width/2,heigth/2),theta,1)
rot_move = np.dot(M,np.array([(width-cols)*0.5,(heigth-rows)*0.5,0]))
M[0,2] += rot_move[0]
M[1, 2] += rot_move[1]
imgout_xuanzhuan = cv2.warpAffine(img,M,(width,heigth),2,0,0)
return imgout_xuanzhuan
def rotate_bound(image, angle):
# grab the dimensions of the image and then determine the
# center
(h, w) = image.shape[:2]
(cX, cY) = (w // 2, h // 2)
# grab the rotation matrix (applying the negative of the
# angle to rotate clockwise), then grab the sine and cosine
# (i.e., the rotation components of the matrix)
M = cv2.getRotationMatrix2D((cX, cY), -angle, 1.0)
cos = np.abs(M[0, 0])
sin = np.abs(M[0, 1])
# compute the new bounding dimensions of the image
nW = int((h * sin) + (w * cos))
nH = int((h * cos) + (w * sin))
# adjust the rotation matrix to take into account translation
M[0, 2] += (nW / 2) - cX
M[1, 2] += (nH / 2) - cY
# perform the actual rotation and return the image
return cv2.warpAffine(image, M, (nW, nH))
#图像透视
def perspective_trans(img):
y1,x1 = img.shape[0:2]
pts1 = np.float32([[0,0],[x1,0],[0,y1],[x1,y1]])
x2_1 = np.random.randint(0, int(x1 / 6))
y2_1 = np.random.randint(0, int(y1 / 6))
x2_2 = np.random.randint(0, int(x1 / 6))
y2_2 = np.random.randint(0, int(y1 / 6))
x2_3 = np.random.randint(0, int(x1 / 6))
y2_3 = np.random.randint(0, int(y1 / 6))
x2_4 = np.random.randint(0, int(x1 / 6))
y2_4 = np.random.randint(0, int(y1 / 6))
pts2 = np.float32([[x2_1, y2_1], [x1-x2_2, y2_2],
[x2_3, y1-y2_3], [x1-x2_4, y1-y2_4]])
MM = cv2.getPerspectiveTransform(pts1,pts2)
imgout_p = cv2.warpPerspective(img,MM,(x1,y1),cv2.INTER_LINEAR,0,0)
imgout = imgout_p[min(y2_1,y2_2):y1 -min(y2_3,y2_4),min(x2_1,x2_3):x1-min(x2_2,x2_4)]
imgout = cv2.resize(imgout,(y1,x1))
return imgout
def main(args):
fgpath = args.fgpath
bgpath = args.bgpath
creatNum = args.num
saveImgpath = args.saveImgpath
saveEdgepath = args.saveEdgepath
DCmakedir(saveImgpath)
DCmakedir(saveEdgepath)
fgImglist = os.listdir(fgpath)
bgImglist = os.listdir(bgpath)
fgImgNum = len(fgImglist)
bgImgNum = len(bgImglist)
for index in range(creatNum):
randomfgIndex = np.random.randint(0,fgImgNum)
randombgIndex = np.random.randint(0,bgImgNum)
fgImg = cv2.imread(os.path.join(fgpath,fgImglist[randomfgIndex]),cv2.IMREAD_COLOR)
bgImg = cv2.imread(os.path.join(bgpath,bgImglist[randombgIndex]),cv2.IMREAD_COLOR)
try:
fgImg.shape
bgImg.shape
except:
continue
if (bgImg.shape[0]<520 or bgImg.shape[1]<520):
if(bgImg.shape[0]< bgImg.shape[1]) :
bgImg = cv2.resize(bgImg,(0, 0), fx=800/bgImg.shape[0], fy=800/bgImg.shape[0])
else:
bgImg = cv2.resize(bgImg,(0, 0), fx=800/bgImg.shape[1], fy=800/bgImg.shape[1])
bg_cut_r = np.random.randint(0,int(bgImg.shape[1]-512))
bg_cut_c = np.random.randint(0,int(bgImg.shape[0]-512))
bgImg = bgImg[bg_cut_c:bg_cut_c+512,bg_cut_r:bg_cut_r+512,:]
M = np.ones(fgImg.shape,dtype="uint8")*5
fgImg = cv2.add(fgImg,M)
need_per = np.random.randint(1,5)
if need_per%2==0:
img = perspective_trans(fgImg)
else:
img = fgImg
need_rotata = | np.random.randint(1,5) | numpy.random.randint |
import numpy as np
arr = | np.ones((5,5)) | numpy.ones |
#!/python
# https://github.com/timestocome
# Simple GRU in Python using numpy, theano
# starter code
# http://www.wildml.com/2015/09/recurrent-neural-networks-tutorial-part-2-implementing-a-language-model-rnn-with-python-numpy-and-theano/
#
# updated to python 3.5 from python 2.x
# updated to Theano version 0.8.0
# adapted to read in 'Alice In Wonderland' and 'Through the Looking Glass' and generate text in same style
# improved comments and variable names
# added regularization, then removed it. Seems to hurt more than help here
# removed sentence start/stop tokens so can more easily adapt to other types of input sequences
# lots of streamlining to make code clearer and faster
# used ReLU instead of sigmoid/tanh as activation function (much faster convergence, accuracy seems slightly better)
# removed one gru layer, the extra layer didn't help
# to do ##########################################################################
# stop after x examples randomly trained or some loss threshold met
# adjust learning rate while training, simple or new self adjusting method?
# track loss, only overwrite saved model if loss is less than previous loss
########################################
# 256 hidden, length=12, ~69 error
import numpy as np
import theano as theano
import theano.tensor as T
from theano.gradient import grad_clip
import pickle
import operator
import timeit
from datetime import datetime
import sys
import random
###############################################################################
# constants
unique_words = 4924 + 1 # unique words in our dictionary, get this from the output after running ReadDataIntoWords.py
rng = np.random.RandomState(42) # set up random stream
not_zero = 1e-6 # avoid divide by zero errors
# network settings to tweak
n_hidden = 256 # hidden layer number of nodes ( hidden layer width )
n_epoch = 4 # number of times to loop through full data set
learning_rate = 1e-4 # limits swing in gradients
adjust_learning_rate = 0.99 # decrease learning rate in regular steps
frequency_adjust_learning_rate = 2000 # how often to decrease learning rate
decay = 0.95 # weight for prior information
length_of_text = 4 # size of string to feed into RNN
n_bptt_truncate = -1 # threshold back propagation through time, -1 means no early cut off
# misc settings for outputing info to user and saving data
number_of_words_to_generate = 12 # max number of words when generating sentences
dump_output = 1000
save_model = 10000
###############################################################################
# Alice in Wonderland, Through the Looking Glass
# Note: this is a small dataset to train a recursive network with
# might do better with a larger text source
# Also might do better with a more mainstream text source, lots of made up words and
# poems and nonsense in the text
#
# Text read in, parsed and tokenized using ReadDataIntoWords.py
# this should be broken into proper sentences but for testing I'm splitting
# it into 8 word strings, no punctuation
# tokenized data is
tokenized_text = np.load('tokenized_document.npy')
# break into x, y
train_x = tokenized_text[0:-1]
train_y = tokenized_text[1:]
n_train = len(train_x)
print("Training examples ", n_train) # 56,206
# break into training vectors
index = 0
x = []
y = []
for i in range(n_train):
x.append(train_x[i : i+length_of_text]) # create a training example
y.append(train_y[i: i+length_of_text]) # shift training by one for targets
x_t = np.array(x)
y_t = np.array(y)
def randomize_data():
training_range = np.arange(len(y))
training_range = np.random.permutation(training_range)
x_train = []
y_train = []
for i in training_range:
x_train.append(x_t[i])
y_train.append(y_t[i])
return x_train, y_train
index_dictionary = pickle.load(open('index_dictionary.pkl', "rb"))
word_dictionary = pickle.load(open('word_dictionary.pkl', "rb"))
def index_to_word(w):
z = index_dictionary.get(w)
if z is None: return -1
else: return z[0]
def word_to_index(i):
z = word_dictionary.get(i)
if z is None: return -1
else: return z[0]
# vectorized versions of dictionary lookups so I can easily send arrays to functions
v_index_to_word = np.vectorize(index_to_word)
v_word_to_index = np.vectorize(word_to_index)
#############################################################################
# useful things
random_loss = np.log(unique_words) * length_of_text
print("Expected loss for random predictions: %f" % (random_loss) )
#############################################################################
# build GRU network
# input (unique_words)
# output (unique_words)
# s (hidden) # output from hidden fed into hidden in next cycle
# U (hidden, unique_words) # input to hidden
# V (unique_words, hidden) # hidden to output
# W (hidden, hidden) # hidden to hidden
class GRU:
def __init__(self, n_words=unique_words, n_hidden=n_hidden, bptt_truncate=n_bptt_truncate):
# init constants
self.n_words = n_words
self.n_hidden = n_hidden
self.bptt_truncate = bptt_truncate
n_gates = 3 # (Z: update gate, R: reset gate, C: previous hidden output)
n_layers = 1
# Initialize the network parameters
# input to hidden weights
E = np.random.uniform(-np.sqrt(1./n_words), np.sqrt(1./n_words), (n_hidden, n_words))
# weights for GRU ( U:inputs, W:previousHidden, V:outputs)
U = np.random.uniform(-np.sqrt(1./n_hidden), np.sqrt(1./n_hidden), (n_gates * n_layers, n_hidden, n_hidden))
W = np.random.uniform(-np.sqrt(1./n_hidden), np.sqrt(1./n_hidden), (n_gates * n_layers, n_hidden, n_hidden))
V = np.random.uniform(-np.sqrt(1./n_hidden), np.sqrt(1./n_hidden), (n_words, n_hidden))
# biases ( Z, R, C )
b = np.zeros((n_gates * n_layers, n_hidden))
# store hidden output ( memory )
c = np.zeros(n_words)
# Theano: Created shared variables
self.E = theano.shared(name='E', value=E.astype(theano.config.floatX))
self.U = theano.shared(name='U', value=U.astype(theano.config.floatX))
self.W = theano.shared(name='W', value=W.astype(theano.config.floatX))
self.V = theano.shared(name='V', value=V.astype(theano.config.floatX))
self.b = theano.shared(name='b', value=b.astype(theano.config.floatX))
self.c = theano.shared(name='c', value=c.astype(theano.config.floatX))
# SGD / rmsprop: Initialize parameters for derivatives
self.mE = theano.shared(name='mE', value=np.zeros(E.shape).astype(theano.config.floatX))
self.mU = theano.shared(name='mU', value=np.zeros(U.shape).astype(theano.config.floatX))
self.mV = theano.shared(name='mV', value=np.zeros(V.shape).astype(theano.config.floatX))
self.mW = theano.shared(name='mW', value=np.zeros(W.shape).astype(theano.config.floatX))
self.mb = theano.shared(name='mb', value=np.zeros(b.shape).astype(theano.config.floatX))
self.mc = theano.shared(name='mc', value=np.zeros(c.shape).astype(theano.config.floatX))
# We store the Theano graph here
self.theano = {}
self.__theano_build__()
def __theano_build__(self):
# setup
E, V, U, W, b, c = self.E, self.V, self.U, self.W, self.b, self.c
x = T.ivector('x')
y = T.ivector('y')
# input, previous hidden layer 1, previous hidden layer 2
# Z = activation(X.U + ST.W + b)
# R = activation(X.U + ST.W + b)
# H = activation(X.U + (ST*R).W + b)
# ST = (1-Z) * H + Z*ST
def forward_propagation(x_t, s_t1_prev):
x_e = E[:, x_t] # input layer
# GRU layer # 1
z_t1 = T.nnet.relu(U[0].dot(x_e) + W[0].dot(s_t1_prev) + b[0])
r_t1 = T.nnet.relu(U[1].dot(x_e) + W[1].dot(s_t1_prev) + b[1])
c_t1 = T.tanh(U[2].dot(x_e) + W[2].dot(s_t1_prev * r_t1) + b[2])
s_t1 = (T.ones_like(z_t1) - z_t1) * c_t1 + z_t1 * s_t1_prev
# Final output calculation
# Theano's softmax returns a matrix with one row, we only need the row
# changing softmax temp (scale) from 1 to lower (0.5) increases network's confidence
o_t = T.nnet.softmax(V.dot(s_t1) + c)[0]
return [o_t, s_t1]
# recurse through GRU layers
[o, s1], updates = theano.scan(
forward_propagation,
sequences = x,
truncate_gradient = self.bptt_truncate,
outputs_info = [None, dict(initial=T.zeros(self.n_hidden))])
prediction = T.argmax(o, axis=1)
o_error = T.sum(T.nnet.categorical_crossentropy(o, y))
# Total cost
cost = o_error
# Gradients
dE = T.grad(cost, E)
dU = T.grad(cost, U)
dW = T.grad(cost, W)
db = T.grad(cost, b)
dV = T.grad(cost, V)
dc = T.grad(cost, c)
# Assign functions
self.predict = theano.function([x], o, allow_input_downcast=True)
self.predict_class = theano.function([x], prediction, allow_input_downcast=True)
self.ce_error = theano.function([x, y], cost, allow_input_downcast=True) # cost to show user
self.bptt = theano.function([x, y], [dE, dU, dW, db, dV, dc], allow_input_downcast=True)
# backwards propagation
learning_rate = T.scalar('learning_rate')
decay = T.scalar('decay')
# rmsprop cache updates
# rms frequent features get small changes, rare ones get large changes
mE = decay * self.mE + (1 - decay) * dE **2
mU = decay * self.mU + (1 - decay) * dU **2
mW = decay * self.mW + (1 - decay) * dW **2
mV = decay * self.mV + (1 - decay) * dV **2
mb = decay * self.mb + (1 - decay) * db **2
mc = decay * self.mc + (1 - decay) * dc **2
# loop backwards
self.sgd_step = theano.function(
[x, y, learning_rate, theano.In(decay, value=0.9)],
[],
updates=[(E, E - learning_rate * dE / T.sqrt(mE + not_zero)),
(U, U - learning_rate * dU / T.sqrt(mU + not_zero)),
(W, W - learning_rate * dW / T.sqrt(mW + not_zero)),
(V, V - learning_rate * dV / T.sqrt(mV + not_zero)),
(b, b - learning_rate * db / T.sqrt(mb + not_zero)),
(c, c - learning_rate * dc / T.sqrt(mc + not_zero)),
(self.mE, mE),
(self.mU, mU),
(self.mW, mW),
(self.mV, mV),
(self.mb, mb),
(self.mc, mc)
], allow_input_downcast=True)
###################################################################################################
# user info functions
def sum_weights(self):
v = self.V.sum()
w = self.W.sum()
e = self.E.sum()
u = self.U.sum()
return v.eval(), w.eval(), e.eval(), u.eval()
def abs_sum_weights(self):
v = (np.abs(self.V)).sum()
w = (np.abs(self.W)).sum()
e = ( | np.abs(self.E) | numpy.abs |
import re
import pickle as pickle
from collections import namedtuple
import numpy as np
import skimage.transform
from scipy.fftpack import fftn, ifftn
from skimage.feature import peak_local_max, canny
from skimage.transform import hough_circle
import skimage.draw
from configuration import config
import utils
import skimage.exposure, skimage.filters
def read_labels(file_path):
id2labels = {}
train_csv = open(file_path)
lines = train_csv.readlines()
i = 0
for item in lines:
if i == 0:
i = 1
continue
id, systole, diastole = item.replace('\n', '').split(',')
id2labels[int(id)] = [float(systole), float(diastole)]
return id2labels
def read_slice(path):
return pickle.load(open(path))['data']
def read_fft_slice(path):
d = pickle.load(open(path))['data']
ff1 = fftn(d)
fh = np.absolute(ifftn(ff1[1, :, :]))
fh[fh < 0.1 * np.max(fh)] = 0.0
d = 1. * fh / np.max(fh)
d = np.expand_dims(d, axis=0)
return d
def read_metadata(path):
d = pickle.load(open(path))['metadata'][0]
metadata = {k: d[k] for k in ['PixelSpacing', 'ImageOrientationPatient', 'ImagePositionPatient', 'SliceLocation',
'PatientSex', 'PatientAge', 'Rows', 'Columns']}
metadata['PixelSpacing'] = np.float32(metadata['PixelSpacing'])
metadata['ImageOrientationPatient'] = np.float32(metadata['ImageOrientationPatient'])
metadata['SliceLocation'] = np.float32(metadata['SliceLocation'])
metadata['ImagePositionPatient'] = np.float32(metadata['ImagePositionPatient'])
metadata['PatientSex'] = 1 if metadata['PatientSex'] == 'F' else -1
metadata['PatientAge'] = utils.get_patient_age(metadata['PatientAge'])
metadata['Rows'] = int(metadata['Rows'])
metadata['Columns'] = int(metadata['Columns'])
return metadata
def sample_augmentation_parameters(transformation):
# TODO: bad thing to mix fixed and random params!!!
if set(transformation.keys()) == {'patch_size', 'mm_patch_size'} or \
set(transformation.keys()) == {'patch_size', 'mm_patch_size', 'mask_roi'}:
return None
shift_x = config().rng.uniform(*transformation.get('translation_range_x', [0., 0.]))
shift_y = config().rng.uniform(*transformation.get('translation_range_y', [0., 0.]))
translation = (shift_x, shift_y)
rotation = config().rng.uniform(*transformation.get('rotation_range', [0., 0.]))
shear = config().rng.uniform(*transformation.get('shear_range', [0., 0.]))
roi_scale = config().rng.uniform(*transformation.get('roi_scale_range', [1., 1.]))
z = config().rng.uniform(*transformation.get('zoom_range', [1., 1.]))
zoom = (z, z)
if 'do_flip' in transformation:
if type(transformation['do_flip']) == tuple:
flip_x = config().rng.randint(2) > 0 if transformation['do_flip'][0] else False
flip_y = config().rng.randint(2) > 0 if transformation['do_flip'][1] else False
else:
flip_x = config().rng.randint(2) > 0 if transformation['do_flip'] else False
flip_y = False
else:
flip_x, flip_y = False, False
sequence_shift = config().rng.randint(30) if transformation.get('sequence_shift', False) else 0
return namedtuple('Params', ['translation', 'rotation', 'shear', 'zoom',
'roi_scale',
'flip_x', 'flip_y',
'sequence_shift'])(translation, rotation, shear, zoom,
roi_scale,
flip_x, flip_y,
sequence_shift)
def transform_norm_rescale(data, metadata, transformation, roi=None, random_augmentation_params=None,
mm_center_location=(.5, .4), mm_patch_size=(128, 128), mask_roi=True):
patch_size = transformation['patch_size']
mm_patch_size = transformation.get('mm_patch_size', mm_patch_size)
mask_roi = transformation.get('mask_roi', mask_roi)
out_shape = (30,) + patch_size
out_data = np.zeros(out_shape, dtype='float32')
roi_center = roi['roi_center'] if roi else None
roi_radii = roi['roi_radii'] if roi else None
# correct orientation
data, roi_center, roi_radii = correct_orientation(data, metadata, roi_center, roi_radii)
# if random_augmentation_params=None -> sample new params
# if the transformation implies no augmentations then random_augmentation_params remains None
if not random_augmentation_params:
random_augmentation_params = sample_augmentation_parameters(transformation)
# build scaling transformation
pixel_spacing = metadata['PixelSpacing']
assert pixel_spacing[0] == pixel_spacing[1]
current_shape = data.shape[-2:]
# scale ROI radii and find ROI center in normalized patch
if roi_center:
mm_center_location = tuple(int(r * ps) for r, ps in zip(roi_center, pixel_spacing))
# scale the images such that they all have the same scale
norm_rescaling = 1. / pixel_spacing[0]
mm_shape = tuple(int(float(d) * ps) for d, ps in zip(current_shape, pixel_spacing))
tform_normscale = build_rescale_transform(downscale_factor=norm_rescaling,
image_shape=current_shape, target_shape=mm_shape)
tform_shift_center, tform_shift_uncenter = build_shift_center_transform(image_shape=mm_shape,
center_location=mm_center_location,
patch_size=mm_patch_size)
patch_scale = max(1. * mm_patch_size[0] / patch_size[0],
1. * mm_patch_size[1] / patch_size[1])
tform_patch_scale = build_rescale_transform(patch_scale, mm_patch_size, target_shape=patch_size)
total_tform = tform_patch_scale + tform_shift_uncenter + tform_shift_center + tform_normscale
# build random augmentation
if random_augmentation_params:
augment_tform = build_augmentation_transform(rotation=random_augmentation_params.rotation,
shear=random_augmentation_params.shear,
translation=random_augmentation_params.translation,
flip_x=random_augmentation_params.flip_x,
flip_y=random_augmentation_params.flip_y,
zoom=random_augmentation_params.zoom)
total_tform = tform_patch_scale + tform_shift_uncenter + augment_tform + tform_shift_center + tform_normscale
# apply transformation per image
for i in range(data.shape[0]):
out_data[i] = fast_warp(data[i], total_tform, output_shape=patch_size)
normalize_contrast_zmuv(out_data)
# apply transformation to ROI and mask the images
if roi_center and roi_radii and mask_roi:
roi_scale = random_augmentation_params.roi_scale if random_augmentation_params else 1 # augmentation
roi_zoom = random_augmentation_params.zoom if random_augmentation_params else (1., 1.)
rescaled_roi_radii = (roi_scale * roi_radii[0], roi_scale * roi_radii[1])
out_roi_radii = (int(roi_zoom[0] * rescaled_roi_radii[0] * pixel_spacing[0] / patch_scale),
int(roi_zoom[1] * rescaled_roi_radii[1] * pixel_spacing[1] / patch_scale))
roi_mask = make_circular_roi_mask(patch_size, (patch_size[0] / 2, patch_size[1] / 2), out_roi_radii)
out_data *= roi_mask
# if the sequence is < 30 timesteps, copy last image
if data.shape[0] < out_shape[0]:
for j in range(data.shape[0], out_shape[0]):
out_data[j] = out_data[j - 1]
# if > 30, remove images
if data.shape[0] > out_shape[0]:
out_data = out_data[:30]
# shift the sequence for a number of time steps
if random_augmentation_params:
out_data = np.roll(out_data, random_augmentation_params.sequence_shift, axis=0)
if random_augmentation_params:
targets_zoom_factor = random_augmentation_params.zoom[0] * random_augmentation_params.zoom[1]
else:
targets_zoom_factor = 1.
return out_data, targets_zoom_factor
def transform_norm_rescale_after(data, metadata, transformation, roi=None, random_augmentation_params=None,
mm_center_location=(.5, .4), mm_patch_size=(128, 128), mask_roi=True):
patch_size = transformation['patch_size']
mm_patch_size = transformation.get('mm_patch_size', mm_patch_size)
mask_roi = transformation.get('mask_roi', mask_roi)
out_shape = (30,) + patch_size
out_data = np.zeros(out_shape, dtype='float32')
roi_center = roi['roi_center'] if roi else None
roi_radii = roi['roi_radii'] if roi else None
# correct orientation
data, roi_center, roi_radii = correct_orientation(data, metadata, roi_center, roi_radii)
# if random_augmentation_params=None -> sample new params
# if the transformation implies no augmentations then random_augmentation_params remains None
if not random_augmentation_params:
random_augmentation_params = sample_augmentation_parameters(transformation)
# build scaling transformation
pixel_spacing = metadata['PixelSpacing']
assert pixel_spacing[0] == pixel_spacing[1]
current_shape = data.shape[-2:]
# scale ROI radii and find ROI center in normalized patch
if roi_center:
mm_center_location = tuple(int(r * ps) for r, ps in zip(roi_center, pixel_spacing))
# scale the images such that they all have the same scale
norm_rescaling = 1. / pixel_spacing[0]
mm_shape = tuple(int(float(d) * ps) for d, ps in zip(current_shape, pixel_spacing))
tform_normscale = build_rescale_transform(downscale_factor=norm_rescaling,
image_shape=current_shape, target_shape=mm_shape)
tform_shift_center, tform_shift_uncenter = build_shift_center_transform(image_shape=mm_shape,
center_location=mm_center_location,
patch_size=mm_patch_size)
patch_scale = max(1. * mm_patch_size[0] / patch_size[0],
1. * mm_patch_size[1] / patch_size[1])
tform_patch_scale = build_rescale_transform(patch_scale, mm_patch_size, target_shape=patch_size)
total_tform = tform_patch_scale + tform_shift_uncenter + tform_shift_center + tform_normscale
# build random augmentation
if random_augmentation_params:
augment_tform = build_augmentation_transform(rotation=random_augmentation_params.rotation,
shear=random_augmentation_params.shear,
translation=random_augmentation_params.translation,
flip_x=random_augmentation_params.flip_x,
flip_y=random_augmentation_params.flip_y,
zoom=random_augmentation_params.zoom)
total_tform = tform_patch_scale + tform_shift_uncenter + augment_tform + tform_shift_center + tform_normscale
# apply transformation per image
for i in range(data.shape[0]):
out_data[i] = fast_warp(data[i], total_tform, output_shape=patch_size)
# apply transformation to ROI and mask the images
if roi_center and roi_radii and mask_roi:
roi_scale = random_augmentation_params.roi_scale if random_augmentation_params else 1 # augmentation
roi_zoom = random_augmentation_params.zoom if random_augmentation_params else (1., 1.)
rescaled_roi_radii = (roi_scale * roi_radii[0], roi_scale * roi_radii[1])
out_roi_radii = (int(roi_zoom[0] * rescaled_roi_radii[0] * pixel_spacing[0] / patch_scale),
int(roi_zoom[1] * rescaled_roi_radii[1] * pixel_spacing[1] / patch_scale))
roi_mask = make_circular_roi_mask(patch_size, (patch_size[0] / 2, patch_size[1] / 2), out_roi_radii)
out_data *= roi_mask
normalize_contrast_zmuv(out_data)
# if the sequence is < 30 timesteps, copy last image
if data.shape[0] < out_shape[0]:
for j in range(data.shape[0], out_shape[0]):
out_data[j] = out_data[j - 1]
# if > 30, remove images
if data.shape[0] > out_shape[0]:
out_data = out_data[:30]
# shift the sequence for a number of time steps
if random_augmentation_params:
out_data = np.roll(out_data, random_augmentation_params.sequence_shift, axis=0)
if random_augmentation_params:
targets_zoom_factor = random_augmentation_params.zoom[0] * random_augmentation_params.zoom[1]
else:
targets_zoom_factor = 1.
return out_data, targets_zoom_factor
def make_roi_mask(img_shape, roi_center, roi_radii):
"""
Makes 2D ROI mask for one slice
:param data:
:param roi:
:return:
"""
mask = np.zeros(img_shape)
mask[max(0, roi_center[0] - roi_radii[0]):min(roi_center[0] + roi_radii[0], img_shape[0]),
max(0, roi_center[1] - roi_radii[1]):min(roi_center[1] + roi_radii[1], img_shape[1])] = 1
return mask
def make_circular_roi_mask(img_shape, roi_center, roi_radii):
mask = np.zeros(img_shape)
rr, cc = skimage.draw.ellipse(roi_center[0], roi_center[1], roi_radii[0], roi_radii[1], img_shape)
mask[rr, cc] = 1.
return mask
tform_identity = skimage.transform.AffineTransform()
def fast_warp(img, tf, output_shape, mode='constant', order=1):
"""
This wrapper function is faster than skimage.transform.warp
"""
m = tf.params # tf._matrix is
return skimage.transform._warps_cy._warp_fast(img, m, output_shape=output_shape, mode=mode, order=order)
def build_centering_transform(image_shape, target_shape=(50, 50)):
rows, cols = image_shape
trows, tcols = target_shape
shift_x = (cols - tcols) / 2.0
shift_y = (rows - trows) / 2.0
return skimage.transform.SimilarityTransform(translation=(shift_x, shift_y))
def build_rescale_transform(downscale_factor, image_shape, target_shape):
"""
estimating the correct rescaling transform is slow, so just use the
downscale_factor to define a transform directly. This probably isn't
100% correct, but it shouldn't matter much in practice.
"""
rows, cols = image_shape
trows, tcols = target_shape
tform_ds = skimage.transform.AffineTransform(scale=(downscale_factor, downscale_factor))
# centering
shift_x = cols / (2.0 * downscale_factor) - tcols / 2.0
shift_y = rows / (2.0 * downscale_factor) - trows / 2.0
tform_shift_ds = skimage.transform.SimilarityTransform(translation=(shift_x, shift_y))
return tform_shift_ds + tform_ds
def build_center_uncenter_transforms(image_shape):
"""
These are used to ensure that zooming and rotation happens around the center of the image.
Use these transforms to center and uncenter the image around such a transform.
"""
center_shift = np.array(
[image_shape[1], image_shape[0]]) / 2.0 - 0.5 # need to swap rows and cols here apparently! confusing!
tform_uncenter = skimage.transform.SimilarityTransform(translation=-center_shift)
tform_center = skimage.transform.SimilarityTransform(translation=center_shift)
return tform_center, tform_uncenter
def build_augmentation_transform(rotation=0, shear=0, translation=(0, 0), flip_x=False, flip_y=False, zoom=(1.0, 1.0)):
if flip_x:
shear += 180 # shear by 180 degrees is equivalent to flip along the X-axis
if flip_y:
shear += 180
rotation += 180
tform_augment = skimage.transform.AffineTransform(scale=(1. / zoom[0], 1. / zoom[1]), rotation=np.deg2rad(rotation),
shear=np.deg2rad(shear), translation=translation)
return tform_augment
def correct_orientation(data, metadata, roi_center, roi_radii):
F = metadata["ImageOrientationPatient"].reshape((2, 3))
f_1 = F[1, :]
f_2 = F[0, :]
y_e = | np.array([0, 1, 0]) | numpy.array |
# This source code file is a part of SigProfilerTopography
# SigProfilerTopography is a tool included as part of the SigProfiler
# computational framework for comprehensive analysis of mutational
# signatures from next-generation sequencing of cancer genomes.
# SigProfilerTopography provides the downstream data analysis of
# mutations and extracted mutational signatures w.r.t.
# nucleosome occupancy, replication time, strand bias and processivity.
# Copyright (C) 2018-2020 <NAME>
# #############################################################
# import sys
# import os
# current_abs_path = os.path.dirname(os.path.realpath(__file__))
# commonsPath = os.path.join(current_abs_path,'commons')
# sys.path.append(commonsPath)
# #############################################################
import math
import time
import numpy as np
import pandas as pd
import scipy
import statsmodels
import matplotlib as plt
import shutil
import platform
import multiprocessing
import SigProfilerMatrixGenerator as matrix_generator
MATRIX_GENERATOR_PATH = matrix_generator.__path__[0]
from SigProfilerMatrixGenerator import version as matrix_generator_version
from SigProfilerSimulator import version as simulator_version
from SigProfilerMatrixGenerator.scripts import SigProfilerMatrixGeneratorFunc as matGen
from SigProfilerSimulator import SigProfilerSimulator as simulator
from SigProfilerTopography import version as topography_version
from SigProfilerTopography.source.commons.TopographyCommons import readProbabilities
from SigProfilerTopography.source.commons.TopographyCommons import readChrBasedMutationsMergeWithProbabilitiesAndWrite
from SigProfilerTopography.source.commons.TopographyCommons import DATA
from SigProfilerTopography.source.commons.TopographyCommons import FIGURE
from SigProfilerTopography.source.commons.TopographyCommons import SAMPLE
from SigProfilerTopography.source.commons.TopographyCommons import K562
from SigProfilerTopography.source.commons.TopographyCommons import MCF7
from SigProfilerTopography.source.commons.TopographyCommons import MEF
from SigProfilerTopography.source.commons.TopographyCommons import MM10
from SigProfilerTopography.source.commons.TopographyCommons import GRCh37
from SigProfilerTopography.source.commons.TopographyCommons import SIGPROFILERTOPOGRAPHY_DEFAULT_FILES
from SigProfilerTopography.source.commons.TopographyCommons import getNucleosomeFile
from SigProfilerTopography.source.commons.TopographyCommons import getReplicationTimeFiles
from SigProfilerTopography.source.commons.TopographyCommons import available_nucleosome_biosamples
from SigProfilerTopography.source.commons.TopographyCommons import available_replication_time_biosamples
from SigProfilerTopography.source.commons.TopographyCommons import EPIGENOMICSOCCUPANCY
from SigProfilerTopography.source.commons.TopographyCommons import NUCLEOSOMEOCCUPANCY
from SigProfilerTopography.source.commons.TopographyCommons import REPLICATIONTIME
from SigProfilerTopography.source.commons.TopographyCommons import REPLICATIONSTRANDBIAS
from SigProfilerTopography.source.commons.TopographyCommons import TRANSCRIPTIONSTRANDBIAS
from SigProfilerTopography.source.commons.TopographyCommons import PROCESSIVITY
from SigProfilerTopography.source.commons.TopographyCommons import EPIGENOMICS
from SigProfilerTopography.source.commons.TopographyCommons import STRANDBIAS
from SigProfilerTopography.source.commons.TopographyCommons import DEFAULT_H3K27ME3_OCCUPANCY_FILE
from SigProfilerTopography.source.commons.TopographyCommons import DEFAULT_H3K36ME3_OCCUPANCY_FILE
from SigProfilerTopography.source.commons.TopographyCommons import DEFAULT_H3K9ME3_OCCUPANCY_FILE
from SigProfilerTopography.source.commons.TopographyCommons import DEFAULT_H3K27AC_OCCUPANCY_FILE
from SigProfilerTopography.source.commons.TopographyCommons import DEFAULT_H3K4ME1_OCCUPANCY_FILE
from SigProfilerTopography.source.commons.TopographyCommons import DEFAULT_H3K4ME3_OCCUPANCY_FILE
from SigProfilerTopography.source.commons.TopographyCommons import DEFAULT_CTCF_OCCUPANCY_FILE
from SigProfilerTopography.source.commons.TopographyCommons import DEFAULT_ATAC_SEQ_OCCUPANCY_FILE
from SigProfilerTopography.source.commons.TopographyCommons import MM10_MEF_NUCLEOSOME_FILE
from SigProfilerTopography.source.commons.TopographyCommons import GM12878_NUCLEOSOME_OCCUPANCY_FILE
from SigProfilerTopography.source.commons.TopographyCommons import K562_NUCLEOSOME_OCCUPANCY_FILE
from SigProfilerTopography.source.commons.TopographyCommons import ENCFF575PMI_mm10_embryonic_facial_prominence_ATAC_seq
from SigProfilerTopography.source.commons.TopographyCommons import ENCFF993SRY_mm10_embryonic_fibroblast_H3K4me1
from SigProfilerTopography.source.commons.TopographyCommons import ENCFF912DNP_mm10_embryonic_fibroblast_H3K4me3
from SigProfilerTopography.source.commons.TopographyCommons import ENCFF611HDQ_mm10_embryonic_fibroblast_CTCF
from SigProfilerTopography.source.commons.TopographyCommons import ENCFF152DUV_mm10_embryonic_fibroblast_POLR2A
from SigProfilerTopography.source.commons.TopographyCommons import ENCFF114VLZ_mm10_embryonic_fibroblast_H3K27ac
from SigProfilerTopography.source.commons.TopographyCommons import SBS
from SigProfilerTopography.source.commons.TopographyCommons import DBS
from SigProfilerTopography.source.commons.TopographyCommons import ID
from SigProfilerTopography.source.commons.TopographyCommons import UNDECLARED
from SigProfilerTopography.source.commons.TopographyCommons import USING_APPLY_ASYNC
from SigProfilerTopography.source.commons.TopographyCommons import USING_APPLY_ASYNC_FOR_EACH_CHROM_AND_SIM
from SigProfilerTopography.source.commons.TopographyCommons import USING_APPLY_ASYNC_FOR_EACH_CHROM_AND_SIM_SPLIT
from SigProfilerTopography.source.commons.TopographyCommons import STRINGENT
from SigProfilerTopography.source.commons.TopographyCommons import DEFAULT_AVERAGE_PROBABILITY
from SigProfilerTopography.source.commons.TopographyCommons import DEFAULT_NUM_OF_SBS_REQUIRED
from SigProfilerTopography.source.commons.TopographyCommons import DEFAULT_NUM_OF_DBS_REQUIRED
from SigProfilerTopography.source.commons.TopographyCommons import DEFAULT_NUM_OF_ID_REQUIRED
from SigProfilerTopography.source.commons.TopographyCommons import DEFAULT_NUM_OF_REAL_DATA_OVERLAP_REQUIRED
from SigProfilerTopography.source.commons.TopographyCommons import CONSIDER_COUNT
from SigProfilerTopography.source.commons.TopographyCommons import CONSIDER_DISTANCE
from SigProfilerTopography.source.commons.TopographyCommons import CONSIDER_DISTANCE_ALL_SAMPLES_TOGETHER
from SigProfilerTopography.source.commons.TopographyCommons import MISSING_SIGNAL
from SigProfilerTopography.source.commons.TopographyCommons import NO_SIGNAL
from SigProfilerTopography.source.commons.TopographyCommons import SBS96
from SigProfilerTopography.source.commons.TopographyCommons import ID
from SigProfilerTopography.source.commons.TopographyCommons import DBS
from SigProfilerTopography.source.commons.TopographyCommons import SUBS
from SigProfilerTopography.source.commons.TopographyCommons import INDELS
from SigProfilerTopography.source.commons.TopographyCommons import DINUCS
from SigProfilerTopography.source.commons.TopographyCommons import SBS_CONTEXTS
from SigProfilerTopography.source.commons.TopographyCommons import SNV
from SigProfilerTopography.source.commons.TopographyCommons import CHRBASED
from SigProfilerTopography.source.commons.TopographyCommons import LIB
from SigProfilerTopography.source.commons.TopographyCommons import getChromSizesDict
from SigProfilerTopography.source.commons.TopographyCommons import getShortNames
from SigProfilerTopography.source.commons.TopographyCommons import copyMafFiles
from SigProfilerTopography.source.commons.TopographyCommons import fillCutoff2Signature2PropertiesListDictionary
from SigProfilerTopography.source.commons.TopographyCommons import fill_signature_number_of_mutations_df
from SigProfilerTopography.source.commons.TopographyCommons import fill_mutations_dictionaries_write
from SigProfilerTopography.source.commons.TopographyCommons import get_mutation_type_context_for_probabilities_file
from SigProfilerTopography.source.commons.TopographyCommons import Table_MutationType_NumberofMutations_NumberofSamples_SamplesList_Filename
from SigProfilerTopography.source.commons.TopographyCommons import Table_ChrLong_NumberofMutations_Filename
from SigProfilerTopography.source.commons.TopographyCommons import Table_SBS_Signature_Discreet_Mode_Cutoff_NumberofMutations_AverageProbability_Filename
from SigProfilerTopography.source.commons.TopographyCommons import Table_DBS_Signature_Discreet_Mode_Cutoff_NumberofMutations_AverageProbability_Filename
from SigProfilerTopography.source.commons.TopographyCommons import Table_ID_Signature_Discreet_Mode_Cutoff_NumberofMutations_AverageProbability_Filename
from SigProfilerTopography.source.commons.TopographyCommons import Table_SBS_Signature_Probability_Mode_NumberofMutations_AverageProbability_Filename
from SigProfilerTopography.source.commons.TopographyCommons import Table_DBS_Signature_Probability_Mode_NumberofMutations_AverageProbability_Filename
from SigProfilerTopography.source.commons.TopographyCommons import Table_ID_Signature_Probability_Mode_NumberofMutations_AverageProbability_Filename
from SigProfilerTopography.source.commons.TopographyCommons import NUMBER_OF_MUTATIONS_IN_EACH_SPLIT
from SigProfilerTopography.source.occupancy.OccupancyAnalysis import occupancyAnalysis
from SigProfilerTopography.source.replicationtime.ReplicationTimeAnalysis import replicationTimeAnalysis
from SigProfilerTopography.source.replicationstrandbias.ReplicationStrandBiasAnalysis import replicationStrandBiasAnalysis
from SigProfilerTopography.source.transcriptionstrandbias.TranscriptionStrandBiasAnalysis import transcriptionStrandBiasAnalysis
from SigProfilerTopography.source.processivity.ProcessivityAnalysis import processivityAnalysis
from SigProfilerTopography.source.plotting.OccupancyAverageSignalFigures import occupancyAverageSignalFigures
from SigProfilerTopography.source.plotting.OccupancyAverageSignalFigures import compute_fold_change_with_p_values_plot_heatmaps
from SigProfilerTopography.source.plotting.ReplicationTimeNormalizedMutationDensityFigures import replicationTimeNormalizedMutationDensityFigures
from SigProfilerTopography.source.plotting.TranscriptionReplicationStrandBiasFigures import transcriptionReplicationStrandBiasFiguresUsingDataframes
from SigProfilerTopography.source.plotting.ProcessivityFigures import processivityFigures
from SigProfilerTopography.source.commons.TopographyCommons import TRANSCRIBED_VERSUS_UNTRANSCRIBED
from SigProfilerTopography.source.commons.TopographyCommons import GENIC_VERSUS_INTERGENIC
from SigProfilerTopography.source.commons.TopographyCommons import LAGGING_VERSUS_LEADING
from SigProfilerTopography.source.commons.TopographyCommons import PLOTTING_FOR_SIGPROFILERTOPOGRAPHY_TOOL
from SigProfilerTopography.source.commons.TopographyCommons import COMBINE_P_VALUES_METHOD_FISHER
from SigProfilerTopography.source.commons.TopographyCommons import WEIGHTED_AVERAGE_METHOD
from SigProfilerTopography.source.commons.TopographyCommons import COLORBAR_SEISMIC
from SigProfilerTopography.source.commons.TopographyCommons import natural_key
############################################################
#Can be move to DataPreparationCommons under /source/commons
#read chr based dinucs (provided by SigProfilerMatrixGenerator) and merge with probabilities (provided by SigProfilerTopography)
def prepareMutationsDataAfterMatrixGenerationAndExtractorForTopography(chromShortNamesList,
inputDir,
outputDir,
jobname,
mutation_type_context,
mutations_probabilities_file_path,
mutation_type_context_for_probabilities,
startSimNum,
endSimNum,
partialDirname,
PCAWG,
verbose):
###########################################################################################
#original matrix generator chrbased data will be under inputDir/output/vcf_files/SNV
#original matrix generator chrbased data will be under inputDir/output/vcf_files/DBS
#original matrix generator chrbased data will be under inputDir/output/vcf_files/ID
#sim1 matrix generator chrbased data will be under inputDir/output/simulations/sim1/96/output/vcf_files/SNV
#sim1 matrix generator chrbased data will be under inputDir/output/simulations/sim1/ID/output/vcf_files/ID
#sim1 matrix generator chrbased data will be under inputDir/output/simulations/sim1/DBS/output/vcf_files/DBS
df_columns_contain_ordered_signatures = None
os.makedirs(os.path.join(outputDir,jobname,DATA,CHRBASED),exist_ok=True)
for simNum in range(1,endSimNum+1):
simName = 'sim%d' % (simNum)
os.makedirs(os.path.join(outputDir,jobname,DATA,CHRBASED,simName), exist_ok=True)
###########################################################################################
###########################################################################################
if ((mutations_probabilities_file_path is not None) and (os.path.exists(mutations_probabilities_file_path))):
##########################################################################################
mutations_probabilities_df = readProbabilities(mutations_probabilities_file_path, verbose)
df_columns_contain_ordered_signatures = mutations_probabilities_df.columns.values
##########################################################################################
if verbose:
print('\tVerbose mutations_probabilities_df.head()')
print('\tVerbose %s' %(mutations_probabilities_df.head()))
print('\tVerbose mutations_probabilities_df.columns.values')
print('\tVerbose %s' %(mutations_probabilities_df.columns.values))
##########################################################################################
#Step1 SigProfilerTopography Python Package
#For Release we will use SAMPLE as it is, no change in SAMPLE column is needed.
# For PCAWG_Matlab
# This statement below is customized for PCAWG_Matlab
# To get rid of inconsistent cancer type names in sample column of chrbased mutation files and probabilities files
# Breast-LobularCA_SP124191
if PCAWG:
mutations_probabilities_df[SAMPLE] = mutations_probabilities_df[SAMPLE].str.split('_',expand=True)[1]
##########################################################################################
############################################################################################
############################## pool.apply_async starts ####################################
############################################################################################
################################
numofProcesses = multiprocessing.cpu_count()
pool = multiprocessing.Pool(processes=numofProcesses)
################################
################################
jobs = []
################################
sim_nums = range(startSimNum,endSimNum+1)
sim_num_chr_tuples = ((sim_num, chrShort) for sim_num in sim_nums for chrShort in chromShortNamesList)
for simNum, chrShort in sim_num_chr_tuples:
simName = 'sim%d' % (simNum)
chr_based_mutation_filename = '%s_seqinfo.txt' % (chrShort)
if (simNum == 0):
matrix_generator_output_dir_path = os.path.join(inputDir, 'output', 'vcf_files', partialDirname)
else:
matrix_generator_output_dir_path = os.path.join(inputDir, 'output', 'simulations', simName,mutation_type_context, 'output', 'vcf_files',partialDirname)
if (os.path.exists(matrix_generator_output_dir_path)):
chr_based_mutation_filepath = os.path.join(matrix_generator_output_dir_path,chr_based_mutation_filename)
inputList = []
inputList.append(chrShort)
inputList.append(outputDir)
inputList.append(jobname)
inputList.append(chr_based_mutation_filepath)
inputList.append(mutations_probabilities_df)
inputList.append(mutation_type_context_for_probabilities)
inputList.append(mutation_type_context)
inputList.append(simNum)
inputList.append(PCAWG)
jobs.append(pool.apply_async(readChrBasedMutationsMergeWithProbabilitiesAndWrite,args=(inputList,)))
################################################################################
##############################################################################
# wait for all jobs to finish
for job in jobs:
if verbose: print('\tVerbose Transcription Strand Bias Worker pid %s job.get():%s ' % (str(os.getpid()), job.get()))
##############################################################################
################################
pool.close()
pool.join()
################################
############################################################################################
############################## pool.apply_async ends ######################################
############################################################################################
###########################################################################################
###########################################################################################
elif ((mutations_probabilities_file_path is None) or (not (os.path.exists(mutations_probabilities_file_path)))):
#For Information
print('--- There is a situation/problem: mutations_probabilities_file_path:%s is None or does not exist.' %(mutations_probabilities_file_path))
############################################################################################
############################## pool.apply_async starts ####################################
############################################################################################
################################
numofProcesses = multiprocessing.cpu_count()
pool = multiprocessing.Pool(processes=numofProcesses)
################################
################################
jobs = []
################################
sim_nums = range(startSimNum,endSimNum+1)
sim_num_chr_tuples = ((sim_num, chrShort) for sim_num in sim_nums for chrShort in chromShortNamesList)
for simNum, chrShort in sim_num_chr_tuples:
simName = 'sim%d' % (simNum)
chr_based_mutation_filename = '%s_seqinfo.txt' % (chrShort)
if (simNum == 0):
matrix_generator_output_dir_path = os.path.join(inputDir, 'output', 'vcf_files', partialDirname)
else:
matrix_generator_output_dir_path = os.path.join(inputDir, 'output', 'simulations', simName,mutation_type_context, 'output', 'vcf_files',partialDirname)
if (os.path.exists(matrix_generator_output_dir_path)):
chr_based_mutation_filepath = os.path.join(matrix_generator_output_dir_path,chr_based_mutation_filename)
inputList = []
inputList.append(chrShort)
inputList.append(outputDir)
inputList.append(jobname)
inputList.append(chr_based_mutation_filepath)
inputList.append(None)
inputList.append(mutation_type_context_for_probabilities)
inputList.append(mutation_type_context)
inputList.append(simNum)
inputList.append(PCAWG)
jobs.append(pool.apply_async(readChrBasedMutationsMergeWithProbabilitiesAndWrite,args=(inputList,)))
################################################################################
##############################################################################
# wait for all jobs to finish
for job in jobs:
if verbose: print('\tVerbose Transcription Strand Bias Worker pid %s job.get():%s ' % (str(os.getpid()), job.get()))
##############################################################################
################################
pool.close()
pool.join()
################################
############################################################################################
############################## pool.apply_async ends ######################################
############################################################################################
return df_columns_contain_ordered_signatures
###########################################################################################
############################################################
#######################################################
#JAN 9, 2020
def check_download_replication_time_files(replication_time_signal_file,replication_time_valley_file,replication_time_peak_file):
current_abs_path = os.path.dirname(os.path.abspath(__file__))
# print(current_abs_path)
#These are currently full path, therefore convert them to filename
replication_time_signal_file=os.path.basename(replication_time_signal_file)
replication_time_valley_file=os.path.basename(replication_time_valley_file)
replication_time_peak_file=os.path.basename(replication_time_peak_file)
os.makedirs(os.path.join(current_abs_path,'lib','replication'),exist_ok=True)
lib_replication_path = os.path.join(current_abs_path,'lib','replication')
if os.path.isabs(lib_replication_path):
# print('%s an absolute path.' %(lib_replication_path))
os.chdir(lib_replication_path)
replication_time_signal_file_path= os.path.join(lib_replication_path,replication_time_signal_file)
replication_time_valley_file_path= os.path.join(lib_replication_path,replication_time_valley_file)
replication_time_peak_file_path= os.path.join(lib_replication_path,replication_time_peak_file)
if not os.path.exists(replication_time_signal_file_path):
print('Does not exists: %s' %(replication_time_signal_file_path))
try:
# print('Downloading %s_signal_wgEncodeSydhNsome_%sSig.npy under %s' %(chrLong,cell_line,chrbased_npy_array_path))
print('Downloading %s under %s' % (replication_time_signal_file, lib_replication_path))
#wget -c Continue getting a partially-downloaded file
#wget -nc If a file is downloaded more than once in the same directory, the local file will be clobbered, or overwritten
# cmd="bash -c '" + 'wget -r -l1 -c -nc --no-parent -nd -P ' + chrombased_npy_path + ' ftp://alexandrovlab-ftp.ucsd.edu/pub/tools/SigProfilerTopography/lib/nucleosome/chrbased/' + filename + "'"
cmd="bash -c '" + 'wget -r -l1 -c -nc --no-parent -nd ftp://alexandrovlab-ftp.ucsd.edu/pub/tools/SigProfilerTopography/lib/replication/' + replication_time_signal_file + "'"
# print(cmd)
os.system(cmd)
except:
# print("The UCSD ftp site is not responding...pulling from sanger ftp now.")
print("The ftp://alexandrovlab-ftp.ucsd.edu site is not responding...")
if not os.path.exists(replication_time_valley_file_path):
print('Does not exists: %s' %(replication_time_valley_file_path))
try:
# print('Downloading %s_signal_wgEncodeSydhNsome_%sSig.npy under %s' %(chrLong,cell_line,chrbased_npy_array_path))
print('Downloading %s under %s' % (replication_time_valley_file, lib_replication_path))
#wget -c Continue getting a partially-downloaded file
#wget -nc If a file is downloaded more than once in the same directory, the local file will be clobbered, or overwritten
# cmd="bash -c '" + 'wget -r -l1 -c -nc --no-parent -nd -P ' + chrombased_npy_path + ' ftp://alexandrovlab-ftp.ucsd.edu/pub/tools/SigProfilerTopography/lib/nucleosome/chrbased/' + filename + "'"
cmd="bash -c '" + 'wget -r -l1 -c -nc --no-parent -nd ftp://alexandrovlab-ftp.ucsd.edu/pub/tools/SigProfilerTopography/lib/replication/' + replication_time_valley_file + "'"
# print(cmd)
os.system(cmd)
except:
# print("The UCSD ftp site is not responding...pulling from sanger ftp now.")
print("The ftp://alexandrovlab-ftp.ucsd.edu site is not responding...")
if not os.path.exists(replication_time_peak_file_path):
print('Does not exists: %s' %(replication_time_peak_file_path))
try:
# print('Downloading %s_signal_wgEncodeSydhNsome_%sSig.npy under %s' %(chrLong,cell_line,chrbased_npy_array_path))
print('Downloading %s under %s' % (replication_time_peak_file, lib_replication_path))
#wget -c Continue getting a partially-downloaded file
#wget -nc If a file is downloaded more than once in the same directory, the local file will be clobbered, or overwritten
# cmd="bash -c '" + 'wget -r -l1 -c -nc --no-parent -nd -P ' + chrombased_npy_path + ' ftp://alexandrovlab-ftp.ucsd.edu/pub/tools/SigProfilerTopography/lib/nucleosome/chrbased/' + filename + "'"
cmd="bash -c '" + 'wget -r -l1 -c -nc --no-parent -nd ftp://alexandrovlab-ftp.ucsd.edu/pub/tools/SigProfilerTopography/lib/replication/' + replication_time_peak_file + "'"
# print(cmd)
os.system(cmd)
except:
# print("The UCSD ftp site is not responding...pulling from sanger ftp now.")
print("The ftp://alexandrovlab-ftp.ucsd.edu site is not responding...")
else:
#It has to be an absolute path
print('%s is not an absolute path.' %(lib_replication_path))
#go back
os.chdir(current_abs_path)
#######################################################
def check_download_sample_probability_files():
current_path = os.getcwd()
os.makedirs(os.path.join(current_path, 'sample_probabilities'), exist_ok=True)
sample_probability_files_path = os.path.join(current_path, 'sample_probabilities')
probability_files = ['COSMIC_DBS78_Decomposed_Mutation_Probabilities.txt',
'COSMIC_SBS96_Decomposed_Mutation_Probabilities.txt']
if os.path.isabs(sample_probability_files_path):
os.chdir(sample_probability_files_path)
for probability_filename in probability_files:
probability_file_path = os.path.join(sample_probability_files_path, probability_filename)
if not os.path.exists(probability_file_path):
print('Does not exists: %s' % (probability_file_path))
try:
print('Downloading %s under %s' % (probability_filename, sample_probability_files_path))
# wget -c Continue getting a partially-downloaded file
# wget -nc If a file is downloaded more than once in the same directory, the local file will be clobbered, or overwritten
# cmd="bash -c '" + 'wget -r -l1 -c -nc --no-parent -nd -P ' + chrombased_npy_path + ' ftp://alexandrovlab-ftp.ucsd.edu/pub/tools/SigProfilerTopography/lib/nucleosome/chrbased/' + filename + "'"
# -r When included, the wget will recursively traverse subdirectories in order to obtain all content.
# -l1 Limit recursion depth to a specific number of levels, by setting the <#> variable to the desired number.
# -c option to resume a download
# -nc, --no-clobber If a file is downloaded more than once in the same directory, Wget's behavior depends on a few options, including -nc. In certain cases, the local file will be clobbered, or overwritten, upon repeated download. In other cases it will be preserved.
# -np, --no-parent Do not ever ascend to the parent directory when retrieving recursively. This is a useful option, since it guarantees that only the files below a certain hierarchy will be downloaded.
# -nd, --no-directories When included, directories will not be created. All files captured in the wget will be copied directly in to the active directory
cmd = "bash -c '" + 'wget -r -l1 -c -nc --no-parent -nd ftp://alexandrovlab-ftp.ucsd.edu/pub/tools/SigProfilerTopography/sample_probability_files/' + probability_filename + "'"
print("cmd: %s" % cmd)
os.system(cmd)
except:
print("The UCSD ftp site is not responding...")
else:
# It has to be an absolute path
print('%s is not an absolute path.' % (sample_probability_files_path))
# go back
os.chdir(current_path)
def check_download_sample_vcf_files():
current_path = os.getcwd()
os.makedirs(os.path.join(current_path, 'sample_vcfs'), exist_ok=True)
sample_vcf_files_path = os.path.join(current_path, 'sample_vcfs')
vcf_files = ['PD4248a.vcf', 'PD4199a.vcf', 'PD4198a.vcf', 'PD4194a.vcf', 'PD4192a.vcf', 'PD4120a.vcf',
'PD4116a.vcf', 'PD4115a.vcf', 'PD4109a.vcf', 'PD4107a.vcf', 'PD4103a.vcf', 'PD4088a.vcf',
'PD4086a.vcf', 'PD4085a.vcf', 'PD4006a.vcf', 'PD4005a.vcf', 'PD3945a.vcf', 'PD3905a.vcf',
'PD3904a.vcf', 'PD3890a.vcf', 'PD3851a.vcf']
if os.path.isabs(sample_vcf_files_path):
os.chdir(sample_vcf_files_path)
for vcf_filename in vcf_files:
vcf_file_path = os.path.join(sample_vcf_files_path, vcf_filename)
if not os.path.exists(vcf_file_path):
print('Does not exists: %s' % (vcf_file_path))
try:
print('Downloading %s under %s' % (vcf_filename, sample_vcf_files_path))
# wget -c Continue getting a partially-downloaded file
# wget -nc If a file is downloaded more than once in the same directory, the local file will be clobbered, or overwritten
# cmd="bash -c '" + 'wget -r -l1 -c -nc --no-parent -nd -P ' + chrombased_npy_path + ' ftp://alexandrovlab-ftp.ucsd.edu/pub/tools/SigProfilerTopography/lib/nucleosome/chrbased/' + filename + "'"
# -r When included, the wget will recursively traverse subdirectories in order to obtain all content.
# -l1 Limit recursion depth to a specific number of levels, by setting the <#> variable to the desired number.
# -c option to resume a download
# -nc, --no-clobber If a file is downloaded more than once in the same directory, Wget's behavior depends on a few options, including -nc. In certain cases, the local file will be clobbered, or overwritten, upon repeated download. In other cases it will be preserved.
# -np, --no-parent Do not ever ascend to the parent directory when retrieving recursively. This is a useful option, since it guarantees that only the files below a certain hierarchy will be downloaded.
# -nd, --no-directories When included, directories will not be created. All files captured in the wget will be copied directly in to the active directory
cmd = "bash -c '" + 'wget -r -l1 -c -nc --no-parent -nd ftp://alexandrovlab-ftp.ucsd.edu/pub/tools/SigProfilerTopography/sample_vcf_files/' + vcf_filename + "'"
print("cmd: %s" % cmd)
os.system(cmd)
except:
print("The UCSD ftp site is not responding...")
else:
# It has to be an absolute path
print('%s is not an absolute path.' % (sample_vcf_files_path))
# go back
os.chdir(current_path)
def check_download_chrbased_npy_atac_seq_files(atac_seq_file,chromNamesList):
current_abs_path = os.path.dirname(os.path.abspath(__file__))
# print(current_abs_path)
os.makedirs(os.path.join(current_abs_path,'lib','epigenomics','chrbased'),exist_ok=True)
chrombased_npy_path = os.path.join(current_abs_path,'lib','epigenomics','chrbased')
# print(chrombased_npy_path)
if os.path.isabs(chrombased_npy_path):
# print('%s an absolute path.' %(chrombased_npy_path))
os.chdir(chrombased_npy_path)
atac_seq_filename_wo_extension = os.path.splitext(os.path.basename(atac_seq_file))[0]
for chrLong in chromNamesList:
filename = '%s_signal_%s.npy' % (chrLong, atac_seq_filename_wo_extension)
chrbased_npy_array_path = os.path.join(chrombased_npy_path, filename)
if not os.path.exists(chrbased_npy_array_path):
print('Does not exists: %s' % (chrbased_npy_array_path))
try:
print('Downloading %s under %s' % (filename, chrbased_npy_array_path))
# wget -c Continue getting a partially-downloaded file
# wget -nc If a file is downloaded more than once in the same directory, the local file will be clobbered, or overwritten
# cmd="bash -c '" + 'wget -r -l1 -c -nc --no-parent -nd -P ' + chrombased_npy_path + ' ftp://alexandrovlab-ftp.ucsd.edu/pub/tools/SigProfilerTopography/lib/nucleosome/chrbased/' + filename + "'"
# -r When included, the wget will recursively traverse subdirectories in order to obtain all content.
# -l1 Limit recursion depth to a specific number of levels, by setting the <#> variable to the desired number.
# -c option to resume a download
# -nc, --no-clobber If a file is downloaded more than once in the same directory, Wget's behavior depends on a few options, including -nc. In certain cases, the local file will be clobbered, or overwritten, upon repeated download. In other cases it will be preserved.
# -np, --no-parent Do not ever ascend to the parent directory when retrieving recursively. This is a useful option, since it guarantees that only the files below a certain hierarchy will be downloaded.
# -nd, --no-directories When included, directories will not be created. All files captured in the wget will be copied directly in to the active directory
cmd = "bash -c '" + 'wget -r -l1 -c -nc --no-parent -nd ftp://alexandrovlab-ftp.ucsd.edu/pub/tools/SigProfilerTopography/lib/epigenomics/chrbased/' + filename + "'"
print("cmd: %s" %cmd)
os.system(cmd)
except:
# print("The UCSD ftp site is not responding...pulling from sanger ftp now.")
print("The UCSD ftp site is not responding...")
else:
#It has to be an absolute path
print('%s is not an absolute path.' %(chrombased_npy_path))
#go back
os.chdir(current_abs_path)
#######################################################
#Nov25, 2019
# Download nucleosome occupancy chr based npy files from ftp alexandrovlab if they do not exists
# We are using this function if user is using our available nucleosome data for GM12878 adnd K562 cell lines
def check_download_chrbased_npy_nuclesome_files(nucleosome_file,chromNamesList):
current_abs_path = os.path.dirname(os.path.abspath(__file__))
# print(current_abs_path)
os.makedirs(os.path.join(current_abs_path,'lib','nucleosome','chrbased'),exist_ok=True)
chrombased_npy_path = os.path.join(current_abs_path,'lib','nucleosome','chrbased')
# print(chrombased_npy_path)
if os.path.isabs(chrombased_npy_path):
# print('%s an absolute path.' %(chrombased_npy_path))
os.chdir(chrombased_npy_path)
nucleosome_filename_wo_extension = os.path.splitext(os.path.basename(nucleosome_file))[0]
for chrLong in chromNamesList:
# GM12878 and K562 comes from woman samples therefore there is no chrY
if chrLong != 'chrY':
# filename = '%s_signal_wgEncodeSydhNsome%sSig.npy' %(chrLong,cell_line)
filename = '%s_signal_%s.npy' % (chrLong, nucleosome_filename_wo_extension)
chrbased_npy_array_path = os.path.join(chrombased_npy_path, filename)
if not os.path.exists(chrbased_npy_array_path):
print('Does not exists: %s' % (chrbased_npy_array_path))
try:
# print('Downloading %s_signal_wgEncodeSydhNsome_%sSig.npy under %s' %(chrLong,cell_line,chrbased_npy_array_path))
print('Downloading %s_signal_%s.npy under %s' % (
chrLong, nucleosome_filename_wo_extension, chrbased_npy_array_path))
# wget -c Continue getting a partially-downloaded file
# wget -nc If a file is downloaded more than once in the same directory, the local file will be clobbered, or overwritten
# cmd="bash -c '" + 'wget -r -l1 -c -nc --no-parent -nd -P ' + chrombased_npy_path + ' ftp://alexandrovlab-ftp.ucsd.edu/pub/tools/SigProfilerTopography/lib/nucleosome/chrbased/' + filename + "'"
cmd = "bash -c '" + 'wget -r -l1 -c -nc --no-parent -nd ftp://alexandrovlab-ftp.ucsd.edu/pub/tools/SigProfilerTopography/lib/nucleosome/chrbased/' + filename + "'"
# print(cmd)
os.system(cmd)
except:
# print("The UCSD ftp site is not responding...pulling from sanger ftp now.")
print("The UCSD ftp site is not responding...")
else:
#It has to be an absolute path
print('%s is not an absolute path.' %(chrombased_npy_path))
#go back
os.chdir(current_abs_path)
#######################################################
def install_default_nucleosome(genome):
chromSizesDict = getChromSizesDict(genome)
chromNamesList = list(chromSizesDict.keys())
if genome==MM10:
#Case1: File is not set, Biosample is not set
nucleosome_biosample = MEF
nucleosome_file = MM10_MEF_NUCLEOSOME_FILE
check_download_chrbased_npy_nuclesome_files(nucleosome_file, chromNamesList)
elif genome == GRCh37:
# Case1: File is not set, Biosample is not set
nucleosome_biosample = K562
nucleosome_file = K562_NUCLEOSOME_OCCUPANCY_FILE
# nucleosome_biosample = GM12878
# nucleosome_file = GM12878_NUCLEOSOME_OCCUPANCY_FILE
check_download_chrbased_npy_nuclesome_files(nucleosome_file, chromNamesList)
def install_default_atac_seq(genome):
chromSizesDict = getChromSizesDict(genome)
chromNamesList = list(chromSizesDict.keys())
if genome==GRCh37:
atac_seq_file = DEFAULT_ATAC_SEQ_OCCUPANCY_FILE
check_download_chrbased_npy_atac_seq_files(atac_seq_file,chromNamesList)
def install_sample_vcf_files():
# Download to where the SigProfilerTopography is run
check_download_sample_vcf_files()
def install_sample_probability_files():
# Download to where the SigProfilerTopography is run
check_download_sample_probability_files()
#######################################################
#For Skin-Melanoma USING_APPLY_ASYNC_FOR_EACH_CHROM_AND_SIM_SPLIT is better
#For others USING_APPLY_ASYNC_FOR_EACH_CHROM_AND_SIM is better
def runOccupancyAnalyses(genome,
outputDir,
jobname,
numofSimulations,
job_tuples,
sample_based,
library_file_with_path,
library_file_memo,
chromSizesDict,
chromNamesList,
ordered_all_sbs_signatures_array,
ordered_all_dbs_signatures_array,
ordered_all_id_signatures_array,
ordered_sbs_signatures_with_cutoffs_array,
ordered_dbs_signatures_with_cutoffs_array,
ordered_id_signatures_with_cutoffs_array,
ordered_sbs_signatures_cutoffs,
ordered_dbs_signatures_cutoffs,
ordered_id_signatures_cutoffs,
computation_type,
occupancy_type,
occupancy_calculation_type,
plusorMinus,
remove_outliers,
quantileValue,
is_discreet,
verbose):
#######################################################################
if (os.path.basename(library_file_with_path) not in SIGPROFILERTOPOGRAPHY_DEFAULT_FILES) and (not os.path.exists(library_file_with_path)):
print('There is no such file under %s' %(library_file_with_path))
#######################################################################
# computation_type = USING_APPLY_ASYNC_FOR_EACH_CHROM_AND_SIM
# computation_type =USING_APPLY_ASYNC_FOR_EACH_CHROM_AND_SIM_SPLIT
occupancyAnalysis(genome,
computation_type,
occupancy_type,
occupancy_calculation_type,
sample_based,
plusorMinus,
chromSizesDict,
chromNamesList,
outputDir,
jobname,
numofSimulations,
job_tuples,
library_file_with_path,
library_file_memo,
ordered_all_sbs_signatures_array,
ordered_all_dbs_signatures_array,
ordered_all_id_signatures_array,
ordered_sbs_signatures_with_cutoffs_array,
ordered_dbs_signatures_with_cutoffs_array,
ordered_id_signatures_with_cutoffs_array,
ordered_sbs_signatures_cutoffs,
ordered_dbs_signatures_cutoffs,
ordered_id_signatures_cutoffs,
remove_outliers,
quantileValue,
is_discreet,
verbose)
#######################################################
#######################################################
def runReplicationTimeAnalysis(genome,
outputDir,
jobname,
numofSimulations,
job_tuples,
sample_based,
replicationTimeFilename,
chromSizesDict,
chromNamesList,
computation_type,
ordered_all_sbs_signatures_array,
ordered_all_dbs_signatures_array,
ordered_all_id_signatures_array,
ordered_sbs_signatures_with_cutoffs,
ordered_dbs_signatures_with_cutoffs,
ordered_id_signatures_with_cutoffs,
ordered_sbs_signatures_cutoffs,
ordered_dbs_signatures_cutoffs,
ordered_id_signatures_cutoffs,
is_discreet,
verbose,
matrix_generator_path):
# Fill np array during runtime managed by replication_time_np_arrays_fill_runtime=True
# Supported computation types
# computation_type= USING_APPLY_ASYNC_FOR_EACH_CHROM_AND_SIM
# computation_type =USING_APPLY_ASYNC_FOR_EACH_CHROM_AND_SIM_SPLIT
replicationTimeAnalysis(computation_type,
sample_based,
genome,
chromSizesDict,
chromNamesList,
outputDir,
jobname,
numofSimulations,
job_tuples,
replicationTimeFilename,
ordered_all_sbs_signatures_array,
ordered_all_dbs_signatures_array,
ordered_all_id_signatures_array,
ordered_sbs_signatures_with_cutoffs,
ordered_dbs_signatures_with_cutoffs,
ordered_id_signatures_with_cutoffs,
ordered_sbs_signatures_cutoffs,
ordered_dbs_signatures_cutoffs,
ordered_id_signatures_cutoffs,
is_discreet,
verbose,
matrix_generator_path)
###############################################
#######################################################
#######################################################
def runReplicationStrandBiasAnalysis(outputDir,
jobname,
numofSimulations,
job_tuples,
sample_based,
all_samples_np_array,
replicationTimeFilename,
replicationTimeValleyFilename,
replicationTimePeakFilename,
chromSizesDict,
chromNamesList,
computation_type,
ordered_all_sbs_signatures_array,
ordered_all_dbs_signatures_array,
ordered_all_id_signatures_array,
ordered_sbs_signatures,
ordered_dbs_signatures,
ordered_id_signatures,
ordered_sbs_signatures_cutoffs,
ordered_dbs_signatures_cutoffs,
ordered_id_signatures_cutoffs,
is_discreet,
verbose):
os.makedirs(os.path.join(outputDir,jobname,DATA,REPLICATIONSTRANDBIAS),exist_ok=True)
smoothedWaveletRepliseqDataFilename = replicationTimeFilename
valleysBEDFilename = replicationTimeValleyFilename
peaksBEDFilename = replicationTimePeakFilename
# Supported computation types
# computation_type= USING_APPLY_ASYNC_FOR_EACH_CHROM_AND_SIM
# computation_type =USING_APPLY_ASYNC_FOR_EACH_CHROM_AND_SIM_SPLIT
replicationStrandBiasAnalysis(outputDir,
jobname,
numofSimulations,
job_tuples,
sample_based,
all_samples_np_array,
chromSizesDict,
chromNamesList,
computation_type,
smoothedWaveletRepliseqDataFilename,
valleysBEDFilename,
peaksBEDFilename,
ordered_all_sbs_signatures_array,
ordered_all_dbs_signatures_array,
ordered_all_id_signatures_array,
ordered_sbs_signatures,
ordered_dbs_signatures,
ordered_id_signatures,
ordered_sbs_signatures_cutoffs,
ordered_dbs_signatures_cutoffs,
ordered_id_signatures_cutoffs,
is_discreet,
verbose)
###############################################
#######################################################
#######################################################
def runTranscriptionStradBiasAnalysis(outputDir,
jobname,
numofSimulations,
job_tuples,
sample_based,
all_samples_np_array,
chromNamesList,
computation_type,
ordered_all_sbs_signatures_array,
ordered_all_dbs_signatures_array,
ordered_all_id_signatures_array,
ordered_sbs_signatures,
ordered_dbs_signatures,
ordered_id_signatures,
ordered_sbs_signatures_cutoffs,
ordered_dbs_signatures_cutoffs,
ordered_id_signatures_cutoffs,
is_discreet,
verbose):
os.makedirs(os.path.join(outputDir,jobname,DATA,TRANSCRIPTIONSTRANDBIAS),exist_ok=True)
# Supported computation types
# computation_type= USING_APPLY_ASYNC_FOR_EACH_CHROM_AND_SIM
# computation_type =USING_APPLY_ASYNC_FOR_EACH_CHROM_AND_SIM_SPLIT
transcriptionStrandBiasAnalysis(outputDir,
jobname,
numofSimulations,
job_tuples,
sample_based,
all_samples_np_array,
computation_type,
chromNamesList,
ordered_all_sbs_signatures_array,
ordered_all_dbs_signatures_array,
ordered_all_id_signatures_array,
ordered_sbs_signatures,
ordered_dbs_signatures,
ordered_id_signatures,
ordered_sbs_signatures_cutoffs,
ordered_dbs_signatures_cutoffs,
ordered_id_signatures_cutoffs,
is_discreet,
verbose)
###############################################
#######################################################
#######################################################
def runProcessivityAnalysis(mutation_types_contexts,
outputDir,
jobname,
numofSimulations,
chromNamesList,
processivity_calculation_type,
inter_mutational_distance_for_processivity,
subsSignature_cutoff_numberofmutations_averageprobability_df,
verbose):
os.makedirs(os.path.join(outputDir,jobname,DATA,PROCESSIVITY),exist_ok=True)
#Internally Set
considerProbabilityInProcessivityAnalysis = True
processivityAnalysis(mutation_types_contexts,
chromNamesList,
processivity_calculation_type,
inter_mutational_distance_for_processivity,
outputDir,
jobname,
numofSimulations,
considerProbabilityInProcessivityAnalysis,
subsSignature_cutoff_numberofmutations_averageprobability_df,
verbose)
###############################################
#######################################################
#######################################################
def deleteOldData(outputDir,jobname,occupancy_type):
#############################################
# Delete the output/jobname/DATA/occupancy_type if exists
jobnamePath = os.path.join(outputDir,jobname,DATA,occupancy_type)
################################################
if (os.path.exists(jobnamePath)):
try:
shutil.rmtree(jobnamePath)
except OSError as e:
print('Error: %s - %s.' % (e.filename, e.strerror))
################################################
#######################################################
#######################################################
def deleteOldFigures(outputDir, jobname, occupancy_type):
jobnamePath = os.path.join(outputDir, jobname, FIGURE, occupancy_type)
print('Topography.py jobnamePath:%s ' %jobnamePath)
############################################################
if (os.path.exists(jobnamePath)):
try:
shutil.rmtree(jobnamePath)
except OSError as e:
print('Error: %s - %s.' % (e.filename, e.strerror))
############################################################
#######################################################
# Depreceated.
# We assume that simulated data will have the same number_of_splits as the real data
def get_job_tuples(chrlong_numberofmutations_df,numofSimulations):
job_tuples = []
sim_nums = range(0, numofSimulations + 1)
for chrLong in chrlong_numberofmutations_df['chrLong'].unique():
number_of_mutations=int(chrlong_numberofmutations_df[chrlong_numberofmutations_df['chrLong']==chrLong]['number_of_mutations'].values[0])
number_of_splits = math.ceil(number_of_mutations / NUMBER_OF_MUTATIONS_IN_EACH_SPLIT)
split_indexes = range(0, number_of_splits)
###############################################################
for sim_num in sim_nums:
for split_index in split_indexes:
job_tuples.append((chrLong, sim_num, split_index))
###############################################################
return job_tuples
def get_all_signatures_array(ordered_all_sbs_signatures_wrt_probabilities_file_array, signature_starts_with):
ordered_all_sbs_signatures = []
if ordered_all_sbs_signatures_wrt_probabilities_file_array is not None:
for i in ordered_all_sbs_signatures_wrt_probabilities_file_array:
if i.startswith(signature_starts_with):
ordered_all_sbs_signatures.append(i)
return np.array(ordered_all_sbs_signatures)
#######################################################
# inputDir ='/oasis/tscc/scratch/burcak/developer/python/SigProfilerTopography/SigProfilerTopography/input_for_matgen/BreastCancer560_subs_indels_dinucs'
# outputDir = '/oasis/tscc/scratch/burcak/developer/python/SigProfilerTopography/SigProfilerTopography/output_test/'
# jobname = 'BreastCancer560'
#Run SigProfilerTopography Analyses
#Former full path now only the filename with extension
# nucleosomeOccupancy = '/oasis/tscc/scratch/burcak/developer/python/SigProfilerTopography/SigProfilerTopography/lib/nucleosome/wgEncodeSydhNsomeGm12878Sig.wig'
# replicationSignal = '/oasis/tscc/scratch/burcak/developer/python/SigProfilerTopography/SigProfilerTopography/lib/replication/GSM923442_hg19_wgEncodeUwRepliSeqMcf7WaveSignalRep1.wig'
# replicationValley = '/oasis/tscc/scratch/burcak/developer/python/SigProfilerTopography/SigProfilerTopography/lib/replication/GSM923442_hg19_wgEncodeUwRepliSeqMcf7ValleysRep1.bed'
# replicationPeak = '/oasis/tscc/scratch/burcak/developer/python/SigProfilerTopography/SigProfilerTopography/lib/replication/GSM923442_hg19_wgEncodeUwRepliSeqMcf7PkRep1.bed'
# subs_probabilities_file_path = '/oasis/tscc/scratch/burcak/developer/python/SigProfilerTopography/SigProfilerTopography/output/560_BRCA_WGS_DINUCS/SBS96/Suggested_Solution/Decomposed_Solution/Mutation_Probabilities.txt'
# indels_probabilities_file_path = '/oasis/tscc/scratch/burcak/developer/python/SigProfilerTopography/SigProfilerTopography/output/560_BRCA_WGS_DINUCS/ID83/Suggested_Solution/Decomposed_Solution/Mutation_Probabilities.txt'
# dinucs_probabilities_file_path = '/oasis/tscc/scratch/burcak/developer/python/SigProfilerTopography/SigProfilerTopography/output/560_BRCA_WGS_DINUCS/DBS78/Suggested_Solution/Decomposed_Solution/Mutation_Probabilities.txt'
def runAnalyses(genome,
inputDir,
outputDir,
jobname,
numofSimulations,
sbs_probabilities = None,
dbs_probabilities = None,
id_probabilities = None,
mutation_types_contexts = None,
mutation_types_contexts_for_signature_probabilities = None,
epigenomics_files = None,
epigenomics_files_memos = None,
epigenomics_biosamples = None,
epigenomics_dna_elements = None,
epigenomics_dir_name = None,
nucleosome_biosample = None,
nucleosome_file = None,
replication_time_biosample = None,
replication_time_signal_file = None,
replication_time_valley_file = None,
replication_time_peak_file = None,
computation_type = USING_APPLY_ASYNC_FOR_EACH_CHROM_AND_SIM,
epigenomics = False,
nucleosome = False,
replication_time = False,
strand_bias = False,
replication_strand_bias = False,
transcription_strand_bias = False,
processivity = False,
sample_based = False,
plot_figures = True,
step1_sim_data = True,
step2_matgen_data = True,
step3_prob_merged_data = True,
step4_tables = True,
is_discreet = True,
average_probability = DEFAULT_AVERAGE_PROBABILITY,
num_of_sbs_required = DEFAULT_NUM_OF_SBS_REQUIRED,
num_of_dbs_required = DEFAULT_NUM_OF_DBS_REQUIRED,
num_of_id_required = DEFAULT_NUM_OF_ID_REQUIRED,
plusorMinus_epigenomics = 1000,
plusorMinus_nucleosome = 1000,
epigenomics_heatmap_significance_level = 0.01,
verbose = False,
matrix_generator_path = MATRIX_GENERATOR_PATH,
PCAWG = False,
plot_epigenomics = False,
plot_nucleosome = False,
plot_replication_time = False,
plot_strand_bias = False,
plot_replication_strand_bias = False,
plot_transcription_strand_bias = False,
plot_processivity = False,
remove_outliers = False,
quantileValue = 0.97,
delete_old = False,
plot_mode = PLOTTING_FOR_SIGPROFILERTOPOGRAPHY_TOOL,
occupancy_calculation_type = MISSING_SIGNAL,
processivity_calculation_type = CONSIDER_DISTANCE,
inter_mutational_distance_for_processivity = 10000,
combine_p_values_method = COMBINE_P_VALUES_METHOD_FISHER,
fold_change_window_size = 100,
num_of_real_data_avg_overlap = DEFAULT_NUM_OF_REAL_DATA_OVERLAP_REQUIRED):
current_abs_path = os.path.dirname(os.path.realpath(__file__))
chromSizesDict = getChromSizesDict(genome)
chromNamesList = list(chromSizesDict.keys())
chromShortNamesList=getShortNames(chromNamesList)
# Filled in Step3
# contains all the columns in order w.r.t. probabilities file
ordered_all_sbs_signatures_wrt_probabilities_file_array = None
ordered_all_dbs_signatures_wrt_probabilities_file_array = None
ordered_all_id_signatures_wrt_probabilities_file_array = None
###################################################
if mutation_types_contexts is None:
mutation_types_contexts=[]
if (sbs_probabilities is not None):
mutation_types_contexts.append(SBS96)
if (id_probabilities is not None):
mutation_types_contexts.append(ID)
if (dbs_probabilities is not None):
mutation_types_contexts.append(DBS)
# If still None
if mutation_types_contexts is None:
print('--- There is a situation/problem: mutation_types_contexts is None.')
print('--- mutation_types_contexts has to be set before SigProfilerTopography run.')
if mutation_types_contexts_for_signature_probabilities is None:
mutation_types_contexts_for_signature_probabilities=mutation_types_contexts
###################################################
###################################################
if step1_sim_data:
step2_matgen_data = True
step3_prob_merged_data = True
step4_tables = True
elif step2_matgen_data:
step3_prob_merged_data = True
step4_tables = True
elif step3_prob_merged_data:
step4_tables = True
###################################################
###################################################
if (average_probability!=DEFAULT_AVERAGE_PROBABILITY) or \
(num_of_sbs_required!=DEFAULT_NUM_OF_SBS_REQUIRED) or \
(num_of_dbs_required!=DEFAULT_NUM_OF_DBS_REQUIRED) or \
(num_of_id_required!=DEFAULT_NUM_OF_ID_REQUIRED):
step4_tables = True
###################################################
#################################################################################
################################## Setting starts ###############################
################## Set full path library files starts ###########################
#################################################################################
if genome is None:
print('Parameter genome:%s must be set for SigProfilerTopography Analysis.' %(genome))
###############################################
if strand_bias:
replication_strand_bias=True
transcription_strand_bias=True
if plot_strand_bias:
plot_replication_strand_bias=True
plot_transcription_strand_bias=True
###############################################
###############################################
# We need full path of the library files
if (genome==GRCh37) and (epigenomics_files==None):
epigenomics_files = [DEFAULT_ATAC_SEQ_OCCUPANCY_FILE,
DEFAULT_H3K27ME3_OCCUPANCY_FILE,
DEFAULT_H3K36ME3_OCCUPANCY_FILE,
DEFAULT_H3K9ME3_OCCUPANCY_FILE,
DEFAULT_H3K27AC_OCCUPANCY_FILE,
DEFAULT_H3K4ME1_OCCUPANCY_FILE,
DEFAULT_H3K4ME3_OCCUPANCY_FILE,
DEFAULT_CTCF_OCCUPANCY_FILE]
epigenomics_files_memos=[]
for epigenomics_file in epigenomics_files:
epigenomics_files_memos.append(os.path.splitext(os.path.basename(epigenomics_file))[0])
# Defines columns in the heatmap
# These strings must be within filenames (without file extension)
# Order is not important
epigenomics_dna_elements = ['H3K27me3', 'H3K36me3', 'H3K9me3', 'H3K27ac', 'H3K4me1', 'H3K4me3', 'CTCF', 'ATAC']
# Defines rows in the detailed heatmap
# These strings must be within filenames (without file extension)
# Order is not important
epigenomics_biosamples = ['breast_epithelium']
for file_index, filename in enumerate(epigenomics_files):
epigenomics_files[file_index] = os.path.join(current_abs_path, LIB, EPIGENOMICS, filename)
# These must be under epigenomics under installed SigPofilerTopography
elif (genome == MM10) and (epigenomics_files == None):
epigenomics_files = [ENCFF575PMI_mm10_embryonic_facial_prominence_ATAC_seq,
ENCFF993SRY_mm10_embryonic_fibroblast_H3K4me1,
ENCFF912DNP_mm10_embryonic_fibroblast_H3K4me3,
ENCFF611HDQ_mm10_embryonic_fibroblast_CTCF,
ENCFF152DUV_mm10_embryonic_fibroblast_POLR2A,
ENCFF114VLZ_mm10_embryonic_fibroblast_H3K27ac]
epigenomics_files_memos = []
for epigenomics_file in epigenomics_files:
epigenomics_files_memos.append(os.path.splitext(os.path.basename(epigenomics_file))[0])
# Defines columns in the heatmap
# These strings must be within filenames (without file extension)
# Order is not important
epigenomics_dna_elements = ['ATAC', 'H3K4me1', 'H3K4me3', 'CTCF', 'POLR2A', 'H3K27ac']
# Defines rows in the detailed heatmap
# These strings must be within filenames (without file extension)
# Order is not important
epigenomics_biosamples = ['embryonic_fibroblast']
for file_index, filename in enumerate(epigenomics_files):
epigenomics_files[file_index] = os.path.join(current_abs_path, LIB, EPIGENOMICS, filename)
###############################################
###############################################
if genome==MM10:
#Case1: File is not set, Biosample is not set
if (nucleosome_file is None) and (nucleosome_biosample is None):
nucleosome_biosample = MEF
nucleosome_file = getNucleosomeFile(nucleosome_biosample)
#Case2: File is not set, Biosample is set
elif (nucleosome_file is None) and (nucleosome_biosample is not None):
if (nucleosome_biosample in available_nucleosome_biosamples):
#Sets the filename without the full path
nucleosome_file = getNucleosomeFile(nucleosome_biosample)
#Case3: nucleosome_file is a filename with fullpath (User provided) , biosample is not set
elif ((nucleosome_file is not None) and (nucleosome_biosample is None)):
# We expect that user has provided nucleosome file with full path
nucleosome_biosample = UNDECLARED
#Case4: nucleosome_file is a filename with fullpath (User provided), biosample is set
#Do nothing use as it is
elif genome==GRCh37:
#Case1: File is not set, Biosample is not set
if (nucleosome_file is None) and (nucleosome_biosample is None):
nucleosome_biosample = K562
nucleosome_file = getNucleosomeFile(nucleosome_biosample)
#Case2: File is not set, Biosample is set
elif (nucleosome_file is None) and (nucleosome_biosample is not None):
if (nucleosome_biosample in available_nucleosome_biosamples):
#Sets the filename without the full path
nucleosome_file = getNucleosomeFile(nucleosome_biosample)
#Case3: nucleosome_file is a filename with fullpath (User provided) , biosample is not set
elif ((nucleosome_file is not None) and (nucleosome_biosample is None)):
# We expect that user has provided nucleosome file with full path
nucleosome_biosample = UNDECLARED
#Case4: nucleosome_file is a filename with fullpath (User provided), biosample is set
#Do nothing use as it is
###############################################
###############################################
if genome==MM10:
# Case1: Files are not set, Biosample is not set
if (replication_time_signal_file is None) and (replication_time_valley_file is None) and (replication_time_peak_file is None) and (replication_time_biosample is None):
replication_time_biosample=MEF
#We only set replication_time_signal_file
# replication_time_valley_file is None
# replication_time_peak_file is None
replication_time_signal_file, replication_time_valley_file,replication_time_peak_file=getReplicationTimeFiles(replication_time_biosample)
elif genome==GRCh37:
# We need full path of the library files
# By default replication_time_biosample=MCF7 and signal, valley, peak files are None
# Case1: Files are not set, Biosample is not set
if (replication_time_signal_file is None) and (replication_time_valley_file is None) and (replication_time_peak_file is None) and (replication_time_biosample is None):
replication_time_biosample=MCF7
replication_time_signal_file, replication_time_valley_file,replication_time_peak_file=getReplicationTimeFiles(replication_time_biosample)
if (replication_time or replication_strand_bias):
# For using SigProfilerTopography Provided Replication Time Files
check_download_replication_time_files(replication_time_signal_file, replication_time_valley_file,replication_time_peak_file)
#Case2: Files are not set, Biosample is set
elif (replication_time_signal_file is None) and (replication_time_valley_file is None) and (replication_time_peak_file is None) and (replication_time_biosample is not None):
if (replication_time_biosample in available_replication_time_biosamples):
replication_time_signal_file, replication_time_valley_file, replication_time_peak_file = getReplicationTimeFiles(replication_time_biosample)
if (replication_time or replication_strand_bias):
# For using SigProfilerTopography Provided Replication Time Files
check_download_replication_time_files(replication_time_signal_file, replication_time_valley_file,replication_time_peak_file)
#Case3: nucleosome_file is a filename with fullpath (User provided) , biosample is not set
elif ((replication_time_signal_file is not None) or (replication_time_valley_file is not None) or (replication_time_peak_file is not None)) and (replication_time_biosample is None):
replication_time_biosample = UNDECLARED
#Case4: Files are set. Biosample is set. Use as it is. Do nothing.
###############################################
###############################################
# data files are named using user provided epigenomics_files_memos or using epigenomics_file_memos_created
epigenomics_file_memos_created = []
# Run for each epigenomics file
if (epigenomics_files_memos is None) or (len(epigenomics_files_memos) != len(epigenomics_files)):
for idx, epigenomics_file in enumerate(epigenomics_files):
epigenomics_file_memo = os.path.splitext(os.path.basename(epigenomics_file))[0]
epigenomics_file_memos_created.append(epigenomics_file_memo)
# Used for plotting
if (epigenomics_files_memos is None) or (len(epigenomics_files_memos) != len(epigenomics_files)):
epigenomics_files_memos = epigenomics_file_memos_created
if (epigenomics_biosamples is None) or (len(epigenomics_biosamples) == 0):
epigenomics_biosamples = [UNDECLARED]
###############################################
#################################################################################
################## Set full path library files ends #############################
################################## Setting ends #################################
#################################################################################
print('#################################################################################')
# print('--- %s' %platform.platform())
# print('--- %s' %platform.system())
#print("--- Operating System: %s" %(platform.uname()[0]))
print("--- SigProfilerTopography starts")
print('#################################################################################')
print('#################################################################################')
print("--- Operating System: %s" %(platform.platform()))
print("--- Release: %s" %platform.uname()[2])
print("--- Version: %s" %platform.uname()[3])
print("--- Nodename: %s" %platform.uname()[1])
print('#################################################################################')
print('#################################################################################')
print("--- Python and Package Versions")
print("--- Python Version: %s" %(str(platform.sys.version_info.major) + "." + str(platform.sys.version_info.minor) + "." + str(platform.sys.version_info.micro)))
print('--- SigProfilerTopography Version:%s' % topography_version.version)
print("--- SigProfilerMatrixGenerator Version: %s" %matrix_generator_version.version)
print("--- SigProfilerSimulator version: %s" %simulator_version.version)
print("--- pandas version: %s" %pd.__version__)
print("--- numpy version: %s" %np.__version__)
print("--- statsmodels version: %s" %statsmodels.__version__)
print("--- scipy version: %s" %scipy.__version__)
print("--- matplotlib version: %s" %plt.__version__)
print('#################################################################################\n')
print('#################################################################################')
print('--- SigProfilerTopography parameters')
print('--- Genome: %s' %(genome))
print('--- inputDir:%s' %inputDir)
print('--- outputDir:%s' %outputDir)
print('--- jobname:%s' %jobname)
if (sbs_probabilities is not None):
print('--- sbs_probabilities:%s' %sbs_probabilities)
if (dbs_probabilities is not None):
print('--- dbs_probabilities:%s' %dbs_probabilities)
if (id_probabilities is not None):
print('--- id_probabilities:%s' %id_probabilities)
print('--- numofSimulations:%d' %numofSimulations)
print('\n--- epigenomics_files:%s' %epigenomics_files)
print('--- epigenomics_files_memos:%s' %epigenomics_files_memos)
print('--- epigenomics_biosamples:%s' %epigenomics_biosamples)
print('--- epigenomics_dna_elements:%s' %epigenomics_dna_elements)
print('--- number of epigenomics_files:%d' %len(epigenomics_files))
print('\n--- nucleosome_biosample:%s' %nucleosome_biosample)
print('--- nucleosome_file:%s' % nucleosome_file)
print('\n--- replication_time_biosample:%s' % replication_time_biosample)
print('--- replication_time_signal_file:%s' % replication_time_signal_file)
print('--- replication_time_valley_file:%s' % replication_time_valley_file)
print('--- replication_time_peak_file:%s' % replication_time_peak_file)
print('\n--- mutation_types_contexts:%s' %mutation_types_contexts)
print('--- mutation_types_contexts_for_signature_probabilities:%s' %mutation_types_contexts_for_signature_probabilities)
print('--- computation_type:%s' %computation_type)
print('--- mutation contribution is_discreet:%s\n' %is_discreet)
if sample_based:
print('--- Sample Based Analysis.')
if epigenomics:
print('--- Epigenomics Analysis.')
if nucleosome:
print('--- Nucleosome Analysis.')
if replication_time:
print('--- Replication Time Analysis.')
if (strand_bias or replication_strand_bias):
print('--- Replication Strand Bias Analysis.')
if (strand_bias or transcription_strand_bias):
print('--- Transcription Strand Bias Analysis.')
if processivity:
print('--- Processivity Analysis.')
print('--- step1_sim_data:%s' %step1_sim_data)
print('--- step2_matgen_data:%s' %step2_matgen_data)
print('--- step3_prob_merged_data:%s' %step3_prob_merged_data)
print('--- step4_tables:%s' %step4_tables)
print('--- plot_figures:%s' %plot_figures)
print('--- average mutation probability required %0.2f' %average_probability)
print('--- minimum number of sbs mutations required: %d' %num_of_sbs_required)
print('--- minimum number of id mutations required: %d' %num_of_id_required)
print('--- minimum number of dbs mutations required: %d' %num_of_dbs_required)
if epigenomics:
print('--- number of bases considered before and after mutation start for epigenomics analysis: %d' %plusorMinus_epigenomics)
if nucleosome:
print('--- number of bases considered before and after mutation start for nucleosome occupancy analysis: %d' %plusorMinus_nucleosome)
print('#################################################################################\n')
print('#################################################################################')
numofProcesses = multiprocessing.cpu_count()
print('--- numofProcesses for multiprocessing: %d' %numofProcesses)
print('#################################################################################\n')
#################################################################################
print('#################################################################################')
print('--- For Genome: %s' %(genome))
print('--- Chromosome names: %s' %(chromNamesList))
print('--- Chromosome short names: %s' % (chromShortNamesList))
print('--- current_abs_path: %s ' % current_abs_path)
print('#################################################################################\n')
#################################################################################
###################################################################################################################
################################################# All Steps starts ################################################
###################################################################################################################
###################################################################################################
######################### SigProfilerMatrixGenerator for original data starts #####################
###################################################################################################
if (step2_matgen_data):
# Run MatrixGenerator for original data: this call prepares chrBased input files for original data with mutation contexts
print('#################################################################################')
print('--- SigProfilerMatrixGenerator for original data')
start_time = time.time()
print('For original data inputDir:%s' % (inputDir))
matrices = matGen.SigProfilerMatrixGeneratorFunc(jobname, genome, inputDir, plot=False, seqInfo=True)
# print('matrices')
# print(matrices)
# original matrix generator chrbased data will be under inputDir/output/vcf_files/SNV
# original matrix generator chrbased data will be under inputDir/output/vcf_files/DBS
# original matrix generator chrbased data will be under inputDir/output/vcf_files/ID
print("--- SigProfilerMatrixGenerator for original data: %s seconds ---" % (time.time() - start_time))
print("--- SigProfilerMatrixGenerator for original data: %f minutess ---" % float((time.time() - start_time) / 60))
print('#################################################################################\n')
###################################################################################################
######################### SigProfilerMatrixGenerator for original data ends #######################
###################################################################################################
###################################################################################################################
################################## Step1 Simulations if any starts ################################################
###################################################################################################################
if ((numofSimulations > 0) and (step1_sim_data)):
###################################################################################################
############################ SigProfilerSimulator for n simulations starts #######################
###################################################################################################
print('#################################################################################')
print('--- SigProfilerSimulator for %d simulations starts' %(numofSimulations))
start_time = time.time()
#Call SigProfilerSimulator separately for each mutation type context otherwise it counts DBS mutations also in SBS mutations
# Topography uses same mutation types with Simulator
# Acceptable contexts for Simulator include {'96', '384', '1536', '6144', 'DBS', 'ID', 'ID415'}.
# '96' or '384' for single base substitutions (Simulator 1536, or 3072)
# 'DBS' for double base substitutions
# 'ID' for indels
for mutation_type_context in mutation_types_contexts:
mutation_type_context_for_simulator = []
mutation_type_context_for_simulator.append(mutation_type_context)
# Please notice that Simulator reverse the given input mutationTypes_for_simulator
print('--- SigProfilerSimulator is running for %s' %(mutation_type_context))
simulator.SigProfilerSimulator(jobname, inputDir, genome, mutation_type_context_for_simulator,simulations=numofSimulations,chrom_based=True, gender='male')
print("--- SigProfilerSimulator for %d simulations: %s seconds" %(numofSimulations,(time.time() - start_time)))
print("--- SigProfilerSimulator for %d simulations: %f minutes" %(numofSimulations,float((time.time()-start_time)/60)))
print('--- SigProfilerSimulator for %d simulations ends' %(numofSimulations))
print('#################################################################################\n')
###################################################################################################
############################ SigProfilerSimulator for n simulations ends #########################
###################################################################################################
###################################################################################################################
################################## Step1 Simulations if any ends ##################################################
###################################################################################################################
###################################################################################################################
################################## Step2 Matrix Generator for n simulations starts ################################
###################################################################################################################
if (step2_matgen_data):
if (numofSimulations > 0):
###################################################################################################
########################### Create simN directories for MatrixGenerator starts ####################
###################################################################################################
print('#################################################################################')
print('--- Create directories for %d simulations under %s/output/simulations/' %(numofSimulations,inputDir))
start_time = time.time()
#Create directories sim1 to SimN under inputDir/output/simulations/
access_rights = 0o755
for simNum in range(1,numofSimulations+1):
try:
simName = 'sim%d' %(simNum)
simDir = os.path.join(inputDir,'output','simulations',simName)
if (not os.path.exists(simDir)):
os.mkdir(simDir, access_rights)
for mutation_type_context in mutation_types_contexts:
simDir = os.path.join(inputDir,'output','simulations',simName,mutation_type_context)
if (not os.path.exists(simDir)):
os.mkdir(simDir, access_rights)
except OSError:
print("Creation of the directory %s failed" %simDir)
# else:
# print("Successfully created the directory %s" %simDir)
for mutation_type_context in mutation_types_contexts:
# Simulator creates one maf file for each simulation for each mutation context
# Simulator creates maf files under inputDir/output/simulations/jobname_simulations_GRCh37_96
# Simulator creates maf files under inputDir/output/simulations/jobname_simulations_GRCh37_ID
# Simulator creates maf files under inputDir/output/simulations/jobname_simulations_GRCh37_DBS
dirName = '%s_simulations_%s_%s' %(jobname, genome,mutation_type_context)
copyFromDir = os.path.join(inputDir,'output','simulations',dirName)
copyToMainDir= os.path.join(inputDir,'output','simulations')
# Topography copies these maf files to inputDir/output/simulations/simX/mutation_type_context/X.maf
# So that, in the next step MatrixGenerator can create chrom based seqinfo text files for each X.maf file
copyMafFiles(copyFromDir,copyToMainDir,mutation_type_context,numofSimulations)
print("--- Create directories and copy files: %s seconds ---" %(time.time()-start_time))
print("--- Create directories and copy files: %f minutes ---" %(float((time.time()-start_time)/60)))
print('#################################################################################\n')
###################################################################################################
########################### Create simN directories for MatrixGenerator ends ######################
###################################################################################################
###################################################################################################
#Important note: Separate directory creation is necessary for Matrix Generator
#inputDir/output/simulations/simX/96/X.maf
#inputDir/output/simulations/simX/ID/X.maf
#inputDir/output/simulations/simX/DBS/X.maf
#enables MatrixGenerator to create chr based simulated data files under
#sim1 matrix generator chrbased data will be under inputDir/output/simulations/simX/96/output/vcf_files/SNV
#sim1 matrix generator chrbased data will be under inputDir/output/simulations/simX/ID/output/vcf_files/ID
#sim1 matrix generator chrbased data will be under inputDir/output/simulations/simX/DBS/output/vcf_files/DBS
#otherwise all simulations maf files will be under
#inputDir/output/simulations/Skin-Melanoma_simulations_GRCh37_96
#inputDir/output/simulations/Skin-Melanoma_simulations_GRCh37_DBS
#inputDir/output/simulations/Skin-Melanoma_simulations_GRCh37_ID
#Then running MatrixGenerator for each simulation will not be possible.
###################################################################################################
###################################################################################################
####################### Run MatrixGenerator for each simulation starts ############################
###################################################################################################
print('#################################################################################')
print('--- Run SigProfilerMatrixGenerator for each simulation starts')
start_time = time.time()
for simNum in range(1,numofSimulations+1):
simName = 'sim%d' %(simNum)
#For each simulation we are calling matrix generator separately for each mutation type context
print('--- SigProfilerMatrixGenerator is run for %s starts' %(simName))
for mutation_type_context in mutation_types_contexts:
simInputDir= os.path.join(inputDir,'output','simulations',simName,mutation_type_context)
print('For %s: %s simInputDir:%s' %(mutation_type_context,simName,simInputDir))
matrices = matGen.SigProfilerMatrixGeneratorFunc(jobname,genome,simInputDir,plot=False, seqInfo=True)
# print('matrices')
# print(matrices)
print('#####################################')
print('--- SigProfilerMatrixGenerator is run for %s ends\n' % (simName))
#sim1 matrix generator chrbased data will be under inputDir/output/simulations/sim1/96/output/vcf_files/SNV
#sim1 matrix generator chrbased data will be under inputDir/output/simulations/sim1/ID/output/vcf_files/ID
#sim1 matrix generator chrbased data will be under inputDir/output/simulations/sim1/DBS/output/vcf_files/DBS
#simN matrix generator chrbased data will be under inputDir/output/simulations/simN/96/output/vcf_files/SNV
#simN matrix generator chrbased data will be under inputDir/output/simulations/simN/ID/output/vcf_files/ID
#simN matrix generator chrbased data will be under inputDir/output/simulations/simN/DBS/output/vcf_files/DBS
print("--- Run MatrixGenerator for each simulation: %s seconds" %(time.time()-start_time))
print("--- Run MatrixGenerator for each simulation: %f minutes" %(float((time.time()-start_time)/60)))
print('--- Run SigProfilerMatrixGenerator for each simulation ends')
print('#################################################################################\n')
###################################################################################################
####################### Run MatrixGenerator for each simulation ends ##############################
###################################################################################################
###################################################################################################################
################################## Step2 Matrix Generator for n simulations ends ##################################
###################################################################################################################
###################################################################################################################
########### Step3 Merge chrom based matrix generator generated files with probabilities starts ####################
###################################################################################################################
if (step3_prob_merged_data):
####################################################################################################################
################## Merge original chr based files with Mutation Probabilities starts ##############################
####################################################################################################################
print('#################################################################################')
print('--- Merge original chr based files with Mutation Probabilities starts')
print('#################################################################################')
startSimNum = 0
endSimNum = 0
start_time = time.time()
# SBS
for mutation_type_context in mutation_types_contexts:
# if (mutation_type_context in SBS_CONTEXTS) and (sbs_probabilities is not None):
if (mutation_type_context in SBS_CONTEXTS):
mutation_type_context_for_probabilities = get_mutation_type_context_for_probabilities_file(mutation_types_contexts_for_signature_probabilities,SUBS)
print('--- Merge %s context mutations with probabilities for %s' % (mutation_type_context, sbs_probabilities))
ordered_all_sbs_signatures_wrt_probabilities_file_array = prepareMutationsDataAfterMatrixGenerationAndExtractorForTopography(chromShortNamesList,
inputDir,
outputDir,
jobname,
mutation_type_context,
sbs_probabilities,
mutation_type_context_for_probabilities,
startSimNum,
endSimNum,
SNV,
PCAWG,
verbose)
# ID
# if ((ID in mutation_types_contexts) and (id_probabilities is not None)):
if (ID in mutation_types_contexts):
mutation_type_context_for_probabilities = get_mutation_type_context_for_probabilities_file(mutation_types_contexts_for_signature_probabilities, INDELS)
print('--- Merge %s mutations with probabilities for %s' % (ID, id_probabilities))
ordered_all_id_signatures_wrt_probabilities_file_array = prepareMutationsDataAfterMatrixGenerationAndExtractorForTopography(chromShortNamesList,
inputDir,
outputDir,
jobname,
ID,
id_probabilities,
mutation_type_context_for_probabilities,
startSimNum,
endSimNum,
ID,
PCAWG,
verbose)
# DBS
# if ((DBS in mutation_types_contexts) and (dbs_probabilities is not None)):
if (DBS in mutation_types_contexts):
mutation_type_context_for_probabilities = get_mutation_type_context_for_probabilities_file(mutation_types_contexts_for_signature_probabilities, DINUCS)
print('--- Merge %s mutations with probabilities for %s' % (DBS, dbs_probabilities))
ordered_all_dbs_signatures_wrt_probabilities_file_array = prepareMutationsDataAfterMatrixGenerationAndExtractorForTopography(chromShortNamesList,
inputDir,
outputDir,
jobname,
DBS,
dbs_probabilities,
mutation_type_context_for_probabilities,
startSimNum,
endSimNum,
DBS,
PCAWG,
verbose)
print("--- Merge original chr based files with Mutation Probabilities: %s seconds" % (time.time() - start_time))
print("--- Merge original chr based files with Mutation Probabilities: %f minutes" % (float((time.time() - start_time) / 60)))
print('--- Merge original chr based files with Mutation Probabilities ends')
print('#################################################################################\n')
####################################################################################################################
################## Merge original chr based files with Mutation Probabilities ends ################################
####################################################################################################################
####################################################################################################################
################## Merge simulations chr based files with Mutation Probabilities starts ###########################
####################################################################################################################
if (numofSimulations > 0):
print('#################################################################################')
print('--- Merge simulations chr based files with Mutation Probabilities starts')
print('#################################################################################')
startSimNum=1
endSimNum=numofSimulations
start_time = time.time()
# SBS
for mutation_type_context in mutation_types_contexts:
# if (mutation_type_context in SBS_CONTEXTS) and (sbs_probabilities is not None):
if (mutation_type_context in SBS_CONTEXTS):
mutation_type_context_for_probabilities = get_mutation_type_context_for_probabilities_file(mutation_types_contexts_for_signature_probabilities, SUBS)
print('--- Merge %s mutations with probabilities for %s' %(mutation_type_context,sbs_probabilities))
prepareMutationsDataAfterMatrixGenerationAndExtractorForTopography(chromShortNamesList,inputDir,outputDir,jobname,mutation_type_context,sbs_probabilities,mutation_type_context_for_probabilities,startSimNum,endSimNum,'SNV',PCAWG,verbose)
# ID
# if ((ID in mutation_types_contexts) and (id_probabilities is not None)):
if (ID in mutation_types_contexts):
mutation_type_context_for_probabilities = get_mutation_type_context_for_probabilities_file(mutation_types_contexts_for_signature_probabilities, ID)
print('--- Merge %s mutations with probabilities for %s' % (ID, id_probabilities))
prepareMutationsDataAfterMatrixGenerationAndExtractorForTopography(chromShortNamesList,inputDir,outputDir,jobname,'ID',id_probabilities,mutation_type_context_for_probabilities,startSimNum,endSimNum,'ID',PCAWG,verbose)
# DBS
# if ((DBS in mutation_types_contexts) and (dbs_probabilities is not None)):
if (DBS in mutation_types_contexts):
mutation_type_context_for_probabilities = get_mutation_type_context_for_probabilities_file(mutation_types_contexts_for_signature_probabilities, DBS)
print('--- Merge %s mutations with probabilities for %s' % (DBS,dbs_probabilities))
prepareMutationsDataAfterMatrixGenerationAndExtractorForTopography(chromShortNamesList,inputDir,outputDir,jobname,'DBS',dbs_probabilities,mutation_type_context_for_probabilities,startSimNum,endSimNum,'DBS',PCAWG,verbose)
print("--- Merge simulations chr based files with Mutation Probabilities: %s seconds" %(time.time()-start_time))
print("--- Merge simulations chr based files with Mutation Probabilities: %f minutes" %(float((time.time()-start_time)/60)))
print('--- Merge simulations chr based files with Mutation Probabilities ends')
print('#################################################################################\n')
####################################################################################################################
################## Merge simulations chr based files with Mutation Probabilities ends #############################
####################################################################################################################
else:
for mutation_type_context in mutation_types_contexts:
if (mutation_type_context in SBS_CONTEXTS):
if ((sbs_probabilities is not None) and (os.path.exists(sbs_probabilities))):
ordered_all_sbs_signatures_wrt_probabilities_file_array = pd.read_csv(sbs_probabilities, sep='\t', nrows=0).columns.values
else:
filename = '%s_%s_for_topography.txt' % ('chr1', SUBS)
chrBasedMutationDFFilePath = os.path.join(outputDir, jobname, DATA, CHRBASED, filename)
if os.path.exists(chrBasedMutationDFFilePath):
ordered_all_sbs_signatures_wrt_probabilities_file_array = pd.read_csv(chrBasedMutationDFFilePath,sep='\t', nrows=0).columns.values
print('ordered_all_sbs_signatures_wrt_probabilities_file_array:%s' %(ordered_all_sbs_signatures_wrt_probabilities_file_array))
else:
print('There is a problem: ordered_all_sbs_signatures_wrt_probabilities_file_array is not filled.')
if (DBS in mutation_types_contexts):
if ((dbs_probabilities is not None) and (os.path.exists(dbs_probabilities))):
ordered_all_dbs_signatures_wrt_probabilities_file_array = pd.read_csv(dbs_probabilities, sep='\t', nrows=0).columns.values
else:
filename = '%s_%s_for_topography.txt' % ('chr1', DINUCS)
chrBasedMutationDFFilePath = os.path.join(outputDir, jobname, DATA, CHRBASED, filename)
if os.path.exists(chrBasedMutationDFFilePath):
ordered_all_dbs_signatures_wrt_probabilities_file_array = pd.read_csv(chrBasedMutationDFFilePath, sep='\t', nrows=0).columns.values
print('ordered_all_dbs_signatures_wrt_probabilities_file_array:%s' %(ordered_all_dbs_signatures_wrt_probabilities_file_array))
else:
print('There is a problem: ordered_all_dbs_signatures_wrt_probabilities_file_array is not filled.')
if (ID in mutation_types_contexts):
if ((id_probabilities is not None) and (os.path.exists(id_probabilities))):
ordered_all_id_signatures_wrt_probabilities_file_array = pd.read_csv(id_probabilities,sep='\t', nrows=0).columns.values
else:
filename = '%s_%s_for_topography.txt' % ('chr1', INDELS)
chrBasedMutationDFFilePath = os.path.join(outputDir, jobname, DATA, CHRBASED, filename)
if os.path.exists(chrBasedMutationDFFilePath):
ordered_all_id_signatures_wrt_probabilities_file_array = pd.read_csv(chrBasedMutationDFFilePath, sep='\t', nrows=0).columns.values
print('ordered_all_id_signatures_wrt_probabilities_file_array:%s' %(ordered_all_id_signatures_wrt_probabilities_file_array))
else:
print('There is a problem: ordered_all_id_signatures_wrt_probabilities_file_array is not filled.')
###################################################################################################################
########### Step# Merge chrom based matrix generator generated files with probabilities ends ######################
###################################################################################################################
#######################################################################################################
################################### Step4 Fill Table Starts ###########################################
#######################################################################################################
# Step4 Initialize these dataframes as empty dataframe
# Step4 We will fill these dataframes if there is the corresponding data
subsSignature_cutoff_numberofmutations_averageprobability_df = pd.DataFrame()
dinucsSignature_cutoff_numberofmutations_averageprobability_df = pd.DataFrame()
indelsSignature_cutoff_numberofmutations_averageprobability_df = pd.DataFrame()
# Fill these pandas dataframes
# cancer_type signature number_of_mutations average_probability samples_list len(samples_list) len(all_samples_list) percentage_of_samples
sbs_signature_number_of_mutations_df = pd.DataFrame()
dbs_signature_number_of_mutations_df = pd.DataFrame()
id_signature_number_of_mutations_df = pd.DataFrame()
mutationtype_numberofmutations_numberofsamples_sampleslist_df = pd.DataFrame()
chrlong_numberofmutations_df = pd.DataFrame()
if (step4_tables):
#################################################################################
print('#################################################################################')
print('--- Fill tables/dictionaries using original data starts')
start_time = time.time()
##################################################################################
# For each signature we will find a cutoff value for mutations with average probability >=0.9
# Our aim is to have at most 10% false positive rate in mutations
# number of mutations >= 5K for subs signatures
# number of mutations >= 1K for indels signatures
# number of mutations >= 200 for dinuc signatures
# If we can not satisfy this condition we will discard the signature
cutoffs = []
for cufoff in np.arange(0.5, 0.91, 0.01):
cutoffs.append("%.2f" % (cufoff))
# Initialize
# mutationType2PropertiesListDict: PropertiesList consists of [NumberofMutations NumberofSamples SamplesList]
mutationType2PropertiesDict = {}
chrLong2NumberofMutationsDict = {}
for mutation_type_context in mutation_types_contexts:
if (mutation_type_context in SBS_CONTEXTS):
sbs_signature_number_of_mutations_df = fill_signature_number_of_mutations_df(outputDir,
jobname,
chromNamesList,
SUBS)
sbs_signature_number_of_mutations_df.to_csv(os.path.join(outputDir,
jobname,
DATA,
Table_SBS_Signature_Probability_Mode_NumberofMutations_AverageProbability_Filename),
sep='\t', header=True, index=False)
# We are reading original data to fill the signature2PropertiesListDict
# We are writing all samples_mutations_cutoffs_tables and signature based decided samples_mutations_cutoffs_tables in table format.
subsSignature_cutoff_numberofmutations_averageprobability_df = fillCutoff2Signature2PropertiesListDictionary(
outputDir,
jobname,
chromNamesList,
SUBS,
cutoffs,
average_probability,
num_of_sbs_required,
num_of_id_required,
num_of_dbs_required,
mutationType2PropertiesDict,
chrLong2NumberofMutationsDict)
if (DBS in mutation_types_contexts):
dbs_signature_number_of_mutations_df = fill_signature_number_of_mutations_df(outputDir,
jobname,
chromNamesList,
DINUCS)
dbs_signature_number_of_mutations_df.to_csv(os.path.join(outputDir,
jobname,
DATA,
Table_DBS_Signature_Probability_Mode_NumberofMutations_AverageProbability_Filename),
sep='\t', header=True, index=False)
# We are reading original data to fill the signature2PropertiesListDict
# We are writing all samples_mutations_cutoffs_tables and signature based decided samples_mutations_cutoffs_tables in table format.
dinucsSignature_cutoff_numberofmutations_averageprobability_df = fillCutoff2Signature2PropertiesListDictionary(
outputDir,
jobname,
chromNamesList,
DINUCS,
cutoffs,
average_probability,
num_of_sbs_required,
num_of_id_required,
num_of_dbs_required,
mutationType2PropertiesDict,
chrLong2NumberofMutationsDict)
if (ID in mutation_types_contexts):
id_signature_number_of_mutations_df = fill_signature_number_of_mutations_df(outputDir,
jobname,
chromNamesList,
INDELS)
id_signature_number_of_mutations_df.to_csv(os.path.join(outputDir,
jobname,
DATA,
Table_ID_Signature_Probability_Mode_NumberofMutations_AverageProbability_Filename),
sep='\t', header=True, index=False)
# We are reading original data to fill the signature2PropertiesListDict
# We are writing all samples_mutations_cutoffs_tables and signature based decided samples_mutations_cutoffs_tables in table format.
indelsSignature_cutoff_numberofmutations_averageprobability_df = fillCutoff2Signature2PropertiesListDictionary(
outputDir,
jobname,
chromNamesList,
INDELS,
cutoffs,
average_probability,
num_of_sbs_required,
num_of_id_required,
num_of_dbs_required,
mutationType2PropertiesDict,
chrLong2NumberofMutationsDict)
####################################################################
# Add the last row
numberofMutations = 0
all_samples = set()
for mutation_type in mutationType2PropertiesDict:
numberofMutations += mutationType2PropertiesDict[mutation_type]['number_of_mutations']
samples_list = mutationType2PropertiesDict[mutation_type]['samples_list']
all_samples = all_samples.union(samples_list)
all_samples_list=list(all_samples)
all_samples_list = sorted(all_samples_list, key=natural_key)
print("--- Number of samples: %d" %len(all_samples_list))
print("--- Samples: %s" %(all_samples_list))
all_samples_np_array=np.array(all_samples_list)
mutationType2PropertiesDict['All']={}
mutationType2PropertiesDict['All']['number_of_mutations'] = numberofMutations
mutationType2PropertiesDict['All']['number_of_samples'] = len(all_samples)
mutationType2PropertiesDict['All']['samples_list'] = all_samples_list
# Write mutationType2PropertiesListDict dictionary as a dataframe starts
filePath = os.path.join(outputDir, jobname, DATA, Table_MutationType_NumberofMutations_NumberofSamples_SamplesList_Filename)
L = sorted([(mutation_type, a['number_of_mutations'], a['number_of_samples'], a['samples_list'])
for mutation_type, a in mutationType2PropertiesDict.items()])
if L:
mutationtype_numberofmutations_numberofsamples_sampleslist_df = pd.DataFrame(L, columns=['mutation_type', 'number_of_mutations', 'number_of_samples', 'samples_list'])
# write this dataframe
mutationtype_numberofmutations_numberofsamples_sampleslist_df.to_csv(filePath, sep='\t', header=True, index=False)
# Write dictionary as a dataframe ends
####################################################################
# Write chrLong2NumberofMutationsDict dictionary as a dataframe starts
filePath = os.path.join(outputDir, jobname, DATA, Table_ChrLong_NumberofMutations_Filename)
L = sorted([(chrLong, number_of_mutations)
for chrLong, number_of_mutations in chrLong2NumberofMutationsDict.items()])
if L:
chrlong_numberofmutations_df = pd.DataFrame(L, columns=['chrLong', 'number_of_mutations'])
# write this dataframe
chrlong_numberofmutations_df.to_csv(filePath, sep='\t', header=True, index=False)
# Write dictionary as a dataframe ends
##################################################################################
# We are reading original data again to fill the mutationType based, sample based and signature based dictionaries
# This part is deprecated
if sample_based:
# Using original data
for mutation_type_context in mutation_types_contexts:
if (mutation_type_context in SBS_CONTEXTS):
fill_mutations_dictionaries_write(outputDir, jobname, chromNamesList, SUBS,
subsSignature_cutoff_numberofmutations_averageprobability_df, num_of_sbs_required, num_of_id_required,
num_of_dbs_required)
if (DBS in mutation_types_contexts):
fill_mutations_dictionaries_write(outputDir, jobname, chromNamesList, DINUCS,
dinucsSignature_cutoff_numberofmutations_averageprobability_df,
num_of_sbs_required,
num_of_id_required,
num_of_dbs_required)
if (ID in mutation_types_contexts):
fill_mutations_dictionaries_write(outputDir, jobname, chromNamesList, INDELS,
indelsSignature_cutoff_numberofmutations_averageprobability_df,
num_of_sbs_required,
num_of_id_required,
num_of_dbs_required)
##################################################################################
print("--- Fill tables/dictionaries using original data: %s seconds" % (time.time() - start_time))
print("--- Fill tables/dictionaries using original data: %f minutes" % (float((time.time() - start_time) / 60)))
print('--- Fill tables/dictionaries using original data ends')
print('#################################################################################\n')
#################################################################################
else:
mutationtype_numberofmutations_numberofsamples_sampleslist_df=pd.read_csv(os.path.join(outputDir,jobname,DATA,Table_MutationType_NumberofMutations_NumberofSamples_SamplesList_Filename),sep='\t', header=0, dtype={'mutation_type':str, 'number_of_mutations':np.int32})
all_samples_string=mutationtype_numberofmutations_numberofsamples_sampleslist_df[mutationtype_numberofmutations_numberofsamples_sampleslist_df['mutation_type']=='All']['samples_list'].values[0]
all_samples_list=eval(all_samples_string)
all_samples_list = sorted(all_samples_list, key=natural_key)
all_samples_np_array=np.array(all_samples_list)
print('sample_based:%s --- len(all_samples_list):%d --- all_samples_list:%s' %(sample_based,len(all_samples_list), all_samples_list))
chrlong_numberofmutations_df = pd.read_csv(os.path.join(outputDir, jobname, DATA, Table_ChrLong_NumberofMutations_Filename), sep='\t',header=0, dtype={'chrLong': str, 'number_of_mutations': np.int32})
for mutation_type_context in mutation_types_contexts:
if (mutation_type_context in SBS_CONTEXTS):
subsSignature_cutoff_numberofmutations_averageprobability_df = pd.read_csv(os.path.join(outputDir, jobname, DATA, Table_SBS_Signature_Discreet_Mode_Cutoff_NumberofMutations_AverageProbability_Filename),sep='\t', header=0, dtype={'cutoff':np.float32,'signature':str, 'number_of_mutations':np.int32,'average_probability':np.float32})
if (DBS in mutation_types_contexts):
dinucsSignature_cutoff_numberofmutations_averageprobability_df = pd.read_csv(os.path.join(outputDir, jobname, DATA, Table_DBS_Signature_Discreet_Mode_Cutoff_NumberofMutations_AverageProbability_Filename), sep='\t',header=0, dtype={'cutoff': np.float32, 'signature': str, 'number_of_mutations': np.int32,'average_probability': np.float32})
if (ID in mutation_types_contexts):
indelsSignature_cutoff_numberofmutations_averageprobability_df= pd.read_csv(os.path.join(outputDir,jobname,DATA, Table_ID_Signature_Discreet_Mode_Cutoff_NumberofMutations_AverageProbability_Filename),sep='\t', header=0, dtype={'cutoff':np.float32,'signature':str, 'number_of_mutations':np.int32,'average_probability':np.float32})
#######################################################################################################
################################### Step4 Fill Table ends #############################################
#######################################################################################################
###################################################################################################################
################################################# All Steps ends ##################################################
###################################################################################################################
####################################################################################################################
# Fill numpy arrays with the signatures in cutoff files
sbs_signatures_with_cutoffs = np.array([])
dbs_signatures_with_cutoffs = np.array([])
id_signatures_with_cutoffs = np.array([])
# Fill ordered_signatures arrays w.r.t the order in probabilities file
# cutoffs_df (e.g.: subsSignature_cutoff_numberofmutations_averageprobability_df) are filled in (Step4=True or False but full_mode=True) or full_mode=False
# ordered_signatures_wrt_probabilities_file are filled in (Step3=True or False but full_mode=True) or full_mode=False
# We are interested in the signatures in cutoffs_df
# But user might have changed the order of lines in cutoffs_df
# Therefore we are setting the order in signatures_array and signatures_cutoff_arrays w.r.t. probabilities file
ordered_sbs_signatures_with_cutoffs = np.array([])
ordered_dbs_signatures_with_cutoffs = np.array([])
ordered_id_signatures_with_cutoffs = np.array([])
# Fill the list with the cutoff values
# Fill ordered_signatures_cutoffs
ordered_sbs_signatures_cutoffs = []
ordered_dbs_signatures_cutoffs = []
ordered_id_signatures_cutoffs = []
if not subsSignature_cutoff_numberofmutations_averageprobability_df.empty:
sbs_signatures_with_cutoffs = subsSignature_cutoff_numberofmutations_averageprobability_df['signature'].values
if not dinucsSignature_cutoff_numberofmutations_averageprobability_df.empty:
dbs_signatures_with_cutoffs = dinucsSignature_cutoff_numberofmutations_averageprobability_df['signature'].values
if not indelsSignature_cutoff_numberofmutations_averageprobability_df.empty:
id_signatures_with_cutoffs = indelsSignature_cutoff_numberofmutations_averageprobability_df['signature'].values
if ordered_all_sbs_signatures_wrt_probabilities_file_array is not None:
df_columns_subs_signatures_mask_array = np.isin(ordered_all_sbs_signatures_wrt_probabilities_file_array, sbs_signatures_with_cutoffs)
ordered_sbs_signatures_with_cutoffs = ordered_all_sbs_signatures_wrt_probabilities_file_array[df_columns_subs_signatures_mask_array]
for signature in ordered_sbs_signatures_with_cutoffs:
cutoff = subsSignature_cutoff_numberofmutations_averageprobability_df[subsSignature_cutoff_numberofmutations_averageprobability_df['signature'] == signature]['cutoff'].values[0]
ordered_sbs_signatures_cutoffs.append(cutoff)
if ordered_all_dbs_signatures_wrt_probabilities_file_array is not None:
df_columns_dbs_signatures_mask_array = | np.isin(ordered_all_dbs_signatures_wrt_probabilities_file_array, dbs_signatures_with_cutoffs) | numpy.isin |
from numpy import array
import numpy as np
import time
import torch
import ray
from src.push_rollout_env import PushRolloutEnv
from src.nn_push import PolicyNet
def main():
import argparse
def collect_as(coll_type):
class Collect_as(argparse.Action):
def __call__(self, parser, namespace, values, options_string=None):
setattr(namespace, self.dest, coll_type(values))
return Collect_as
parser = argparse.ArgumentParser(description='PAC-Bayes Opt')
parser.add_argument('--obj_folder', type=str) # '/home/ubuntu/Box_v4/'
parser.add_argument('--posterior_path', type=str, default=None)
arg_con = parser.parse_args()
obj_folder = arg_con.obj_folder
training_details_dic_path = arg_con.posterior_path # 'push_result/push_pac_easy/train_details'
# Load decoder policy
z_total_dim = 5
actor = PolicyNet(
input_num_chann=1,
dim_mlp_append=10,
num_mlp_output=2, # x/y only
out_cnn_dim=40,
z_conv_dim=1,
z_mlp_dim=4,
img_size=150).to('cpu')
actor.load_state_dict(torch.load('pretrained/push_pretrained_decoder.pt'))
# Load posterior if specified path; load prior otherwise
if training_details_dic_path is not None:
training_details_dic = torch.load(training_details_dic_path)
mu = training_details_dic['best_bound_data'][3]
logvar_ps = training_details_dic['best_bound_data'][4]
sigma = (0.5*logvar_ps).exp()
else:
mu = torch.zeros((1, z_total_dim))
sigma = torch.ones((1, z_total_dim))
print('mu:', mu)
print('sigma:', sigma)
# Run
with torch.no_grad():
# Initialize rollout env
rollout_env = PushRolloutEnv(
actor=actor,
z_total_dim=z_total_dim,
num_cpus=10,
y_target_range=0.15)
#* Run single
zs = torch.normal(mean=mu.repeat(5,1), std=sigma.repeat(5,1))
for ind in range(5):
info = rollout_env.roll_single(
zs=zs[ind],
objPos=array([0.51, -0.09, 0.035]),
objOrn=array([0., 0., -0.6]),
objPath=obj_folder+'2010.urdf',
mu=0.3,
sigma=0.01)
info = rollout_env.roll_single(
zs=zs[ind],
objPos=array([0.58, 0.012, 0.035]),
objOrn=array([0., 0., -0.5]),
objPath=obj_folder+'2020.urdf',
mu=0.3,
sigma=0.01)
info = rollout_env.roll_single(
zs=zs[ind],
objPos= | array([0.62, -0.08, 0.035]) | numpy.array |
import tensorflow as tf
from sklearn.metrics import roc_curve, precision_recall_curve
from tqdm import tqdm
from utils.loss_utils import cross_entropy
import os
import numpy as np
from utils.plot_utils import plot_, add_augment
class BaseModel(object):
def __init__(self, sess, conf):
self.sess = sess
self.conf = conf
self.input_shape = [None, self.conf.height, self.conf.width, self.conf.channel]
self.output_shape = [None, self.conf.num_cls]
self.create_placeholders()
def create_placeholders(self):
with tf.name_scope('Input'):
self.inputs_pl = tf.placeholder(tf.float32, self.input_shape, name='input')
self.labels_pl = tf.placeholder(tf.int64, self.output_shape, name='annotation')
self.keep_prob_pl = tf.placeholder(tf.float32)
def loss_func(self):
with tf.name_scope('Loss'):
self.y_prob = tf.nn.softmax(self.logits, axis=-1)
with tf.name_scope('cross_entropy'):
loss = cross_entropy(self.labels_pl, self.logits)
with tf.name_scope('total'):
if self.conf.use_reg:
with tf.name_scope('L2_loss'):
l2_loss = tf.reduce_sum(
self.conf.lmbda * tf.stack([tf.nn.l2_loss(v) for v in tf.get_collection('weights')]))
self.total_loss = loss + l2_loss
else:
self.total_loss = loss
self.mean_loss, self.mean_loss_op = tf.metrics.mean(self.total_loss)
def accuracy_func(self):
with tf.name_scope('Accuracy'):
self.y_pred = tf.argmax(self.logits, axis=1, name='y_pred')
self.y_prob = tf.nn.softmax(self.logits, axis=1)
self.y_pred_ohe = tf.one_hot(self.y_pred, depth=self.conf.num_cls)
correct_prediction = tf.equal(tf.argmax(self.labels_pl, axis=1), self.y_pred, name='correct_pred')
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32), name='accuracy_op')
self.mean_accuracy, self.mean_accuracy_op = tf.metrics.mean(accuracy)
def configure_network(self):
self.loss_func()
self.accuracy_func()
global_step = tf.get_variable('global_step', [], initializer=tf.constant_initializer(0), trainable=False)
learning_rate = tf.train.exponential_decay(self.conf.init_lr,
global_step,
decay_steps=2000,
decay_rate=0.97,
staircase=True)
self.learning_rate = tf.maximum(learning_rate, self.conf.lr_min)
with tf.name_scope('Optimizer'):
optimizer = tf.train.AdamOptimizer(learning_rate=self.learning_rate)
self.train_op = optimizer.minimize(self.total_loss, global_step=global_step)
self.sess.run(tf.global_variables_initializer())
trainable_vars = tf.trainable_variables()
self.saver = tf.train.Saver(var_list=trainable_vars, max_to_keep=1000)
self.train_writer = tf.summary.FileWriter(self.conf.logdir + self.conf.run_name + '/train/', self.sess.graph)
self.valid_writer = tf.summary.FileWriter(self.conf.logdir + self.conf.run_name + '/valid/')
self.configure_summary()
print('*' * 50)
print('Total number of trainable parameters: {}'.
format(np.sum([np.prod(v.get_shape().as_list()) for v in tf.trainable_variables()])))
print('*' * 50)
def configure_summary(self):
summary_list = [tf.summary.scalar('learning_rate', self.learning_rate),
tf.summary.scalar('loss', self.mean_loss),
tf.summary.scalar('accuracy', self.mean_accuracy)]
self.merged_summary = tf.summary.merge(summary_list)
def save_summary(self, summary, step, mode):
# print('----> Summarizing at step {}'.format(step))
if mode == 'train':
self.train_writer.add_summary(summary, step)
elif mode == 'valid':
self.valid_writer.add_summary(summary, step)
self.sess.run(tf.local_variables_initializer())
def train(self):
self.sess.run(tf.local_variables_initializer())
if self.conf.reload_step > 0:
self.reload(self.conf.reload_step)
print('----> Continue Training from step #{}'.format(self.conf.reload_step))
self.best_validation_loss = input('Enter the approximate best validation loss you got last time')
self.best_accuracy = input('Enter the approximate best validation accuracy (in range [0, 1])')
else:
self.best_validation_loss = 100
self.best_accuracy = 0
print('----> Start Training')
if self.conf.data == 'mnist':
from DataLoaders.mnist_loader import DataLoader
elif self.conf.data == 'cifar':
from DataLoaders.CIFARLoader import DataLoader
else:
print('wrong data name')
self.data_reader = DataLoader(self.conf)
self.data_reader.get_data(mode='train')
self.data_reader.get_data(mode='valid')
self.num_train_batch = self.data_reader.count_num_batch(self.conf.batch_size, mode='train')
self.num_batch = self.data_reader.count_num_batch(self.conf.batch_size, mode='valid')
for epoch in range(self.conf.max_epoch):
self.data_reader.randomize()
for train_step in range(self.num_train_batch):
glob_step = epoch * self.num_train_batch + train_step
start = train_step * self.conf.batch_size
end = (train_step + 1) * self.conf.batch_size
x_batch, y_batch = self.data_reader.next_batch(start, end, mode='train')
feed_dict = {self.inputs_pl: x_batch, self.labels_pl: y_batch, self.keep_prob_pl: self.conf.keep_prob}
if train_step % self.conf.SUMMARY_FREQ == 0 and train_step != 0:
_, _, _, summary = self.sess.run([self.train_op,
self.mean_loss_op,
self.mean_accuracy_op,
self.merged_summary], feed_dict=feed_dict)
loss, acc = self.sess.run([self.mean_loss, self.mean_accuracy])
self.save_summary(summary, glob_step + self.conf.reload_step, mode='train')
print('epoch {0}/{1}, step: {2:<6}, train_loss= {3:.4f}, train_acc={4:.01%}'.
format(epoch, self.conf.max_epoch, glob_step, loss, acc))
else:
self.sess.run([self.train_op, self.mean_loss_op, self.mean_accuracy_op], feed_dict=feed_dict)
if glob_step % self.conf.VAL_FREQ == 0 and glob_step != 0:
self.evaluate(train_step=glob_step, dataset='valid')
def test(self, step_num, dataset='test'):
self.sess.run(tf.local_variables_initializer())
print('loading the model.......')
self.reload(step_num)
if self.conf.data == 'mnist':
from DataLoaders.mnist_loader import DataLoader
elif self.conf.data == 'mnist_bg':
from DataLoaders.bg_mnist_loader import DataLoader
elif self.conf.data == 'cifar':
from DataLoaders.CIFARLoader import DataLoader
else:
print('wrong data name')
self.data_reader = DataLoader(self.conf)
self.data_reader.get_data(mode=dataset)
self.num_batch = self.data_reader.count_num_batch(self.conf.batch_size, mode=dataset)
print('-' * 25 + 'Test' + '-' * 25)
if not self.conf.bayes:
self.evaluate(dataset=dataset, train_step=step_num)
else:
self.MC_evaluate(dataset=dataset, train_step=step_num)
def save(self, step):
print('----> Saving the model at step #{0}'.format(step))
checkpoint_path = os.path.join(self.conf.modeldir + self.conf.run_name, self.conf.model_name)
self.saver.save(self.sess, checkpoint_path, global_step=step)
def reload(self, step):
checkpoint_path = os.path.join(self.conf.modeldir + self.conf.run_name, self.conf.model_name)
model_path = checkpoint_path + '-' + str(step)
if not os.path.exists(model_path + '.meta'):
print('----> No such checkpoint found', model_path)
return
print('----> Restoring the model...')
self.saver.restore(self.sess, model_path)
print('----> Model successfully restored')
def evaluate(self, dataset='valid', train_step=None):
self.sess.run(tf.local_variables_initializer())
for step in range(self.num_batch):
start = self.conf.val_batch_size * step
end = self.conf.val_batch_size * (step + 1)
data_x, data_y = self.data_reader.next_batch(start=start, end=end, mode=dataset)
feed_dict = {self.inputs_pl: data_x,
self.labels_pl: data_y,
self.keep_prob_pl: 1}
self.sess.run([self.mean_loss_op, self.mean_accuracy_op], feed_dict=feed_dict)
loss, acc = self.sess.run([self.mean_loss, self.mean_accuracy])
if dataset == "valid": # save the summaries and improved model in validation mode
print('-' * 30)
print('valid_loss = {0:.4f}, val_acc = {1:.01%}'.format(loss, acc))
summary_valid = self.sess.run(self.merged_summary, feed_dict=feed_dict)
self.save_summary(summary_valid, train_step, mode='valid')
if loss < self.best_validation_loss:
self.best_validation_loss = loss
if acc > self.best_accuracy:
self.best_accuracy = acc
print('>>>>>>>> Both model validation loss and accuracy improved; saving the model......')
else:
print('>>>>>>>> model validation loss improved; saving the model......')
self.save(train_step)
elif acc > self.best_accuracy:
self.best_accuracy = acc
print('>>>>>>>> model accuracy improved; saving the model......')
self.save(train_step)
print('-' * 30)
elif dataset == 'test':
print('test_loss = {0:.4f}, test_acc = {1:.02%}'.format(loss, acc))
def MC_evaluate(self, dataset='test', train_step=None):
num_rounds = 10
self.sess.run(tf.local_variables_initializer())
all_std, all_error = np.array([]), np.array([])
mean_tpr, std_tpr = np.array([]), np.array([])
mean_npv, std_npv = np.array([]), np.array([])
mean_acc, std_acc = np.array([]), | np.array([]) | numpy.array |
from kamodo import Kamodo, kamodofy
import pandas as pd
import numpy as np
import scipy
import time
import datetime
from datetime import timezone
import urllib, json
import plotly.express as px
import plotly.graph_objects as go
import pandas as pd
from pandas import DatetimeIndex
from collections.abc import Iterable
def ror_get_info(runID):
'''Query run information for given runID'''
server = "https://ccmc.gsfc.nasa.gov/RoR_WWW/VMR/"
query = '{}/files.php?id={}'.format(server, runID)
response = urllib.request.urlopen(query)
data = json.loads(response.read())
return data
def ror_show_info(runID):
'''Display run information for a given runID.'''
result=ror_get_info(runID)
print("Run information for runID =",runID,"from the CCMC RoR system.")
for item in result['info']:
for k in item:
print(k.rjust(25),':',item[k])
sats = []
for sat in result['satellites']:
satname = sat['name']
sats.append(satname)
k='Satellite extractions'
print(k.rjust(25),':',sats)
def ror_return_satellites(runID):
'''Display list of satellites as python array for given runID.'''
result=ror_get_info(runID)
sats = []
for sat in result['satellites']:
satname = sat['name']
sats.append(satname)
return sats
def ror_get_extraction(runID, coord, satellite):
'''Query for file contents from server'''
server = "https://ccmc.gsfc.nasa.gov/RoR_WWW/VMR/"
query = '{}/{}/{}/{}_{}.txt'.format(server, runID, satellite, coord, satellite)
print(query)
response = urllib.request.urlopen(query)
file = response.read()
return file
class SATEXTRACT(Kamodo):
def __init__(self,
runID, # ccmc runs-on-request run id
coord, # coordinate system
satellite, # satellite
debug=1,
server="https://ccmc.gsfc.nasa.gov/RoR_WWW/VMR/",
**kwargs):
super(SATEXTRACT, self).__init__(**kwargs)
self.verbose=False # overrides kwarg
# self.symbol_registry=dict() # wipes any user-defined symbols
# self.signatures=dict() # wipes any user-defined signatures
self.RE=6.3781E3
self.server = server # should be set by keyword
self.runID = runID
self.coordinates = coord
self.satellite = satellite
self.debug = debug
if self.debug > 0:
print(' -server: CCMC RoR')
print(' -runID: ',runID)
print(' -coordinate system: ',coord)
print(' -satellite: ',satellite)
self.variables=dict()
self.file = ror_get_extraction(runID, coord, satellite).decode('ascii')
self.parse_file()
ts=self.tsarray[0]
self.start = datetime.datetime.fromtimestamp(ts,tz=timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
ts=self.tsarray[-1]
self.stop = datetime.datetime.fromtimestamp(ts,tz=timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
if self.debug > 0:
print(" ")
print(" -date start: ",self.start)
print(" end: ",self.stop)
for varname in self.variables:
if varname == "N":
continue
units = self.variables[varname]['units']
if self.debug > 0:
print('... registering ',varname,units)
self.register_variable(varname, units)
# classification of position into coordinates to assist visualizion
self.possible_coords=('TOD','J2K','GEO','GM','GSM','GSE','SM')
self.possible_directions=('x','y','z')
self.coords=dict()
for varname in self.variables:
size = self.variables[varname]['size']
if size == 1:
# Look for position values
direction = varname.lower()
key = self.coordinates
if key in self.possible_coords and direction in self.possible_directions:
if key not in self.coords:
self.coords[key] = dict(coord=key)
self.coords[key]['size'] = size
self.coords[key][direction] = varname
# Change 'fill' values in data to NaNs
self.fill2nan()
def parse_file(self):
import re
vars=[]
units=[]
times=[]
arrays = []
if self.debug > 0:
print("===> Printing File Header ...")
for line in self.file.splitlines(False):
A = re.match('^# ', line)
B = re.match('# Run', line)
C = re.match('# Coordinate', line)
D = re.match('# Satellite', line)
E = re.match('# Year', line)
F = re.match('# \[year\]', line)
G = re.match('# Data type', line)
if A or B or C or D or E or F or G:
if A:
if self.debug > 0:
print("-> ",line)
if B:
# Find runname and fill value
parts=re.sub(' +', ' ', line).split(' ')
self.runname = parts[3]
self.fillvalue = parts[6]
if C:
# Check that coordinate system matches
parts=re.sub(' +', ' ', line).split(' ')
if self.coordinates != parts[3]:
print("ERROR: Coordinate system does not match.",self.coordinates,parts[3])
if D:
# Check that satellite name matches
parts=re.sub(' +', ' ', line).split(' ')
if self.satellite != parts[3]:
print("ERROR: Satellite does not match.",self.satellite,parts[3])
if E:
# Variable names, remove . and change N and B_1
parts=re.sub(' +', ' ', line).strip().split(' ')
for p in parts[7:]:
p=re.sub("\.","",p)
p=re.sub("B_1","B1",p)
p=re.sub("^N$","rho",p)
vars.append(p)
if self.debug > 1:
print(len(vars), vars)
if F:
# Variable units, remove [] and fix exponents
parts=re.sub(' +', ' ', line).strip().split(' ')
if self.modelname == "GUMICS":
# missing x,y,z --put before other units
units.append('R_E')
units.append('R_E')
units.append('R_E')
for p in parts[7:]:
if self.modelname == "BATSRUS":
# need a unit applied for status variable, currently missing
if vars[len(units)] == "status":
units.append('')
p=re.sub("cm\^-3","1/cm^3",p)
p=re.sub("m2","m^2",p)
p=re.sub("m3","m^3",p)
p=re.sub("\[","",p)
p=re.sub("\]","",p)
p=re.sub("Vm/A","V/A",p) # This is wrong but use it for now
p=re.sub("nJ/m","J/m",p) # This is wrong but use it for now
units.append(p)
if self.modelname == "LFM" and p == "nPa":
# missing X,Y,Z,Vol --unknown Vol units
units.append('R_E')
units.append('R_E')
units.append('R_E')
units.append('')
if self.modelname == "OpenGGCM" and p == "V/A":
# missing eflx,efly,eflz --units are unknown
units.append('')
units.append('')
units.append('')
if self.debug > 1:
print(len(units), units)
if G:
# Pull out the model name
parts=re.sub(' +', ' ', line).split(' ')
self.modelname = parts[3]
else:
parts=re.sub(' +', ' ', line).strip().split(' ')
year=parts[0]
month=parts[1]
day=parts[2]
hour=parts[3]
minute=parts[4]
second=parts[5]
ms=0
if '.' in second:
(second,ms)=second.split('.')
dd=datetime.datetime(int(year),int(month),int(day),
hour=int(hour),minute=int(minute),second=int(second),
microsecond=int(ms)*1000,tzinfo=datetime.timezone.utc)
times.append(dd)
for s in parts[6:]:
arrays.append(float(s))
# self.dtarray=np.array([dd for dd in times])
self.dtarray = pd.to_datetime(times)
self.tsarray = np.array([d.timestamp() for d in self.dtarray])
self.dtarrayclean = np.array([datetime.datetime.fromtimestamp(d,tz=timezone.utc).strftime("%Y-%m-%d %H:%M:%S") for d in self.tsarray])
nvar=len(vars)
nval=len(arrays)
npos=int(nval/nvar)
arrays=np.array(arrays)
arrays=arrays.reshape((npos,nvar))
i=0
for var in vars:
self.variables[var] = dict(units=units[i],
data=arrays[:,i],
size=1,
fill=self.fillvalue)
i+=1
return
def register_variable(self, varname, units):
"""register variables into Kamodo for this service, CCMC ROR satellite extractions"""
data = self.variables[varname]['data']
times = self.dtarray
ser = pd.Series(data, index=pd.DatetimeIndex(times))
@kamodofy(units = units,
citation = "De Zeeuw 2020",
data = None)
def interpolate(t=times):
ts = t
isiterable = isinstance(t, Iterable)
if isinstance(ts, DatetimeIndex):
pass
elif isinstance(ts, float):
ts = pd.to_datetime([ts], utc=True, unit='s')
elif isiterable:
if isinstance(ts[0], float):
ts = pd.to_datetime(ts, utc=True, unit='s')
ts = DatetimeIndex(ts)
else:
raise NotImplementedError(ts)
ser_ = ser.reindex(ser.index.union(ts))
ser_interpolated = ser_.interpolate(method='time')
result = ser_interpolated.reindex(ts)
if isiterable:
return result.values
else:
return result.values[0]
# store the interpolator
self.variables[varname]['interpolator'] = interpolate
# update docstring for this variable
interpolate.__doc__ = "A function that returns {} in [{}].".format(varname,units)
var_reg = '{}__{}'.format(varname, self.coordinates)
self[var_reg] = interpolate
def fill2nan(self):
'''
Replaces fill value in data with NaN.
Not Yet called by default. Call as needed.
'''
for varname in self.variables:
data = self.variables[varname]['data']
fill = self.variables[varname]['fill']
if fill is not None:
mask = data==float(fill)
nbad = np.count_nonzero(mask)
if nbad > 0:
if self.debug > 0:
print("Found",nbad,"fill values, replacing with NaN for variable",
varname,"of size",data.size)
data[mask]=np.nan
self.variables[varname]['data'] = data
def get_plot(self, type="1Dpos", scale="R_E", var="", groupby="all",
quiver=False, quiverscale="5.", quiverskip="0"):
'''
Return a plotly figure object.
type = 1Dvar => 1D plot of variable value vs Time (also all variables option)
1Dpos (default) => 1D location x,y,z vs Time
3Dpos => 3D location colored by altitude
3Dvar => View variable on 3D position (also quiver and groupby options)
scale = km, R_E (default)
var = variable name for variable value plots
groupby = day, hour, all (default) => groupings for 3Dvar plots
quiver = True, False (default) => if var is a vector value and 3Dvar plot, then
turn on quivers and color by vector magnitude
quiverscale = 5. (default) => length of quivers in units of RE
quiverskip = (default) => now many quivers to skip displaying
'''
quiverscale=float(quiverscale)
if scale == "km":
quiverscale=quiverscale*self.RE
quiverskip=int(quiverskip)
coord=self.coordinates
# Set plot title for plots
txttop=self.satellite + " position extracted from run " + self.runname + "<br>"\
+ self.start + " to " + self.stop + "<br>" + coord
if type == '1Dvar':
if var == "":
print("No plot variable passed in.")
return
fig=go.Figure()
if var == "all":
# Create menu pulldown for each variable
steps = []
i=0
for varname in self.variables:
ytitle=varname+" ["+self.variables[varname]['units']+"]"
step = dict(
label=ytitle,
method="update",
args=[{"visible": [False] * len(self.variables)}],
)
step["args"][0]["visible"][i] = True # Toggle i'th trace to "visible"
steps.append(step)
if self.variables[varname]['size'] == 1:
x=self.variables[varname]['data']
fig.add_trace(go.Scatter(x=self.dtarray, y=x, mode='lines+markers',
name=varname, visible=False))
elif self.variables[varname]['size'] == 3:
x=self.variables[varname]['data'][:,0]
y=self.variables[varname]['data'][:,1]
z=self.variables[varname]['data'][:,2]
fig.add_trace(go.Scatter(x=self.dtarray, y=x, mode='lines+markers',
name=varname, visible=False))
fig.add_trace(go.Scatter(x=self.dtarray, y=y, mode='lines+markers',
name=varname, visible=False))
fig.add_trace(go.Scatter(x=self.dtarray, y=z, mode='lines+markers',
name=varname, visible=False))
i+=1
fig.data[0].visible=True
fig.update_layout(updatemenus=list([dict(buttons=steps)]))
fig.update_xaxes(title_text="Time")
fig.update_layout(hovermode="x")
fig.update_layout(title_text=txttop)
else:
# Standard single/vector variable plot
if self.variables[var]['size'] == 1:
x=self.variables[var]['data']
fig.add_trace(go.Scatter(x=self.dtarray, y=x, mode='lines+markers', name=var))
elif self.variables[var]['size'] == 3:
x=self.variables[var]['data'][:,0]
y=self.variables[var]['data'][:,1]
z=self.variables[var]['data'][:,2]
fig.add_trace(go.Scatter(x=self.dtarray, y=x, mode='lines+markers', name=var))
fig.add_trace(go.Scatter(x=self.dtarray, y=y, mode='lines+markers', name=var))
fig.add_trace(go.Scatter(x=self.dtarray, y=z, mode='lines+markers', name=var))
ytitle=var+" ["+self.variables[var]['units']+"]"
fig.update_xaxes(title_text="Time")
fig.update_yaxes(title_text=ytitle)
fig.update_layout(hovermode="x")
fig.update_layout(title_text=txttop)
return fig
if type == '1Dpos':
fig=go.Figure()
xvarname = self.coords[coord]['x']
if self.coords[coord]['size'] == 1:
x=self.variables[self.coords[coord]['x']]['data']
y=self.variables[self.coords[coord]['y']]['data']
z=self.variables[self.coords[coord]['z']]['data']
elif self.coords[coord]['size'] == 3:
x=self.variables[self.coords[coord]['x']]['data'][:,0]
y=self.variables[self.coords[coord]['y']]['data'][:,1]
z=self.variables[self.coords[coord]['z']]['data'][:,2]
if scale == "km":
if self.variables[xvarname]['units'] == "R_E":
x=x*self.RE
y=y*self.RE
z=z*self.RE
ytitle="Position [km]"
else:
if self.variables[xvarname]['units'] == "km":
x=x/self.RE
y=y/self.RE
z=z/self.RE
ytitle="Position [R_E]"
fig.add_trace(go.Scatter(x=self.dtarray, y=x,
mode='lines+markers', name=self.coords[coord]['x']))
fig.add_trace(go.Scatter(x=self.dtarray, y=y,
mode='lines+markers', name=self.coords[coord]['y']))
fig.add_trace(go.Scatter(x=self.dtarray, y=z,
mode='lines+markers', name=self.coords[coord]['z']))
fig.update_xaxes(title_text="Time")
fig.update_yaxes(title_text=ytitle)
fig.update_layout(hovermode="x")
fig.update_layout(title_text=txttop)
return fig
if type == "3Dpos":
xvarname = self.coords[coord]['x']
if self.coords[coord]['size'] == 1:
x=self.variables[self.coords[coord]['x']]['data']
y=self.variables[self.coords[coord]['y']]['data']
z=self.variables[self.coords[coord]['z']]['data']
elif self.coords[coord]['size'] == 3:
x=self.variables[self.coords[coord]['x']]['data'][:,0]
y=self.variables[self.coords[coord]['y']]['data'][:,1]
z=self.variables[self.coords[coord]['z']]['data'][:,2]
if scale == "km":
if self.variables[xvarname]['units'] == "R_E":
x=x*self.RE
y=y*self.RE
z=z*self.RE
r=(np.sqrt(x**2 + y**2 + z**2))-self.RE
else:
if self.variables[xvarname]['units'] == "km":
x=x/self.RE
y=y/self.RE
z=z/self.RE
r=(np.sqrt(x**2 + y**2 + z**2))-1.
fig=px.scatter_3d(
x=x,
y=y,
z=z,
color=r)
bartitle = "Altitude [" + scale + "]"
fig.update_layout(coloraxis=dict(colorbar=dict(title=bartitle)))
fig.update_layout(scene=dict(xaxis=dict(title=dict(text="X ["+scale+"]")),
yaxis=dict(title=dict(text="Y ["+scale+"]")),
zaxis=dict(title=dict(text="Z ["+scale+"]"))))
fig.update_layout(title_text=txttop)
return fig
if type == "3Dvar":
if var == "":
print("No plot variable passed in.")
return
xvarname = self.coords[coord]['x']
vard=self.variables[var]['data']
varu=self.variables[var]['units']
if quiver:
if "_x" in var or "_y" in var or"_z" in var:
var=var.split('_')[0]
qxvar=var+"_x"
qyvar=var+"_y"
qzvar=var+"_z"
qxvard=self.variables[qxvar]['data']
qyvard=self.variables[qyvar]['data']
qzvard=self.variables[qzvar]['data']
vard = np.sqrt(np.square(qxvard) +\
np.square(qyvard) +\
| np.square(qzvard) | numpy.square |
# -*- coding: utf-8 -*-
# Copyright 2018-2022 the orix developers
#
# This file is part of orix.
#
# orix is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# orix is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with orix. If not, see <http://www.gnu.org/licenses/>.
from diffpy.structure import Lattice, Structure
import numpy as np
import pytest
from orix.crystal_map import Phase
from orix.quaternion import Orientation, symmetry
from orix.vector import Miller
from orix.vector.miller import _round_indices, _transform_space, _UVTW2uvw, _uvw2UVTW
TRIGONAL_PHASE = Phase(
point_group="321", structure=Structure(lattice=Lattice(4.9, 4.9, 5.4, 90, 90, 120))
)
TETRAGONAL_LATTICE = Lattice(0.5, 0.5, 1, 90, 90, 90)
TETRAGONAL_PHASE = Phase(
point_group="4", structure=Structure(lattice=TETRAGONAL_LATTICE)
)
CUBIC_PHASE = Phase(point_group="m-3m")
class TestMiller:
def test_init_raises(self):
with pytest.raises(ValueError, match="Exactly *"):
_ = Miller(phase=Phase(point_group="m-3m"))
with pytest.raises(ValueError, match="Exactly *"):
_ = Miller(xyz=[0, 1, 2], hkl=[3, 4, 5], phase=Phase(point_group="m-3m"))
with pytest.raises(ValueError, match="A phase with a crystal lattice and "):
_ = Miller(hkl=[1, 1, 1])
def test_repr(self):
m = Miller(hkil=[1, 1, -2, 0], phase=TRIGONAL_PHASE)
assert repr(m) == "Miller (1,), point group 321, hkil\n" "[[ 1. 1. -2. 0.]]"
def test_coordinate_format_raises(self):
m = Miller(hkl=[1, 1, 1], phase=TETRAGONAL_PHASE)
with pytest.raises(ValueError, match="Available coordinate formats are "):
m.coordinate_format = "abc"
def test_set_coordinates(self):
m = Miller(xyz=[1, 2, 0], phase=TETRAGONAL_PHASE)
assert np.allclose(m.data, m.coordinates)
def test_get_item(self):
v = [[1, 1, 1], [2, 0, 0]]
m = Miller(hkl=v, phase=TETRAGONAL_PHASE)
assert not np.may_share_memory(m.data, m[0].data)
assert not np.may_share_memory(m.data, m[:].data)
m2 = m[0]
m2.hkl = [1, 1, 2]
assert np.allclose(m.hkl, v)
def test_set_hkl_hkil(self):
m1 = Miller(hkl=[[1, 1, 1], [2, 0, 0]], phase=TETRAGONAL_PHASE)
assert np.allclose(m1.data, [[2, 2, 1], [4, 0, 0]])
assert np.allclose([m1.h, m1.k, m1.l], [[1, 2], [1, 0], [1, 0]])
m1.hkl = [[1, 2, 0], [1, 1, 0]]
assert np.allclose(m1.data, [[2, 4, 0], [2, 2, 0]])
assert np.allclose([m1.h, m1.k, m1.l], [[1, 1], [2, 1], [0, 0]])
m2 = Miller(hkil=[[1, 1, -2, 1], [2, 0, -2, 0]], phase=TRIGONAL_PHASE)
assert np.allclose(m2.data, [[0.20, 0.35, 0.19], [0.41, 0.24, 0]], atol=0.01)
assert np.allclose([m2.h, m2.k, m2.i, m2.l], [[1, 2], [1, 0], [-2, -2], [1, 0]])
m2.hkil = [[1, 2, -3, 1], [2, 1, -3, 1]]
assert np.allclose(m2.data, [[0.20, 0.59, 0.19], [0.41, 0.47, 0.19]], atol=0.01)
assert np.allclose([m2.h, m2.k, m2.i, m2.l], [[1, 2], [2, 1], [-3, -3], [1, 1]])
def test_set_uvw_UVTW(self):
m1 = Miller(uvw=[[1, 1, 1], [2, 0, 0]], phase=TETRAGONAL_PHASE)
assert np.allclose(m1.data, [[0.5, 0.5, 1], [1, 0, 0]])
assert np.allclose([m1.u, m1.v, m1.w], [[1, 2], [1, 0], [1, 0]])
m1.uvw = [[1, 2, 0], [1, 1, 0]]
assert np.allclose(m1.data, [[0.5, 1, 0], [0.5, 0.5, 0]])
assert np.allclose([m1.u, m1.v, m1.w], [[1, 1], [2, 1], [0, 0]])
m2 = Miller(UVTW=[[1, 1, -2, 1], [2, 0, -2, 0]], phase=TRIGONAL_PHASE)
assert np.allclose(m2.data, [[7.35, 12.73, 5.4], [14.7, 8.49, 0]], atol=0.01)
assert np.allclose([m2.U, m2.V, m2.T, m2.W], [[1, 2], [1, 0], [-2, -2], [1, 0]])
m2.UVTW = [[1, 2, -3, 1], [2, 1, -3, 1]]
assert np.allclose(m2.data, [[7.35, 21.22, 5.4], [14.7, 16.97, 5.4]], atol=0.01)
assert np.allclose([m2.U, m2.V, m2.T, m2.W], [[1, 2], [2, 1], [-3, -3], [1, 1]])
def test_length(self):
# Direct lattice vectors
m1 = Miller(uvw=[0, -0.5, 0.5], phase=TETRAGONAL_PHASE)
assert np.allclose(m1.length, 0.559, atol=1e-3)
# Reciprocal lattice vectors
m2 = Miller(hkl=[[1, 2, 0], [3, 1, 1]], phase=TETRAGONAL_PHASE)
assert np.allclose(m2.length, [4.472, 6.403], atol=1e-3)
assert np.allclose(1 / m2.length, [0.224, 0.156], atol=1e-3)
# Vectors
m3 = Miller(xyz=[[1, 0, 0], [0, 1, 0], [0, 0, 1]], phase=TETRAGONAL_PHASE)
assert np.allclose(m3.length, [1, 1, 1])
def test_init_from_highest_indices(self):
m1 = Miller.from_highest_indices(phase=TETRAGONAL_PHASE, hkl=[3, 2, 1])
assert np.allclose(np.max(m1.hkl, axis=0), [3, 2, 1])
m2 = Miller.from_highest_indices(phase=TETRAGONAL_PHASE, uvw=[1, 2, 3])
assert np.allclose(np.max(m2.uvw, axis=0), [1, 2, 3])
with pytest.raises(ValueError, match="Either highest `hkl` or `uvw` indices "):
_ = Miller.from_highest_indices(phase=TETRAGONAL_PHASE)
with pytest.raises(ValueError, match="All indices*"):
_ = Miller.from_highest_indices(phase=TETRAGONAL_PHASE, hkl=[3, 2, -1])
def test_init_from_min_dspacing(self):
# Tested against EMsoft v5.0
m1 = Miller.from_min_dspacing(phase=TETRAGONAL_PHASE, min_dspacing=0.05)
assert m1.coordinate_format == "hkl"
assert m1.size == 14078
assert np.allclose(np.max(m1.hkl, axis=0), [9, 9, 19])
assert np.allclose(np.min(1 / m1.length), 0.0315, atol=1e-4)
m2 = Miller.from_min_dspacing(phase=TRIGONAL_PHASE, min_dspacing=0.5)
assert m2.size == 6068
assert np.allclose(np.max(m2.hkl, axis=0), [8, 8, 10])
assert np.allclose(np.min(1 / m2.length), 0.2664, atol=1e-4)
def test_deepcopy(self):
m = Miller(hkl=[1, 1, 0], phase=TETRAGONAL_PHASE)
m2 = m.deepcopy()
m2.coordinate_format = "uvw"
assert m2.coordinate_format == "uvw"
assert m.coordinate_format == "hkl"
def test_get_nearest(self):
assert (
Miller(uvw=[1, 0, 0], phase=TETRAGONAL_PHASE).get_nearest()
== NotImplemented
)
def test_mean(self):
# Tested against MTEX v5.6.0
m1 = Miller(hkl=[[1, 2, 0], [3, 1, 1]], phase=TETRAGONAL_PHASE)
m1_mean = m1.mean()
assert isinstance(m1_mean, Miller)
assert m1_mean.coordinate_format == "hkl"
assert np.allclose(m1_mean.hkl, [2, 1.5, 0.5])
m2 = Miller(UVTW=[[1, 2, -3, 0], [3, 1, -4, 1]], phase=TRIGONAL_PHASE)
m2_mean = m2.mean()
assert m2_mean.coordinate_format == "UVTW"
assert np.allclose(m2_mean.UVTW, [2, 1.5, -3.5, 0.5])
assert m2.mean(use_symmetry=True) == NotImplemented
def test_round(self):
# Tested against MTEX v5.6.0
m1 = Miller(uvw=[[1, 1, 0], [1, 1, 1]], phase=TETRAGONAL_PHASE)
m1perp = m1[0].cross(m1[1])
m1round = m1perp.round()
assert isinstance(m1round, Miller)
assert m1round.coordinate_format == "hkl"
assert np.allclose(m1round.hkl, [1, -1, 0])
m2 = Miller(hkil=[1, 1, -2, 3], phase=TRIGONAL_PHASE)
m2.coordinate_format = "UVTW"
m2round = m2.round()
assert np.allclose(m2round.UVTW, [3, 3, -6, 11])
m3 = Miller(xyz=[[0.1, 0.2, 0.3], [1, 0.5, 1]], phase=TRIGONAL_PHASE)
assert m3.coordinate_format == "xyz"
m3round = m3.round()
assert np.allclose(m3.data, m3round.data)
assert not np.may_share_memory(m3.data, m3round.data)
def test_symmetrise_raises(self):
m = Miller(uvw=[1, 0, 0], phase=TETRAGONAL_PHASE)
with pytest.raises(ValueError, match="`unique` must be True when"):
_ = m.symmetrise(return_multiplicity=True)
with pytest.raises(ValueError, match="`unique` must be True when"):
_ = m.symmetrise(return_index=True)
def test_symmetrise(self):
# Also thoroughly tested in the TestMillerPointGroup* classes
# Test from MTEX' v5.6.0 documentation
m = Miller(UVTW=[1, -2, 1, 3], phase=TRIGONAL_PHASE)
_, mult = m.symmetrise(return_multiplicity=True, unique=True)
assert mult == 6
m2 = Miller(uvw=[[1, 0, 0], [1, 1, 0], [1, 1, 1]], phase=CUBIC_PHASE)
_, idx = m2.symmetrise(unique=True, return_index=True)
assert np.allclose(idx, np.array([0] * 6 + [1] * 12 + [2] * 8))
_, mult2, _ = m2.symmetrise(
unique=True, return_multiplicity=True, return_index=True
)
assert np.allclose(mult2, [6, 12, 8])
def test_unique(self):
# From the "Crystal geometry" notebook
diamond = Phase(space_group=227)
m = Miller.from_highest_indices(phase=diamond, uvw=[10, 10, 10])
assert m.size == 9260
m2 = m.unique(use_symmetry=True)
assert m2.size == 285
m3, idx = m2.unit.unique(return_index=True)
assert m3.size == 205
assert isinstance(m3, Miller)
assert np.allclose(idx[:10], [65, 283, 278, 269, 255, 235, 208, 282, 272, 276])
def test_multiply_orientation(self):
o = Orientation.from_euler(np.deg2rad([45, 0, 0]))
o.symmetry = CUBIC_PHASE.point_group
m = Miller(hkl=[[1, 1, 1], [2, 0, 0]], phase=CUBIC_PHASE)
m2 = o * m
assert isinstance(m2, Miller)
assert m2.coordinate_format == "hkl"
assert np.allclose(m2.data, [[np.sqrt(2), 0, 1], [np.sqrt(2), -np.sqrt(2), 0]])
def test_overwritten_vector3d_methods(self):
lattice = Lattice(1, 1, 1, 90, 90, 90)
phase1 = Phase(point_group="m-3m", structure=Structure(lattice=lattice))
phase2 = Phase(point_group="432", structure=Structure(lattice=lattice))
m1 = Miller(hkl=[[1, 1, 1], [2, 0, 0]], phase=phase1)
m2 = Miller(hkil=[[1, 1, -2, 0], [2, 1, -3, 1]], phase=phase2)
assert not m1._compatible_with(m2)
with pytest.raises(ValueError, match="The crystal lattices and symmetries"):
_ = m1.angle_with(m2)
with pytest.raises(ValueError, match="The crystal lattices and symmetries"):
_ = m1.cross(m2)
with pytest.raises(ValueError, match="The crystal lattices and symmetries"):
_ = m1.dot(m2)
with pytest.raises(ValueError, match="The crystal lattices and symmetries"):
_ = m1.dot_outer(m2)
m3 = Miller(hkl=[[2, 0, 0], [1, 1, 1]], phase=phase1)
assert m1._compatible_with(m3)
def test_is_hexagonal(self):
assert Miller(hkil=[1, 1, -2, 1], phase=TRIGONAL_PHASE).is_hexagonal
assert not Miller(hkil=[1, 1, -2, 1], phase=TETRAGONAL_PHASE).is_hexagonal
def test_various_shapes(self):
v = np.array([[1, 2, 0], [3, 1, 1], [1, 1, 1], [2, 0, 0], [1, 2, 3], [2, 2, 2]])
# Initialization of vectors work as expected
shape1 = (2, 3)
m1 = Miller(hkl=v.reshape(shape1 + (3,)), phase=TETRAGONAL_PHASE)
assert m1.shape == shape1
assert np.allclose(m1.hkl, v.reshape(shape1 + (3,)))
shape2 = (2, 3)[::-1]
m2 = Miller(uvw=v.reshape(shape2 + (3,)), phase=TETRAGONAL_PHASE)
assert m2.shape == shape2
assert np.allclose(m2.uvw, v.reshape(shape2 + (3,)))
# Vector length and multiplicity
assert m1.length.shape == m1.shape
assert m1.multiplicity.shape == m1.shape
# Symmetrically equivalent vectors
m3, mult, idx = m1.symmetrise(
unique=True, return_multiplicity=True, return_index=True
)
assert m3.shape == (24,)
assert np.allclose(mult, [4] * m1.size)
assert np.allclose(
idx, [0] * 4 + [1] * 4 + [2] * 4 + [3] * 4 + [4] * 4 + [5] * 4
)
# Unit vectors
m4 = m1.unit
assert m4.shape == shape1
# Overwritten Vector3d methods
assert m1.angle_with(m1).shape == shape1
assert m1.cross(m1).shape == shape1
assert m1.dot(m1).shape == shape1
assert m1.dot_outer(m1).shape == shape1 + shape1
assert m1.mean().shape == (1,)
# Round
m5 = m1.round()
assert m5.shape == shape1
# Unique vectors
assert m5.unique(use_symmetry=True).shape == (5,)
assert m5.unique().shape == (5,)
# Reshape
m6 = m1.reshape(*shape2)
assert np.allclose(m6.hkl, v.reshape(shape2 + (3,)))
assert m1._compatible_with(m6) # Phase carries over
def test_transpose(self):
# test 2d
shape = (11, 5)
v = np.random.randint(-5, 5, shape + (3,))
m1 = Miller(hkl=v, phase=TETRAGONAL_PHASE)
m2 = m1.transpose()
assert m1.shape == m2.shape[::-1]
assert m1.phase == m2.phase
# test 2d
shape = (11, 5, 4)
v = np.random.randint(-5, 5, shape + (3,))
m1 = Miller(hkl=v, phase=TETRAGONAL_PHASE)
m2 = m1.transpose(0, 2, 1)
assert m2.shape == (11, 4, 5)
assert m1.phase == m2.phase
m2 = m1.transpose(1, 0, 2)
assert m2.shape == (5, 11, 4)
assert m1.phase == m2.phase
def test_in_fundamental_sector(self):
"""Ensure projecting Miller indices to a fundamental sector
retains type and coordinate format, gives the correct indices,
and that it's possible to project to a different point group's
sector.
"""
h = Miller(uvw=(-1, 1, 0), phase=Phase())
with pytest.raises(ValueError, match="`symmetry` must be passed or "):
_ = h.in_fundamental_sector()
h.phase = CUBIC_PHASE
h2 = h.in_fundamental_sector()
assert isinstance(h2, Miller)
assert np.allclose(h2.phase.point_group.data, h.phase.point_group.data)
assert h2.coordinate_format == h.coordinate_format
h3 = h.in_fundamental_sector(CUBIC_PHASE.point_group)
assert np.allclose((h2.data, h3.data), (1, 0, 1))
assert h2 <= h.phase.point_group.fundamental_sector
h4 = h.in_fundamental_sector(symmetry.D6h)
assert np.allclose(h4.phase.point_group.data, h.phase.point_group.data)
assert np.allclose(h4.data, (1.366, 0.366, 0), atol=1e-3)
def test_transform_space(self):
"""Cover all lines in private function."""
lattice = TETRAGONAL_LATTICE
# Don't share memory
v1 = np.array([1, 1, 1])
v2 = _transform_space(v1, "d", "d", lattice)
assert not np.may_share_memory(v1, v2)
# Incorrect space
with pytest.raises(ValueError, match="`space_in` and `space_out` must be one "):
_transform_space(v1, "direct", "cartesian", lattice)
# uvw -> hkl -> uvw
v3 = np.array([1, 0, 1])
v4 = _transform_space(v3, "d", "r", lattice)
v5 = _transform_space(v4, "r", "d", lattice)
assert np.allclose(v4, [0.25, 0, 1])
assert np.allclose(v5, v3)
class TestMillerBravais:
def test_uvw2UVTW(self):
"""Indices taken from Table 1.1 in 'Introduction to Conventional
Transmission Electron Microscopy (DeGraef, 2003)'.
"""
# fmt: off
uvw = [
[ 1, 0, 0],
[ 1, 1, 0],
[ 0, 0, 1],
[ 0, 1, 1],
[ 2, 1, 0],
[ 2, 1, 1],
[ 0, 1, 0],
[-1, 1, 0],
[ 1, 0, 1],
[ 1, 1, 1],
[ 1, 2, 0],
[ 1, 1, 2],
]
UVTW = [
[ 2, -1, -1, 0],
[ 1, 1, -2, 0],
[ 0, 0, 0, 1],
[-1, 2, -1, 3],
[ 1, 0, -1, 0],
[ 1, 0, -1, 1],
[-1, 2, -1, 0],
[-1, 1, 0, 0],
[ 2, -1, -1, 3],
[ 1, 1, -2, 3],
[ 0, 1, -1, 0],
[ 1, 1, -2, 6],
]
# fmt: on
assert np.allclose(_round_indices(_uvw2UVTW(uvw)), UVTW)
assert np.allclose(_round_indices(_UVTW2uvw(UVTW)), uvw)
assert np.allclose(_round_indices(_uvw2UVTW(_UVTW2uvw(UVTW))), UVTW)
assert np.allclose(_round_indices(_UVTW2uvw(_uvw2UVTW(uvw))), uvw)
m1 = Miller(uvw=uvw, phase=TETRAGONAL_PHASE)
assert np.allclose(m1.uvw, uvw)
m2 = Miller(UVTW=UVTW, phase=TETRAGONAL_PHASE)
assert np.allclose(m2.UVTW, UVTW)
assert np.allclose(m1.unit.data, m2.unit.data)
# MTEX convention
assert np.allclose(_uvw2UVTW(uvw, convention="mtex") / 3, _uvw2UVTW(uvw))
assert np.allclose(_UVTW2uvw(UVTW, convention="mtex") * 3, _UVTW2uvw(UVTW))
def test_mtex_convention(self):
# Same result without convention="mtex" because of rounding...
UVTW = [2, 1, -3, 1]
uvw = _UVTW2uvw(UVTW, convention="mtex")
assert np.allclose(_round_indices(uvw), [5, 4, 1])
def test_trigonal_crystal(self):
# Examples from MTEX' documentation:
# https://mtex-toolbox.github.io/CrystalDirections.html
m = Miller(UVTW=[2, 1, -3, 1], phase=TRIGONAL_PHASE)
assert np.allclose(m.U + m.V + m.T, 0)
n = Miller(hkil=[1, 1, -2, 3], phase=TRIGONAL_PHASE)
assert np.allclose(n.h + n.k + n.i, 0)
m.coordinate_format = "uvw"
mround = m.round()
assert np.allclose(mround.uvw, [5, 4, 1])
assert np.allclose([mround.u[0], mround.v[0], mround.w[0]], [5, 4, 1])
n.coordinate_format = "UVTW"
nround = n.round()
assert np.allclose(nround.UVTW, [3, 3, -6, 11])
assert np.allclose(
[nround.U[0], nround.V[0], nround.T[0], nround.W[0]], [3, 3, -6, 11]
)
# Examples from MTEX' documentation:
# https://mtex-toolbox.github.io/CrystalOperations.html
m1 = Miller(hkil=[1, -1, 0, 0], phase=TRIGONAL_PHASE)
m2 = Miller(hkil=[1, 0, -1, 0], phase=TRIGONAL_PHASE)
assert np.allclose(m1.cross(m2).round().UVTW, [0, 0, 0, 1])
m3 = Miller(UVTW=[0, 0, 0, 1], phase=TRIGONAL_PHASE)
m4 = Miller(UVTW=[1, -2, 1, 3], phase=TRIGONAL_PHASE)
assert np.allclose(m3.cross(m4).round().hkil, [1, 0, -1, 0])
m5 = m4.symmetrise(unique=True)
assert m5.size == 6
# fmt: off
assert np.allclose(
m5.coordinates,
[
[ 1, -2, 1, 3],
[ 1, 1, -2, 3],
[-2, 1, 1, 3],
[ 1, 1, -2, -3],
[-2, 1, 1, -3],
[ 1, -2, 1, -3],
]
)
# fmt: on
m6 = Miller(hkil=[1, 1, -2, 0], phase=TRIGONAL_PHASE)
m7 = Miller(hkil=[-1, -1, 2, 0], phase=TRIGONAL_PHASE)
assert np.allclose(np.rad2deg(m6.angle_with(m7)[0]), 180)
assert np.allclose(np.rad2deg(m6.angle_with(m7, use_symmetry=True)[0]), 60)
def test_convention_not_met(self):
with pytest.raises(ValueError, match="The Miller-Bravais indices convention"):
_ = Miller(hkil=[1, 1, -1, 0], phase=TETRAGONAL_PHASE)
with pytest.raises(ValueError, match="The Miller-Bravais indices convention"):
_ = Miller(UVTW=[1, 1, -1, 0], phase=TETRAGONAL_PHASE)
class TestDeGraefExamples:
# Tests from examples in chapter 1 in Introduction to Conventional
# Transmission Electron Microscopy (DeGraef, 2003)
def test_tetragonal_crystal(self):
# a = b = 0.5 nm, c = 1 nm
lattice = TETRAGONAL_LATTICE
# Example 1.1: Direct metric tensor
assert np.allclose(lattice.metrics, [[0.25, 0, 0], [0, 0.25, 0], [0, 0, 1]])
# Example 1.2: Distance between two points (length of a vector)
answer = np.sqrt(5) / 4 # nm
p1 = np.array([0.5, 0, 0.5])
p2 = np.array([0.5, 0.5, 0])
assert np.allclose(lattice.dist(p1, p2), answer)
m1 = Miller(uvw=p1 - p2, phase=TETRAGONAL_PHASE)
assert np.allclose(m1.length, answer)
# Example 1.3, 1.4: Dot product and angle between two directions
m2 = Miller(uvw=[1, 2, 0], phase=TETRAGONAL_PHASE)
m3 = Miller(uvw=[3, 1, 1], phase=TETRAGONAL_PHASE)
assert np.allclose(m2.dot(m3), 5 / 4) # nm^2
assert np.allclose(np.rad2deg(m2.angle_with(m3)[0]), 53.30, atol=0.01)
# Example 1.5: Reciprocal metric tensor
lattice_recip = lattice.reciprocal()
assert np.allclose(lattice_recip.metrics, [[4, 0, 0], [0, 4, 0], [0, 0, 1]])
# Example 1.6, 1.7: Angle between two plane normals
m4 = Miller(hkl=[1, 2, 0], phase=TETRAGONAL_PHASE)
m5 = Miller(hkl=[3, 1, 1], phase=TETRAGONAL_PHASE)
assert np.allclose(np.rad2deg(m4.angle_with(m5)[0]), 45.7, atol=0.1)
# Example 1.8: Reciprocal components of a lattice vector
m6 = Miller(uvw=[1, 1, 4], phase=TETRAGONAL_PHASE)
assert np.allclose(m6.hkl, [0.25, 0.25, 4])
m7 = Miller(hkl=m6.hkl, phase=TETRAGONAL_PHASE)
assert np.allclose(m7.round().hkl, [1, 1, 16])
# Example 1.9: Reciprocal lattice parameters
assert np.allclose(lattice_recip.abcABG(), [2, 2, 1, 90, 90, 90])
# Example 1.10, 1.11: Cross product of two directions
m8 = Miller(uvw=[1, 1, 0], phase=TETRAGONAL_PHASE)
m9 = Miller(uvw=[1, 1, 1], phase=TETRAGONAL_PHASE)
m10 = m8.cross(m9)
assert m10.coordinate_format == "hkl"
assert np.allclose(m10.coordinates, [0.25, -0.25, 0])
assert np.allclose(m10.uvw, [1, -1, 0])
assert np.allclose(m10.round().coordinates, [1, -1, 0])
# Example 1.12: Cross product of two reciprocal lattice vectors
m11 = Miller(hkl=[1, 1, 0], phase=TETRAGONAL_PHASE)
m12 = Miller(hkl=[1, 1, 1], phase=TETRAGONAL_PHASE)
m13 = m11.cross(m12)
assert m13.coordinate_format == "uvw"
assert np.allclose(m13.coordinates, [4, -4, 0])
assert np.allclose(m13.hkl, [1, -1, 0])
assert np.allclose(m13.round().coordinates, [1, -1, 0])
# Run tests for all systems: $ pytest -k TestMillerPointGroups
# Run tests for one system: $ pytest -k TestMillerPointGroupsMonoclinic
class TestMillerPointGroups:
hkl = [[0, 0, 1], [0, 1, 1], [1, 1, 1]]
phase = Phase(structure=Structure(lattice=Lattice(1, 1, 1, 90, 90, 90)))
class TestMillerPointGroupsTriclinic(TestMillerPointGroups):
# Triclinic: 1, -1
def test_group_1(self):
self.phase.point_group = "1"
m = Miller(hkl=self.hkl, phase=self.phase)
assert np.allclose(m.symmetrise(unique=False).hkl, self.hkl)
m_unique = m.symmetrise(unique=True)
assert np.allclose(m_unique.hkl, self.hkl)
mult = m.multiplicity
assert np.allclose(mult, [1, 1, 1])
assert np.sum(mult) == m_unique.size
def test_group_bar1(self):
self.phase.point_group = "-1"
m = Miller(hkl=self.hkl, phase=self.phase)
# fmt: off
assert np.allclose(
m.symmetrise(unique=False).hkl,
[
[ 0, 0, 1],
[ 0, 0, -1],
[ 0, 1, 1],
[ 0, -1, -1],
[ 1, 1, 1],
[-1, -1, -1],
],
)
m_unique = m.symmetrise(unique=True)
assert np.allclose(
m_unique.hkl,
[
[ 0, 0, 1],
[ 0, 0, -1],
[ 0, 1, 1],
[ 0, -1, -1],
[ 1, 1, 1],
[-1, -1, -1],
],
)
# fmt: on
mult = m.multiplicity
assert np.allclose(mult, [2, 2, 2])
assert np.sum(mult) == m_unique.size
class TestMillerPointGroupsMonoclinic(TestMillerPointGroups):
# Monoclinic: 2 (121), m (1m1), 2/m
def test_group_121(self):
self.phase.point_group = "121"
m = Miller(hkl=self.hkl, phase=self.phase)
# fmt: off
assert np.allclose(
m.symmetrise(unique=False).hkl,
[
[ 0, 0, 1],
[ 0, 0, -1],
[ 0, 1, 1],
[ 0, 1, -1],
[ 1, 1, 1],
[-1, 1, -1],
],
)
m_unique = m.symmetrise(unique=True)
assert np.allclose(
m_unique.hkl,
[
[ 0, 0, 1],
[ 0, 0, -1],
[ 0, 1, 1],
[ 0, 1, -1],
[ 1, 1, 1],
[-1, 1, -1],
],
)
# fmt: on
mult = m.multiplicity
assert np.allclose(mult, [2, 2, 2])
assert np.sum(mult) == m_unique.size
def test_group_1m1(self):
self.phase.point_group = "1m1"
m = Miller(hkl=self.hkl, phase=self.phase)
# fmt: off
assert np.allclose(
m.symmetrise(unique=False).hkl,
[
[ 0, 0, 1],
[ 0, 0, 1],
[ 0, 1, 1],
[ 0, -1, 1],
[ 1, 1, 1],
[ 1, -1, 1],
],
)
m_unique = m.symmetrise(unique=True)
assert np.allclose(
m_unique.hkl,
[
[ 0, 0, 1],
[ 0, 1, 1],
[ 0, -1, 1],
[ 1, 1, 1],
[ 1, -1, 1],
],
)
# fmt: on
mult = m.multiplicity
assert np.allclose(mult, [1, 2, 2])
assert np.sum(mult) == m_unique.size
def test_group_2overm(self):
self.phase.point_group = "2/m"
m = Miller(hkl=self.hkl, phase=self.phase)
# fmt: off
assert np.allclose(
m.symmetrise(unique=False).hkl,
[
[ 0, 0, 1],
[ 0, 0, 1],
[ 0, 0, -1],
[ 0, 0, -1],
[ 0, 1, 1],
[ 0, -1, 1],
[ 0, 1, -1],
[ 0, -1, -1],
[ 1, 1, 1],
[-1, -1, 1],
[ 1, 1, -1],
[-1, -1, -1],
],
)
m_unique = m.symmetrise(unique=True)
assert np.allclose(
m_unique.hkl,
[
[ 0, 0, 1],
[ 0, 0, -1],
[ 0, 1, 1],
[ 0, -1, 1],
[ 0, 1, -1],
[ 0, -1, -1],
[ 1, 1, 1],
[-1, -1, 1],
[ 1, 1, -1],
[-1, -1, -1],
],
)
# fmt: on
mult = m.multiplicity
assert np.allclose(mult, [2, 4, 4])
assert np.sum(mult) == m_unique.size
class TestMillerPointGroupsOrthorhombic(TestMillerPointGroups):
# Orthorhombic: 222, mm2, 2/m 2/m 2/m (mmm)
def test_group_222(self):
self.phase.point_group = "222"
m = Miller(hkl=self.hkl, phase=self.phase)
# fmt: off
assert np.allclose(
m.symmetrise(unique=False).hkl,
[
[ 0, 0, 1],
[ 0, 0, 1],
[ 0, 0, -1],
[ 0, 0, -1],
[ 0, 1, 1],
[ 0, -1, 1],
[ 0, -1, -1],
[ 0, 1, -1],
[ 1, 1, 1],
[-1, -1, 1],
[ 1, -1, -1],
[-1, 1, -1],
],
)
m_unique = m.symmetrise(unique=True)
assert np.allclose(
m_unique.hkl,
[
[ 0, 0, 1],
[ 0, 0, -1],
[ 0, 1, 1],
[ 0, -1, 1],
[ 0, -1, -1],
[ 0, 1, -1],
[ 1, 1, 1],
[-1, -1, 1],
[ 1, -1, -1],
[-1, 1, -1],
],
)
# fmt: on
mult = m.multiplicity
assert np.allclose(mult, [2, 4, 4])
assert np.sum(mult) == m_unique.size
def test_group_mm2(self):
self.phase.point_group = "mm2"
m = Miller(hkl=self.hkl, phase=self.phase)
# fmt: off
assert np.allclose(
m.symmetrise(unique=False).hkl,
[
[ 0, 0, 1],
[ 0, 0, -1],
[ 0, 0, -1],
[ 0, 0, 1],
[ 0, 1, 1],
[ 0, -1, -1],
[ 0, 1, -1],
[ 0, -1, 1],
[ 1, 1, 1],
[ 1, -1, -1],
[ 1, 1, -1],
[ 1, -1, 1],
],
)
m_unique = m.symmetrise(unique=True)
assert np.allclose(
m_unique.hkl,
[
[ 0, 0, 1],
[ 0, 0, -1],
[ 0, 1, 1],
[ 0, -1, -1],
[ 0, 1, -1],
[ 0, -1, 1],
[ 1, 1, 1],
[ 1, -1, -1],
[ 1, 1, -1],
[ 1, -1, 1],
],
)
# fmt: on
mult = m.multiplicity
assert np.allclose(mult, [2, 4, 4])
assert np.sum(mult) == m_unique.size
def test_group_2overm_2overm_2overm(self):
self.phase.point_group = "mmm"
m = Miller(hkl=self.hkl, phase=self.phase)
# fmt: off
assert np.allclose(
m.symmetrise(unique=False).hkl,
[
[ 0, 0, 1],
[ 0, 0, -1],
[ 0, 0, 1],
[ 0, 0, -1],
[ 0, 0, 1],
[ 0, 0, -1],
[ 0, 0, 1],
[ 0, 0, -1],
[ 0, 1, 1],
[ 0, 1, -1],
[ 0, 1, 1],
[ 0, 1, -1],
[ 0, -1, 1],
[ 0, -1, -1],
[ 0, -1, 1],
[ 0, -1, -1],
[ 1, 1, 1],
[ 1, 1, -1],
[-1, 1, 1],
[-1, 1, -1],
[ 1, -1, 1],
[ 1, -1, -1],
[-1, -1, 1],
[-1, -1, -1],
],
)
m_unique = m.symmetrise(unique=True)
assert np.allclose(
m_unique.hkl,
[
[ 0, 0, 1],
[ 0, 0, -1],
[ 0, 1, 1],
[ 0, 1, -1],
[ 0, -1, 1],
[ 0, -1, -1],
[ 1, 1, 1],
[ 1, 1, -1],
[-1, 1, 1],
[-1, 1, -1],
[ 1, -1, 1],
[ 1, -1, -1],
[-1, -1, 1],
[-1, -1, -1],
],
)
# fmt: on
mult = m.multiplicity
assert np.allclose(mult, [2, 4, 8])
assert np.sum(mult) == m_unique.size
class TestMillerPointGroupsTetragonal(TestMillerPointGroups):
# Tetragonal: 4, -4, 4/m, 422, 4mm, -42m, 4/m 2/m 2/m
def test_group_4(self):
self.phase.point_group = "4"
m = Miller(hkl=self.hkl, phase=self.phase)
# fmt: off
assert np.allclose(
m.symmetrise(unique=False).hkl,
[
[ 0, 0, 1],
[ 0, 0, 1],
[ 0, 0, 1],
[ 0, 0, 1],
[ 0, 1, 1],
[-1, 0, 1],
[ 0, -1, 1],
[ 1, 0, 1],
[ 1, 1, 1],
[-1, 1, 1],
[-1, -1, 1],
[ 1, -1, 1],
],
)
m_unique = m.symmetrise(unique=True)
assert np.allclose(
m_unique.hkl,
[
[ 0, 0, 1],
[ 0, 1, 1],
[-1, 0, 1],
[ 0, -1, 1],
[ 1, 0, 1],
[ 1, 1, 1],
[-1, 1, 1],
[-1, -1, 1],
[ 1, -1, 1],
],
)
# fmt: on
mult = m.multiplicity
assert np.allclose(mult, [1, 4, 4])
assert np.sum(mult) == m_unique.size
def test_group_bar4(self):
self.phase.point_group = "-4"
m = Miller(hkl=self.hkl, phase=self.phase)
# fmt: off
assert np.allclose(
m.symmetrise(unique=False).hkl,
[
[ 0, 0, 1],
[ 0, 0, -1],
[ 0, 0, 1],
[ 0, 0, -1],
[ 0, 1, 1],
[ 1, 0, -1],
[ 0, -1, 1],
[-1, 0, -1],
[ 1, 1, 1],
[ 1, -1, -1],
[-1, -1, 1],
[-1, 1, -1],
],
)
m_unique = m.symmetrise(unique=True)
assert np.allclose(
m_unique.hkl,
[
[ 0, 0, 1],
[ 0, 0, -1],
[ 0, 1, 1],
[ 1, 0, -1],
[ 0, -1, 1],
[-1, 0, -1],
[ 1, 1, 1],
[ 1, -1, -1],
[-1, -1, 1],
[-1, 1, -1],
],
)
# fmt: on
mult = m.multiplicity
assert np.allclose(mult, [2, 4, 4])
assert np.sum(mult) == m_unique.size
def test_group_4overm(self):
self.phase.point_group = "4/m"
m = Miller(hkl=self.hkl, phase=self.phase)
# fmt: off
assert np.allclose(
m.symmetrise(unique=False).hkl,
[
[ 0, 0, 1],
[ 0, 0, 1],
[ 0, 0, 1],
[ 0, 0, 1],
[ 0, 0, -1],
[ 0, 0, -1],
[ 0, 0, -1],
[ 0, 0, -1],
[ 0, 1, 1],
[-1, 0, 1],
[ 0, -1, 1],
[ 1, 0, 1],
[ 0, 1, -1],
[-1, 0, -1],
[ 0, -1, -1],
[ 1, 0, -1],
[ 1, 1, 1],
[-1, 1, 1],
[-1, -1, 1],
[ 1, -1, 1],
[ 1, 1, -1],
[-1, 1, -1],
[-1, -1, -1],
[ 1, -1, -1],
],
)
m_unique = m.symmetrise(unique=True)
assert np.allclose(
m_unique.hkl,
[
[ 0, 0, 1],
[ 0, 0, -1],
[ 0, 1, 1],
[-1, 0, 1],
[ 0, -1, 1],
[ 1, 0, 1],
[ 0, 1, -1],
[-1, 0, -1],
[ 0, -1, -1],
[ 1, 0, -1],
[ 1, 1, 1],
[-1, 1, 1],
[-1, -1, 1],
[ 1, -1, 1],
[ 1, 1, -1],
[-1, 1, -1],
[-1, -1, -1],
[ 1, -1, -1],
],
)
# fmt: on
mult = m.multiplicity
assert np.allclose(mult, [2, 8, 8])
assert np.sum(mult) == m_unique.size
def test_group_422(self):
self.phase.point_group = "422"
m = Miller(hkl=self.hkl, phase=self.phase)
# fmt: off
assert np.allclose(
m.symmetrise(unique=False).hkl,
[
[ 0, 0, 1],
[ 0, 0, 1],
[ 0, 0, 1],
[ 0, 0, 1],
[ 0, 0, -1],
[ 0, 0, -1],
[ 0, 0, -1],
[ 0, 0, -1],
[ 0, 1, 1],
[-1, 0, 1],
[ 0, -1, 1],
[ 1, 0, 1],
[ 0, -1, -1],
[ 1, 0, -1],
[ 0, 1, -1],
[-1, 0, -1],
[ 1, 1, 1],
[-1, 1, 1],
[-1, -1, 1],
[ 1, -1, 1],
[ 1, -1, -1],
[ 1, 1, -1],
[-1, 1, -1],
[-1, -1, -1],
],
)
m_unique = m.symmetrise(unique=True)
assert np.allclose(
m_unique.hkl,
[
[ 0, 0, 1],
[ 0, 0, -1],
[ 0, 1, 1],
[-1, 0, 1],
[ 0, -1, 1],
[ 1, 0, 1],
[ 0, -1, -1],
[ 1, 0, -1],
[ 0, 1, -1],
[-1, 0, -1],
[ 1, 1, 1],
[-1, 1, 1],
[-1, -1, 1],
[ 1, -1, 1],
[ 1, -1, -1],
[ 1, 1, -1],
[-1, 1, -1],
[-1, -1, -1],
],
)
# fmt: on
mult = m.multiplicity
assert | np.allclose(mult, [2, 8, 8]) | numpy.allclose |
from IPython.core.display import display, HTML
import matplotlib.image as mpimg
import matplotlib.pyplot as plt
import numpy as np
import pickle
import cv2
import glob
import time
import os
from feature_extraction import extractFeatures, configParams, extract_hog_features, extract_color_features
def search_windows(img, windows, classifier, X_scaler):
hog_feat = configParams['use_hog_feat']
spatial_feat = configParams['use_spatial_feat']
hist_feat = configParams['use_hist_feat']
# Create an empty list to receive positive detection windows
on_windows = []
count_window = 0
count_car_window = 0
# Iterate over all windows in the list
for window in windows:
# Extract the test window from original image
window_img = cv2.resize(img[window[0][1]:window[1][1],
window[0][0]:window[1][0]],
(64, 64))
# Extract features for that window
img_features = extractFeatures(window_img, verbose=False,
hog_feat=hog_feat, spatial_feat=spatial_feat, hist_feat=hist_feat)
# Scale extracted features to be fed to classifier
test_features = X_scaler.transform(np.array(img_features).reshape(1, -1))
# Predict using your classifier
prediction = classifier.predict(test_features)
# If positive (prediction == 1) then save the window
count_window += 1
if prediction == 1:
count_car_window += 1
on_windows.append(window)
# Return windows for positive detections
return on_windows
def slide_window(img, x_start_stop=[None, None], y_start_stop=[None, None],
xy_window=(64, 64), xy_overlap=(0.5, 0.5)):
# If x and/or y start/stop positions not defined, set to image size
if x_start_stop[0] == None:
x_start_stop[0] = 0
if x_start_stop[1] == None:
x_start_stop[1] = img.shape[1]
if y_start_stop[0] == None:
y_start_stop[0] = 0
if y_start_stop[1] == None:
y_start_stop[1] = img.shape[0]
# Compute the span of the region to be searched
xspan = x_start_stop[1] - x_start_stop[0]
yspan = y_start_stop[1] - y_start_stop[0]
# Compute the number of pixels per step in x/y
nx_pix_per_step = np.int(xy_window[0]*(1 - xy_overlap[0]))
ny_pix_per_step = np.int(xy_window[1]*(1 - xy_overlap[1]))
# Compute the number of windows in x/y
nx_buffer = np.int(xy_window[0]*(xy_overlap[0]))
ny_buffer = np.int(xy_window[1]*(xy_overlap[1]))
nx_windows = np.int((xspan-nx_buffer)/nx_pix_per_step)
ny_windows = np.int((yspan-ny_buffer)/ny_pix_per_step)
# Initialize a list to append window positions to
window_list = []
# Loop through finding x and y window positions
# Note: you could vectorize this step, but in practice
# you'll be considering windows one by one with your
# classifier, so looping makes sense
for ys in range(ny_windows):
for xs in range(nx_windows):
# Calculate window position
startx = xs*nx_pix_per_step + x_start_stop[0]
endx = startx + xy_window[0]
starty = ys*ny_pix_per_step + y_start_stop[0]
endy = starty + xy_window[1]
# Append window position to list
window_list.append(((startx, starty), (endx, endy)))
# Return the list of windows
return window_list
# Define a function to draw bounding boxes
def draw_boxes(img, bboxes, color=(0, 0, 255), thick=6):
imcopy = np.copy(img)
for bbox in bboxes:
# Draw a rectangle
cv2.rectangle(imcopy, (bbox[0][0], bbox[0][1]), (bbox[1][0], bbox[1][1]),
color, thick)
return imcopy
def findCars(img, y_start_stop, svc, X_scaler, scale=1):
hog_feat = configParams['use_hog_feat']
spatial_feat = configParams['use_spatial_feat']
hist_feat = configParams['use_hist_feat']
car_windows = []
all_windows = []
draw_img = np.copy(img)
img_cropped = img[y_start_stop[0]:y_start_stop[1], :, :]
if scale != 1:
imshape = img_cropped.shape
img_cropped = cv2.resize(img_cropped,
(np.int(imshape[1]/scale), np.int(imshape[0]/scale)))
ch1 = img_cropped[:,:,0]
ch2 = img_cropped[:,:,1]
ch3 = img_cropped[:,:,2]
orient = configParams['hog_n_orientations']
pix_per_cell = configParams['hog_pixels_per_cell']
cells_per_block = configParams['hog_cells_per_block']
# Define blocks and steps as above
nxblocks = (ch1.shape[1] // pix_per_cell) - cells_per_block + 1
nyblocks = (ch1.shape[0] // pix_per_cell) - cells_per_block + 1
nfeat_per_block = orient * cells_per_block**2
# 64 was the orginal sampling rate, with 8 cells and 8 pix per cell
window = 64
nblocks_per_window = (window // pix_per_cell) - cells_per_block + 1
cells_per_step = 2 # Instead of overlap, define how many cells to step
nxsteps = (nxblocks - nblocks_per_window) // cells_per_step
nysteps = (nyblocks - nblocks_per_window) // cells_per_step
# Compute HOG features for the entire image
hogg, _ = extract_hog_features(img_cropped, hog_feat=hog_feat, visualize=False)
# sprint ("hogg.shape = {}".format(hogg.shape))
hog1 = hogg[0]
hog2 = hogg[1]
hog3 = hogg[2]
count_window = 0
count_car_window = 0
for xb in range(nxsteps):
for yb in range(nysteps):
ypos = yb*cells_per_step
xpos = xb*cells_per_step
# Extract HOG for this patch
hog_feat1 = hog1[ypos:ypos+nblocks_per_window, xpos:xpos+nblocks_per_window].ravel()
hog_feat2 = hog2[ypos:ypos+nblocks_per_window, xpos:xpos+nblocks_per_window].ravel()
hog_feat3 = hog3[ypos:ypos+nblocks_per_window, xpos:xpos+nblocks_per_window].ravel()
hog_features = np.hstack((hog_feat1, hog_feat2, hog_feat3))
if configParams['use_gray_img'] is True:
hog_features = hogg[ypos:ypos+nblocks_per_window,
xpos:xpos+nblocks_per_window].ravel()
xleft = xpos * pix_per_cell
ytop = ypos * pix_per_cell
# Extract the image patch
subimg = cv2.resize(img_cropped[ytop:ytop+window, xleft:xleft+window], (64,64))
# Get color features
color_features = extract_color_features(subimg, spatial_feat=spatial_feat, hist_feat=hist_feat)
# Combine HOG and color features
img_features = np.hstack((hog_features, color_features))
# Scale features and make a prediction
test_features = X_scaler.transform(img_features.reshape(1, -1))
test_prediction = svc.predict(test_features)
xbox_left = np.int(xleft * scale)
ytop_draw = np.int(ytop * scale)
win_draw = | np.int(window * scale) | numpy.int |
from __future__ import print_function
import numpy as np
import itertools
from numpy.testing import (assert_equal,
assert_almost_equal,
assert_array_equal,
assert_array_almost_equal,
suppress_warnings)
import pytest
from pytest import raises as assert_raises
from pytest import warns as assert_warns
from scipy.spatial import SphericalVoronoi, distance
from scipy.spatial import _spherical_voronoi as spherical_voronoi
from scipy.spatial.transform import Rotation
from scipy.optimize import linear_sum_assignment
TOL = 1E-10
class TestSphericalVoronoi(object):
def setup_method(self):
self.points = np.array([
[-0.78928481, -0.16341094, 0.59188373],
[-0.66839141, 0.73309634, 0.12578818],
[0.32535778, -0.92476944, -0.19734181],
[-0.90177102, -0.03785291, -0.43055335],
[0.71781344, 0.68428936, 0.12842096],
[-0.96064876, 0.23492353, -0.14820556],
[0.73181537, -0.22025898, -0.6449281],
[0.79979205, 0.54555747, 0.25039913]]
)
# Issue #9386
self.hemisphere_points = np.array([
[0.88610999, -0.42383021, 0.18755541],
[0.51980039, -0.72622668, 0.4498915],
[0.56540011, -0.81629197, -0.11827989],
[0.69659682, -0.69972598, 0.15854467]])
# Issue #8859
phi = np.linspace(0, 2 * np.pi, 10, endpoint=False) # azimuth angle
theta = np.linspace(0.001, np.pi * 0.4, 5) # polar angle
theta = theta[np.newaxis, :].T
phiv, thetav = np.meshgrid(phi, theta)
phiv = np.reshape(phiv, (50, 1))
thetav = np.reshape(thetav, (50, 1))
x = np.cos(phiv) * np.sin(thetav)
y = np.sin(phiv) * np.sin(thetav)
z = np.cos(thetav)
self.hemisphere_points2 = np.concatenate([x, y, z], axis=1)
def test_constructor(self):
center = np.array([1, 2, 3])
radius = 2
s1 = SphericalVoronoi(self.points)
# user input checks in SphericalVoronoi now require
# the radius / center to match the generators so adjust
# accordingly here
s2 = SphericalVoronoi(self.points * radius, radius)
s3 = SphericalVoronoi(self.points + center, center=center)
s4 = SphericalVoronoi(self.points * radius + center, radius, center)
assert_array_equal(s1.center, np.array([0, 0, 0]))
assert_equal(s1.radius, 1)
assert_array_equal(s2.center, np.array([0, 0, 0]))
assert_equal(s2.radius, 2)
assert_array_equal(s3.center, center)
assert_equal(s3.radius, 1)
assert_array_equal(s4.center, center)
assert_equal(s4.radius, radius)
def test_vertices_regions_translation_invariance(self):
sv_origin = SphericalVoronoi(self.points)
center = np.array([1, 1, 1])
sv_translated = SphericalVoronoi(self.points + center, center=center)
| assert_equal(sv_origin.regions, sv_translated.regions) | numpy.testing.assert_equal |
import cea
import os
import pandas as pd
import numpy as np
import pickle
from scipy.stats import triang
from scipy.stats import norm
from scipy.stats import uniform
from pyDOE import lhs
from cea.demand import demand_main
from geopandas import GeoDataFrame as Gdf
import cea.inputlocator as inputlocator
from cea.demand.calibration.settings import subset_samples
from keras.layers import Input, Dense
from keras.models import Model
import scipy.io
from keras.models import Sequential
from keras.callbacks import EarlyStopping
from sklearn.preprocessing import MinMaxScaler
import cea.config
__author__ = "<NAME>"
__copyright__ = "Copyright 2017, Architecture and Building Systems - ETH Zurich"
__credits__ = ["<NAME>","<NAME>"]
__license__ = "MIT"
__version__ = "0.1"
__maintainer__ = "<NAME>"
__email__ = "<EMAIL>"
__status__ = "Testing"
all_results=[]
def simulate_demand_sample(locator, building_name, output_parameters):
"""
This script runs the cea demand tool in series and returns a single value of cvrmse and rmse.
:param locator: pointer to location of files in CEA
:param building_name: name of building
:param output_parameters: building load to consider in the anlysis
:return:
"""
# force simulation to be sequential and to only do one building
gv = cea.globalvar.GlobalVariables()
gv.multiprocessing = False
gv.print_totals = False
gv.simulate_building_list = [building_name]
gv.testing = True
#import weather and measured data
weather_path = locator.get_default_weather()
#weather_path = 'C:\CEAforArcGIS\cea\databases\weather\Zurich.epw'
#calculate demand timeseries for buidling an calculate cvrms
demand_main.demand_calculation(locator, weather_path, gv)
output_folder=locator.get_demand_results_folder()
file_path=os.path.join(output_folder, "%(building_name)s.xls" % locals())
#file_path=locator.get_demand_results_file(building_name)
new_calcs = pd.read_excel(file_path)
#cv_rmse, rmse = calc_cv_rmse(time_series_simulation[output_parameters].values, time_series_measured[output_parameters].values)
return new_calcs #cv_rmse, rmse
def latin_sampler(locator, num_samples, variables, region):
"""
This script creates a matrix of m x n samples using the latin hypercube sampler.
for this, it uses the database of probability distribtutions stored in locator.get_uncertainty_db()
:param locator: pointer to locator of files of CEA
:param num_samples: number of samples to do
:param variables: list of variables to sample
:return:
1. design: a matrix m x n with the samples
2. pdf_list: a dataframe with properties of the probability density functions used in the excercise.
"""
# get probability density function PDF of variables of interest
variable_groups = ('ENVELOPE', 'INDOOR_COMFORT', 'INTERNAL_LOADS')
database = pd.concat([pd.read_excel(locator.get_uncertainty_db(region), group, axis=1)
for group in variable_groups])
pdf_list = database[database['name'].isin(variables)].set_index('name')
# get number of variables
num_vars = pdf_list.shape[0] #alternatively use len(variables)
# get design of experiments
design = lhs(num_vars, samples=num_samples)
for i, variable in enumerate(variables):
distribution = pdf_list.loc[variable, 'distribution']
min = pdf_list.loc[variable,'min']
max = pdf_list.loc[variable,'max']
mu = pdf_list.loc[variable,'mu']
stdv = pdf_list.loc[variable,'stdv']
if distribution == 'triangular':
loc = min
scale = max - min
c = (mu - min) / (max - min)
design[:, i] = triang(loc=loc, c=c, scale=scale).ppf(design[:, i])
elif distribution == 'normal':
design[:, i] = norm(loc=mu, scale=stdv).ppf(design[:, i])
else: # assume it is uniform
design[:, i] = uniform(loc=min, scale=max).ppf(design[:, i])
return design, pdf_list
def prep_NN_inputs(NN_input,NN_target,NN_delays):
#NN_input.to_csv('TEMP.csv', index=False, header=False, float_format='%.3f', decimal='.')
#file_path_temp = 'C:\CEAforArcGIS\cea\surrogate\Temp.csv'
#input1 = pd.read_csv(file_path_temp)
input1=NN_input
target1=NN_target
nS, nF = input1.shape
nSS, nT = target1.shape
nD=NN_delays
aD=nD+1
input_matrix_features=np.zeros((nS+nD, aD*nF))
rowsF, colsF=input_matrix_features.shape
input_matrix_targets=np.zeros((nS+nD, aD*nT))
rowsFF, ColsFF = input_matrix_targets.shape
i=1
while i<aD+1:
j=i-1
aS=nS+j
m1=(i*nF)-(nF)
m2=(i*nF)
n1=(i*nT)-(nT)
n2=(i*nT)
input_matrix_features[j:aS, m1:m2]=input1
input_matrix_targets[j:aS, n1:n2]=target1
i=i+1
trimmed_inputn = input_matrix_features[nD:nS,:]
trimmed_inputt = input_matrix_targets[nD:nS, 2:]
NN_input_ready=np.concatenate([trimmed_inputn, trimmed_inputt], axis=1)
NN_target_ready=target1[nD:nS,:]
return NN_input_ready, NN_target_ready
def sampling_main(locator, variables, building_name, building_load, region):
"""
This script creates samples using a lating Hypercube sample of 5 variables of interest.
then runs the demand calculation of CEA for all the samples. It delivers a json file storing
the results of cv_rmse and rmse for each sample.
for more details on the work behind this please check:
<NAME>., <NAME>., <NAME>. Bayesian calibration of Dynamic building Energy Models. Applied Energy 2017.
:param locator: pointer to location of CEA files
:param variables: input variables of CEA to sample. They must be 5!
:param building_name: name of building to calibrate
:param building_load: name of building load to calibrate
:return:
1. a file storing values of cv_rmse and rmse for all samples. the file is sotred in
file(locator.get_calibration_cvrmse_file(building_name)
2 a file storing information about variables, the building_load and the probability distribtuions used in the
excercise. the file is stored in locator.get_calibration_problem(building_name)
:rtype: .json and .pkl
"""
# create list of samples with a LHC sampler and save to disk
samples, pdf_list = latin_sampler(locator, subset_samples, variables, region)
np.save(locator.get_calibration_samples(building_name), samples)
# create problem and save to disk as json
problem = {'variables':variables,
'building_load':building_load, 'probabiltiy_vars':pdf_list}
pickle.dump(problem, file(locator.get_calibration_problem(building_name), 'w'))
nn_X_ht = []
nn_X_cl = []
nn_T_ht = []
nn_T_cl = []
nn_X_ht = np.array(nn_X_ht)
nn_X_cl = np.array(nn_X_cl)
nn_T_ht = np.array(nn_T_ht)
nn_T_cl = np.array(nn_T_cl)
for i in range(subset_samples):
#create list of tubles with variables and sample
sample = zip(variables,samples[i,:])
#create overrides and return pointer to files
apply_sample_parameters(locator, sample)
simulate_demand_sample(locator, building_name, building_load)
# define the inputs
intended_parameters=['people','Eaf','Elf','Qwwf','I_rad','I_sol','T_ext','rh_ext',
'ta_hs_set','ta_cs_set','theta_a','Qhsf', 'Qcsf']
# collect the simulation results
file_path = os.path.join(locator.get_demand_results_folder(), "%(building_name)s.xls" % locals())
calcs_outputs_xls = pd.read_excel(file_path)
temp_file=os.path.join(locator.get_temporary_folder(), "%(building_name)s.csv" % locals())
calcs_outputs_xls.to_csv(temp_file, index=False, header=True, float_format='%.3f', decimal='.')
calcs_trimmed_csv=pd.read_csv(temp_file, usecols=intended_parameters)
calcs_trimmed_csv['I_real'] = calcs_trimmed_csv['I_rad'] + calcs_trimmed_csv['I_sol']
calcs_trimmed_csv['ta_hs_set'].fillna(0, inplace=True)
calcs_trimmed_csv['ta_cs_set'].fillna(50, inplace=True)
NN_input=calcs_trimmed_csv
input_drops = ['I_rad', 'I_sol', 'theta_a', 'Qhsf', 'Qcsf']
NN_input = NN_input.drop(input_drops, 1)
NN_input=np.array(NN_input)
target1=calcs_trimmed_csv['Qhsf']
target2=calcs_trimmed_csv['Qcsf']
target3=calcs_trimmed_csv['theta_a']
NN_target_ht = pd.concat([target1, target3], axis=1)
NN_target_cl = pd.concat([target2, target3], axis=1)
NN_target_ht=np.array(NN_target_ht)
NN_target_cl=np.array(NN_target_cl)
#return NN_input, NN_target_ht, NN_target_cl
NN_delays=1
NN_input_ready_ht, NN_target_ready_ht=prep_NN_inputs(NN_input, NN_target_ht, NN_delays)
NN_input_ready_cl, NN_target_ready_cl = prep_NN_inputs(NN_input, NN_target_cl, NN_delays)
one_array_override=np.array(pd.read_csv(locator.get_building_overrides(),skiprows=1,nrows=1))
one_array_override1=np.delete(one_array_override,0,1)
rows_override, cols_override=one_array_override1.shape
rows_NN_input, cols_NN_input=NN_input_ready_ht.shape
random_variables_matrix=[]
random_variables_matrix=np.array(random_variables_matrix)
vector_of_ones = | np.ones((rows_NN_input, 1)) | numpy.ones |
'''
Below code is borrowed from <NAME>
'''
import torch
import numpy as np
import cv2
from scipy.optimize import linear_sum_assignment
from shapely.geometry import Polygon
from homography import Homography, load_i24_csv
import utils
from utils_data_association import count_overlaps
import numpy.linalg as LA
import matplotlib.pyplot as plt
import utils_vis as vis
import pickle
class MOT_Evaluator():
def __init__(self,gt_path,rec_path,tf_path, camera_name, homography,params = None):
"""
gt_path - string, path to i24 csv file for ground truth tracks
rec_path - string, path to i24 csv for rectified tracks
homography - Homography object containing relevant scene information
params - dict of parameter values to change
"""
self.gtmode = ""
self.recmode = ""
self.match_iou = 0
self.cutoff_frame = 10000
# store homography
self.hg = homography
self.tf_path = tf_path
self.camera_name = camera_name
# data is stored as a groupby object. get frame f_idx by "self.gt.get_group(f_idx)"
# load ground truth data
# start with meter
cols_to_convert = ["speed","x","y","width","length","height"]
pts = ["fbr_x","fbr_y","fbl_x","fbl_y","bbr_x","bbr_y","bbl_x","bbl_y"]
self.gt = utils.read_data(gt_path)
if np.mean(self.gt.y.values) > 40:
self.gt[cols_to_convert] = self.gt[cols_to_convert] / 3.281
if "bbr_x" not in self.gt or np.mean(self.gt.bbr_y.values) > 40 or "Manual" in self.gt["Generation method"].unique():
self.gt = utils.img_to_road(self.gt, tf_path, camera_name)
# calculate GT velocities TODO:assume freeflow constant velocity
# self.gt = utils.calc_dynamics(self.gt) # finite difference
self.gt = self.gt.groupby("ID").apply(self.estimate_speed).reset_index(drop=True)
# load rec data
self.rec = utils.read_data(rec_path)
if "veh rear x" in self.rec:
self.rec = self.rec.rename(columns={"veh rear x": "x", "veh center y":"y", "Object ID": "ID"})
if np.mean(self.rec.y.values) > 40:
self.rec[cols_to_convert] = self.rec[cols_to_convert] / 3.281
if "bbr_x" not in self.rec or np.mean(self.rec.bbr_y.values) > 40:
self.rec = utils.img_to_road(self.rec, tf_path, camera_name)
if params is not None:
if "match_iou" in params.keys():
self.match_iou = params["match_iou"]
if "cutoff_frame" in params.keys():
self.cutoff_frame = params["cutoff_frame"]
if "sequence" in params.keys():
self.sequence = params["sequence"]
if "gtmode" in params.keys():
self.gtmode = params["gtmode"]
if "recmode" in params.keys():
self.recmode = params["recmode"]
if "score_threshold" in params.keys():
self.score_threshold = params["score_threshold"]
if self.recmode != "rec":
self.rec = self.rec.groupby("ID").apply(utils.calc_dynamics_car).reset_index(drop=True)
# select under cut-off frames
if self.cutoff_frame:
self.gt = self.gt[self.gt["Frame #"]<=self.cutoff_frame]
self.rec = self.rec[self.rec["Frame #"]<=self.cutoff_frame]
# create dict for storing metrics
n_classes = len(self.hg.class_heights.keys())
class_confusion_matrix = np.zeros([n_classes,n_classes])
self.m = {
"FP":0,
"FP edge-case":0,
"FP @ 0.2":0,
"FN @ 0.2":0,
"FN":0,
"TP":0,
"pre_thresh_IOU":[],
"match_IOU":[],
"state_err":[],
"im_bot_err":[],
"im_top_err":[],
"cls":class_confusion_matrix,
"ids":{}, # key: gt_id, value: matched rec_id
"ids_rec":{}, # key: rec_id, value: matched gt_id
"gt_ids":[],
"rec_ids":[],
"Changed ID pair":[],
"trajectory_score": {}, # key: gt_id, value: score of the matched rec_id
"ids > score":[],
"overlap_gt": 0,
"overlap_rec": 0,
"space_gap_gt":[],
"space_gap_rec":[],
"overlap_rec_ids": set()
}
units = {}
units["Match IOU"] = ""
units["Pre-threshold IOU"] = ""
units["Trajectory score"] = ""
units["Spacing before"] = ""
units["Spacing after"] = ""
units["Width precision"] = "ft"
units["Height precision"] = "ft"
units["Length precision"] = "ft"
units["Velocity precision"] = "ft/s"
units["X precision"] = "ft"
units["Y precision"] = "ft"
units["df"] = "m"
self.units = units
if self.sequence is not None:
self.cap = cv2.VideoCapture(self.sequence)
def estimate_speed(self, car):
temp = car[~car["bbr_x"].isna()]
if len(temp)<2:
return None
v_bbr = (max(temp.bbr_x.values)-min(temp.bbr_x.values))/(max(temp.Timestamp.values)-min(temp.Timestamp.values))
v_fbr = (max(temp.fbr_x.values)-min(temp.fbr_x.values))/(max(temp.Timestamp.values)-min(temp.Timestamp.values))
avgv = (v_bbr+v_fbr)/2
car["speed"] = avgv if avgv<50 else np.nan
return car
def iou(self,a,b):
"""
Description
-----------
Calculates intersection over union for all sets of boxes in a and b
Parameters
----------
a : tensor of size [8,3]
bounding boxes in relative coords
b : array of size [8,3]
bounding boxes in relative coords
Returns
-------
iou - float between [0,1] if a, b are valid boxes, -1 otherwise
average iou for a and b
"""
# if has invalid measurements
if torch.isnan(a).any() or torch.isnan(b).any():
return 0
# ignore the top
area_a = (a[2]-a[0]) * (a[3]-a[1])
area_b = (b[2]-b[0]) * (b[3]-b[1])
minx = max(a[0], b[0])
maxx = min(a[2], b[2])
miny = max(a[1], b[1])
maxy = min(a[3], b[3])
intersection = max(0, maxx-minx) * max(0,maxy-miny)
union = area_a + area_b - intersection + 1e-06
iou = intersection/union
return iou
def score_trajectory(self):
'''
compute euclidean distance between GT trajectories and rec trajectories
'''
# convert back to meter
if self.units["df"] == "ft":
cols_to_convert = ["fbr_x", "fbr_y","fbl_x" ,"fbl_y","bbr_x","bbr_y","bbl_x","bbl_y", "speed","x","y","width","length","height"]
self.rec[cols_to_convert] = self.rec[cols_to_convert] / 3.281
self.gt[cols_to_convert] = self.gt[cols_to_convert] / 3.281
self.units["df"] = "m"
gt_groups = self.gt.groupby('ID')
rec_groups = self.rec.groupby('ID')
if self.metrics['Matched IDs rec']:
for rec_id in self.metrics['Matched IDs rec']:
gt_id = self.metrics['Matched IDs rec'][rec_id][0]
gt_car = gt_groups.get_group(gt_id)
rec_car = rec_groups.get_group(rec_id)
start = max(gt_car['Frame #'].iloc[0],rec_car['Frame #'].iloc[0])
end = min(gt_car['Frame #'].iloc[-1],rec_car['Frame #'].iloc[-1])
gt_car = gt_car.loc[(gt_car['Frame #'] >= start) & (gt_car['Frame #'] <= end)]
rec_car = rec_car.loc[(rec_car['Frame #'] >= start) & (rec_car['Frame #'] <= end)]
Y1 = np.array(gt_car[['bbr_x','bbr_y', 'fbr_x','fbr_y','fbl_x','fbl_y','bbl_x', 'bbl_y']])
Yre = np.array(rec_car[['bbr_x','bbr_y', 'fbr_x','fbr_y','fbl_x','fbl_y','bbl_x', 'bbl_y']])
try:
diff = Y1-Yre
score = np.nanmean(LA.norm(diff,axis=1))
if score > self.score_threshold:
self.m["ids > score"].append(rec_id)
self.m["trajectory_score"][rec_id] = score
except ValueError:
print("Encounter unmatched dimension when computing trajectory score")
else:
print('Run evaluate first.')
scores = list(self.m["trajectory_score"].values())
scores = [x for x in scores if np.isnan(x) == False]
scores_mean_std = np.nanmean(scores),np.nanstd(scores)
metrics = {}
metrics["Trajectory score"] = scores_mean_std
metrics["IDs > score threshold"] = self.m["ids > score"]
if hasattr(self, "metrics"):
self.metrics = dict(list(self.metrics.items()) + list(metrics.items()))
else:
self.metrics = metrics
return
def iou_ts(self,a,b):
"""
Description
-----------
Calculates intersection over union for track a and b in time-space diagram
Parameters
----------
a : 1x8
b : 1x8
Returns
-------
iou - float between [0,1]
"""
a,b = np.reshape(a,(1,-1)), np.reshape(b,(1,-1))
p = Polygon([(a[0,2*i],a[0,2*i+1]) for i in range(4)])
q = Polygon([(b[0,2*i],b[0,2*i+1]) for i in range(4)])
intersection_area = p.intersection(q).area
union_area = min(p.area, q.area)
iou = float(intersection_area/union_area)
return iou
def get_invalid(self, df):
'''
valid: length covers more than 50% of the FOV
invalid: length covers less than 10% of FOV, or
crashes with any valid tracks
undetermined: tracks that are short but not overlaps with any valid tracks
'''
# convert units
if np.mean(df.y.values) > 40:
cols_to_convert = ["fbr_x", "fbr_y","fbl_x" ,"fbl_y","bbr_x","bbr_y","bbl_x","bbl_y", "speed","x","y","width","length","height"]
df[cols_to_convert] = df[cols_to_convert] / 3.281
xmin, xmax = min(df["x"].values),max(df["x"].values)
groups = df.groupby("ID")
groupList = list(groups.groups)
pts = ['bbr_x','bbr_y','fbr_x','fbr_y','fbl_x','fbl_y','bbl_x', 'bbl_y']
valid = {}
invalid = set()
for carid, group in groups:
if (max(group.x.values)-min(group.x.values)>0.4*(xmax-xmin)): # long tracks
frames = group["Frame #"].values
first = group.head(1)
last = group.tail(1)
x0, x1 = max(first.bbr_x.values[0],first.fbr_x.values[0]),min(first.bbr_x.values[0],first.fbr_x.values[0])
x2, x3 = min(last.bbr_x.values[0],last.fbr_x.values[0]),max(last.bbr_x.values[0],last.fbr_x.values[0])
y0, y1 = max(first.bbr_y.values[0],first.bbl_y.values[0]),min(first.bbr_y.values[0],first.bbl_y.values[0])
y2, y3 = min(last.bbr_y.values[0],last.bbl_y.values[0]),max(last.bbr_y.values[0],last.bbl_y.values[0])
t0,t1 = min(frames), max(frames)
valid[carid] = [np.array([t0,x0,t0,x1,t1,x2,t1,x3]),np.array([t0,y0,t0,y1,t1,y2,t1,y3])]
# check crash within valid
valid_list = list(valid.keys())
for i,car1 in enumerate(valid_list):
bx,by = valid[car1]
for car2 in valid_list[i+1:]:
ax,ay = valid[car2]
ioux = self.iou_ts(ax,bx)
iouy = self.iou_ts(ay,by)
if ioux > 0 and iouy > 0: # trajectory overlaps with a valid track
if bx[4]-bx[0] > ax[4]-ax[0]: # keep the longer track
invalid.add(car2)
else:
invalid.add(car1)
valid = set(valid.keys())
valid = valid-invalid
print("Valid tracklets: {}/{}".format(len(valid),len(groupList)))
return valid
def evaluate_tracks(self):
'''
Compute:
# valid and invalid tracks
- valid if x covers the range of camera FOV
- invalid if otherwise or the ratio of missing data is > threshold
# collisions
** IN SPACE **
Returns
-------
None.
'''
valid = self.get_invalid(self.rec)
groups = self.rec.groupby("ID")
self.metrics["Valid tracklets/total"] = "{} / {}".format(len(valid),groups.ngroups)
# invalid_gt, valid_gt, invalid_rec, valid_rec = [],[],[],[]
# xmin, xmax, _, _ = utils.get_camera_range(self.gt['camera'].dropna().unique())
# xrange = xmax-xmin
# alpha = 0.5
# xmin, xmax = xmin + alpha*xrange, xmax-alpha*xrange # buffered 1-2*alpha%
# # invalid if tracks don't cover xmin to xmax, or tracks has < 5 valid measurements
# print("Evaluating tracks...")
# gt_groups = self.gt.groupby("ID")
# for gt_id, gt in gt_groups:
# x_df = gt[["bbr_x","bbl_x","fbr_x","fbl_x"]]
# xleft = x_df.min().min()
# xright = x_df.max().max()
# # missing_rate = x_df[["bbr_x"]].isna().sum().values[0]/len(x_df)
# valid_meas = gt.count().bbr_x
# if xleft > xmin or xright < xmax or valid_meas < 5:
# invalid_gt.append(gt_id)
# else:
# valid_gt.append(gt_id)
# # do the same for rec
# rec_groups = self.rec.groupby("ID")
# for rec_id, rec in rec_groups:
# x_df = rec[["bbr_x","bbl_x","fbr_x","fbl_x"]]
# xleft = x_df.min().min()
# xright = x_df.max().max()
# valid_meas = rec.count().bbr_x
# if xleft > xmin or xright < xmax or valid_meas < 5:
# invalid_rec.append(rec_id)
# else:
# valid_rec.append(rec_id)
# summarize
# metrics = {}
# metrics["# Invalid IDs/total (before)"] = "{} / {}".format(len(invalid_gt),gt_groups.ngroups)
# metrics["# Invalid IDs/total (after)"] = "{} / {}".format(len(invalid_rec),rec_groups.ngroups)
# metrics["Invalid rec IDs"] = invalid_rec
# # metrics["Occurances of collision in rec"] = len(overlaps_rec)
# if hasattr(self, "metrics"):
# self.metrics = dict(list(self.metrics.items()) + list(metrics.items()))
# else:
# self.metrics = metrics
# plot some invalid tracks
# for rec_id in invalid_rec[:5]:
# car = rec_groups.get_group(rec_id)
# vis.plot_track_df(car, title=str(rec_id))
return
def evaluate(self):
# TODO: convert gt and rec unit from m to ft
cols_to_convert = ["fbr_x", "fbr_y","fbl_x","fbl_y","bbr_x","bbr_y","bbl_x","bbl_y", "speed","x","y","width","length","height"]
if "height" not in self.gt:
self.gt["height"] = 0
if "height" not in self.rec:
self.rec["height"] = 0
if self.units["df"] == "m":
self.gt[cols_to_convert] = self.gt[cols_to_convert] * 3.281
self.rec[cols_to_convert] = self.rec[cols_to_convert] * 3.281
self.units["df"] = "ft"
# for each frame:
gt_frames = self.gt.groupby('Frame #')
rec_frames = self.rec.groupby('Frame #')
for f_idx in range(self.cutoff_frame):
print("\rAggregating metrics for frame {}/{}".format(f_idx,self.cutoff_frame),end = "\r",flush = True)
if self.sequence:
_,im = self.cap.read()
try:
gt = gt_frames.get_group(f_idx)
except KeyError:
if f_idx in rec_frames.groups.keys():
frame = rec_frames.get_group(f_idx)
self.m["FP"] += len(frame)
ids = frame['ID'].values
for id in ids:
if id not in self.m["rec_ids"]:
self.m["rec_ids"].append(id)
continue
try:
rec = rec_frames.get_group(f_idx)
except KeyError:
if f_idx in gt_frames.groups.keys():
frame = gt_frames.get_group(f_idx)
self.m["FN"] += len(frame)
ids = frame['ID'].values
for id in ids:
if id not in self.m["gt_ids"]:
self.m["gt_ids"].append(id)
continue
# store ground truth as tensors
gt_ids = gt['ID'].values
gt_classes = gt["Object class"].values
if self.gtmode == "gt": # start from image
# TODO: fill nan as 0 for velocity
gt_im = np.array(gt[["fbrx","fbry", "fblx", "fbly", "bbrx", "bbry", "bblx", "bbly", "ftrx", "ftry", "ftlx", "ftly", "btrx", "btry", "btlx", "btly"]])
gt_im = torch.from_numpy(np.stack(gt_im)).reshape(-1,8,2)
# two pass estimate of object heights
heights = self.hg.guess_heights(gt_classes)
gt_state = self.hg.im_to_state(gt_im,heights = heights)
repro_boxes = self.hg.state_to_im(gt_state)
refined_heights = self.hg.height_from_template(repro_boxes,heights,gt_im)
# get other formulations for boxes
gt_state = self.hg.im_to_state(gt_im,heights = refined_heights)
gt_space = self.hg.state_to_space(gt_state)
gt_velocities = gt["speed"].values
gt_velocities = torch.tensor(gt_velocities).float()
gt_state = torch.cat((gt_state,gt_velocities.unsqueeze(1)),dim = 1)
else: # start from space (raw, DA)
gt_space = np.array(gt[['fbr_x','fbr_y', 'fbl_x','fbl_y','bbr_x','bbr_y','bbl_x', 'bbl_y']])
gt_space = torch.from_numpy(np.stack(gt_space)).reshape(-1,4,2)
gt_space = torch.cat((gt_space,gt_space),dim = 1)
d = gt_space.size()[0]
zero_heights = torch.zeros((d,8,1))
gt_space = torch.cat([gt_space,zero_heights],dim=2)
gt_im = self.hg.space_to_im(gt_space)
# store pred as tensors (we start from state)
rec_ids = rec['ID'].values
rec_classes = rec["Object class"].values
if self.recmode == "da":
# rec_space = np.array(rec[['bbr_x','bbr_y', 'fbr_x','fbr_y','fbl_x','fbl_y','bbl_x', 'bbl_y']])
rec_space = np.array(rec[['fbr_x','fbr_y', 'fbl_x','fbl_y','bbr_x','bbr_y','bbl_x', 'bbl_y']])
rec_space = torch.from_numpy(np.stack(rec_space)).reshape(-1,4,2)
rec_space = torch.cat((rec_space,rec_space),dim = 1)
d = rec_space.size()[0]
zero_heights = torch.zeros((d,8,1))
rec_space = torch.cat([rec_space,zero_heights],dim=2)
rec_im = self.hg.space_to_im(rec_space)
heights = self.hg.guess_heights(rec_classes)
rec_state = self.hg.im_to_state(rec_im,heights = heights)
# TODO: estimate speed from space
rec_velocities = rec["speed"].values
rec_velocities = torch.tensor(rec_velocities).float()
rec_state = torch.cat((rec_state,rec_velocities.unsqueeze(1)),dim = 1)
elif self.recmode == "rec": # start from states
rec_state = np.array(rec[["x","y","length","width","height","direction","speed"]])
rec_state = torch.from_numpy(np.stack(rec_state)).reshape(-1,7).float()
rec_space = self.hg.state_to_space(rec_state)
rec_im = self.hg.state_to_im(rec_state)
else: # start from image
rec_im = np.array(rec[["fbrx","fbry","fblx", "fbly", "bbrx", "bbry", "bblx", "bbly", "ftrx", "ftry", "ftlx", "ftly", "btrx", "btry", "btlx", "btly"]])
rec_im = torch.from_numpy(np.stack(rec_im)).reshape(-1,8,2)
# two pass estimate of object heights
heights = self.hg.guess_heights(rec_classes)
rec_state = self.hg.im_to_state(rec_im,heights = heights)
repro_boxes = self.hg.state_to_im(rec_state)
refined_heights = self.hg.height_from_template(repro_boxes,heights,rec_im)
# get other formulations for boxes
rec_state = self.hg.im_to_state(rec_im,heights = refined_heights)
rec_space = self.hg.state_to_space(rec_state)
rec_velocities = rec["speed"].values
rec_velocities = torch.tensor(rec_velocities).float()
rec_state = torch.cat((rec_state,rec_velocities.unsqueeze(1)),dim = 1)
# compute matches based on space location ious
first = gt_space.clone() # xmin,ymin,xmax,ymax
boxes_new = torch.zeros([first.shape[0],4])
boxes_new[:,0] = torch.min(first[:,0:4,0],dim = 1)[0]
boxes_new[:,2] = torch.max(first[:,0:4,0],dim = 1)[0]
boxes_new[:,1] = torch.min(first[:,0:4,1],dim = 1)[0]
boxes_new[:,3] = torch.max(first[:,0:4,1],dim = 1)[0]
first = boxes_new
second = rec_space.clone()
boxes_new = torch.zeros([second.shape[0],4])
boxes_new[:,0] = torch.min(second[:,0:4,0],dim = 1)[0]
boxes_new[:,2] = torch.max(second[:,0:4,0],dim = 1)[0]
boxes_new[:,1] = torch.min(second[:,0:4,1],dim = 1)[0]
boxes_new[:,3] = torch.max(second[:,0:4,1],dim = 1)[0]
second = boxes_new
# find distances between first and second
ious = np.zeros([len(first),len(second)])
for i in range(0,len(first)):
for j in range(0,len(second)):
ious[i,j] = self.iou(first[i],second[j])
# get matches and keep those above threshold
a, b = linear_sum_assignment(ious,maximize = True) # a,b are row,col: matched idx pair of the matrix ious
matches = []
gt_im_matched_idxs = []
rec_im_matched_idxs = []
for i in range(len(a)):
iou = ious[a[i],b[i]]
self.m["pre_thresh_IOU"].append(iou)
if iou >= self.match_iou:
matches.append([a[i],b[i]])
gt_im_matched_idxs.append(a[i])
rec_im_matched_idxs.append(b[i])
self.m["match_IOU"].append(iou)
# find relative distance, overlaps (crashes) and spacing in first and second
d = len(first)
dx,dy = torch.ones((d,d))*(999), torch.ones((d,d))*(-1) # upper triangle matrices
for i in range(0,d):
for j in range(i+1,d):
dx[i][j] = abs(first[i][0]-first[j][0])
dy[i][j] = abs(first[i][1]-first[j][1])
if self.iou(first[i],first[j]) > 0:
self.m["overlap_gt"] += 1
# extract leader and spacing information
dy[dy<0] = float('nan')
for i in range(d):
js = torch.where((dy[i]>=0)&(dy[i]<0.3)) # all potential leaders of i
if len(dx[i][js])> 0:
# j = torch.argmin(dx[i][js]) # immediate leader
self.m["space_gap_gt"].append(min(dx[i][js]))
d = len(second)
dx,dy = torch.ones((d,d))*(999), torch.ones((d,d))*(-1) # upper triangle matrices
for i in range(0,d):
for j in range(i+1,d):
dx[i][j] = abs(second[i][0]-second[j][0])
dy[i][j] = abs(second[i][1]-second[j][1])
if self.iou(second[i],second[j]) > 0:
self.m["overlap_rec"] += 1
self.m["overlap_rec_ids"].add((rec_ids[i],rec_ids[j]))
# extract leader and spacing information
dy[dy<0] = float('nan')
for i in range(d):
js = torch.where((dy[i]>=0)&(dy[i]<0.3)) # all potential leaders of i
if len(dx[i][js])> 0:
# j = torch.argmin(dx[i][js]) # immediate leader
self.m["space_gap_rec"].append(min(dx[i][js]))
# plot
if True and self.sequence:
# gt
unmatched_idxs = []
for i in range(len(gt_im)):
if i not in gt_im_matched_idxs:
unmatched_idxs.append(i)
gt_im_unmatched = gt_im[unmatched_idxs]
# preds
unmatched_idxs = []
for i in range(len(rec_im)):
if i not in rec_im_matched_idxs:
unmatched_idxs.append(i)
rec_im_unmatched = rec_im[unmatched_idxs]
rec_im_matched = rec_im[rec_im_matched_idxs]
gt_im_matched = gt_im[gt_im_matched_idxs]
self.hg.plot_boxes(im,rec_im_matched, color = (255,0,0)) # blue
self.hg.plot_boxes(im,gt_im_matched,color = (0,255,0)) # green
self.hg.plot_boxes(im, gt_im_unmatched,color = (0,0,255),thickness =2) # red, FN
self.hg.plot_boxes(im, rec_im_unmatched,color = (0,100,255),thickness =2) # orange, FP
cv2.imshow("frame",im)
key = cv2.waitKey(1)
if key == ord("p"):
cv2.waitKey(0)
if key == ord("q"):
self.cap.release()
cv2.destroyAllWindows()
return
# store the ID associated with each ground truth object
for match in matches:
gt_id = gt_ids[match[0]]
rec_id = rec_ids[match[1]]
if gt_id != rec_id and (gt_id, rec_id) not in self.m['Changed ID pair']:
self.m['Changed ID pair'].append((gt_id, rec_id))
try:
if rec_id != self.m["ids"][gt_id][-1]:
self.m["ids"][gt_id].append(rec_id)
except KeyError:
self.m["ids"][gt_id] = [rec_id]
try:
if gt_id != self.m["ids_rec"][rec_id][-1]:
self.m["ids_rec"][rec_id].append(gt_id)
except KeyError:
self.m["ids_rec"][rec_id] = [gt_id]
if rec_id not in self.m["rec_ids"]:
self.m["rec_ids"].append(rec_id)
if gt_id not in self.m["gt_ids"]:
self.m["gt_ids"].append(gt_id)
# of the pred objects not in b, dont count as FP those that fall outside of frame
for i in range(len(rec_ids)):
if i not in b: # no match
obj = rec_im[i]
if obj[0,0] < 0 or obj[2,0] < 0 or obj[0,0] > 1920 or obj[2,0] > 1920:
self.m["FP edge-case"] += 1
continue
if obj[0,1] < 0 or obj[2,1] < 0 or obj[0,1] > 1080 or obj[2,1] > 1080:
self.m["FP edge-case"] += 1
self.m["TP"] += len(matches)
invalid_rec = torch.sum(torch.sum(torch.isnan(rec_space), dim=1),dim=1)>0
invalid_gt = torch.sum(torch.sum(torch.isnan(gt_space), dim=1),dim=1)>0
self.m["FP"] += max(0,(len(rec_space)-sum(invalid_rec) - len(matches)))
self.m["FN"] += max(0,(len(gt_space)-sum(invalid_gt) - len(matches)))
# self.m["FP @ 0.2"] += max(0,len(rec_space)-sum(invalid_rec) - len(a))
# self.m["FN @ 0.2"] += max(0,len(gt_space)-sum(invalid_gt) - len(a))
# if self.recmode == "state":
for match in matches:
# for each match, store error in L,W,H,x,y,velocity
state_err = torch.clamp(torch.abs(rec_state[match[1]] - gt_state[match[0]]),0,500)
self.m["state_err"].append(state_err)
# for each match, store absolute 3D bbox pixel error for top and bottom
bot_err = torch.clamp(torch.mean(torch.sqrt(torch.sum(torch.pow(rec_im[match[1],0:4,:] - gt_im[match[0],0:4,:],2),dim = 1))),0,500)
top_err = torch.clamp(torch.mean(torch.sqrt(torch.sum(torch.pow(rec_im[match[1],4:8,:] - gt_im[match[0],4:8,:],2),dim = 1))),0,500)
self.m["im_bot_err"].append(bot_err)
self.m["im_top_err"].append(top_err)
if self.sequence:
self.cap.release()
cv2.destroyAllWindows()
# at the end:
metrics = {}
metrics["TP"] = self.m["TP"]
metrics["FP"] = self.m["FP"]
metrics["FN"] = self.m["FN"]
# metrics["FP @ 0.2"] = self.m["FP @ 0.2"]
# metrics["FN @ 0.2"] = self.m["FN @ 0.2"]
# metrics["iou_threshold"] = self.match_iou
metrics["True unique objects"] = len(self.m["gt_ids"])
metrics["recicted unique objects"] = len(self.m["rec_ids"])
metrics["FP edge-case"] = self.m["FP edge-case"]
# Compute detection recall, detection precision, detection False alarm rate
metrics["Recall"] = self.m["TP"]/(self.m["TP"]+self.m["FN"])
metrics["Precision"] = self.m["TP"]/(self.m["TP"]+self.m["FP"])
metrics["False Alarm Rate"] = self.m["FP"]/self.m["TP"]
# Compute fragmentations - # of IDs assocated with each GT
metrics["Fragmentations"] = sum([len(self.m["ids"][key])-1 for key in self.m["ids"]])
metrics["Fragments"] = [self.m["ids"][key] for key in self.m["ids"] if len(self.m["ids"][key])>1]
metrics["Matched IDs"] = self.m["ids"]
metrics["Matched IDs rec"] = self.m["ids_rec"]
# Count ID switches - any time a rec ID appears in two GT object sets
count = 0
switched_ids = []
for rec_id in self.m["rec_ids"]:
rec_id_count = 0
for gt_id in self.m["ids"]:
if rec_id in self.m["ids"][gt_id]:
rec_id_count += 1
if rec_id_count > 1:
switched_ids.append(rec_id)
count += (rec_id_count -1) # penalize for more than one gt being matched to the same rec_id
metrics["ID switches"] = (count, switched_ids)
# metrics["Changed ID pair"] = self.m["Changed ID pair"]
# Compute MOTA
metrics["MOTA"] = 1 - (self.m["FN"] + metrics["ID switches"][0] + self.m["FP"] + metrics["Fragmentations"])/(self.m["TP"])
metrics["MOTA edge-case"] = 1 - (self.m["FN"] + metrics["ID switches"][0] + self.m["FP"]- self.m["FP edge-case"]+ metrics["Fragmentations"])/(self.m["TP"])
# metrics["MOTA @ 0.2"] = 1 - (self.m["FN @ 0.2"] + metrics["ID switches"][0] + self.m["FP @ 0.2"])/(self.m["TP"])
ious = np.array(self.m["match_IOU"])
iou_mean_stddev = np.mean(ious),np.std(ious)
pre_ious = np.array(self.m["pre_thresh_IOU"])
pre_iou_mean_stddev = np.mean(pre_ious),np.std(pre_ious)
spacing_gt = | np.array(self.m["space_gap_gt"]) | numpy.array |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.