prompt
stringlengths 19
879k
| completion
stringlengths 3
53.8k
| api
stringlengths 8
59
|
---|---|---|
import numpy as np
import numpy.testing as npt
import pandas as pd
from stumpy import maamped, config
import pytest
from dask.distributed import Client, LocalCluster
import naive
@pytest.fixture(scope="module")
def dask_cluster():
cluster = LocalCluster(n_workers=2, threads_per_worker=2)
yield cluster
cluster.close()
test_data = [
(np.array([[584, -11, 23, 79, 1001, 0, -19]], dtype=np.float64), 3),
(np.random.uniform(-1000, 1000, [5, 20]).astype(np.float64), 5),
]
substitution_locations = [slice(0, 0), 0, -1, slice(1, 3), [0, 3]]
def test_maamped_int_input(dask_cluster):
with pytest.raises(TypeError):
with Client(dask_cluster) as dask_client:
maamped(dask_client, np.arange(20).reshape(2, 10), 5)
@pytest.mark.filterwarnings("ignore:\\s+Port 8787 is already in use:UserWarning")
@pytest.mark.parametrize("T, m", test_data)
def test_maamped(T, m, dask_cluster):
with Client(dask_cluster) as dask_client:
excl_zone = int(np.ceil(m / 4))
ref_P, ref_I = naive.maamp(T, m, excl_zone)
comp_P, comp_I = maamped(dask_client, T, m)
npt.assert_almost_equal(ref_P, comp_P)
npt.assert_almost_equal(ref_I, comp_I)
@pytest.mark.filterwarnings("ignore:\\s+Port 8787 is already in use:UserWarning")
@pytest.mark.parametrize("T, m", test_data)
def test_maamped_include(T, m, dask_cluster):
with Client(dask_cluster) as dask_client:
for width in range(T.shape[0]):
for i in range(T.shape[0] - width):
include = np.asarray(range(i, i + width + 1))
excl_zone = int(np.ceil(m / 4))
ref_P, ref_I = naive.maamp(T, m, excl_zone, include)
comp_P, comp_I = maamped(dask_client, T, m, include)
npt.assert_almost_equal(ref_P, comp_P)
npt.assert_almost_equal(ref_I, comp_I)
@pytest.mark.filterwarnings("ignore:\\s+Port 8787 is already in use:UserWarning")
@pytest.mark.parametrize("T, m", test_data)
def test_maamped_discords(T, m, dask_cluster):
with Client(dask_cluster) as dask_client:
excl_zone = int(np.ceil(m / 4))
ref_P, ref_I = naive.maamp(T, m, excl_zone, discords=True)
comp_P, comp_I = maamped(dask_client, T, m, discords=True)
npt.assert_almost_equal(ref_P, comp_P)
npt.assert_almost_equal(ref_I, comp_I)
@pytest.mark.filterwarnings("ignore:\\s+Port 8787 is already in use:UserWarning")
@pytest.mark.parametrize("T, m", test_data)
def test_maamped_include_discords(T, m, dask_cluster):
with Client(dask_cluster) as dask_client:
for width in range(T.shape[0]):
for i in range(T.shape[0] - width):
include = np.asarray(range(i, i + width + 1))
excl_zone = int(np.ceil(m / 4))
ref_P, ref_I = naive.maamp(T, m, excl_zone, include, discords=True)
comp_P, comp_I = maamped(dask_client, T, m, include, discords=True)
npt.assert_almost_equal(ref_P, comp_P)
npt.assert_almost_equal(ref_I, comp_I)
@pytest.mark.filterwarnings("ignore:\\s+Port 8787 is already in use:UserWarning")
@pytest.mark.parametrize("T, m", test_data)
def test_maamped_df(T, m, dask_cluster):
with Client(dask_cluster) as dask_client:
excl_zone = int(np.ceil(m / 4))
ref_P, ref_I = naive.maamp(T, m, excl_zone)
df = pd.DataFrame(T.T)
comp_P, comp_I = maamped(dask_client, df, m)
npt.assert_almost_equal(ref_P, comp_P)
npt.assert_almost_equal(ref_I, comp_I)
@pytest.mark.filterwarnings("ignore:\\s+Port 8787 is already in use:UserWarning")
def test_maamped_constant_subsequence_self_join(dask_cluster):
with Client(dask_cluster) as dask_client:
T_A = np.concatenate(
(np.zeros(20, dtype=np.float64), np.ones(5, dtype=np.float64))
)
T = np.array([T_A, T_A, np.random.rand(T_A.shape[0])])
m = 3
excl_zone = int(np.ceil(m / 4))
ref_P, ref_I = naive.maamp(T, m, excl_zone)
comp_P, comp_I = maamped(dask_client, T, m)
npt.assert_almost_equal(ref_P, comp_P) # ignore indices
@pytest.mark.filterwarnings("ignore:\\s+Port 8787 is already in use:UserWarning")
def test_maamped_identical_subsequence_self_join(dask_cluster):
with Client(dask_cluster) as dask_client:
identical = np.random.rand(8)
T_A = np.random.rand(20)
T_A[1 : 1 + identical.shape[0]] = identical
T_A[11 : 11 + identical.shape[0]] = identical
T = np.array([T_A, T_A, np.random.rand(T_A.shape[0])])
m = 3
excl_zone = int( | np.ceil(m / 4) | numpy.ceil |
from collections import OrderedDict
import astropy.coordinates as coord
import astropy.units as u
# import mpl_toolkits.basemap as bm
import numpy as np
import pandas as pd
import spherical_geometry.polygon as sp
from gbmgeometry.position_interpolator import PositionInterpolator
from gbmgeometry.utils.gbm_time import GBMTime
from gbmgeometry.utils.plotting import SphericalCircle, skyplot
from .gbm_detector import (
BGO0,
BGO1,
NaI0,
NaI1,
NaI2,
NaI3,
NaI4,
NaI5,
NaI6,
NaI7,
NaI8,
NaI9,
NaIA,
NaIB,
)
from .gbm_frame import GBMFrame
# import seaborn as sns
_det_color_cycle = np.linspace(0, 1, 12)
class GBM(object):
def __init__(self, quaternion, sc_pos=None, gbm_time=None):
"""
:param quaternion:
:param sc_pos:
:param gbm_time:
:returns:
:rtype:
"""
if gbm_time is not None:
if isinstance(gbm_time, str):
self._gbm_time = GBMTime.from_UTC_fits(gbm_time)
else:
# assuming MET
self._gbm_time = GBMTime.from_MET(gbm_time)
else:
self._gbm_time = None
self._quaternion = quaternion
self._sc_pos = sc_pos
if sc_pos is not None:
self._earth_pos_norm = self.geo_to_gbm(
-self._sc_pos / np.linalg.norm(self._sc_pos)
)
scxn, scyn, sczn = self._earth_pos_norm
earth_theta = np.arccos(
sczn / np.sqrt(scxn * scxn + scyn * scyn + sczn * sczn)
)
earth_phi = np.arctan2(scyn, scxn)
earth_ra = np.rad2deg(earth_phi)
if earth_ra < 0:
earth_ra = earth_ra + 360
earth_dec = 90 - np.rad2deg(earth_theta)
# earth as SkyCoord
self._earth_position = coord.SkyCoord(
lon=earth_ra * u.deg,
lat=earth_dec * u.deg,
unit="deg",
frame=GBMFrame(
quaternion_1=quaternion[0],
quaternion_2=quaternion[1],
quaternion_3=quaternion[2],
quaternion_4=quaternion[3],
sc_pos_X=sc_pos[0],
sc_pos_Y=sc_pos[1],
sc_pos_Z=sc_pos[2],
),
)
if self._gbm_time is not None:
self.n0 = NaI0(quaternion, sc_pos, self._gbm_time.time)
self.n1 = NaI1(quaternion, sc_pos, self._gbm_time.time)
self.n2 = NaI2(quaternion, sc_pos, self._gbm_time.time)
self.n3 = NaI3(quaternion, sc_pos, self._gbm_time.time)
self.n4 = NaI4(quaternion, sc_pos, self._gbm_time.time)
self.n5 = NaI5(quaternion, sc_pos, self._gbm_time.time)
self.n6 = NaI6(quaternion, sc_pos, self._gbm_time.time)
self.n7 = NaI7(quaternion, sc_pos, self._gbm_time.time)
self.n8 = NaI8(quaternion, sc_pos, self._gbm_time.time)
self.n9 = NaI9(quaternion, sc_pos, self._gbm_time.time)
self.na = NaIA(quaternion, sc_pos, self._gbm_time.time)
self.nb = NaIB(quaternion, sc_pos, self._gbm_time.time)
self.b0 = BGO0(quaternion, sc_pos, self._gbm_time.time)
self.b1 = BGO1(quaternion, sc_pos, self._gbm_time.time)
else:
self.n0 = NaI0(quaternion, sc_pos, None)
self.n1 = NaI1(quaternion, sc_pos, None)
self.n2 = NaI2(quaternion, sc_pos, None)
self.n3 = NaI3(quaternion, sc_pos, None)
self.n4 = NaI4(quaternion, sc_pos, None)
self.n5 = NaI5(quaternion, sc_pos, None)
self.n6 = NaI6(quaternion, sc_pos, None)
self.n7 = NaI7(quaternion, sc_pos, None)
self.n8 = NaI8(quaternion, sc_pos, None)
self.n9 = NaI9(quaternion, sc_pos, None)
self.na = NaIA(quaternion, sc_pos, None)
self.nb = NaIB(quaternion, sc_pos, None)
self.b0 = BGO0(quaternion, sc_pos, None)
self.b1 = BGO1(quaternion, sc_pos, None)
self._detectors = OrderedDict(
n0=self.n0,
n1=self.n1,
n2=self.n2,
n3=self.n3,
n4=self.n4,
n5=self.n5,
n6=self.n6,
n7=self.n7,
n8=self.n8,
n9=self.n9,
na=self.na,
nb=self.nb,
b0=self.b0,
b1=self.b1,
)
@classmethod
def from_position_interpolator(
cls, pos_interp: PositionInterpolator, time: float = 0
):
"""
Create a GBM directly from an interpolator
"""
met = pos_interp.met(time)
return cls(pos_interp.quaternion(time), pos_interp.sc_pos(time), gbm_time=met)
def set_quaternion(self, quaternion):
"""FIXME! briefly describe function
:param quaternion:
:returns:
:rtype:
"""
for key in self._detectors.keys():
self._detectors[key].set_quaternion(quaternion)
self._quaternion = quaternion
def set_sc_pos(self, sc_pos):
"""FIXME! briefly describe function
:param sc_pos:
:returns:
:rtype:
"""
for key in self._detectors.keys():
self._detectors[key].set_sc_pos(sc_pos)
self._sc_pos = sc_pos
def get_good_detectors(self, point, fov):
"""
Returns a list of detectors containing the point in the FOV
Parameters
----------
point
fov
Returns
-------
"""
good_detectors = self._contains_point(point, fov)
return good_detectors
def get_fov(self, radius, fermi_frame=False):
"""
Parameters
----------
fermi_frame
radius
"""
polys = []
for key in self._detectors.keys():
if key[0] == "b":
this_rad = 90
else:
this_rad = radius
polys.append(self._detectors[key].get_fov(this_rad, fermi_frame))
polys = np.array(polys)
return polys
def get_good_fov(self, point, radius, fermi_frame=False):
"""
Returns the detectors that contain the given point
for the given angular radius
Parameters
----------
point
radius
"""
good_detectors = self._contains_point(point, radius)
polys = []
for key in good_detectors:
polys.append(self._detectors[key].get_fov(radius, fermi_frame))
return [polys, good_detectors]
def get_sun_angle(self, keys=None):
"""
Returns
-------
"""
angles = []
if keys is None:
for key in self._detectors.keys():
angles.append(self._detectors[key].sun_angle)
else:
for key in keys:
angles.append(self._detectors[key].sun_angle)
return angles
def get_centers(self, keys=None):
"""
Returns
-------
"""
centers = []
if keys is None:
for key in self._detectors.keys():
centers.append(self._detectors[key].get_center())
else:
for key in keys:
centers.append(self._detectors[key].get_center())
return centers
def get_separation(self, source):
"""
Get the andular separation of the detectors from a point
Parameters
"""
out = {}
for k, v in self._detectors.items():
out[k] = v.get_center().separation(source).deg
return pd.Series(out)
def get_earth_points(self, fermi_frame=False):
"""
Returns
-------
"""
if self._sc_pos is not None:
self._calc_earth_points(fermi_frame)
return self._earth_points
else:
print("No spacecraft position set")
def _calc_earth_points(self, fermi_frame):
xyz_position = coord.SkyCoord(
x=self._sc_pos[0],
y=self._sc_pos[1],
z=self._sc_pos[2],
frame="icrs",
representation="cartesian",
)
earth_radius = 6371.0 * u.km
fermi_radius = np.sqrt((self._sc_pos ** 2).sum())
horizon_angle = 90 - np.rad2deg(
np.arccos((earth_radius / fermi_radius).to(u.dimensionless_unscaled)).value
)
horizon_angle = (180 - horizon_angle) * u.degree
num_points = 300
ra_grid_tmp = np.linspace(0, 360, num_points)
dec_range = [-90, 90]
cosdec_min = np.cos(np.deg2rad(90.0 + dec_range[0]))
cosdec_max = np.cos(np.deg2rad(90.0 + dec_range[1]))
v = np.linspace(cosdec_min, cosdec_max, num_points)
v = np.arccos(v)
v = np.rad2deg(v)
v -= 90.0
dec_grid_tmp = v
ra_grid = np.zeros(num_points ** 2)
dec_grid = np.zeros(num_points ** 2)
itr = 0
for ra in ra_grid_tmp:
for dec in dec_grid_tmp:
ra_grid[itr] = ra
dec_grid[itr] = dec
itr += 1
if fermi_frame:
all_sky = coord.SkyCoord(
Az=ra_grid,
Zen=dec_grid,
frame=GBMFrame(quaternion=self._quaternion),
unit="deg",
)
else:
all_sky = coord.SkyCoord(ra=ra_grid, dec=dec_grid, frame="icrs", unit="deg")
condition = all_sky.separation(xyz_position) > horizon_angle
# self.seps = all_sky.separation(xyz_position)
self._earth_points = all_sky[condition]
@property
def detectors(self):
return self._detectors
def _contains_point(self, point, radius):
"""
returns detectors that contain a points
"""
condition = []
steps = 500
for key in self._detectors.keys():
if key[0] == "b":
this_rad = 90
else:
this_rad = radius
j2000 = self._detectors[key]._center.icrs
poly = sp.SphericalPolygon.from_cone(
j2000.ra.value, j2000.dec.value, this_rad, steps=steps
)
if poly.contains_point(point.cartesian.xyz.value):
condition.append(key)
return condition
def plot_detector_pointings(self, ax=None, fov=None, show_earth=True, **kwargs):
if ax is None:
skymap_kwargs = {}
if "projection" in kwargs:
skymap_kwargs["projection"] = kwargs.pop("projection")
if "center" in kwargs:
skymap_kwargs["center"] = kwargs.pop("center")
if "radius" in kwargs:
skymap_kwargs["radius"] = kwargs.pop("radius")
ax = skyplot(**skymap_kwargs)
_defaults = dict(edgecolor="#13ED9B", lw=1, facecolor="#13ED9B", alpha=0.3)
for k, v in _defaults.items():
if k not in kwargs:
kwargs[k] = v
for k, v in self._detectors.items():
v.plot_pointing(ax=ax, fov=fov, **kwargs)
if show_earth:
circle = SphericalCircle(
self._earth_position.icrs.ra,
self._earth_position.icrs.dec,
67,
vertex_unit=u.deg,
resolution=5000,
# edgecolor=color,
transform=ax.get_transform("icrs"),
edgecolor="none",
facecolor="#13ACED",
alpha=0.1,
zorder=-3000,
)
ax.add_patch(circle)
return ax.get_figure()
def geo_to_gbm(self, pos_geo):
""" Compute the transformation from heliocentric Sgr coordinates to
spherical Galactic.
"""
q1, q2, q3, q4 = self._quaternion # q1,q2,q3,q4
sc_matrix = | np.zeros((3, 3)) | numpy.zeros |
# RUN: SUPPORTLIB=%mlir_runner_utils_dir/libmlir_c_runner_utils%shlibext %PYTHON %s | FileCheck %s
from string import Template
import numpy as np
import os
import sys
import tempfile
_SCRIPT_PATH = os.path.dirname(os.path.abspath(__file__))
sys.path.append(_SCRIPT_PATH)
from tools import mlir_pytaco
from tools import testing_utils as testing_utils
# Define the aliases to shorten the code.
_COMPRESSED = mlir_pytaco.ModeFormat.COMPRESSED
_DENSE = mlir_pytaco.ModeFormat.DENSE
def _init_3d(T, I, J, K):
for i in range(I):
for j in range(J):
for k in range(K):
T.insert([i, j, k], i + j + k + 1)
def _init_2d(T, I, J):
for i in range(I):
for j in range(J):
T.insert([i, j], i + j + 1)
def _init_1d_with_value(T, I, v):
for i in range(I):
T.insert([i], v)
def test_expect_error(name, code, error):
"""Executes the code then verifies the expected error message."""
try:
exec(code)
except ValueError as e:
passed = "passed" if (str(e).startswith(error)) else "failed"
print(f"test_{name}: {passed}")
# CHECK-LABEL: test_tensor_dtype
@testing_utils.run_test
def test_tensor_dtype():
passed = mlir_pytaco.DType(mlir_pytaco.Type.INT16).is_int()
passed += mlir_pytaco.DType(mlir_pytaco.Type.INT32).is_int()
passed += mlir_pytaco.DType(mlir_pytaco.Type.INT64).is_int()
passed += mlir_pytaco.DType(mlir_pytaco.Type.FLOAT32).is_float()
passed += mlir_pytaco.DType(mlir_pytaco.Type.FLOAT64).is_float()
# CHECK: Number of passed: 5
print("Number of passed:", passed)
# CHECK: test_mode_ordering_not_int: passed
test_expect_error("mode_ordering_not_int",
"m = mlir_pytaco.ModeOrdering(['x'])",
"Ordering must be a list of integers")
# CHECK: test_mode_ordering_not_permutation: passed
test_expect_error("mode_ordering_not_permutation",
"m = mlir_pytaco.ModeOrdering([2, 1])", "Invalid ordering")
# CHECK: test_mode_format_invalid: passed
test_expect_error("mode_format_invalid",
"m = mlir_pytaco.ModeFormatPack(['y'])",
"Formats must be a list of ModeFormat")
# CHECK: test_expect_mode_format_pack: passed
test_expect_error("expect_mode_format_pack", ("""
mode_ordering = mlir_pytaco.ModeOrdering([0, 1, 2])
f = mlir_pytaco.Format(["x"], mode_ordering)
"""), "Expected a list of ModeFormat")
# CHECK: test_expect_mode_ordering: passed
test_expect_error("expect_mode_ordering", ("""
mode_format_pack = mlir_pytaco.ModeFormatPack([_COMPRESSED, _COMPRESSED])
f = mlir_pytaco.Format(mode_format_pack, "x")
"""), "Expected ModeOrdering")
# CHECK: test_inconsistent_mode_format_pack_and_mode_ordering: passed
test_expect_error("inconsistent_mode_format_pack_and_mode_ordering", ("""
mode_format_pack = mlir_pytaco.ModeFormatPack([_COMPRESSED, _COMPRESSED])
mode_ordering = mlir_pytaco.ModeOrdering([0, 1, 2])
f = mlir_pytaco.Format(mode_format_pack, mode_ordering)
"""), "Inconsistent ModeFormatPack and ModeOrdering")
# CHECK-LABEL: test_format_default_ordering
@testing_utils.run_test
def test_format_default_ordering():
f = mlir_pytaco.Format([_COMPRESSED, _COMPRESSED])
passed = 0
passed += np.array_equal(f.ordering.ordering, [0, 1])
# CHECK: Number of passed: 1
print("Number of passed:", passed)
# CHECK-LABEL: test_format_explicit_ordering
@testing_utils.run_test
def test_format_explicit_ordering():
f = mlir_pytaco.Format([_COMPRESSED, _DENSE], [1, 0])
passed = 0
passed += np.array_equal(f.ordering.ordering, [1, 0])
# CHECK: Number of passed: 1
print("Number of passed:", passed)
# CHECK-LABEL: test_index_var
@testing_utils.run_test
def test_index_var():
i = mlir_pytaco.IndexVar()
j = mlir_pytaco.IndexVar()
passed = (i.name != j.name)
vars = mlir_pytaco.get_index_vars(10)
passed += (len(vars) == 10)
passed += (all([isinstance(e, mlir_pytaco.IndexVar) for e in vars]))
# CHECK: Number of passed: 3
print("Number of passed:", passed)
# CHECK: test_tensor_invalid_first_argument: passed
test_expect_error("tensor_invalid_first_argument",
"t = mlir_pytaco.Tensor('f')", "Invalid first argument")
# CHECK: test_tensor_inconsistent_shape_and_format: passed
test_expect_error("tensor_inconsistent_shape_and_format", ("""
mode_format_pack = mlir_pytaco.ModeFormatPack([_COMPRESSED, _COMPRESSED])
mode_ordering = mlir_pytaco.ModeOrdering([0, 1])
f = mlir_pytaco.Format(mode_format_pack, mode_ordering)
t = mlir_pytaco.Tensor([3], f)
"""), "Inconsistent shape and format")
# CHECK: test_tensor_invalid_format: passed
test_expect_error("tensor_invalid_format", "t = mlir_pytaco.Tensor([3], 'f')",
"Invalid format argument")
# CHECK: test_tensor_insert_nonlist_coordinate: passed
test_expect_error("tensor_insert_nonlist_coordinate", ("""
t = mlir_pytaco.Tensor([3])
t.insert(1, 0)
"""), "Non list coordinate detected")
# CHECK: test_tensor_insert_too_much_coordinate: passed
test_expect_error("tensor_insert_too_much_coordinate", ("""
t = mlir_pytaco.Tensor([3])
t.insert([0, 0], 0)
"""), "Invalid coordinate")
# CHECK: test_tensor_insert_coordinate_outof_range: passed
test_expect_error("tensor_insert_coordinate_outof_range", ("""
t = mlir_pytaco.Tensor([1, 1])
t.insert([1, 0], 0)
"""), "Invalid coordinate")
# CHECK: test_tensor_insert_coordinate_nonint: passed
test_expect_error("tensor_insert_coordinate_nonint", ("""
t = mlir_pytaco.Tensor([1, 1])
t.insert([0, "xy"], 0)
"""), "Non integer coordinate detected")
# CHECK: test_tensor_insert_invalid_value: passed
test_expect_error("tensor_insert_invalid_value", ("""
t = mlir_pytaco.Tensor([1, 1])
t.insert([0, 0], "x")
"""), "Value is neither int nor float")
# CHECK: test_access_non_index_var_index: passed
test_expect_error("access_non_index_var_index", ("""
t = mlir_pytaco.Tensor([5, 6])
i = mlir_pytaco.IndexVar()
a = mlir_pytaco.Access(t, (i, "j"))
"""), "Indices contain non IndexVar")
# CHECK: test_access_inconsistent_rank_indices: passed
test_expect_error("access_inconsistent_rank_indices", ("""
t = mlir_pytaco.Tensor([5, 6])
i = mlir_pytaco.IndexVar()
a = mlir_pytaco.Access(t, (i,))
"""), "Invalid indices for rank")
# CHECK: test_access_invalid_indices_for_rank: passed
test_expect_error("access_invalid_indices_for_rank", ("""
t = mlir_pytaco.Tensor([5, 6])
i, j, k = mlir_pytaco.get_index_vars(3)
a = mlir_pytaco.Access(t, (i,j, k))
"""), "Invalid indices for rank")
# CHECK: test_invalid_indices: passed
test_expect_error("invalid_indices", ("""
i, j = mlir_pytaco.get_index_vars(2)
A = mlir_pytaco.Tensor([2, 3])
B = mlir_pytaco.Tensor([2, 3])
C = mlir_pytaco.Tensor([2, 3], _DENSE)
C[i, j] = A[1, j] + B[i, j]
"""), "Expected IndexVars")
# CHECK: test_invalid_operation: passed
test_expect_error("invalid_operation", ("""
i, j = mlir_pytaco.get_index_vars(2)
A = mlir_pytaco.Tensor([2, 3])
C = mlir_pytaco.Tensor([2, 3], _DENSE)
C[i, j] = A[i, j] + i
"""), "Expected IndexExpr")
# CHECK: test_inconsistent_rank_indices: passed
test_expect_error("inconsistent_rank_indices", ("""
i, j = mlir_pytaco.get_index_vars(2)
A = mlir_pytaco.Tensor([2, 3])
C = mlir_pytaco.Tensor([2, 3], _DENSE)
C[i, j] = A[i]
"""), "Invalid indices for rank")
# CHECK: test_destination_index_not_used_in_source: passed
test_expect_error("destination_index_not_used_in_source", ("""
i, j = mlir_pytaco.get_index_vars(2)
A = mlir_pytaco.Tensor([3])
C = mlir_pytaco.Tensor([3], _DENSE)
C[j] = A[i]
C.evaluate()
"""), "Destination IndexVar not used in the source expression")
# CHECK: test_destination_dim_not_consistent_with_source: passed
test_expect_error("destination_dim_not_consistent_with_source", ("""
i = mlir_pytaco.IndexVar()
A = mlir_pytaco.Tensor([3])
C = mlir_pytaco.Tensor([5], _DENSE)
C[i] = A[i]
C.evaluate()
"""), "Inconsistent destination dimension for IndexVar")
# CHECK: test_inconsistent_source_dim: passed
test_expect_error("inconsistent_source_dim", ("""
i = mlir_pytaco.IndexVar()
A = mlir_pytaco.Tensor([3])
B = mlir_pytaco.Tensor([5])
C = mlir_pytaco.Tensor([3], _DENSE)
C[i] = A[i] + B[i]
C.evaluate()
"""), "Inconsistent source dimension for IndexVar")
# CHECK-LABEL: test_tensor_all_dense_sparse
@testing_utils.run_test
def test_tensor_all_dense_sparse():
a = mlir_pytaco.Tensor([4], [_DENSE])
passed = (not a.is_dense())
passed += (a.order == 1)
passed += (a.shape[0] == 4)
# CHECK: Number of passed: 3
print("Number of passed:", passed)
# CHECK-LABEL: test_tensor_true_dense
@testing_utils.run_test
def test_tensor_true_dense():
a = mlir_pytaco.Tensor.from_array(np.random.uniform(size=5))
passed = a.is_dense()
passed += (a.order == 1)
passed += (a.shape[0] == 5)
# CHECK: Number of passed: 3
print("Number of passed:", passed)
# CHECK-LABEL: test_tensor_copy
@testing_utils.run_test
def test_tensor_copy():
i, j = mlir_pytaco.get_index_vars(2)
I = 2
J = 3
A = mlir_pytaco.Tensor([I, J])
A.insert([0, 1], 5.0)
A.insert([1, 2], 6.0)
B = mlir_pytaco.Tensor([I, J])
B[i, j] = A[i, j]
passed = (B._assignment is not None)
passed += (B._engine is None)
try:
B.compute()
except ValueError as e:
passed += (str(e).startswith("Need to invoke compile"))
B.compile()
passed += (B._engine is not None)
B.compute()
passed += (B._assignment is None)
passed += (B._engine is None)
indices, values = B.get_coordinates_and_values()
passed += np.array_equal(indices, [[0, 1], [1, 2]])
passed += np.allclose(values, [5.0, 6.0])
# No temporary tensor is used.
passed += (B._stats.get_total() == 0)
# CHECK: Number of passed: 9
print("Number of passed:", passed)
# CHECK-LABEL: test_tensor_trivial_reduction
@testing_utils.run_test
def test_tensor_trivial_reduction():
i, j = mlir_pytaco.get_index_vars(2)
I = 2
J = 3
A = mlir_pytaco.Tensor([I, J])
A.insert([0, 1], 5.0)
A.insert([0, 2], 3.0)
A.insert([1, 2], 6.0)
B = mlir_pytaco.Tensor([I])
B[i] = A[i, j]
indices, values = B.get_coordinates_and_values()
passed = np.array_equal(indices, [[0], [1]])
passed += np.allclose(values, [8.0, 6.0])
# No temporary tensor is used.
passed += (B._stats.get_total() == 0)
# CHECK: Number of passed: 3
print("Number of passed:", passed)
# CHECK-LABEL: test_binary_add
@testing_utils.run_test
def test_binary_add():
i = mlir_pytaco.IndexVar()
A = mlir_pytaco.Tensor([4])
B = mlir_pytaco.Tensor([4])
C = mlir_pytaco.Tensor([4])
A.insert([1], 10)
A.insert([2], 1)
B.insert([3], 20)
B.insert([2], 2)
C[i] = A[i] + B[i]
indices, values = C.get_coordinates_and_values()
passed = np.array_equal(indices, [[1], [2], [3]])
passed += np.array_equal(values, [10., 3., 20.])
# No temporary tensor is used.
passed += (C._stats.get_total() == 0)
# CHECK: Number of passed: 3
print("Number of passed:", passed)
# CHECK-LABEL: test_binary_add_sub
@testing_utils.run_test
def test_binary_add_sub():
i = mlir_pytaco.IndexVar()
j = mlir_pytaco.IndexVar()
A = mlir_pytaco.Tensor([2, 3])
B = mlir_pytaco.Tensor([2, 3])
C = mlir_pytaco.Tensor([2, 3])
D = mlir_pytaco.Tensor([2, 3])
A.insert([0, 1], 10)
A.insert([1, 2], 40)
B.insert([0, 0], 20)
B.insert([1, 2], 30)
C.insert([0, 1], 5)
C.insert([1, 2], 7)
D[i, j] = A[i, j] + B[i, j] - C[i, j]
indices, values = D.get_coordinates_and_values()
passed = np.array_equal(indices, [[0, 0], [0, 1], [1, 2]])
passed += | np.array_equal(values, [20., 5., 63.]) | numpy.array_equal |
# -*- coding=utf-8 -*-
import numpy as np
from sklearn.cluster import KMeans, SpectralClustering
from sklearn.mixture import GaussianMixture
from skimage.measure import label
def net_center_posprocessing(pred, centers, pixel_wise_feature, gt):
'''
根据net维护的center,得到seg的结果
:param pred: [512, 512]
:param centers: [2, 256]
:param pixel_wise_feature: [512, 512, 256]
:param gt: [512, 512]
:return:
'''
# print(np.shape(pred), np.shape(centers), np.shape(pixel_wise_feature), np.shape(gt))
from metrics import dice
distances1 = np.sum((pixel_wise_feature - centers[0]) ** 2, axis=2, keepdims=True)
distances2 = np.sum((pixel_wise_feature - centers[1]) ** 2, axis=2, keepdims=True)
distances = np.concatenate([distances1, distances2], axis=2)
optimized_pred = | np.argmin(distances, axis=2) | numpy.argmin |
# -*- coding: utf-8 -*-
import matplotlib.patches as mpatches
import matplotlib.lines as mlines
import seaborn as sns
import pandas as pd
import copy
import matplotlib.pyplot as plt
from ..enumerations import AssayRole, SampleType
import numpy
import plotly.graph_objs as go
from ..enumerations import VariableType
def plotSpectraInteractive(dataset, samples=None, xlim=None, featureNames=None, sampleLabels='Sample ID', nmrDataset=True):
"""
Plot spectra from *dataset*.
#:param Dataset dataset: Dataset to plot from
:param samples: Index of samples to plot, if ``None`` plot all spectra
:type samples: None or list of int
:param xlim: Tuple of (minimum value, maximum value) defining a feature range to plot
:type xlim: (float, float)
"""
if not dataset.VariableType == VariableType.Spectral:
raise TypeError('Variables in dataset must be continuous.')
if featureNames is None:
featureNames = dataset.Attributes['Feature Names']
elif featureNames not in dataset.featureMetadata.columns:
raise KeyError('featureNames=%s is not a column in dataset.featureMetadata.' % (featureNames))
if sampleLabels not in dataset.sampleMetadata.columns:
raise KeyError('sampleLabels=%s is not a column in dataset.sampleMetadata.' % (sampleLabels))
##
# Filter features
##
featureMask = dataset.featureMask
if xlim is not None:
featureMask = (dataset.featureMetadata[featureNames].values > xlim[0]) & \
(dataset.featureMetadata[featureNames].values < xlim[1]) & \
featureMask
features = dataset.featureMetadata.loc[featureMask, 'ppm'].values.squeeze()
X = dataset.intensityData[:, featureMask]
##
# Filter samples
##
sampleMask = dataset.sampleMask
if samples is None:
samples = numpy.arange(X.shape[0])[sampleMask]
elif isinstance(samples, int):
samples = [samples]
elif isinstance(samples, numpy.ndarray):
sampleMask = sampleMask & samples
samples = numpy.arange(dataset.noSamples)[sampleMask]
data = list()
if X.ndim == 1:
trace = go.Scattergl(
x = features,
y = X,
name = dataset.sampleMetadata.loc[samples, sampleLabels],
mode = 'lines',
)
data.append(trace)
else:
for i in samples:
trace = go.Scattergl(
x = features,
y = X[i, :],
name = str(dataset.sampleMetadata.loc[i, sampleLabels]),
mode = 'lines',
)
data.append(trace)
if nmrDataset:
autorange = 'reversed'
else:
autorange = True
layout = go.Layout(
# title='',
legend=dict(
orientation="h"),
hovermode = "closest",
xaxis=dict(
autorange=autorange
),
yaxis = dict(
showticklabels=False
),
)
figure = go.Figure(data=data, layout=layout)
return figure
def plotPW(nmrData, savePath=None, title='', figureFormat='png', dpi=72, figureSize=(11,7)):
"""
plotPW(nmrData, savePath=None, figureFormat='png', dpi=72, figureSize=(11,7))
Visualise peak width values as box plot
:param nmrData nmrdataset
Dataset object
:param title string
Text for the figure title
:param savePath None or str
If None, plot interactively, otherwise attempt to save at this path
:param format str
Format to save figure
:param dpi int
Resolution to draw at
:param figureSize tuple
Specify size of figure
"""
# Load toolbox wide color scheme
if 'sampleTypeColours' in nmrData.Attributes.keys():
sTypeColourDict = copy.deepcopy(nmrData.Attributes['sampleTypeColours'])
for stype in SampleType:
if stype.name in sTypeColourDict.keys():
sTypeColourDict[stype] = sTypeColourDict.pop(stype.name)
else:
sTypeColourDict = {SampleType.StudySample: 'b', SampleType.StudyPool: 'g', SampleType.ExternalReference: 'r',
SampleType.MethodReference: 'm', SampleType.ProceduralBlank: 'c', 'Other': 'grey',
'Study Sample': 'b', 'Study Reference': 'g', 'Long-Term Reference': 'r',
'Method Reference': 'm', 'Blank': 'c', 'Unspecified SampleType or AssayRole': 'grey'}
sns.set_color_codes(palette='deep')
fig, ax = plt.subplots(1, figsize=figureSize, dpi=dpi)
# Masks for different sample categories
SSmask = (nmrData.sampleMetadata['SampleType'] == SampleType.StudySample) & (nmrData.sampleMetadata['AssayRole'] == AssayRole.Assay)
SPmask = (nmrData.sampleMetadata['SampleType'] == SampleType.StudyPool) & (nmrData.sampleMetadata['AssayRole'] == AssayRole.PrecisionReference)
ERmask = (nmrData.sampleMetadata['SampleType'] == SampleType.ExternalReference) & (nmrData.sampleMetadata['AssayRole'] == AssayRole.PrecisionReference)
SRDmask = (nmrData.sampleMetadata['SampleType'] == SampleType.StudyPool) & (nmrData.sampleMetadata['AssayRole'] == AssayRole.LinearityReference)
Blankmask = nmrData.sampleMetadata['SampleType'] == SampleType.ProceduralBlank
UnclearRolemask = (SSmask==False) & (SPmask==False) & (ERmask==False) & (SRDmask == False) & (Blankmask==False)
#all the pw values
pw_ER = nmrData.sampleMetadata[ERmask]['Line Width (Hz)']
pw_SP = nmrData.sampleMetadata[SPmask]['Line Width (Hz)']
pw_SS = nmrData.sampleMetadata[SSmask]['Line Width (Hz)']
pw_SRD = nmrData.sampleMetadata[SRDmask]['Line Width (Hz)']
pw_Blank = nmrData.sampleMetadata[Blankmask]['Line Width (Hz)']
pw_Unknown = nmrData.sampleMetadata[UnclearRolemask]['Line Width (Hz)']
tempDF = pd.concat([pw_SS, pw_SP, pw_ER, pw_SRD, pw_Blank, pw_Unknown], axis=1)#put them all together in a new df
tempDF.columns = ['Study Sample', 'Study Reference', 'Long-Term Reference', 'Serial Dilution', 'Blank', 'Unspecified SampleType or AssayRole']
tempDF.dropna(axis='columns', how='all', inplace=True) # remove empty columns
#all the outliers only
pw_ER = pw_ER.where(pw_ER>nmrData.Attributes['LWFailThreshold'], numpy.nan) #anything smaller than pw threshold set to NaN so doesnt plot
pw_SP = pw_SP.where(pw_SP>nmrData.Attributes['LWFailThreshold'], numpy.nan)
pw_SS = pw_SS.where(pw_SS>nmrData.Attributes['LWFailThreshold'], numpy.nan)
pw_SRD = pw_SRD.where(pw_SRD>nmrData.Attributes['LWFailThreshold'], numpy.nan)
pw_Blank = pw_Blank.where(pw_Blank>nmrData.Attributes['LWFailThreshold'], numpy.nan)
pw_Unknown = pw_Unknown.where(pw_Unknown>nmrData.Attributes['LWFailThreshold'], numpy.nan)
tempDF_outliers = pd.concat([pw_SS, pw_SP, pw_ER, pw_SRD, pw_Blank, pw_Unknown], axis=1)#put them all together in a new df
tempDF_outliers.columns = ['Study Sample', 'Study Reference', 'Long-Term Reference', 'Serial Dilution', 'Blank', 'Unspecified SampleType or AssayRole']
tempDF_outliers.dropna(axis='columns', how='all', inplace=True) # remove empty columns
#plot fail threshold line only if there exists values greater than the fail (normally 1.4 set in SOP)
if | numpy.max(nmrData.sampleMetadata['Line Width (Hz)']) | numpy.max |
import os
import numpy as np
import itertools
from numpy.core.shape_base import _block_slicing
import prody as pr
import datetime
from scipy.sparse.csr import csr_matrix
from scipy.sparse import lil_matrix
from scipy.sparse.sputils import matrix
from ..basic import hull
from ..basic import utils
from ..basic.filter import Search_filter
from ..basic.constant import one_letter_code
from .graph import Graph
from .comb_info import CombInfo
from sklearn.neighbors import NearestNeighbors, radius_neighbors_graph
import multiprocessing as mp
from multiprocessing.dummy import Pool as ThreadPool
'''
test_matrix = np.array(
[[0, 0, 1, 1],
[0, 0, 1, 0],
[0, 0, 0, 1],
[0, 0, 0, 0]],
dtype = bool
)
test_paths = calc_adj_matrix_paths(test_matrix, num_iter)
paths = calc_adj_matrix_paths(m_adj_matrix)
for i in range(len(ss.vdms)):
if '5od1' in ss.vdms[i].query.getTitle():
print(i)
print(ss.vdms[i].query.getTitle())
index = [3776, 4387*1+2865, 4387*2+2192]
index == [3776, 7252, 10966]
all_vdms = []
for i in range(len(wins)):
all_vdms.extend(ss.vdms)
all_vdms[7252].query.getTitle()
adj_matrix[3776, 7252]
adj_matrix[3776, 10966]
adj_matrix[7252, 10966]
win_mask[3776, 7252]
win_mask[3776, 10966]
win_mask[7252, 10966]
paths = calc_adj_matrix_paths(m_adj_matrix)
'''
def calc_adj_matrix_paths(m_adj_matrix, num_iter =3):
paths = []
for r in range(m_adj_matrix.shape[0]):
inds = m_adj_matrix.rows[r]
if len(inds) < num_iter-1:
continue
for _comb in itertools.combinations(inds, num_iter-1):
comb = [r]
comb.extend(_comb)
valid = calc_adj_matrix_paths_helper(m_adj_matrix, comb, num_iter, 1)
if valid:
#print(comb)
paths.append(comb)
return paths
def calc_adj_matrix_paths_helper( m_adj_matrix, comb, num_iter, iter):
if iter >= num_iter -1:
return True
r_curr = comb[iter]
for r_next in comb[iter+1:]:
if not m_adj_matrix[r_curr, r_next]:
return False
return calc_adj_matrix_paths_helper(m_adj_matrix, comb, num_iter, iter +1)
def neighbor_generate_nngraph(ss):
'''
Instead of doing this in a pairwise way as the function 'search.neighbor_generate_pair_dict'.
Here we calc one nearest neighbor object and graph.
ss is the search.Search_vdM object.
'''
wins = sorted(list(ss.neighbor_query_dict.keys()))
metal_vdm_size = len(ss.all_metal_vdm.get_metal_mem_coords())
#calc radius_neighbors_graph
all_coords = []
win_labels = []
vdm_inds = []
for inx in range(len(wins)):
wx = wins[inx]
win_labels.extend([wx]*metal_vdm_size)
n_x = ss.neighbor_query_dict[wx].get_metal_mem_coords()
all_coords.extend(n_x)
vdm_inds.extend(range(metal_vdm_size))
#nbrs = NearestNeighbors(radius= ss.metal_metal_dist).fit(all_coords)
#adj_matrix = nbrs.radius_neighbors_graph(all_coords).astype(bool)
adj_matrix = radius_neighbors_graph(all_coords, radius= ss.metal_metal_dist).astype(bool)
#print(adj_matrix.shape)
#metal_clashing with bb
bb_coords = ss.target.select('name N C CA O').getCoords()
nbrs_bb = NearestNeighbors(radius= 3.5).fit(all_coords)
adj_matrix_bb = nbrs_bb.radius_neighbors_graph(bb_coords).astype(bool)
#print(adj_matrix_bb.shape)
# #create mask
# mask = generate_filter_mask(ss, wins, win_labels, metal_vdm_size, adj_matrix_bb)
# #calc modified adj matrix
# m_adj_matrix = adj_matrix.multiply(mask)
m_adj_matrix = filter_adj_matrix(ss, wins, metal_vdm_size, adj_matrix, adj_matrix_bb)
return m_adj_matrix, win_labels, vdm_inds
def generate_filter_mask(ss, wins, win_labels, metal_vdm_size, adj_matrix_bb):
'''
One issue for the mask method is that the matrix is sparse, there will be a lot of unnecessary calculation.
For example, filter phi psi, if a vdm is never be in any neighbor, there is no need to calc it.
'''
wins = sorted(list(ss.neighbor_query_dict.keys()))
metal_vdm_size = len(ss.all_metal_vdm.get_metal_mem_coords())
win_mask = np.ones((len(win_labels), len(win_labels)), dtype=bool)
win_mask = np.triu(win_mask)
# win filter: vdm on the same position don't connect.
for inx in range(len(wins)):
win_mask[inx*metal_vdm_size:(inx+1)*metal_vdm_size, inx*metal_vdm_size:(inx+1)*metal_vdm_size] = 0
# Metal bb Clashing filter.
metal_clashing_vec = np.ones(len(win_labels), dtype=bool)
for i in range(adj_matrix_bb.shape[0]):
metal_clashing_vec *= ~(adj_matrix_bb[i].toarray().reshape(len(win_labels),))
labels_m = np.broadcast_to(metal_clashing_vec, (len(wins)*metal_vdm_size, len(wins)*metal_vdm_size))
win_mask *= labels_m.T
win_mask *= labels_m
# Modify mask with aa filter.
if ss.validateOriginStruct:
v_aa = np.array([v.aa_type for v in ss.vdms])
ress = [one_letter_code[ss.target.select('name CA and resindex ' + str(wx)).getResnames()[0]] for wx in wins]
labels = np.zeros(len(wins)*metal_vdm_size, dtype=bool)
for inx in range(len(wins)):
labels[inx*metal_vdm_size:(inx+1)*metal_vdm_size] = v_aa == ress[inx]
labels_m = np.broadcast_to(labels, (len(wins)*metal_vdm_size, len(wins)*metal_vdm_size))
win_mask *= labels_m.T
win_mask *= labels_m
if ss.search_filter.filter_abple:
v_abples = | np.array([v.abple for v in ss.vdms]) | numpy.array |
# This module has been generated automatically from space group information
# obtained from the Computational Crystallography Toolbox
#
"""
Space groups
This module contains a list of all the 230 space groups that can occur in
a crystal. The variable space_groups contains a dictionary that maps
space group numbers and space group names to the corresponding space
group objects.
.. moduleauthor:: <NAME> <<EMAIL>>
"""
#-----------------------------------------------------------------------------
# Copyright (C) 2013 The Mosaic Development Team
#
# Distributed under the terms of the BSD License. The full license is in
# the file LICENSE.txt, distributed as part of this software.
#-----------------------------------------------------------------------------
import numpy as N
class SpaceGroup(object):
"""
Space group
All possible space group objects are created in this module. Other
modules should access these objects through the dictionary
space_groups rather than create their own space group objects.
"""
def __init__(self, number, symbol, transformations):
"""
:param number: the number assigned to the space group by
international convention
:type number: int
:param symbol: the Hermann-Mauguin space-group symbol as used
in PDB and mmCIF files
:type symbol: str
:param transformations: a list of space group transformations,
each consisting of a tuple of three
integer arrays (rot, tn, td), where
rot is the rotation matrix and tn/td
are the numerator and denominator of the
translation vector. The transformations
are defined in fractional coordinates.
:type transformations: list
"""
self.number = number
self.symbol = symbol
self.transformations = transformations
self.transposed_rotations = N.array([N.transpose(t[0])
for t in transformations])
self.phase_factors = N.exp(N.array([(-2j*N.pi*t[1])/t[2]
for t in transformations]))
def __repr__(self):
return "SpaceGroup(%d, %s)" % (self.number, repr(self.symbol))
def __len__(self):
"""
:return: the number of space group transformations
:rtype: int
"""
return len(self.transformations)
def symmetryEquivalentMillerIndices(self, hkl):
"""
:param hkl: a set of Miller indices
:type hkl: Scientific.N.array_type
:return: a tuple (miller_indices, phase_factor) of two arrays
of length equal to the number of space group
transformations. miller_indices contains the Miller
indices of each reflection equivalent by symmetry to the
reflection hkl (including hkl itself as the first element).
phase_factor contains the phase factors that must be applied
to the structure factor of reflection hkl to obtain the
structure factor of the symmetry equivalent reflection.
:rtype: tuple
"""
hkls = N.dot(self.transposed_rotations, hkl)
p = N.multiply.reduce(self.phase_factors**hkl, -1)
return hkls, p
space_groups = {}
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(1, 'P 1', transformations)
space_groups[1] = sg
space_groups['P 1'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(2, 'P -1', transformations)
space_groups[2] = sg
space_groups['P -1'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(3, 'P 1 2 1', transformations)
space_groups[3] = sg
space_groups['P 1 2 1'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(4, 'P 1 21 1', transformations)
space_groups[4] = sg
space_groups['P 1 21 1'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(5, 'C 1 2 1', transformations)
space_groups[5] = sg
space_groups['C 1 2 1'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(6, 'P 1 m 1', transformations)
space_groups[6] = sg
space_groups['P 1 m 1'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(7, 'P 1 c 1', transformations)
space_groups[7] = sg
space_groups['P 1 c 1'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(8, 'C 1 m 1', transformations)
space_groups[8] = sg
space_groups['C 1 m 1'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(9, 'C 1 c 1', transformations)
space_groups[9] = sg
space_groups['C 1 c 1'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(10, 'P 1 2/m 1', transformations)
space_groups[10] = sg
space_groups['P 1 2/m 1'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(11, 'P 1 21/m 1', transformations)
space_groups[11] = sg
space_groups['P 1 21/m 1'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(12, 'C 1 2/m 1', transformations)
space_groups[12] = sg
space_groups['C 1 2/m 1'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(13, 'P 1 2/c 1', transformations)
space_groups[13] = sg
space_groups['P 1 2/c 1'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(14, 'P 1 21/c 1', transformations)
space_groups[14] = sg
space_groups['P 1 21/c 1'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(15, 'C 1 2/c 1', transformations)
space_groups[15] = sg
space_groups['C 1 2/c 1'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(16, 'P 2 2 2', transformations)
space_groups[16] = sg
space_groups['P 2 2 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(17, 'P 2 2 21', transformations)
space_groups[17] = sg
space_groups['P 2 2 21'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(18, 'P 21 21 2', transformations)
space_groups[18] = sg
space_groups['P 21 21 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(19, 'P 21 21 21', transformations)
space_groups[19] = sg
space_groups['P 21 21 21'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(20, 'C 2 2 21', transformations)
space_groups[20] = sg
space_groups['C 2 2 21'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(21, 'C 2 2 2', transformations)
space_groups[21] = sg
space_groups['C 2 2 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(22, 'F 2 2 2', transformations)
space_groups[22] = sg
space_groups['F 2 2 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(23, 'I 2 2 2', transformations)
space_groups[23] = sg
space_groups['I 2 2 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(24, 'I 21 21 21', transformations)
space_groups[24] = sg
space_groups['I 21 21 21'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(25, 'P m m 2', transformations)
space_groups[25] = sg
space_groups['P m m 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(26, 'P m c 21', transformations)
space_groups[26] = sg
space_groups['P m c 21'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(27, 'P c c 2', transformations)
space_groups[27] = sg
space_groups['P c c 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(28, 'P m a 2', transformations)
space_groups[28] = sg
space_groups['P m a 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(29, 'P c a 21', transformations)
space_groups[29] = sg
space_groups['P c a 21'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(30, 'P n c 2', transformations)
space_groups[30] = sg
space_groups['P n c 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(31, 'P m n 21', transformations)
space_groups[31] = sg
space_groups['P m n 21'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(32, 'P b a 2', transformations)
space_groups[32] = sg
space_groups['P b a 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(33, 'P n a 21', transformations)
space_groups[33] = sg
space_groups['P n a 21'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(34, 'P n n 2', transformations)
space_groups[34] = sg
space_groups['P n n 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(35, 'C m m 2', transformations)
space_groups[35] = sg
space_groups['C m m 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(36, 'C m c 21', transformations)
space_groups[36] = sg
space_groups['C m c 21'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(37, 'C c c 2', transformations)
space_groups[37] = sg
space_groups['C c c 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(38, 'A m m 2', transformations)
space_groups[38] = sg
space_groups['A m m 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(39, 'A b m 2', transformations)
space_groups[39] = sg
space_groups['A b m 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(40, 'A m a 2', transformations)
space_groups[40] = sg
space_groups['A m a 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(41, 'A b a 2', transformations)
space_groups[41] = sg
space_groups['A b a 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(42, 'F m m 2', transformations)
space_groups[42] = sg
space_groups['F m m 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([3,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([3,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([3,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([3,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(43, 'F d d 2', transformations)
space_groups[43] = sg
space_groups['F d d 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(44, 'I m m 2', transformations)
space_groups[44] = sg
space_groups['I m m 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(45, 'I b a 2', transformations)
space_groups[45] = sg
space_groups['I b a 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(46, 'I m a 2', transformations)
space_groups[46] = sg
space_groups['I m a 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(47, 'P m m m', transformations)
space_groups[47] = sg
space_groups['P m m m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = | N.array([-1,0,0,0,-1,0,0,0,-1]) | numpy.array |
from networkunit.tests.test_correlation_matrix_test import correlation_matrix_test
from networkunit.capabilities.cap_ProducesSpikeTrains import ProducesSpikeTrains
from networkunit.plots.plot_correlation_matrix import correlation_matrix as plot_correlation_matrix
from networkunit.plots import alpha as _alpha
from elephant.spike_train_correlation import corrcoef, cch
import matplotlib.pyplot as plt
import matplotlib as mpl
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.ticker import NullFormatter
from matplotlib import colors, colorbar
import seaborn as sns
from copy import copy
from abc import ABCMeta, abstractmethod
from quantities import ms, Quantity
import numpy as np
class generalized_correlation_matrix_test(correlation_matrix_test):
"""
Test to compare the different kinds of correlation matrices of a set of
spiking neurons in a network.
The statistical testing method needs to be set in form of a
sciunit.Score as score_type.
Parameters (in dict params)
----------
binsize: quantity, None (default: 2*ms)
Size of bins used to calculate the correlation coefficients.
num_bins: int, None (default: None)
Number of bins within t_start and t_stop used to calculate
the correlation coefficients.
t_start: quantity, None
Start of time window used to calculate the correlation coefficients.
t_stop: quantity, None
Stop of time window used to calculate the correlation coefficients.
nan_to_num: bool
If true, np.nan are set to 0, and np.inf to largest finite float.
binary: bool
If true, the binned spike trains are set to be binary.
cluster_matrix : bool
If true, the matrix is clustered by the hierarchical cluster algorithm
scipy.cluster.hierachy.linkage() with 'method' determined by the
cluster_method.
cluster_method : string (default: 'ward')
Method for the hierarchical clustering if cluster_matrix=True
remove_autocorr: bool
If true, the diagonal values of the matrix are set to 0.
edge_threshold: float
Passed to draw_graph() and determines the threshold above which edges
are draw in the graph corresponding to the matrix.
maxlag : int
Maximum shift (in number of bins) between spike trains which should
still be considered in the calculating the correlation measure.
time_reduction: 'sum', 'max', 'threshold x.x'
Method how to include lagged correlations between spike trains.
sum - calculates the sum of the normalized CCH within +- maxlag
max - takes the maximum of the CCH within +- maxlag
threshold x.x - sums up the part of the CCH above the threshold x.x
and within +- maxlag
"""
required_capabilities = (ProducesSpikeTrains, )
params = {'maxlag': 100, # in bins
'binsize': 2*ms,
'time_reduction': 'threshold 0.13'
}
def generate_cc_matrix(self, spiketrains, binary=False, model=None, **kwargs):
if hasattr(model, 'cch_array')\
and 'binsize{}_maxlag{}'.format(self.params['binsize'],self.params['maxlag'])\
in model.cch_array:
cch_array = model.cch_array['binsize{}_maxlag{}'\
.format(self.params['binsize'],self.params['maxlag'])]
else:
cch_array = self.generate_cch_array(spiketrains=spiketrains,
**self.params)
if model is not None:
if not hasattr(model, 'cch_array'):
model.cch_array = {}
model.cch_array['binsize{}_maxlag{}'\
.format(self.params['binsize'], self.params['maxlag'])] = cch_array
pairs_idx = np.triu_indices(len(spiketrains), 1)
pairs = [[i, j] for i, j in zip(pairs_idx[0], pairs_idx[1])]
if 'time_reduction' not in self.params:
raise KeyError("A method for 'time_reduction' needs to be set!")
return self.generalized_cc_matrix(cch_array, pairs,
self.params['time_reduction'])
def generalized_cc_matrix(self, cch_array, pair_ids, time_reduction,
rescale=False, **kwargs):
B = len(np.squeeze(cch_array)[0])
if time_reduction == 'sum':
cc_array = np.sum(np.squeeze(cch_array), axis=1)
if rescale:
cc_array = cc_array / float(B)
if time_reduction == 'max':
cc_array = np.amax(np.squeeze(cch_array), axis=1)
if time_reduction[:3] == 'lag':
lag = int(time_reduction[3:])
cc_array = np.squeeze(cch_array)[:, B/2 + lag]
if time_reduction[:9] == 'threshold':
th = float(time_reduction[10:])
th_cch_array = np.array([a[a>th] for a in np.squeeze(cch_array)])
if rescale:
cc_array = np.array([np.sum(cch)/float(len(cch)) if len(cch)
else np.sum(cch)
for cch in th_cch_array])
else:
cc_array = np.array([np.sum(cch) for cch in th_cch_array])
N = len(cc_array)
dim = .5*(1 + np.sqrt(8.*N + 1))
assert not dim - int(dim)
dim = int(dim)
cc_mat = np.ones((dim,dim))
for count, (i,j) in enumerate(pair_ids):
cc_mat[i,j] = cc_array[count]
cc_mat[j,i] = cc_array[count]
return cc_mat
def generate_cch_array(self, spiketrains, maxlag=None, model=None,
**kwargs):
if 'binsize' in self.params:
binsize = self.params['binsize']
elif 'num_bins' in self.params:
t_lims = [(st.t_start, st.t_stop) for st in spiketrains]
tmin = min(t_lims, key=lambda f: f[0])[0]
tmax = max(t_lims, key=lambda f: f[1])[1]
T = tmax - tmin
binsize = T / float(self.params['num_bins'])
else:
raise AttributeError("Neither bin size or number of bins was set!")
if maxlag is None:
maxlag = self.params['maxlag']
else:
self.params['maxlag'] = maxlag
if type(maxlag) == Quantity:
maxlag = int(float(maxlag.rescale('ms'))
/ float(binsize.rescale('ms')))
if hasattr(model, 'cch_array') and \
'binsize{}_maxlag{}'.format(binsize, maxlag) in model.cch_array:
cch_array = model.cch_array['binsize{}_maxlag{}'.format(binsize, maxlag)]
else:
try:
from mpi4py import MPI
mpi = True
except:
mpi = False
N = len(spiketrains)
B = 2 * maxlag + 1
pairs_idx = np.triu_indices(N, 1)
pairs = [[i, j] for i, j in zip(pairs_idx[0], pairs_idx[1])]
if mpi:
comm = MPI.COMM_WORLD
rank = comm.Get_rank()
Nnodes = comm.Get_size()
print('Using MPI with {} node'.format(Nnodes))
comm.Barrier()
if rank == 0:
split = np.array_split(pairs, Nnodes)
else:
split = None
pair_per_node = int(np.ceil(float(len(pairs)) / Nnodes))
split_pairs = comm.scatter(split, root=0)
else:
split_pairs = pairs
pair_per_node = len(pairs)
cch_array = np.zeros((pair_per_node, B))
max_cc = 0
for count, (i, j) in enumerate(split_pairs):
binned_sts_i = self.robust_BinnedSpikeTrain(spiketrains[i],
binsize=binsize)
binned_sts_j = self.robust_BinnedSpikeTrain(spiketrains[j],
binsize=binsize)
cch_array[count] = np.squeeze(cch(binned_sts_i,
binned_sts_j,
window=[-maxlag, maxlag],
cross_corr_coef=True,
)[0])
max_cc = max([max_cc, max(cch_array[count])])
if mpi:
pop_cch = comm.gather(cch_array, root=0)
pop_max_cc = comm.gather(max_cc, root=0)
if rank == 0:
cch_array = pop_cch
max_cc = pop_max_cc#
if model is not None:
if not hasattr(model, 'cch_array'):
model.cch_array = {}
model.cch_array['binsize{}_maxlag{}'.format(binsize, maxlag)] = cch_array
return cch_array
def _calc_color_array(self, cch_array, threshold=.5, **kwargs):
# save as array with only >threshold value
# and a second array with their (i,j,t)
squeezed_cch_array = np.squeeze(cch_array)
N = len(squeezed_cch_array)
B = len(squeezed_cch_array[0])
dim = int(.5 * (1 + np.sqrt(8. * N + 1)))
pairs = np.triu_indices(dim, 1)
pair_ids = [[i, j] for i, j in zip(pairs[0], pairs[1])]
binnums = np.arange(B)
try:
from mpi4py import MPI
mpi = True
except:
mpi = False
if mpi:
comm = MPI.COMM_WORLD
rank = comm.Get_rank()
Nnodes = comm.Get_size()
print('rank', rank, 'and size (Nnodes)', Nnodes)
comm.Barrier()
if rank == 0:
split = np.array_split(squeezed_cch_array, Nnodes)
else:
split = None
cch_per_node = int(np.ceil(float(len(squeezed_cch_array)) / Nnodes))
split_cchs = comm.scatter(split, root=0)
else:
split_cchs = squeezed_cch_array
pair_per_node = len(squeezed_cch_array)
# color_array_inst = np.zeros((cch_per_node, B), dtype=int)
color_array_inst = np.array([], dtype=int)
pair_tau_ids = np.array([0,0,0], dtype=int)
for count, cch in enumerate(split_cchs):
mask = (cch >= threshold)
int_color_cch = (cch[mask] - threshold) / (1. - threshold) * 10.
i,j = pair_ids[count]
if binnums[mask].size:
pair_tau_ids = np.vstack((pair_tau_ids,
np.array([(i,j,t) for t in binnums[mask]])))
color_array_inst = np.append(color_array_inst,
int_color_cch.astype(int))
if mpi:
color_array = comm.gather(color_array_inst, root=0)
if rank == 0:
pop_color_array = color_array
else:
pop_color_array = color_array_inst
return pop_color_array, pair_tau_ids[1:]
def plot_cch_space(self, model, threshold=.05,
palette=sns.cubehelix_palette(10, start=.3, rot=.6),
alpha=False, **kwargs):
# color_array is an sparse int array of the thresholded cchs
# transformed to [0..9] -> 0 is transparent, 1-9 is used for indexing the
# color palette. Since the color_cch is rescaled there is exactly one
# element with value 10, which always projected to k
cch_array = self.generate_cch_array(model.spiketrains, maxlag=None, model=model, **kwargs)
color_array, pair_tau_ids = self._calc_color_array(cch_array, threshold=threshold, **kwargs)
colorarray = np.squeeze(color_array)
N = len(model.spiketrains)
B = len(model.spiketrains[0])
max_cc = np.max(cch_array)
palette = palette + [[0, 0, 0]] # single max value is black
binsize = self.params['binsize']
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.set_xlabel('Neuron i')
ax.set_xlim3d(0, N)
ax.set_ylabel(r'$\tau$ [ms]')
ax.set_ylim3d(-B / 2 * float(binsize), B / 2 * float(binsize))
ax.set_zlabel('Neuron j')
ax.set_zlim3d(0, N)
tau = (np.arange(B) - B / 2) * float(binsize)
for count, (i, j, t) in enumerate(pair_tau_ids):
if alpha:
color = _alpha(palette[colorarray[count]],
1. - colorarray[count] / 10.)
else:
color = palette[colorarray[count]]
if t < 1:
t = 1
print('border value shifted')
elif t == B - 1:
t = B - 2
print('border value shifted')
try:
ax.plot([j, j], tau[t - 1:t + 1], [i, i], c=color)
except:
print('value dropped')
# expects the outer most values for tau not to be significant
cax = plt.gcf().add_subplot(222, aspect=10, anchor=(1.1, .5))
cmap = colors.ListedColormap(palette)
# ticks = np.around(np.linspace(threshold, max_cc, 11))
cb = colorbar.ColorbarBase(cax, cmap=cmap, orientation='vertical')
cax.yaxis.set_visible(True)
cax.yaxis.set_ticks([0,1])
print(max_cc)
cax.set_yticklabels(['{:.2f}'.format(threshold), '{:.2f}'.format(max_cc)])
return ax, palette
def draw_pop_cch(self, model, hist_filter=None, color=None,
bins=100, figsize=8, **kwargs):
if color is None:
color = sns.color_palette()[0]
cch_array = self.generate_cch_array(model.spiketrains, maxlag=None, model=model, **kwargs)
ccharray = copy(np.squeeze(cch_array))
N = len(ccharray)
B = len(ccharray[0])
binsize = self.params['binsize']
w = B / 2 * float(binsize)
tau = np.array(list( | np.linspace(-w, w, B / 2 * 2 + 1) | numpy.linspace |
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import os
from fracdiff import fast_frac_diff
if __name__ == '__main__':
x = np.arange(0, 30, 1)
for i, d in enumerate(np.arange(-1, 1.01, 0.01)):
print(i)
fracs = fast_frac_diff(x, d=d)
a = pd.DataFrame(data=np.transpose([ | np.array(fracs) | numpy.array |
import os
import cv2
import glob
import shutil
import scipy.misc
import numpy as np
import pandas as pd
from PIL import Image
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import xml.etree.ElementTree as ET
from ray.util.multiprocessing import Pool
def f(index):
return index
def get_transform(center, scale, res, pad_scale=2, rot=0):
"""
General image processing functions
"""
# Generate transformation matrix
h = 200 * scale
t = | np.zeros((3, 3)) | numpy.zeros |
# Created by woochanghwang at 18/11/2020
import sys, time
import pandas as pd
import numpy
import networkx, random
import mygene
import multiprocessing as mp
def check_has_path(G,node_from,node_to):
return(networkx.has_path(G,node_from,node_to))
def get_shortest_path_length_between(G, source_id, target_id):
return networkx.shortest_path_length(G, source_id, target_id)
def calculate_closest_distance(network, nodes_from, nodes_to, lengths=None):
values_outer = []
if lengths is None:
for node_from in nodes_from:
values = []
for node_to in nodes_to:
# print("from - to", node_from, node_to)
if not check_has_path(network,node_from,node_to): continue
val = get_shortest_path_length_between(network, node_from, node_to)
values.append(val)
if len(values) == 0: continue
d = min(values)
# print (d)
values_outer.append(d)
else:
for node_from in nodes_from:
values = []
vals = lengths[node_from]
for node_to in nodes_to:
val = vals[node_to]
values.append(val)
d = min(values)
values_outer.append(d)
d = | numpy.mean(values_outer) | numpy.mean |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import itertools
import numpy as np
from scipy import stats
from sklearn import preprocessing
from .geometry import Geometry
from .sampler import sample
class Hypercube(Geometry):
def __init__(self, xmin, xmax):
if len(xmin) != len(xmax):
raise ValueError("Dimensions of xmin and xmax do not match.")
if np.any(np.array(xmin) >= np.array(xmax)):
raise ValueError("xmin >= xmax")
self.xmin, self.xmax = np.array(xmin), np.array(xmax)
self.side_length = self.xmax - self.xmin
super(Hypercube, self).__init__(
len(xmin), (self.xmin, self.xmax), np.linalg.norm(self.side_length)
)
self.volume = np.prod(self.side_length)
def inside(self, x):
return np.logical_and(
np.all(x >= self.xmin, axis=-1), np.all(x <= self.xmax, axis=-1)
)
def on_boundary(self, x):
_on_boundary = np.logical_or(
np.any(np.isclose(x, self.xmin), axis=-1),
np.any(np.isclose(x, self.xmax), axis=-1),
)
return np.logical_and(self.inside(x), _on_boundary)
def boundary_normal(self, x):
_n = np.isclose(x, self.xmin) * -1.0 + np.isclose(x, self.xmax) * 1.0
# For vertices, the normal is averaged for all directions
idx = np.count_nonzero(_n, axis=-1) > 1
if | np.any(idx) | numpy.any |
"""
Code based on random_transform in keras.processing.image from 2016.
(https://github.com/fchollet/keras)
Keras copyright:
All contributions by <NAME>: Copyright (c) 2015, <NAME>.
All contributions by Google: Copyright (c) 2015, Google, Inc.
All contributions by Microsoft: Copyright (c) 2017, Microsoft, Inc.
All other contributions: Copyright (c) 2015-2017, the respective contributors.
(All rights reserved by copyright holders of all contributions.)
Modified:
Copyright 2017, <NAME>
Copyright 2016, <NAME>
Copyright 2016, <NAME>
"""
import os
import numpy as np
import scipy.ndimage as ndi
import SimpleITK as sitk
"""
Apply data augmentation to all images in an N-dimensional stack. Assumes the
final two axes are spatial axes (not considering the channel axis).
Arguments are as defined for image_random_transform.
"""
def image_stack_random_transform(x, *args, y=None, channel_axis=1, **kwargs):
# Make sure these are numpy arrays.
x_arr = np.array(x)
if y is not None:
y_arr = np.array(y)
x_shape = list(x_arr.shape)
y_shape = list(y_arr.shape)
x_shape[channel_axis] = None
y_shape[channel_axis] = None
if x_shape!=y_shape:
raise ValueError("Error: inputs x and y to "
"image_stack_random_transform must have the same "
"shape. Shapes are {} and {} for x, y."
"".format(x_arr.shape, y_arr.shape))
# Move channel axis to just before spatial axes.
std_channel_axis = x_arr.ndim-1-2
if channel_axis!=std_channel_axis:
x_arr = np.moveaxis(x_arr, source=channel_axis,
destination=std_channel_axis)
if y is not None:
x_arr = np.moveaxis(y_arr, source=channel_axis,
destination=std_channel_axis)
# Compute indices to iterate over (everything except channel and spatial).
x_indices = np.ndindex(x_arr.shape[:-3])
if y is not None:
y_indices = np.ndindex(y_arr.shape[:-3])
# Random transform on each value.
x_out, y_out = None, None
if y is not None:
for idx_x, idx_y in zip(np.ndindex(x_arr.shape[:-3]),
np.ndindex(y_arr.shape[:-3])):
xt, yt = image_random_transform(x_arr[idx_x], y_arr[idx_y],
*args, channel_axis=0, **kwargs)
out_shape_x = x_arr.shape[:-2]+xt.shape[-2:]
out_shape_y = y_arr.shape[:-2]+xt.shape[-2:]
if x_out is None:
x_out = np.zeros(out_shape_x, dtype=np.float32)
if y_out is None:
y_out = np.zeros(out_shape_y, dtype=np.float32)
x_out[idx_x], y_out[idx_y] = xt, yt
else:
for idx_x in np.ndindex(x_arr.shape[:-3]):
xt = image_random_transform(x_arr[idx_x],
*args, channel_axis=0, **kwargs)
out_shape = x_arr.shape[:-2]+xt.shape[-2:]
if x_out is None:
x_out = np.zeros(out_shape, dtype=np.float32)
x_out[idx_x] = xt
# Move channel axis back to where it was.
if channel_axis!=std_channel_axis:
x_out = np.moveaxis(x_out, source=std_channel_axis,
destination=channel_axis)
if y is not None:
y_out = np.moveaxis(y_out, source=std_channel_axis,
destination=channel_axis)
if y is not None:
return x_out, y_out
return x_out
"""
Data augmentation for 2D images using random image transformations. This code
handles on input images alone or jointly on input images and their
corresponding output images (eg. input images and corresponding segmentation
masks).
x : A single 2D input image (ndim=3, channel and 2 spatial dims).
y : A single output image or mask.
rotation_range : Positive degree value, specifying the maximum amount to rotate
the image in any direction about its center.
width_shift_range : Float specifying the maximum distance by which to shift the
image horizontally, as a fraction of the image's width.
height_shift_range : Float specifying the maximum distance by which to shift
the image vertically, as a fraction of the image's height.
shear_range : Positive degree value, specifying the maximum horizontal sheer of
the image.
zoom_range : The maximum absolute deviation of the image scale from one.
(I.e. zoom_range of 0.2 allows zooming the image to scales within the
range [0.8, 1.2]).
intensity_shift_range : The maximum absolute value by which to shift image
intensities up or down.
fill_mode : Once an image is spatially transformed, fill any empty space with
the 'nearest', 'reflect', or 'constant' strategy. Mode 'nearest' fills the
space with the values of the nearest pixels; mode 'reflect' fills the space
with a mirror image of the image along its nearest border or corner;
'constant' fills it with the constant value defined in `cval`.
cval : The constant value with which to fill any empty space in a transformed
input image when using `fill_mode='constant'`.
cvalMask : The constant value with which to fill any empty space in a
transformed target image when using `fill_mode='constant'`.
horizontal_flip : Boolean, whether to randomly flip images horizontally.
vertical_flip : Boolean, whether to randomly flip images vertically.
spline_warp : Boolean, whether to apply a b-spline nonlineary warp.
warp_sigma : Standard deviation of control point jitter in spline warp.
warp_grid_size : Integer s specifying an a grid with s by s control points.
crop_size : Tuple specifying the size of random crops taken of transformed
images. Crops are always taken from within the transformed image, with no
padding.
channel_axis : The axis in the input images that corresponds to the channel.
Remaining axes are the two spatial axes.
rng : A numpy random number generator.
"""
def image_random_transform(x, y=None, rotation_range=0., width_shift_range=0.,
height_shift_range=0., shear_range=0.,
zoom_range=0., intensity_shift_range=0.,
fill_mode='nearest', cval_x=0., cval_y=0.,
horizontal_flip=False, vertical_flip=False,
spline_warp=False, warp_sigma=0.1, warp_grid_size=3,
crop_size=None, channel_axis=0, n_warp_threads=None,
rng=None):
# Set random number generator
if rng is None:
rng = np.random.RandomState()
# x is a single image, so we don't have batch dimension
assert(x.ndim == 3)
if y is not None:
assert(y.ndim == 3)
img_row_index = 1
img_col_index = 2
img_channel_index = channel_axis
# Nonlinear spline warping
if spline_warp:
if n_warp_threads is None:
n_warp_threads = os.cpu_count()
warp_field = _gen_warp_field(shape=x.shape[-2:],
sigma=warp_sigma,
grid_size=warp_grid_size,
n_threads=n_warp_threads,
rng=rng)
x = _apply_warp(x, warp_field,
interpolator=sitk.sitkNearestNeighbor,
fill_mode=fill_mode,
cval=cval_x,
n_threads=n_warp_threads)
if y is not None:
y = np.round(_apply_warp(y, warp_field,
interpolator=sitk.sitkNearestNeighbor,
fill_mode=fill_mode,
cval=cval_y,
n_threads=n_warp_threads))
# use composition of homographies to generate final transform that needs
# to be applied
if np.isscalar(zoom_range):
zoom_range = [1 - zoom_range, 1 + zoom_range]
elif len(zoom_range) == 2:
zoom_range = [zoom_range[0], zoom_range[1]]
else:
raise Exception('zoom_range should be a float or '
'a tuple or list of two floats. '
'Received arg: ', zoom_range)
if zoom_range[0] == 1 and zoom_range[1] == 1:
zx, zy = 1, 1
else:
zx, zy = rng.uniform(zoom_range[0], zoom_range[1], 2)
zoom_matrix = np.array([[zx, 0, 0],
[0, zy, 0],
[0, 0, 1]])
if rotation_range:
theta = np.pi / 180 * rng.uniform(-rotation_range, rotation_range)
else:
theta = 0
rotation_matrix = np.array([[np.cos(theta), -np.sin(theta), 0],
[np.sin(theta), np.cos(theta), 0],
[0, 0, 1]])
if height_shift_range:
tx = rng.uniform(-height_shift_range, height_shift_range) \
* x.shape[img_row_index]
else:
tx = 0
if width_shift_range:
ty = rng.uniform(-width_shift_range, width_shift_range) \
* x.shape[img_col_index]
else:
ty = 0
translation_matrix = np.array([[1, 0, tx],
[0, 1, ty],
[0, 0, 1]])
if shear_range:
shear = np.pi / 180 * rng.uniform(-shear_range, shear_range)
else:
shear = 0
shear_matrix = np.array([[1, -np.sin(shear), 0],
[0, np.cos(shear), 0],
[0, 0, 1]])
transform_matrix = np.dot(np.dot(np.dot(rotation_matrix, shear_matrix),
translation_matrix), zoom_matrix)
h, w = x.shape[img_row_index], x.shape[img_col_index]
transform_matrix = _transform_matrix_offset_center(transform_matrix, h, w)
x = _apply_transform_matrix(x, transform_matrix, img_channel_index,
fill_mode=fill_mode, cval=cval_x)
if y is not None:
y = _apply_transform_matrix(y, transform_matrix, img_channel_index,
fill_mode=fill_mode, cval=cval_y)
if intensity_shift_range != 0:
x = _random_intensity_shift(x, intensity_shift_range, img_channel_index,
rng=rng)
if horizontal_flip:
if rng.random_sample() < 0.5:
x = _flip_axis(x, img_col_index)
if y is not None:
y = _flip_axis(y, img_col_index)
if vertical_flip:
if rng.random_sample() < 0.5:
x = _flip_axis(x, img_row_index)
if y is not None:
y = _flip_axis(y, img_row_index)
# Crop
crop = list(crop_size) if crop_size else None
if crop:
h, w = x.shape[img_row_index], x.shape[img_col_index]
if crop[0] < h:
top = rng.randint(h - crop[0])
else:
print('Data augmentation: Crop height >= image size')
top, crop[0] = 0, h
if crop[1] < w:
left = rng.randint(w - crop[1])
else:
print('Data augmentation: Crop width >= image size')
left, crop[1] = 0, w
x = x[:, top:top+crop[0], left:left+crop[1]]
if y is not None:
y = y[:, top:top+crop[0], left:left+crop[1]]
if y is None:
return x
else:
return x, y
def _transform_matrix_offset_center(matrix, x, y):
o_x = float(x) / 2 + 0.5
o_y = float(y) / 2 + 0.5
offset_matrix = np.array([[1, 0, o_x],
[0, 1, o_y],
[0, 0, 1]])
reset_matrix = np.array([[1, 0, -o_x],
[0, 1, -o_y],
[0, 0, 1]])
transform_matrix = np.dot(np.dot(offset_matrix, matrix), reset_matrix)
return transform_matrix
def _apply_transform_matrix(x, transform_matrix, channel_index=0,
fill_mode='nearest', cval=0.):
x_ = np.copy(x)
x_ = np.rollaxis(x_, channel_index, 0)
final_affine_matrix = transform_matrix[:2, :2]
final_offset = transform_matrix[:2, 2]
channel_images = [ndi.interpolation.affine_transform(\
x_channel, final_affine_matrix, final_offset,
order=0, mode=fill_mode, cval=cval)\
for x_channel in x_]
x_out = np.stack(channel_images, axis=0)
x_out = np.rollaxis(x_out, 0, channel_index+1)
return x_out
def _random_intensity_shift(x, intensity, channel_index=0, rng=None):
x_ = np.copy(x)
x_ = np.rollaxis(x_, channel_index, 0)
channel_images = [np.clip(x_channel + \
rng.uniform(-intensity, intensity),
np.min(x_), np.max(x_)) for x_channel in x_]
x_out = np.stack(channel_images, axis=0)
x_out = np.rollaxis(x_out, 0, channel_index+1)
return x_out
def _flip_axis(x, axis):
x_ = np.copy(x)
x_ = np.asarray(x_).swapaxes(axis, 0)
x_ = x_[::-1, ...]
x_ = x_.swapaxes(0, axis)
x_out = x_
return x_out
def _gen_warp_field(shape, sigma=0.1, grid_size=3, n_threads=1, rng=None):
# Initialize bspline transform
args = shape+(sitk.sitkFloat32,)
ref_image = sitk.Image(*args)
tx = sitk.BSplineTransformInitializer(ref_image, [grid_size, grid_size])
# Initialize shift in control points:
# mesh size = number of control points - spline order
p = sigma * rng.randn(grid_size+3, grid_size+3, 2)
# Anchor the edges of the image
p[:, 0, :] = 0
p[:, -1:, :] = 0
p[0, :, :] = 0
p[-1:, :, :] = 0
# Set bspline transform parameters to the above shifts
tx.SetParameters(p.flatten())
# Compute deformation field
displacement_filter = sitk.TransformToDisplacementFieldFilter()
displacement_filter.SetReferenceImage(ref_image)
displacement_filter.SetNumberOfThreads(n_threads)
displacement_field = displacement_filter.Execute(tx)
return displacement_field
def _pad_image(x, pad_amount, mode='reflect', cval=0.):
e = pad_amount
assert(len(x.shape)>=2)
shape = list(x.shape)
shape[:2] += 2*e
if mode == 'constant':
x_padded = np.ones(shape, dtype=np.float32)*cval
x_padded[e:-e, e:-e] = x.copy()
else:
x_padded = np.zeros(shape, dtype=np.float32)
x_padded[e:-e, e:-e] = x.copy()
if mode == 'reflect':
x_padded[:e, e:-e] = np.flipud(x[:e, :]) # left edge
x_padded[-e:, e:-e] = np.flipud(x[-e:, :]) # right edge
x_padded[e:-e, :e] = np.fliplr(x[:, :e]) # top edge
x_padded[e:-e, -e:] = np.fliplr(x[:, -e:]) # bottom edge
x_padded[:e, :e] = np.fliplr(np.flipud(x[:e, :e])) # top-left corner
x_padded[-e:, :e] = np.fliplr(np.flipud(x[-e:, :e])) # top-right
x_padded[:e, -e:] = np.fliplr(np.flipud(x[:e, -e:])) # bottom-left
x_padded[-e:, -e:] = np.fliplr(np.flipud(x[-e:, -e:])) # bottom-right
elif mode == 'zero' or mode == 'constant':
pass
elif mode == 'nearest':
x_padded[:e, e:-e] = x[[0], :] # left edge
x_padded[-e:, e:-e] = x[[-1], :] # right edge
x_padded[e:-e, :e] = x[:, [0]] # top edge
x_padded[e:-e, -e:] = x[:, [-1]] # bottom edge
x_padded[:e, :e] = x[[0], [0]] # top-left corner
x_padded[-e:, :e] = x[[-1], [0]] # top-right corner
x_padded[:e, -e:] = x[[0], [-1]] # bottom-left corner
x_padded[-e:, -e:] = x[[-1], [-1]] # bottom-right corner
else:
raise ValueError("Unsupported padding mode \"{}\"".format(mode))
return x_padded
def _apply_warp(x, warp_field, fill_mode='reflect',
interpolator=sitk.sitkLinear,
cval=0, channel_index=0, n_threads=1):
# Expand deformation field (and later the image), padding for the largest
# deformation
warp_field_arr = sitk.GetArrayFromImage(warp_field)
max_deformation = np.max( | np.abs(warp_field_arr) | numpy.abs |
# -*- coding: utf-8 -*-
#
# wavファイルの一部の区間をフーリエ変換し,
# 振幅スペクトルをプロットします.
#
# wavデータを読み込むためのモジュール(wave)をインポート
import wave
# 数値演算用モジュール(numpy)をインポート
import numpy as np
# プロット用モジュール(matplotlib)をインポート
import matplotlib.pyplot as plt
#
# メイン関数
#
if __name__ == "__main__":
# 開くwavファイル
wav_file = '../data/wav/BASIC5000_0001.wav'
# 分析する時刻.BASIC5000_0001.wav では,
# 以下の時刻は音素"o"を発話している
target_time = 0.58
# FFT(高速フーリエ変換)を行う範囲のサンプル数
# 2のべき乗である必要がある
fft_size = 1024
# プロットを出力するファイル(pngファイル)
out_plot = './pre_emphasis.png'
# wavファイルを開き、以降の処理を行う
with wave.open(wav_file) as wav:
# サンプリング周波数 [Hz] を取得
sampling_frequency = wav.getframerate()
# wavデータを読み込む
waveform = wav.readframes(wav.getnframes())
# 読み込んだデータはバイナリ値(16bit integer)
# なので,数値(整数)に変換する
waveform = np.frombuffer(waveform, dtype=np.int16)
# 分析する時刻をサンプル番号に変換
target_index = | np.int(target_time * sampling_frequency) | numpy.int |
from typing import Tuple
import numpy as np
import pandas as pd
from scipy import interpolate
_YOUNG_MODULES = {
'concrete': 2.05e4,
'steel': 2.05e5
}
def get_results(mode, condition, bottom_condition, material, diameter, length, level, force, soil_data, div_num) -> dict:
diameter = float(diameter) # mm
length = float(length) * 1e3 # to mm
level = float(level) * 1e3 # to mm
force = float(force) * 1e3 # to N
div_num = int(div_num)
div_size = length / div_num
x = np.linspace(-level, length - level, div_num + 1)
kh0s = kh_by_soil_data(diameter, x, soil_data)
stiffness = pile_stiffness(diameter, diameter, 0, material)
k0 = top_condition_to_stiffness(mode, condition, bottom_condition, div_num, div_size, stiffness, diameter, kh0s, force)
y, dec = solve_y(mode, bottom_condition, div_num, div_size, stiffness, diameter, kh0s, k0, force)
t = np.gradient(y, div_size) # solve degree
m = -np.gradient(t, div_size) * stiffness # solve moment
q = np.gradient(m, div_size) # solve shear
q[2] = -force
return dict(
x=x / 1e3, # m
dec=dec,
kh0s=kh0s * 1e6, # kN/m3 (低減前の地盤反力係数)
y=y[2:-2], # mm
t=t[2:-2] * 1e3, # x10^3 rad
m=m[2:-2] / 1e6, # kNm
q=q[2:-2] / 1e3 # kN
)
def kh_by_soil_data(diameter: float, x: np.ndarray, soil_data: dict):
depth = np.array(soil_data.get('depth')) * 1e3
alpha = np.array(soil_data.get('alpha'))
beta = np.array(soil_data.get('adopted_reductions'))
E0 = np.array(soil_data.get('E0'))
kh = alpha * beta * E0 * (diameter / 10) ** (-3 / 4)
fitted = interpolate.interp1d(depth, kh) # 線形補間
fitted_kh = fitted(x)
return fitted_kh / 1e6 # N/mm2
def top_condition_to_stiffness(mode, condition, bottom_condition, div_num, div_size, stiffness, diameter, kh0s, force) -> float:
condition = float(condition)
if condition == 1.0:
k0 = np.inf
elif condition == 0.0:
k0 = 10e-15
else:
k0 = half_condition_solver(mode, bottom_condition, condition, div_num, div_size, stiffness, diameter, kh0s, force)
return k0
def half_condition_solver(mode, bottom_condition, condition, div_num, div_size, stiffness, diameter, kh0s, force):
y_at_fix, _ = solve_y(mode, bottom_condition, div_num, div_size, stiffness, diameter, kh0s, np.inf, force)
y_at_pin, _ = solve_y(mode, bottom_condition, div_num, div_size, stiffness, diameter, kh0s, 10e-15, force)
moment_at_fix = -np.gradient(np.gradient(y_at_fix, div_size), div_size)[2] * stiffness
degree_at_pin = np.gradient(y_at_pin, div_size)[2]
condition = float(condition)
half_moment = moment_at_fix * condition
half_degree = degree_at_pin * (1 - condition)
k0 = half_moment / half_degree
err = 1.1e6
while err > 1.0e6:
y, _ = solve_y(mode, bottom_condition, div_num, div_size, stiffness, diameter, kh0s, k0, force)
m = -np.gradient(np.gradient(y, div_size), div_size)[2] * stiffness
err = m - half_moment
k0 = k0 * half_moment / m
return k0
def pile_stiffness(diameter: float, thickness: float, thickness_margin: float, material: str) -> float:
sec1 = np.pi * (diameter - thickness_margin * 2) ** 4 / 64
sec2 = np.pi * (diameter - thickness) ** 4 / 64
return (sec1 - sec2) * _YOUNG_MODULES.get(material)
def solve_y(mode, bottom_condition, div_num, div_size, stiffness, diameter, kh0s, k0, force):
if mode == 'liner':
y, dec = deformation_analysis_by_FDM(bottom_condition, div_num, div_size, stiffness, diameter, kh0s, k0, force)
elif mode == 'non_liner':
y, dec = deformation_analysis_by_non_liner_FDM(bottom_condition, div_num, div_size, stiffness, diameter, kh0s, k0, force)
elif mode == 'non_liner_single':
y, dec = deformation_analysis_by_non_liner_single_FDM(bottom_condition, div_num, div_size, stiffness, diameter, kh0s, k0, force)
else:
y, dec = deformation_analysis_by_FDM(bottom_condition, div_num, div_size, stiffness, diameter, kh0s, k0, force)
return y, dec
def deformation_analysis_by_FDM(bottom_condition, div_num: int, div_size: float, stiffness: float, diameter: float, khs: np.ndarray, k0: float, force: float) -> Tuple[np.ndarray, np.ndarray]:
def _left_matrix(bottom_condition, n, h, ei, b, khs, k0):
left = np.zeros((n + 5, n + 5))
# head row
left[0, 0:5] = [-1, 2, 0, -2, 1]
left[1, 0:5] = [0, ei / k0 - h, -2 * ei / k0, ei / k0 + h, 0]
# general row
c1s = 6 + h ** 4 * khs * b / ei
for i in range(2, n + 3):
left[i, i - 2:i + 3] = [1, -4, c1s[i - 2], -4, 1]
# tail row
if bottom_condition == "free":
left[-1, -5:] = [-1, 2, 0, -2, 1]
left[-2, -5:] = [0, 1, -2, 1, 0]
elif bottom_condition == "pin":
left[-1, -5:] = [1, 0, 1, 0, 1]
left[-2, -5:] = [0, 1, 1, 1, 0]
else:
left[-1, -5:] = [1, 0, 1, 0, 1]
left[-2, -5:] = [0, 1, 1, 1, 0]
return left
def _right_matrix(n, h, ei, force):
right = np.zeros(n + 5)
right[0] = -2 * force * h ** 3 / ei
return right
left = _left_matrix(bottom_condition, div_num, div_size, stiffness, diameter, khs, k0)
right = _right_matrix(div_num, div_size, stiffness, force)
y = -np.linalg.solve(left, right) # 連立方程式を解く
dec = np.ones_like(y) # 低減係数(線形計算の場合は1.0)
return y, dec
def deformation_analysis_by_non_liner_FDM(bottom_condition, div_num: int, div_size: float, stiffness: float, diameter: float, khs: np.ndarray, k0: float, force: float) -> Tuple[np.ndarray, np.ndarray]:
dec_khs = khs
y, _ = deformation_analysis_by_FDM(bottom_condition, div_num, div_size, stiffness, diameter, khs, k0, force) # 初期値
err = np.ones_like(khs)
dec = err
while np.any(err > 0.1):
dec = np.where(np.abs(y) > 10, (np.abs(y) / 10) ** (-1 / 2), 1.0) # 地盤の非線形考慮
dec_khs = khs * dec[2:-2]
new_y, _ = deformation_analysis_by_FDM(bottom_condition, div_num, div_size, stiffness, diameter, dec_khs, k0, force)
err = np.abs(new_y - y)
y = new_y
return y, dec
def deformation_analysis_by_non_liner_single_FDM(bottom_condition, div_num: int, div_size: float, stiffness: float, diameter: float, khs: np.ndarray, k0: float, force: float) -> Tuple[np.ndarray, np.ndarray]:
dec_khs = khs
y, _ = deformation_analysis_by_FDM(bottom_condition, div_num, div_size, stiffness, diameter, khs, k0, force) # 初期値
err = np.ones_like(khs)
dec = err
while np.any(err > 0.1):
dec = np.where( | np.abs(y) | numpy.abs |
#!/usr/bin/env python3
'''
Use custom_utils.sample_cube_surface_points and visualize the sampled points
'''
import random
from .training_env import make_training_env
import numpy as np
import pybullet as p
import time
from .utils import apply_transform, CylinderMarker, VisualCubeOrientation
from rrc_simulation import TriFingerPlatform
from rrc_simulation.gym_wrapper.envs import cube_env
from .training_env.wrappers import RenderWrapper
from gym.wrappers import Monitor, TimeLimit
import gym
from .grasping import Cube, CoulombFriction, Transform, CubePD, get_rotation_between_vecs, Contact, PDController
from .save_video import merge_videos
from .utils import set_seed, action_type_to
import argparse
def get_contacts(T):
contacts = [Contact(c, T) for c in p.getContactPoints()]
# arm body_id = 1, cube_body_id = 4
contacts = [c for c in contacts if c.bodyA == 1 and c.bodyB == 4]
return [c for c in contacts if c.linkA % 5 == 0] # just look at tip contacts
def get_torque_shrink_coef(org_torque, add_torque):
slack = 0.36 - org_torque
neg_torque = np.sign(add_torque) == -1
slack[neg_torque] = 0.36 + org_torque[neg_torque]
slack[np.isclose(slack, 0.0)] = 0 # avoid numerical instability
assert np.all(slack >= 0), f'slack: {slack}'
ratio = slack / np.abs(add_torque)
return min(1.0, np.min(ratio))
# def get_tip_forces(obs, wrench):
# cube = Cube(0.0325, CoulombFriction(mu=1.0))
# T_cube_to_base = Transform(pos=obs['object_position'],
# ori=obs['object_orientation'])
# R_cube_to_base = Transform(pos=np.zeros(3), ori=obs['object_orientation'])
# T_base_to_cube = T_cube_to_base.inverse()
# contacts = get_contacts(T_base_to_cube)
# if len(contacts) == 0:
# return get_tip_forces_back_up(obs, wrench)
# forces = cube.solve_for_tip_forces([c.TA for c in contacts], wrench)
# if forces is None:
# return get_tip_forces_back_up(obs, wrench)
#
# # print(forces)
# tips_cube_frame = T_base_to_cube(obs['robot_tip_positions'])
# wrench_at_tips = np.zeros((3, 6))
# for f, c in zip(forces, contacts):
# ind = (c.linkA - 1) // 5
# T = Transform(pos=tips_cube_frame[ind] - c.contact_posA,
# ori=np.array([0, 0, 0, 1]))
# # rotate from contact frame to cube_frame
# f[:3] = c.TA.adjoint().dot(f)[:3]
# # translate to tip position and rotate to world axes
# f = R_cube_to_base(T).adjoint().dot(f)
#
# # add to tip wrenches
# wrench_at_tips[ind] += f
# # print(wrench_at_tips)
# return wrench_at_tips
class Viz(object):
def __init__(self):
self.goal_viz = None
self.cube_viz = None
self.initialized = False
self.markers = []
def reset(self, obs):
if self.goal_viz:
del self.goal_viz
del self.cube_viz
self.goal_viz = VisualCubeOrientation(obs['goal_object_position'],
obs['goal_object_orientation'])
self.cube_viz = VisualCubeOrientation(obs['object_position'],
obs['object_orientation'])
if self.markers:
for m in self.markers:
del m
self.markers = []
self.initialized = True
def update_cube_orientation(self, obs):
self.cube_viz.set_state(obs['object_position'],
obs['object_orientation'])
def update_tip_force_markers(self, obs, tip_wrenches, force):
cube_force = apply_transform(np.zeros(3), obs['object_orientation'],
force[None])[0]
self._set_markers([w[:3] for w in tip_wrenches],
obs['robot_tip_positions'],
cube_force, obs['object_position'])
def _set_markers(self, forces, tips, cube_force, cube_pos):
from const import FORCE_COLOR_RED, FORCE_COLOR_GREEN, FORCE_COLOR_BLUE
R = 0.005
L = 0.2
ms = []
cube_force = cube_force / np.linalg.norm(cube_force)
force_colors = [FORCE_COLOR_RED, FORCE_COLOR_GREEN, FORCE_COLOR_BLUE]
q = get_rotation_between_vecs(np.array([0, 0, 1]), cube_force)
if not self.markers:
ms.append(CylinderMarker(R, L, cube_pos + 0.5 * L * cube_force,
q, color=(0, 0, 1, 0.5)))
else:
self.markers[0].set_state(cube_pos + 0.5 * L * cube_force, q)
ms.append(self.markers[0])
for i, (f, t) in enumerate(zip(forces, tips)):
f = f / np.linalg.norm(f)
q = get_rotation_between_vecs(np.array([0, 0, 1]), f)
if not self.markers:
color = force_colors[i]
ms.append(CylinderMarker(R, L, t + 0.5 * L * f,
q, color=color))
else:
self.markers[i+1].set_state(t + 0.5 * L * f, q)
ms.append(self.markers[i+1])
self.markers = ms
class TipPD(object):
def __init__(self, gains, tips_cube_frame, max_force=1.0):
self.pd_tip1 = PDController(*gains)
self.pd_tip2 = PDController(*gains)
self.pd_tip3 = PDController(*gains)
self.tips_cube_frame = tips_cube_frame
self.max_force = max_force
def _scale(self, x, lim):
norm = np.linalg.norm(x)
if norm > lim:
return x * lim / norm
return x
def __call__(self, obs):
tips = obs['robot_tip_positions']
goal_tips = apply_transform(obs['object_position'],
obs['object_orientation'],
self.tips_cube_frame)
f = [self.pd_tip1(goal_tips[0] - tips[0]),
self.pd_tip2(goal_tips[1] - tips[1]),
self.pd_tip3(goal_tips[2] - tips[2])]
return [self._scale(ff, self.max_force) for ff in f]
class ForceControlPolicy(object):
def __init__(self, env, apply_torques=True, tip_pd=None, mu=1.0,
grasp_force=0.0, viz=None, use_inv_dynamics=True):
self.cube_pd = CubePD()
self.tip_pd = tip_pd
self.cube = Cube(0.0325, CoulombFriction(mu=mu))
self.env = env
self.apply_torques = apply_torques
self.viz = viz
self.use_inv_dynamics = use_inv_dynamics
self.grasp_force = grasp_force
def __call__(self, obs, target_pos=None, target_quat=None):
target_pos = obs['goal_object_position'] if target_pos is None else target_pos
target_quat = obs['goal_object_orientation'] if target_quat is None else target_quat
force, torque = self.cube_pd(target_pos,
target_quat,
obs['object_position'],
obs['object_orientation'])
if not self.apply_torques:
torque[:] = 0
wrench_cube_frame = np.concatenate([force, torque])
tip_wrenches = self.get_tip_forces(obs, wrench_cube_frame)
if self.tip_pd:
tip_forces = self.tip_pd(obs)
for i in range(3):
tip_wrenches[i][:3] += tip_forces[i]
if self.viz:
self.viz.update_tip_force_markers(obs, tip_wrenches, force)
Js = self._calc_jacobians(obs)
torque = sum([Js[i].T.dot(tip_wrenches[i]) for i in range(3)])
if self.use_inv_dynamics:
stable_torque = self.inverse_dynamics(
obs, self.env.platform.simfinger.finger_id)
# shrink torque control to be within torque limits
if np.any(np.abs(stable_torque + torque) > 0.36):
slack = 0.36 - stable_torque
neg_torque = np.sign(torque) == -1
slack[neg_torque] = 0.36 + stable_torque[neg_torque]
assert np.all(slack > 0)
ratio = slack / np.abs(torque)
torque = torque * min(1.0, np.min(ratio))
else:
stable_torque = np.zeros_like(torque)
if np.any(np.abs(torque) > 0.36):
torque = torque * 0.36 / np.max(np.abs(torque))
if self.grasp_force != 0:
grasp_torque = self.get_grasp_torque(obs, f=self.grasp_force, Js=Js)
coef = get_torque_shrink_coef(torque + stable_torque, grasp_torque)
grasp_torque = coef * grasp_torque
else:
grasp_torque = torque * 0
# if coef > 0:
# print('grasp torque!!', coef)
return torque + stable_torque + grasp_torque
def get_tip_forces(self, obs, wrench):
T_cube_to_base = Transform(pos=obs['object_position'],
ori=obs['object_orientation'])
tips = obs['robot_tip_positions']
tips_cube_frame = T_cube_to_base.inverse()(tips)
contacts = [self.cube.contact_from_tip_position(tip)
for tip in tips_cube_frame]
tip_forces = self.cube.solve_for_tip_forces(contacts, wrench)
if tip_forces is None:
tip_forces = np.zeros((3, 6))
# Rotate forces to world frame axes.
for i, (f, c) in enumerate(zip(tip_forces, contacts)):
tip_forces[i][:3] = T_cube_to_base(c).adjoint().dot(f)[:3]
return tip_forces
def inverse_dynamics(self, obs, id):
torque = p.calculateInverseDynamics(id, list(obs['robot_position']),
list(obs['robot_velocity']),
[0. for _ in range(9)])
return np.array(torque)
def get_grasp_torque(self, obs, f, Js=None):
if Js is None:
Js = self._calc_jacobians(obs)
tip_to_center = obs['object_position'] - obs['robot_tip_positions']
inward_force_vec = f * (tip_to_center / | np.linalg.norm(obs['robot_tip_positions'] - obs['object_position'], axis=1) | numpy.linalg.norm |
# -*- coding: utf-8 -*-
"""
This is the main python script containing the training loop.
Input hyperparameters can be set up through argparse.
Based on the work:
Deep Flow Prediction - <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME> (TUM)
@author: <NAME> - <EMAIL>
"""
import os, random, argparse, numpy as np, pandas as pd, scipy.io as sio
from pathlib import Path
from os.path import normpath
from itertools import product
from skimage.draw import disk
import torch
import torch.nn as nn
from torch.utils.data import TensorDataset, DataLoader
import torch.optim as optim
from hyperdash import Experiment
#%% Parse arguments
def parseArguments():
parser = argparse.ArgumentParser()
parser.add_argument("--path", "-p", type=str, default='C:\\Users\\Xabier\\PhD\\Frontiers\\GitHub\\unet', #'D:\\PhD\\Frontiers\\GitHub\\unet',
help="Base path with the code and data folders")
parser.add_argument("--data", "-d", type=str, default='ECAP',
help="Choose dataset to be employed when running the code.")
parser.add_argument("--experiment", "-exp", type=str, default='Prueba',
help="Choose the name of the experiment to be logged into hyperdash.")
parser.add_argument("--data_type", "-dt", nargs='+', type=str, default=['c'],
help="Choose data representation. c: Cartesian grid, b: Bullseye plot")
parser.add_argument("--folds", "-f", type=int, default=8,
help="Number of folds if cross-validation == True (Not list).")
parser.add_argument("--num_epoch", "-ep", nargs='+', type=int, default=[300],
help="Number of epochs")
parser.add_argument("--learn_rate", "-lr", nargs='+', type=float, default=[0.001],
help="Learning rate")
parser.add_argument("--batch_size", "-bs", nargs='+',type=int, default=[16],
help="Number of folds if cross-validation == True")
parser.add_argument("--drop_rate", "-dr", nargs='+', type=float, default=[0.1],
help="Drop rate")
parser.add_argument("--exponential", "-expo", nargs='+', type=int, default=[6],
help="Channel exponent to control network size")
parser.add_argument("--decaylr", "-dlr", type=bool, default=False,
help="If True learning rate decay is employed")
parser.add_argument("--split", "-s", nargs='+', type=float, default=[0.8],
help="Training-testing split")
parser.add_argument("--seed", "-se", nargs='+', type=int, default=[None],
help="Random seed")
parser.add_argument("--loss_func", "-loss", nargs='+', type=str, default=['L1'],
help="Loss function. Options 'L1','SmoothL1','MSE")
parser.add_argument("--cross", "-cr", type=bool, default=False,
help="Cross-validation or hyperparameter tuning (Not list)")
parser.add_argument("--results_by", "-rb", nargs='+', type=str, default=[],
help="Activation function. 'elu' or 'relu'")
parser.add_argument("--threshold", "-th", nargs='+', type=float, default=[1,2,3,4,5,6,20,30,50],
help="Thresholds for binary classification")
args = parser.parse_args()
return args
args = parseArguments()
#%% Change dir and import models
os.chdir(args.path+'\\code\\')
data_path = args.path +'\\data\\'
from DfpNet import TurbNetG, weights_init
import utils
#%% Function definitions
def train(loader):
# Set the model in training mode: Just affects to dropout and batchnorm
model.train()
#Epoch loss
loss_all = 0
for data in loader: # Get Batch
# compute LR decay
if decayLr:
currLr = utils.computeLR(epoch, num_epoch, lr*0.1, lr)
if currLr < lr:
for g in optimizer.param_groups:
g['lr'] = currLr
shape, ecap = data
shape, ecap = shape.to(device),ecap.to(device) # Data to GPU
batch_len = shape.shape[0]
optimizer.zero_grad() # Zero out the gradients
output = model(shape) # Forward pass batch
if data_type == 'b':
filt_temp = torch.tensor(filt_l.repeat(batch_len,0)).float().to(device)
ecap,output = torch.mul(ecap,filt_temp), torch.mul(output,filt_temp)
filt_rat= filt_ratio.to(device)
# Compute the batch loss
loss = crit(output, ecap)*filt_rat if data_type == 'b' else crit(output, ecap)
#loss = crit(output, ecap)*filt_rat if data_type == 'b' else crit(output, ecap) # Compute the batch loss
loss.backward() # Calculate gradients (backpropagation)
loss_all += batch_len * loss.item()
optimizer.step() # Update weights
return loss_all / train_len
def evaluate(loader,len_data):
#Set the model for evaluation
model.eval()
loss_all = 0
conf = np.zeros([len(thresholds),4])
with torch.no_grad():
for data in loader:
shape, ecap = data
shape, ecap = shape.to(device),ecap.to(device) # Data to GPU
batch_len = shape.shape[0]
pred = model(shape)
conf += thresholding(pred, ecap)/(ecap.shape[3]**2*ecap.shape[0])
if not data_type == 'c':
filt_temp = torch.tensor(filt_l.repeat(batch_len,0)).float().to(device)
ecap,pred = torch.mul(ecap,filt_temp), torch.mul(pred,filt_temp)
filt_rat= filt_ratio.to(device)
loss = crit(pred, ecap) if data_type == 'c' else crit(pred, ecap)*filt_rat
loss_all += batch_len * loss.item()
return loss_all/len_data, conf/len_data
def predict(loader):
#Set the model for evaluation
model.eval()
predictions = []
labels = []
shape_out = []
with torch.no_grad():
for data in loader:
shape, ecap = data
shape = shape.to(device)
shape_new = shape.detach().squeeze().cpu().numpy()* max_ori + min_ori
if data_type == 'b':
shape_out.append(np.multiply(shape_new,filt))
else:
shape_out.append(shape_new)
# Ground truth
lab = ecap.detach().squeeze().cpu().numpy()
labels.append(lab)
# Prediction
pred = model(shape).squeeze().detach().cpu().numpy()
predictions.append(pred)
return np.array(labels),np.array(predictions), | np.array(shape_out) | numpy.array |
import pytest
import numpy as np
import numpy.testing as npt
import scipy.stats as st
from scipy.special import expit
from scipy import linalg
import numpy.random as nr
import theano
import pymc3 as pm
from pymc3.distributions.distribution import (draw_values,
_DrawValuesContext,
_DrawValuesContextBlocker)
from .helpers import SeededTest
from .test_distributions import (
build_model, Domain, product, R, Rplus, Rplusbig, Runif, Rplusdunif,
Unit, Nat, NatSmall, I, Simplex, Vector, PdMatrix,
PdMatrixChol, PdMatrixCholUpper, RealMatrix, RandomPdMatrix
)
def pymc3_random(dist, paramdomains, ref_rand, valuedomain=Domain([0]),
size=10000, alpha=0.05, fails=10, extra_args=None,
model_args=None):
if model_args is None:
model_args = {}
model = build_model(dist, valuedomain, paramdomains, extra_args)
domains = paramdomains.copy()
for pt in product(domains, n_samples=100):
pt = pm.Point(pt, model=model)
pt.update(model_args)
p = alpha
# Allow KS test to fail (i.e., the samples be different)
# a certain number of times. Crude, but necessary.
f = fails
while p <= alpha and f > 0:
s0 = model.named_vars['value'].random(size=size, point=pt)
s1 = ref_rand(size=size, **pt)
_, p = st.ks_2samp(np.atleast_1d(s0).flatten(),
np.atleast_1d(s1).flatten())
f -= 1
assert p > alpha, str(pt)
def pymc3_random_discrete(dist, paramdomains,
valuedomain=Domain([0]), ref_rand=None,
size=100000, alpha=0.05, fails=20):
model = build_model(dist, valuedomain, paramdomains)
domains = paramdomains.copy()
for pt in product(domains, n_samples=100):
pt = pm.Point(pt, model=model)
p = alpha
# Allow Chisq test to fail (i.e., the samples be different)
# a certain number of times.
f = fails
while p <= alpha and f > 0:
o = model.named_vars['value'].random(size=size, point=pt)
e = ref_rand(size=size, **pt)
o = np.atleast_1d(o).flatten()
e = np.atleast_1d(e).flatten()
observed = dict(zip(*np.unique(o, return_counts=True)))
expected = dict(zip(*np.unique(e, return_counts=True)))
for e in expected.keys():
expected[e] = (observed.get(e, 0), expected[e])
k = np.array([v for v in expected.values()])
if np.all(k[:, 0] == k[:, 1]):
p = 1.
else:
_, p = st.chisquare(k[:, 0], k[:, 1])
f -= 1
assert p > alpha, str(pt)
class TestDrawValues(SeededTest):
def test_draw_scalar_parameters(self):
with pm.Model():
y = pm.Normal('y1', mu=0., sigma=1.)
mu, tau = draw_values([y.distribution.mu, y.distribution.tau])
npt.assert_almost_equal(mu, 0)
npt.assert_almost_equal(tau, 1)
def test_draw_dependencies(self):
with pm.Model():
x = pm.Normal('x', mu=0., sigma=1.)
exp_x = pm.Deterministic('exp_x', pm.math.exp(x))
x, exp_x = draw_values([x, exp_x])
npt.assert_almost_equal(np.exp(x), exp_x)
def test_draw_order(self):
with pm.Model():
x = pm.Normal('x', mu=0., sigma=1.)
exp_x = pm.Deterministic('exp_x', pm.math.exp(x))
# Need to draw x before drawing log_x
exp_x, x = draw_values([exp_x, x])
npt.assert_almost_equal(np.exp(x), exp_x)
def test_draw_point_replacement(self):
with pm.Model():
mu = pm.Normal('mu', mu=0., tau=1e-3)
sigma = pm.Gamma('sigma', alpha=1., beta=1., transform=None)
y = pm.Normal('y', mu=mu, sigma=sigma)
mu2, tau2 = draw_values([y.distribution.mu, y.distribution.tau],
point={'mu': 5., 'sigma': 2.})
npt.assert_almost_equal(mu2, 5)
npt.assert_almost_equal(tau2, 1 / 2.**2)
def test_random_sample_returns_nd_array(self):
with pm.Model():
mu = pm.Normal('mu', mu=0., tau=1e-3)
sigma = pm.Gamma('sigma', alpha=1., beta=1., transform=None)
y = pm.Normal('y', mu=mu, sigma=sigma)
mu, tau = draw_values([y.distribution.mu, y.distribution.tau])
assert isinstance(mu, np.ndarray)
assert isinstance(tau, np.ndarray)
class TestDrawValuesContext:
def test_normal_context(self):
with _DrawValuesContext() as context0:
assert context0.parent is None
context0.drawn_vars['root_test'] = 1
with _DrawValuesContext() as context1:
assert id(context1.drawn_vars) == id(context0.drawn_vars)
assert context1.parent == context0
with _DrawValuesContext() as context2:
assert id(context2.drawn_vars) == id(context0.drawn_vars)
assert context2.parent == context1
context2.drawn_vars['leaf_test'] = 2
assert context1.drawn_vars['leaf_test'] == 2
context1.drawn_vars['root_test'] = 3
assert context0.drawn_vars['root_test'] == 3
assert context0.drawn_vars['leaf_test'] == 2
def test_blocking_context(self):
with _DrawValuesContext() as context0:
assert context0.parent is None
context0.drawn_vars['root_test'] = 1
with _DrawValuesContext() as context1:
assert id(context1.drawn_vars) == id(context0.drawn_vars)
assert context1.parent == context0
with _DrawValuesContextBlocker() as blocker:
assert id(blocker.drawn_vars) != id(context0.drawn_vars)
assert blocker.parent is None
blocker.drawn_vars['root_test'] = 2
with _DrawValuesContext() as context2:
assert id(context2.drawn_vars) == id(blocker.drawn_vars)
assert context2.parent == blocker
context2.drawn_vars['root_test'] = 3
context2.drawn_vars['leaf_test'] = 4
assert blocker.drawn_vars['root_test'] == 3
assert 'leaf_test' not in context1.drawn_vars
assert context0.drawn_vars['root_test'] == 1
class BaseTestCases:
class BaseTestCase(SeededTest):
shape = 5
def setup_method(self, *args, **kwargs):
super().setup_method(*args, **kwargs)
self.model = pm.Model()
def get_random_variable(self, shape, with_vector_params=False, name=None):
if with_vector_params:
params = {key: value * np.ones(self.shape, dtype=np.dtype(type(value))) for
key, value in self.params.items()}
else:
params = self.params
if name is None:
name = self.distribution.__name__
with self.model:
if shape is None:
return self.distribution(name, transform=None, **params)
else:
return self.distribution(name, shape=shape, transform=None, **params)
@staticmethod
def sample_random_variable(random_variable, size):
try:
return random_variable.random(size=size)
except AttributeError:
return random_variable.distribution.random(size=size)
@pytest.mark.parametrize('size', [None, 5, (4, 5)], ids=str)
def test_scalar_parameter_shape(self, size):
rv = self.get_random_variable(None)
if size is None:
expected = 1,
else:
expected = np.atleast_1d(size).tolist()
actual = np.atleast_1d(self.sample_random_variable(rv, size)).shape
assert tuple(expected) == actual
@pytest.mark.parametrize('size', [None, 5, (4, 5)], ids=str)
def test_scalar_shape(self, size):
shape = 10
rv = self.get_random_variable(shape)
if size is None:
expected = []
else:
expected = np.atleast_1d(size).tolist()
expected.append(shape)
actual = np.atleast_1d(self.sample_random_variable(rv, size)).shape
assert tuple(expected) == actual
@pytest.mark.parametrize('size', [None, 5, (4, 5)], ids=str)
def test_parameters_1d_shape(self, size):
rv = self.get_random_variable(self.shape, with_vector_params=True)
if size is None:
expected = []
else:
expected = np.atleast_1d(size).tolist()
expected.append(self.shape)
actual = self.sample_random_variable(rv, size).shape
assert tuple(expected) == actual
@pytest.mark.parametrize('size', [None, 5, (4, 5)], ids=str)
def test_broadcast_shape(self, size):
broadcast_shape = (2 * self.shape, self.shape)
rv = self.get_random_variable(broadcast_shape, with_vector_params=True)
if size is None:
expected = []
else:
expected = np.atleast_1d(size).tolist()
expected.extend(broadcast_shape)
actual = np.atleast_1d(self.sample_random_variable(rv, size)).shape
assert tuple(expected) == actual
@pytest.mark.parametrize('shape', [(), (1,), (1, 1), (1, 2), (10, 10, 1), (10, 10, 2)], ids=str)
def test_different_shapes_and_sample_sizes(self, shape):
prefix = self.distribution.__name__
rv = self.get_random_variable(shape, name='%s_%s' % (prefix, shape))
for size in (None, 1, 5, (4, 5)):
if size is None:
s = []
else:
try:
s = list(size)
except TypeError:
s = [size]
if s == [1]:
s = []
if shape not in ((), (1,)):
s.extend(shape)
e = tuple(s)
a = self.sample_random_variable(rv, size).shape
assert e == a
class TestNormal(BaseTestCases.BaseTestCase):
distribution = pm.Normal
params = {'mu': 0., 'tau': 1.}
class TestTruncatedNormal(BaseTestCases.BaseTestCase):
distribution = pm.TruncatedNormal
params = {'mu': 0., 'tau': 1., 'lower':-0.5, 'upper':0.5}
class TestSkewNormal(BaseTestCases.BaseTestCase):
distribution = pm.SkewNormal
params = {'mu': 0., 'sigma': 1., 'alpha': 5.}
class TestHalfNormal(BaseTestCases.BaseTestCase):
distribution = pm.HalfNormal
params = {'tau': 1.}
class TestUniform(BaseTestCases.BaseTestCase):
distribution = pm.Uniform
params = {'lower': 0., 'upper': 1.}
class TestTriangular(BaseTestCases.BaseTestCase):
distribution = pm.Triangular
params = {'c': 0.5, 'lower': 0., 'upper': 1.}
class TestWald(BaseTestCases.BaseTestCase):
distribution = pm.Wald
params = {'mu': 1., 'lam': 1., 'alpha': 0.}
class TestBeta(BaseTestCases.BaseTestCase):
distribution = pm.Beta
params = {'alpha': 1., 'beta': 1.}
class TestKumaraswamy(BaseTestCases.BaseTestCase):
distribution = pm.Kumaraswamy
params = {'a': 1., 'b': 1.}
class TestExponential(BaseTestCases.BaseTestCase):
distribution = pm.Exponential
params = {'lam': 1.}
class TestLaplace(BaseTestCases.BaseTestCase):
distribution = pm.Laplace
params = {'mu': 1., 'b': 1.}
class TestLognormal(BaseTestCases.BaseTestCase):
distribution = pm.Lognormal
params = {'mu': 1., 'tau': 1.}
class TestStudentT(BaseTestCases.BaseTestCase):
distribution = pm.StudentT
params = {'nu': 5., 'mu': 0., 'lam': 1.}
class TestPareto(BaseTestCases.BaseTestCase):
distribution = pm.Pareto
params = {'alpha': 0.5, 'm': 1.}
class TestCauchy(BaseTestCases.BaseTestCase):
distribution = pm.Cauchy
params = {'alpha': 1., 'beta': 1.}
class TestHalfCauchy(BaseTestCases.BaseTestCase):
distribution = pm.HalfCauchy
params = {'beta': 1.}
class TestGamma(BaseTestCases.BaseTestCase):
distribution = pm.Gamma
params = {'alpha': 1., 'beta': 1.}
class TestInverseGamma(BaseTestCases.BaseTestCase):
distribution = pm.InverseGamma
params = {'alpha': 0.5, 'beta': 0.5}
class TestChiSquared(BaseTestCases.BaseTestCase):
distribution = pm.ChiSquared
params = {'nu': 2.}
class TestWeibull(BaseTestCases.BaseTestCase):
distribution = pm.Weibull
params = {'alpha': 1., 'beta': 1.}
class TestExGaussian(BaseTestCases.BaseTestCase):
distribution = pm.ExGaussian
params = {'mu': 0., 'sigma': 1., 'nu': 1.}
class TestVonMises(BaseTestCases.BaseTestCase):
distribution = pm.VonMises
params = {'mu': 0., 'kappa': 1.}
class TestGumbel(BaseTestCases.BaseTestCase):
distribution = pm.Gumbel
params = {'mu': 0., 'beta': 1.}
class TestLogistic(BaseTestCases.BaseTestCase):
distribution = pm.Logistic
params = {'mu': 0., 's': 1.}
class TestLogitNormal(BaseTestCases.BaseTestCase):
distribution = pm.LogitNormal
params = {'mu': 0., 'sigma': 1.}
class TestBinomial(BaseTestCases.BaseTestCase):
distribution = pm.Binomial
params = {'n': 5, 'p': 0.5}
class TestBetaBinomial(BaseTestCases.BaseTestCase):
distribution = pm.BetaBinomial
params = {'n': 5, 'alpha': 1., 'beta': 1.}
class TestBernoulli(BaseTestCases.BaseTestCase):
distribution = pm.Bernoulli
params = {'p': 0.5}
class TestDiscreteWeibull(BaseTestCases.BaseTestCase):
distribution = pm.DiscreteWeibull
params = {'q': 0.25, 'beta': 2.}
class TestPoisson(BaseTestCases.BaseTestCase):
distribution = pm.Poisson
params = {'mu': 1.}
class TestNegativeBinomial(BaseTestCases.BaseTestCase):
distribution = pm.NegativeBinomial
params = {'mu': 1., 'alpha': 1.}
class TestConstant(BaseTestCases.BaseTestCase):
distribution = pm.Constant
params = {'c': 3}
class TestZeroInflatedPoisson(BaseTestCases.BaseTestCase):
distribution = pm.ZeroInflatedPoisson
params = {'theta': 1., 'psi': 0.3}
class TestZeroInflatedNegativeBinomial(BaseTestCases.BaseTestCase):
distribution = pm.ZeroInflatedNegativeBinomial
params = {'mu': 1., 'alpha': 1., 'psi': 0.3}
class TestZeroInflatedBinomial(BaseTestCases.BaseTestCase):
distribution = pm.ZeroInflatedBinomial
params = {'n': 10, 'p': 0.6, 'psi': 0.3}
class TestDiscreteUniform(BaseTestCases.BaseTestCase):
distribution = pm.DiscreteUniform
params = {'lower': 0., 'upper': 10.}
class TestGeometric(BaseTestCases.BaseTestCase):
distribution = pm.Geometric
params = {'p': 0.5}
class TestCategorical(BaseTestCases.BaseTestCase):
distribution = pm.Categorical
params = {'p': np.ones(BaseTestCases.BaseTestCase.shape)}
def get_random_variable(self, shape, with_vector_params=False, **kwargs): # don't transform categories
return super().get_random_variable(shape, with_vector_params=False, **kwargs)
def test_probability_vector_shape(self):
"""Check that if a 2d array of probabilities are passed to categorical correct shape is returned"""
p = np.ones((10, 5))
assert pm.Categorical.dist(p=p).random().shape == (10,)
class TestScalarParameterSamples(SeededTest):
def test_bounded(self):
# A bit crude...
BoundedNormal = pm.Bound(pm.Normal, upper=0)
def ref_rand(size, tau):
return -st.halfnorm.rvs(size=size, loc=0, scale=tau ** -0.5)
pymc3_random(BoundedNormal, {'tau': Rplus}, ref_rand=ref_rand)
def test_uniform(self):
def ref_rand(size, lower, upper):
return st.uniform.rvs(size=size, loc=lower, scale=upper - lower)
pymc3_random(pm.Uniform, {'lower': -Rplus, 'upper': Rplus}, ref_rand=ref_rand)
def test_normal(self):
def ref_rand(size, mu, sigma):
return st.norm.rvs(size=size, loc=mu, scale=sigma)
pymc3_random(pm.Normal, {'mu': R, 'sigma': Rplus}, ref_rand=ref_rand)
def test_truncated_normal(self):
def ref_rand(size, mu, sigma, lower, upper):
return st.truncnorm.rvs((lower-mu)/sigma, (upper-mu)/sigma, size=size, loc=mu, scale=sigma)
pymc3_random(pm.TruncatedNormal, {'mu': R, 'sigma': Rplusbig, 'lower':-Rplusbig, 'upper':Rplusbig},
ref_rand=ref_rand)
def test_skew_normal(self):
def ref_rand(size, alpha, mu, sigma):
return st.skewnorm.rvs(size=size, a=alpha, loc=mu, scale=sigma)
pymc3_random(pm.SkewNormal, {'mu': R, 'sigma': Rplus, 'alpha': R}, ref_rand=ref_rand)
def test_half_normal(self):
def ref_rand(size, tau):
return st.halfnorm.rvs(size=size, loc=0, scale=tau ** -0.5)
pymc3_random(pm.HalfNormal, {'tau': Rplus}, ref_rand=ref_rand)
def test_wald(self):
# Cannot do anything too exciting as scipy wald is a
# location-scale model of the *standard* wald with mu=1 and lam=1
def ref_rand(size, mu, lam, alpha):
return st.wald.rvs(size=size, loc=alpha)
pymc3_random(pm.Wald,
{'mu': Domain([1., 1., 1.]), 'lam': Domain(
[1., 1., 1.]), 'alpha': Rplus},
ref_rand=ref_rand)
def test_beta(self):
def ref_rand(size, alpha, beta):
return st.beta.rvs(a=alpha, b=beta, size=size)
pymc3_random(pm.Beta, {'alpha': Rplus, 'beta': Rplus}, ref_rand=ref_rand)
def test_exponential(self):
def ref_rand(size, lam):
return nr.exponential(scale=1. / lam, size=size)
pymc3_random(pm.Exponential, {'lam': Rplus}, ref_rand=ref_rand)
def test_laplace(self):
def ref_rand(size, mu, b):
return st.laplace.rvs(mu, b, size=size)
pymc3_random(pm.Laplace, {'mu': R, 'b': Rplus}, ref_rand=ref_rand)
def test_lognormal(self):
def ref_rand(size, mu, tau):
return np.exp(mu + (tau ** -0.5) * st.norm.rvs(loc=0., scale=1., size=size))
pymc3_random(pm.Lognormal, {'mu': R, 'tau': Rplusbig}, ref_rand=ref_rand)
def test_student_t(self):
def ref_rand(size, nu, mu, lam):
return st.t.rvs(nu, mu, lam**-.5, size=size)
pymc3_random(pm.StudentT, {'nu': Rplus, 'mu': R, 'lam': Rplus}, ref_rand=ref_rand)
def test_cauchy(self):
def ref_rand(size, alpha, beta):
return st.cauchy.rvs(alpha, beta, size=size)
pymc3_random(pm.Cauchy, {'alpha': R, 'beta': Rplusbig}, ref_rand=ref_rand)
def test_half_cauchy(self):
def ref_rand(size, beta):
return st.halfcauchy.rvs(scale=beta, size=size)
pymc3_random(pm.HalfCauchy, {'beta': Rplusbig}, ref_rand=ref_rand)
def test_gamma_alpha_beta(self):
def ref_rand(size, alpha, beta):
return st.gamma.rvs(alpha, scale=1. / beta, size=size)
pymc3_random(pm.Gamma, {'alpha': Rplusbig, 'beta': Rplusbig}, ref_rand=ref_rand)
def test_gamma_mu_sigma(self):
def ref_rand(size, mu, sigma):
return st.gamma.rvs(mu**2 / sigma**2, scale=sigma ** 2 / mu, size=size)
pymc3_random(pm.Gamma, {'mu': Rplusbig, 'sigma': Rplusbig}, ref_rand=ref_rand)
def test_inverse_gamma(self):
def ref_rand(size, alpha, beta):
return st.invgamma.rvs(a=alpha, scale=beta, size=size)
pymc3_random(pm.InverseGamma, {'alpha': Rplus, 'beta': Rplus}, ref_rand=ref_rand)
def test_pareto(self):
def ref_rand(size, alpha, m):
return st.pareto.rvs(alpha, scale=m, size=size)
pymc3_random(pm.Pareto, {'alpha': Rplusbig, 'm': Rplusbig}, ref_rand=ref_rand)
def test_ex_gaussian(self):
def ref_rand(size, mu, sigma, nu):
return nr.normal(mu, sigma, size=size) + | nr.exponential(scale=nu, size=size) | numpy.random.exponential |
'''Trains a simple convnet on the MNIST dataset.
Gets to 99.25% test accuracy after 12 epochs
(there is still a lot of margin for parameter tuning).
16 seconds per epoch on a GRID K520 GPU.
'''
from __future__ import print_function
import keras
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten
from keras.layers import Conv2D, MaxPooling2D
from keras import backend as K
batch_size = 128
num_classes = 10
epochs = 12
# input image dimensions
img_rows, img_cols = 28, 28
# the data, split between train and test sets
(x_train, y_train), (x_test, y_test) = mnist.load_data()
if K.image_data_format() == 'channels_first':
x_train = x_train.reshape(x_train.shape[0], 1, img_rows, img_cols)
x_test = x_test.reshape(x_test.shape[0], 1, img_rows, img_cols)
input_shape = (1, img_rows, img_cols)
else:
x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1)
x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 1)
input_shape = (img_rows, img_cols, 1)
x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
x_train /= 255
x_test /= 255
print('x_train shape:', x_train.shape)
print(x_train.shape[0], 'train samples')
print(x_test.shape[0], 'test samples')
# convert class vectors to binary class matrices
y_train = keras.utils.to_categorical(y_train, num_classes)
y_test = keras.utils.to_categorical(y_test, num_classes)
model = Sequential()
model.add(Conv2D(32, kernel_size=(3, 3),
activation='relu',
input_shape=input_shape))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(num_classes, activation='softmax'))
model.compile(loss=keras.losses.categorical_crossentropy,
optimizer=keras.optimizers.Adadelta(),
metrics=['accuracy'])
model.fit(x_train, y_train,
batch_size=batch_size,
epochs=epochs,
verbose=1,
validation_data=(x_test, y_test))
score = model.evaluate(x_test, y_test, verbose=0)
print('Test loss:', score[0])
print('Test accuracy:', score[1])
# Save model
json_string = model.to_json()
with open('./model.json', 'w') as f:
f.write(json_string)
model.save_weights('./last_weight.h5')
# Save test data
import numpy as np
import pickle
ids = np.arange(start=0, stop=len(x_test))
with open('./ids.pkl', 'wb') as f:
pickle.dump(ids, f)
with open('./x_test_10000.pkl', 'wb') as f:
pickle.dump(x_test, f)
with open('./y_test_10000.tsv', 'w') as f:
for label in y_test:
f.write(str(label) + '\n')
import scipy.misc
def images_to_sprite(data):
"""
Creates the sprite image
:param data: [batch_size, height, weight, n_channel]
:return data: Sprited image::[height, weight, n_channel]
"""
if len(data.shape) == 3:
data = np.tile(data[..., np.newaxis], (1, 1, 1, 3))
data = data.astype(np.float32)
min = np.min(data.reshape((data.shape[0], -1)), axis=1)
data = (data.transpose(1, 2, 3, 0) - min).transpose(3, 0, 1, 2)
max = np.max(data.reshape((data.shape[0], -1)), axis=1)
data = (data.transpose(1, 2, 3, 0) / max).transpose(3, 0, 1, 2)
n = int(np.ceil(np.sqrt(data.shape[0])))
padding = ((0, n ** 2 - data.shape[0]), (0, 0),
(0, 0)) + ((0, 0),) * (data.ndim - 3)
data = np.pad(data, padding, mode='constant',
constant_values=0)
data = data.reshape((n, n) + data.shape[1:]).transpose(
(0, 2, 1, 3) + tuple(range(4, data.ndim + 1))
)
data = data.reshape(
(n * data.shape[1], n * data.shape[3]) + data.shape[4:])
data = (data * 255).astype(np.uint8)
return data
simg = images_to_sprite(x_test)
scipy.misc.imsave('./MNIST_sprites.png', | np.squeeze(simg) | numpy.squeeze |
import os
import warnings
from six import BytesIO
from six.moves import cPickle
import numpy as np
from numpy.testing import assert_almost_equal, assert_allclose
import pandas as pd
import pandas.util.testing as tm
import pytest
from sm2 import datasets
from sm2.regression.linear_model import OLS
from sm2.tsa.arima_model import AR, ARMA, ARIMA
from sm2.tsa.arima_process import arma_generate_sample
from sm2.tools.sm_exceptions import MissingDataError
from .results import results_arma, results_arima
DECIMAL_4 = 4
DECIMAL_3 = 3
DECIMAL_2 = 2
DECIMAL_1 = 1
current_path = os.path.dirname(os.path.abspath(__file__))
path = os.path.join(current_path, 'results', 'y_arma_data.csv')
y_arma = pd.read_csv(path, float_precision='high').values
cpi_dates = pd.PeriodIndex(start='1959q1', end='2009q3', freq='Q')
sun_dates = pd.PeriodIndex(start='1700', end='2008', freq='A')
cpi_predict_dates = pd.PeriodIndex(start='2009q3', end='2015q4', freq='Q')
sun_predict_dates = pd.PeriodIndex(start='2008', end='2033', freq='A')
@pytest.mark.not_vetted
@pytest.mark.skip(reason="fa, Arma not ported from upstream")
def test_compare_arma():
# dummies to avoid flake8 warnings until porting
fa = None
Arma = None
# import statsmodels.sandbox.tsa.fftarma as fa
# from statsmodels.tsa.arma_mle import Arma
# this is a preliminary test to compare
# arma_kf, arma_cond_ls and arma_cond_mle
# the results returned by the fit methods are incomplete
# for now without random.seed
np.random.seed(9876565)
famod = fa.ArmaFft([1, -0.5], [1., 0.4], 40)
x = famod.generate_sample(nsample=200, burnin=1000)
modkf = ARMA(x, (1, 1))
reskf = modkf.fit(trend='nc', disp=-1)
dres = reskf
modc = Arma(x)
resls = modc.fit(order=(1, 1))
rescm = modc.fit_mle(order=(1, 1), start_params=[0.4, 0.4, 1.], disp=0)
# decimal 1 corresponds to threshold of 5% difference
# still different sign corrected
assert_almost_equal(resls[0] / dres.params,
np.ones(dres.params.shape),
decimal=1)
# TODO: Is the next comment still accurate. It is retained from upstream
# where there was a commented-out assertion after the comment
# rescm also contains variance estimate as last element of params
assert_almost_equal(rescm.params[:-1] / dres.params,
np.ones(dres.params.shape),
decimal=1)
@pytest.mark.not_vetted
class CheckArmaResultsMixin(object):
"""
res2 are the results from gretl. They are in results/results_arma.
res1 are from sm2
"""
decimal_params = DECIMAL_4
def test_params(self):
assert_almost_equal(self.res1.params,
self.res2.params,
self.decimal_params)
decimal_aic = DECIMAL_4
def test_aic(self):
assert_almost_equal(self.res1.aic,
self.res2.aic,
self.decimal_aic)
decimal_bic = DECIMAL_4
def test_bic(self):
assert_almost_equal(self.res1.bic,
self.res2.bic,
self.decimal_bic)
decimal_arroots = DECIMAL_4
def test_arroots(self):
assert_almost_equal(self.res1.arroots,
self.res2.arroots,
self.decimal_arroots)
decimal_maroots = DECIMAL_4
def test_maroots(self):
assert_almost_equal(self.res1.maroots,
self.res2.maroots,
self.decimal_maroots)
decimal_bse = DECIMAL_2
def test_bse(self):
assert_almost_equal(self.res1.bse,
self.res2.bse,
self.decimal_bse)
decimal_cov_params = DECIMAL_4
def test_covparams(self):
assert_almost_equal(self.res1.cov_params(),
self.res2.cov_params,
self.decimal_cov_params)
decimal_hqic = DECIMAL_4
def test_hqic(self):
assert_almost_equal(self.res1.hqic,
self.res2.hqic,
self.decimal_hqic)
decimal_llf = DECIMAL_4
def test_llf(self):
assert_almost_equal(self.res1.llf,
self.res2.llf,
self.decimal_llf)
decimal_resid = DECIMAL_4
def test_resid(self):
assert_almost_equal(self.res1.resid,
self.res2.resid,
self.decimal_resid)
decimal_fittedvalues = DECIMAL_4
def test_fittedvalues(self):
assert_almost_equal(self.res1.fittedvalues,
self.res2.fittedvalues,
self.decimal_fittedvalues)
decimal_pvalues = DECIMAL_2
def test_pvalues(self):
assert_almost_equal(self.res1.pvalues,
self.res2.pvalues,
self.decimal_pvalues)
decimal_t = DECIMAL_2 # only 2 decimal places in gretl output
def test_tvalues(self):
assert_almost_equal(self.res1.tvalues,
self.res2.tvalues,
self.decimal_t)
decimal_sigma2 = DECIMAL_4
def test_sigma2(self):
assert_almost_equal(self.res1.sigma2,
self.res2.sigma2,
self.decimal_sigma2)
@pytest.mark.smoke
def test_summary(self):
self.res1.summary()
@pytest.mark.not_vetted
class CheckForecastMixin(object):
decimal_forecast = DECIMAL_4
def test_forecast(self):
assert_almost_equal(self.res1.forecast_res,
self.res2.forecast,
self.decimal_forecast)
decimal_forecasterr = DECIMAL_4
def test_forecasterr(self):
assert_almost_equal(self.res1.forecast_err,
self.res2.forecasterr,
self.decimal_forecasterr)
@pytest.mark.not_vetted
class CheckDynamicForecastMixin(object):
decimal_forecast_dyn = 4
def test_dynamic_forecast(self):
assert_almost_equal(self.res1.forecast_res_dyn,
self.res2.forecast_dyn,
self.decimal_forecast_dyn)
#def test_forecasterr(self):
# assert_almost_equal(self.res1.forecast_err_dyn,
# self.res2.forecasterr_dyn,
# DECIMAL_4)
@pytest.mark.not_vetted
class CheckArimaResultsMixin(CheckArmaResultsMixin):
def test_order(self):
assert self.res1.k_diff == self.res2.k_diff
assert self.res1.k_ar == self.res2.k_ar
assert self.res1.k_ma == self.res2.k_ma
decimal_predict_levels = DECIMAL_4
def test_predict_levels(self):
assert_almost_equal(self.res1.predict(typ='levels'),
self.res2.linear,
self.decimal_predict_levels)
@pytest.mark.not_vetted
class Test_Y_ARMA11_NoConst(CheckArmaResultsMixin, CheckForecastMixin):
@classmethod
def setup_class(cls):
endog = y_arma[:, 0]
cls.res1 = ARMA(endog, order=(1, 1)).fit(trend='nc', disp=-1)
fc_res, fc_err, ci = cls.res1.forecast(10)
cls.res1.forecast_res = fc_res
cls.res1.forecast_err = fc_err
cls.res2 = results_arma.Y_arma11()
# TODO: share with test_ar? other test classes?
def test_pickle(self):
fh = BytesIO()
# test wrapped results load save pickle
self.res1.save(fh)
fh.seek(0, 0)
res_unpickled = self.res1.__class__.load(fh)
assert type(res_unpickled) is type(self.res1) # noqa:E721
# TODO: Test equality instead of just type equality?
@pytest.mark.not_vetted
class Test_Y_ARMA14_NoConst(CheckArmaResultsMixin):
@classmethod
def setup_class(cls):
endog = y_arma[:, 1]
cls.res1 = ARMA(endog, order=(1, 4)).fit(trend='nc', disp=-1)
cls.res2 = results_arma.Y_arma14()
@pytest.mark.not_vetted
@pytest.mark.slow
class Test_Y_ARMA41_NoConst(CheckArmaResultsMixin, CheckForecastMixin):
decimal_maroots = DECIMAL_3
@classmethod
def setup_class(cls):
endog = y_arma[:, 2]
cls.res1 = ARMA(endog, order=(4, 1)).fit(trend='nc', disp=-1)
(cls.res1.forecast_res, cls.res1.forecast_err,
confint) = cls.res1.forecast(10)
cls.res2 = results_arma.Y_arma41()
@pytest.mark.not_vetted
class Test_Y_ARMA22_NoConst(CheckArmaResultsMixin):
@classmethod
def setup_class(cls):
endog = y_arma[:, 3]
cls.res1 = ARMA(endog, order=(2, 2)).fit(trend='nc', disp=-1)
cls.res2 = results_arma.Y_arma22()
@pytest.mark.not_vetted
class Test_Y_ARMA50_NoConst(CheckArmaResultsMixin, CheckForecastMixin):
@classmethod
def setup_class(cls):
endog = y_arma[:, 4]
cls.res1 = ARMA(endog, order=(5, 0)).fit(trend='nc', disp=-1)
(cls.res1.forecast_res, cls.res1.forecast_err,
confint) = cls.res1.forecast(10)
cls.res2 = results_arma.Y_arma50()
@pytest.mark.not_vetted
class Test_Y_ARMA02_NoConst(CheckArmaResultsMixin):
@classmethod
def setup_class(cls):
endog = y_arma[:, 5]
cls.res1 = ARMA(endog, order=(0, 2)).fit(trend='nc', disp=-1)
cls.res2 = results_arma.Y_arma02()
@pytest.mark.not_vetted
class Test_Y_ARMA11_Const(CheckArmaResultsMixin, CheckForecastMixin):
@classmethod
def setup_class(cls):
endog = y_arma[:, 6]
cls.res1 = ARMA(endog, order=(1, 1)).fit(trend="c", disp=-1)
(cls.res1.forecast_res, cls.res1.forecast_err,
confint) = cls.res1.forecast(10)
cls.res2 = results_arma.Y_arma11c()
@pytest.mark.not_vetted
class Test_Y_ARMA14_Const(CheckArmaResultsMixin):
@classmethod
def setup_class(cls):
endog = y_arma[:, 7]
cls.res1 = ARMA(endog, order=(1, 4)).fit(trend="c", disp=-1)
cls.res2 = results_arma.Y_arma14c()
@pytest.mark.not_vetted
class Test_Y_ARMA41_Const(CheckArmaResultsMixin, CheckForecastMixin):
decimal_cov_params = DECIMAL_3
decimal_fittedvalues = DECIMAL_3
decimal_resid = DECIMAL_3
decimal_params = DECIMAL_3
@classmethod
def setup_class(cls):
endog = y_arma[:, 8]
cls.res2 = results_arma.Y_arma41c()
cls.res1 = ARMA(endog, order=(4, 1)).fit(trend="c", disp=-1,
start_params=cls.res2.params)
(cls.res1.forecast_res, cls.res1.forecast_err,
confint) = cls.res1.forecast(10)
@pytest.mark.not_vetted
class Test_Y_ARMA22_Const(CheckArmaResultsMixin):
@classmethod
def setup_class(cls):
endog = y_arma[:, 9]
cls.res1 = ARMA(endog, order=(2, 2)).fit(trend="c", disp=-1)
cls.res2 = results_arma.Y_arma22c()
@pytest.mark.not_vetted
class Test_Y_ARMA50_Const(CheckArmaResultsMixin, CheckForecastMixin):
@classmethod
def setup_class(cls):
endog = y_arma[:, 10]
cls.res1 = ARMA(endog, order=(5, 0)).fit(trend="c", disp=-1)
(cls.res1.forecast_res, cls.res1.forecast_err,
confint) = cls.res1.forecast(10)
cls.res2 = results_arma.Y_arma50c()
@pytest.mark.not_vetted
class Test_Y_ARMA02_Const(CheckArmaResultsMixin):
@classmethod
def setup_class(cls):
endog = y_arma[:, 11]
cls.res1 = ARMA(endog, order=(0, 2)).fit(trend="c", disp=-1)
cls.res2 = results_arma.Y_arma02c()
# cov_params and tvalues are off still but not as much vs. R
@pytest.mark.not_vetted
class Test_Y_ARMA11_NoConst_CSS(CheckArmaResultsMixin):
decimal_t = DECIMAL_1
@classmethod
def setup_class(cls):
endog = y_arma[:, 0]
cls.res1 = ARMA(endog, order=(1, 1)).fit(method="css",
trend="nc", disp=-1)
cls.res2 = results_arma.Y_arma11("css")
# better vs. R
@pytest.mark.not_vetted
class Test_Y_ARMA14_NoConst_CSS(CheckArmaResultsMixin):
decimal_fittedvalues = DECIMAL_3
decimal_resid = DECIMAL_3
decimal_t = DECIMAL_1
@classmethod
def setup_class(cls):
endog = y_arma[:, 1]
cls.res1 = ARMA(endog, order=(1, 4)).fit(method="css",
trend="nc", disp=-1)
cls.res2 = results_arma.Y_arma14("css")
# bse, etc. better vs. R
# maroot is off because maparams is off a bit (adjust tolerance?)
@pytest.mark.not_vetted
class Test_Y_ARMA41_NoConst_CSS(CheckArmaResultsMixin):
decimal_t = DECIMAL_1
decimal_pvalues = 0
decimal_cov_params = DECIMAL_3
decimal_maroots = DECIMAL_1
@classmethod
def setup_class(cls):
endog = y_arma[:, 2]
cls.res1 = ARMA(endog, order=(4, 1)).fit(method="css",
trend="nc", disp=-1)
cls.res2 = results_arma.Y_arma41("css")
# same notes as above
@pytest.mark.not_vetted
class Test_Y_ARMA22_NoConst_CSS(CheckArmaResultsMixin):
decimal_t = DECIMAL_1
decimal_resid = DECIMAL_3
decimal_pvalues = DECIMAL_1
decimal_fittedvalues = DECIMAL_3
@classmethod
def setup_class(cls):
endog = y_arma[:, 3]
cls.res1 = ARMA(endog, order=(2, 2)).fit(method="css",
trend="nc", disp=-1)
cls.res2 = results_arma.Y_arma22("css")
# NOTE: gretl just uses least squares for AR CSS
# so BIC, etc. is
# -2*res1.llf + np.log(nobs)*(res1.q+res1.p+res1.k)
# with no adjustment for p and no extra sigma estimate
# NOTE: so our tests use x-12 arima results which agree with us and are
# consistent with the rest of the models
@pytest.mark.not_vetted
class Test_Y_ARMA50_NoConst_CSS(CheckArmaResultsMixin):
decimal_t = 0
decimal_llf = DECIMAL_1 # looks like rounding error?
@classmethod
def setup_class(cls):
endog = y_arma[:, 4]
cls.res1 = ARMA(endog, order=(5, 0)).fit(method="css",
trend="nc", disp=-1)
cls.res2 = results_arma.Y_arma50("css")
@pytest.mark.not_vetted
class Test_Y_ARMA02_NoConst_CSS(CheckArmaResultsMixin):
@classmethod
def setup_class(cls):
endog = y_arma[:, 5]
cls.res1 = ARMA(endog, order=(0, 2)).fit(method="css",
trend="nc", disp=-1)
cls.res2 = results_arma.Y_arma02("css")
# NOTE: our results are close to --x-12-arima option and R
@pytest.mark.not_vetted
class Test_Y_ARMA11_Const_CSS(CheckArmaResultsMixin):
decimal_params = DECIMAL_3
decimal_cov_params = DECIMAL_3
decimal_t = DECIMAL_1
@classmethod
def setup_class(cls):
endog = y_arma[:, 6]
cls.res1 = ARMA(endog, order=(1, 1)).fit(trend="c",
method="css", disp=-1)
cls.res2 = results_arma.Y_arma11c("css")
@pytest.mark.not_vetted
class Test_Y_ARMA14_Const_CSS(CheckArmaResultsMixin):
decimal_t = DECIMAL_1
decimal_pvalues = DECIMAL_1
@classmethod
def setup_class(cls):
endog = y_arma[:, 7]
cls.res1 = ARMA(endog, order=(1, 4)).fit(trend="c",
method="css", disp=-1)
cls.res2 = results_arma.Y_arma14c("css")
@pytest.mark.not_vetted
class Test_Y_ARMA41_Const_CSS(CheckArmaResultsMixin):
decimal_t = DECIMAL_1
decimal_cov_params = DECIMAL_1
decimal_maroots = DECIMAL_3
decimal_bse = DECIMAL_1
@classmethod
def setup_class(cls):
endog = y_arma[:, 8]
cls.res1 = ARMA(endog, order=(4, 1)).fit(trend="c",
method="css", disp=-1)
cls.res2 = results_arma.Y_arma41c("css")
@pytest.mark.not_vetted
class Test_Y_ARMA22_Const_CSS(CheckArmaResultsMixin):
decimal_t = 0
decimal_pvalues = DECIMAL_1
@classmethod
def setup_class(cls):
endog = y_arma[:, 9]
cls.res1 = ARMA(endog, order=(2, 2)).fit(trend="c",
method="css", disp=-1)
cls.res2 = results_arma.Y_arma22c("css")
@pytest.mark.not_vetted
class Test_Y_ARMA50_Const_CSS(CheckArmaResultsMixin):
decimal_t = DECIMAL_1
decimal_params = DECIMAL_3
decimal_cov_params = DECIMAL_2
@classmethod
def setup_class(cls):
endog = y_arma[:, 10]
cls.res1 = ARMA(endog, order=(5, 0)).fit(trend="c",
method="css", disp=-1)
cls.res2 = results_arma.Y_arma50c("css")
@pytest.mark.not_vetted
class Test_Y_ARMA02_Const_CSS(CheckArmaResultsMixin):
@classmethod
def setup_class(cls):
endog = y_arma[:, 11]
cls.res1 = ARMA(endog, order=(0, 2)).fit(trend="c",
method="css", disp=-1)
cls.res2 = results_arma.Y_arma02c("css")
@pytest.mark.not_vetted
class Test_ARIMA101(CheckArmaResultsMixin):
# just make sure this works
@classmethod
def setup_class(cls):
endog = y_arma[:, 6]
cls.res1 = ARIMA(endog, (1, 0, 1)).fit(trend="c", disp=-1)
(cls.res1.forecast_res, cls.res1.forecast_err,
confint) = cls.res1.forecast(10)
cls.res2 = results_arma.Y_arma11c()
cls.res2.k_diff = 0
cls.res2.k_ar = 1
cls.res2.k_ma = 1
@pytest.mark.not_vetted
class Test_ARIMA111(CheckArimaResultsMixin, CheckForecastMixin,
CheckDynamicForecastMixin):
decimal_llf = 3
decimal_aic = 3
decimal_bic = 3
decimal_cov_params = 2 # this used to be better?
decimal_t = 0
@classmethod
def setup_class(cls):
cpi = datasets.macrodata.load_pandas().data['cpi'].values
cls.res1 = ARIMA(cpi, (1, 1, 1)).fit(disp=-1)
cls.res2 = results_arima.ARIMA111()
# make sure endog names changes to D.cpi
(cls.res1.forecast_res,
cls.res1.forecast_err,
conf_int) = cls.res1.forecast(25)
# TODO: fix the indexing for the end here, I don't think this is right
# if we're going to treat it like indexing
# the forecast from 2005Q1 through 2009Q4 is indices
# 184 through 227 not 226
# note that the first one counts in the count so 164 + 64 is 65
# predictions
cls.res1.forecast_res_dyn = cls.res1.predict(start=164, end=164 + 63,
typ='levels',
dynamic=True)
def test_freq(self):
assert_almost_equal(self.res1.arfreq, [0.0000], 4)
assert_almost_equal(self.res1.mafreq, [0.0000], 4)
@pytest.mark.not_vetted
class Test_ARIMA111CSS(CheckArimaResultsMixin, CheckForecastMixin,
CheckDynamicForecastMixin):
decimal_forecast = 2
decimal_forecast_dyn = 2
decimal_forecasterr = 3
decimal_arroots = 3
decimal_cov_params = 3
decimal_hqic = 3
decimal_maroots = 3
decimal_t = 1
decimal_fittedvalues = 2 # because of rounding when copying
decimal_resid = 2
decimal_predict_levels = DECIMAL_2
@classmethod
def setup_class(cls):
cpi = datasets.macrodata.load_pandas().data['cpi'].values
cls.res1 = ARIMA(cpi, (1, 1, 1)).fit(disp=-1, method='css')
cls.res2 = results_arima.ARIMA111(method='css')
cls.res2.fittedvalues = - cpi[1:-1] + cls.res2.linear
# make sure endog names changes to D.cpi
(fc_res, fc_err, conf_int) = cls.res1.forecast(25)
cls.res1.forecast_res = fc_res
cls.res1.forecast_err = fc_err
cls.res1.forecast_res_dyn = cls.res1.predict(start=164, end=164 + 63,
typ='levels',
dynamic=True)
@pytest.mark.not_vetted
class Test_ARIMA112CSS(CheckArimaResultsMixin):
decimal_llf = 3
decimal_aic = 3
decimal_bic = 3
decimal_arroots = 3
decimal_maroots = 2
decimal_t = 1
decimal_resid = 2
decimal_fittedvalues = 3
decimal_predict_levels = DECIMAL_3
@classmethod
def setup_class(cls):
cpi = datasets.macrodata.load_pandas().data['cpi'].values
cls.res1 = ARIMA(cpi, (1, 1, 2)).fit(disp=-1, method='css',
start_params=[.905322, -.692425,
1.07366, 0.172024])
cls.res2 = results_arima.ARIMA112(method='css')
cls.res2.fittedvalues = - cpi[1:-1] + cls.res2.linear
# make sure endog names changes to D.cpi
#(cls.res1.forecast_res,
# cls.res1.forecast_err,
# conf_int) = cls.res1.forecast(25)
#cls.res1.forecast_res_dyn = cls.res1.predict(start=164, end=226,
# typ='levels',
# dynamic=True)
# TODO: fix the indexing for the end here, I don't think this is right
# if we're going to treat it like indexing
# the forecast from 2005Q1 through 2009Q4 is indices
# 184 through 227 not 226
# note that the first one counts in the count so 164 + 64 is 65
# predictions
#cls.res1.forecast_res_dyn = self.predict(start=164, end=164+63,
# typ='levels', dynamic=True)
# since we got from gretl don't have linear prediction in differences
def test_freq(self):
assert_almost_equal(self.res1.arfreq, [0.5000], 4)
assert_almost_equal(self.res1.mafreq, [0.5000, 0.5000], 4)
#class Test_ARIMADates(CheckArmaResults, CheckForecast, CheckDynamicForecast):
# @classmethod
# def setup_class(cls):
# cpi = datasets.macrodata.load_pandas().data['cpi'].values
# dates = pd.date_range('1959', periods=203, freq='Q')
# cls.res1 = ARIMA(cpi, dates=dates, freq='Q').fit(order=(1, 1, 1),
# disp=-1)
# cls.res2 = results_arima.ARIMA111()
# # make sure endog names changes to D.cpi
# cls.decimal_llf = 3
# cls.decimal_aic = 3
# cls.decimal_bic = 3
# (cls.res1.forecast_res,
# cls.res1.forecast_err,
# conf_int) = cls.res1.forecast(25)
@pytest.mark.not_vetted
@pytest.mark.slow
def test_start_params_bug():
data = np.array([
1368., 1187, 1090, 1439, 2362, 2783, 2869, 2512, 1804,
1544, 1028, 869, 1737, 2055, 1947, 1618, 1196, 867, 997, 1862, 2525,
3250, 4023, 4018, 3585, 3004, 2500, 2441, 2749, 2466, 2157, 1847,
1463, 1146, 851, 993, 1448, 1719, 1709, 1455, 1950, 1763, 2075, 2343,
3570, 4690, 3700, 2339, 1679, 1466, 998, 853, 835, 922, 851, 1125,
1299, 1105, 860, 701, 689, 774, 582, 419, 846, 1132, 902, 1058, 1341,
1551, 1167, 975, 786, 759, 751, 649, 876, 720, 498, 553, 459, 543,
447, 415, 377, 373, 324, 320, 306, 259, 220, 342, 558, 825, 994,
1267, 1473, 1601, 1896, 1890, 2012, 2198, 2393, 2825, 3411, 3406,
2464, 2891, 3685, 3638, 3746, 3373, 3190, 2681, 2846, 4129, 5054,
5002, 4801, 4934, 4903, 4713, 4745, 4736, 4622, 4642, 4478, 4510,
4758, 4457, 4356, 4170, 4658, 4546, 4402, 4183, 3574, 2586, 3326,
3948, 3983, 3997, 4422, 4496, 4276, 3467, 2753, 2582, 2921, 2768,
2789, 2824, 2482, 2773, 3005, 3641, 3699, 3774, 3698, 3628, 3180,
3306, 2841, 2014, 1910, 2560, 2980, 3012, 3210, 3457, 3158, 3344,
3609, 3327, 2913, 2264, 2326, 2596, 2225, 1767, 1190, 792, 669,
589, 496, 354, 246, 250, 323, 495, 924, 1536, 2081, 2660, 2814, 2992,
3115, 2962, 2272, 2151, 1889, 1481, 955, 631, 288, 103, 60, 82, 107,
185, 618, 1526, 2046, 2348, 2584, 2600, 2515, 2345, 2351, 2355,
2409, 2449, 2645, 2918, 3187, 2888, 2610, 2740, 2526, 2383, 2936,
2968, 2635, 2617, 2790, 3906, 4018, 4797, 4919, 4942, 4656, 4444,
3898, 3908, 3678, 3605, 3186, 2139, 2002, 1559, 1235, 1183, 1096,
673, 389, 223, 352, 308, 365, 525, 779, 894, 901, 1025, 1047, 981,
902, 759, 569, 519, 408, 263, 156, 72, 49, 31, 41, 192, 423, 492,
552, 564, 723, 921, 1525, 2768, 3531, 3824, 3835, 4294, 4533, 4173,
4221, 4064, 4641, 4685, 4026, 4323, 4585, 4836, 4822, 4631, 4614,
4326, 4790, 4736, 4104, 5099, 5154, 5121, 5384, 5274, 5225, 4899,
5382, 5295, 5349, 4977, 4597, 4069, 3733, 3439, 3052, 2626, 1939,
1064, 713, 916, 832, 658, 817, 921, 772, 764, 824, 967, 1127, 1153,
824, 912, 957, 990, 1218, 1684, 2030, 2119, 2233, 2657, 2652, 2682,
2498, 2429, 2346, 2298, 2129, 1829, 1816, 1225, 1010, 748, 627, 469,
576, 532, 475, 582, 641, 605, 699, 680, 714, 670, 666, 636, 672,
679, 446, 248, 134, 160, 178, 286, 413, 676, 1025, 1159, 952, 1398,
1833, 2045, 2072, 1798, 1799, 1358, 727, 353, 347, 844, 1377, 1829,
2118, 2272, 2745, 4263, 4314, 4530, 4354, 4645, 4547, 5391, 4855,
4739, 4520, 4573, 4305, 4196, 3773, 3368, 2596, 2596, 2305, 2756,
3747, 4078, 3415, 2369, 2210, 2316, 2263, 2672, 3571, 4131, 4167,
4077, 3924, 3738, 3712, 3510, 3182, 3179, 2951, 2453, 2078, 1999,
2486, 2581, 1891, 1997, 1366, 1294, 1536, 2794, 3211, 3242, 3406,
3121, 2425, 2016, 1787, 1508, 1304, 1060, 1342, 1589, 2361, 3452,
2659, 2857, 3255, 3322, 2852, 2964, 3132, 3033, 2931, 2636, 2818, 3310,
3396, 3179, 3232, 3543, 3759, 3503, 3758, 3658, 3425, 3053, 2620, 1837,
923, 712, 1054, 1376, 1556, 1498, 1523, 1088, 728, 890, 1413, 2524,
3295, 4097, 3993, 4116, 3874, 4074, 4142, 3975, 3908, 3907, 3918, 3755,
3648, 3778, 4293, 4385, 4360, 4352, 4528, 4365, 3846, 4098, 3860, 3230,
2820, 2916, 3201, 3721, 3397, 3055, 2141, 1623, 1825, 1716, 2232, 2939,
3735, 4838, 4560, 4307, 4975, 5173, 4859, 5268, 4992, 5100, 5070, 5270,
4760, 5135, 5059, 4682, 4492, 4933, 4737, 4611, 4634, 4789, 4811, 4379,
4689, 4284, 4191, 3313, 2770, 2543, 3105, 2967, 2420, 1996, 2247, 2564,
2726, 3021, 3427, 3509, 3759, 3324, 2988, 2849, 2340, 2443, 2364, 1252,
623, 742, 867, 684, 488, 348, 241, 187, 279, 355, 423, 678, 1375, 1497,
1434, 2116, 2411, 1929, 1628, 1635, 1609, 1757, 2090, 2085, 1790, 1846,
2038, 2360, 2342, 2401, 2920, 3030, 3132, 4385, 5483, 5865, 5595, 5485,
5727, 5553, 5560, 5233, 5478, 5159, 5155, 5312, 5079, 4510, 4628, 4535,
3656, 3698, 3443, 3146, 2562, 2304, 2181, 2293, 1950, 1930, 2197, 2796,
3441, 3649, 3815, 2850, 4005, 5305, 5550, 5641, 4717, 5131, 2831, 3518,
3354, 3115, 3515, 3552, 3244, 3658, 4407, 4935, 4299, 3166, 3335, 2728,
2488, 2573, 2002, 1717, 1645, 1977, 2049, 2125, 2376, 2551, 2578, 2629,
2750, 3150, 3699, 4062, 3959, 3264, 2671, 2205, 2128, 2133, 2095, 1964,
2006, 2074, 2201, 2506, 2449, 2465, 2064, 1446, 1382, 983, 898, 489,
319, 383, 332, 276, 224, 144, 101, 232, 429, 597, 750, 908, 960, 1076,
951, 1062, 1183, 1404, 1391, 1419, 1497, 1267, 963, 682, 777, 906,
1149, 1439, 1600, 1876, 1885, 1962, 2280, 2711, 2591, 2411])
with warnings.catch_warnings():
warnings.simplefilter("ignore")
ARMA(data, order=(4, 1)).fit(start_ar_lags=5, disp=-1)
@pytest.mark.not_vetted
def test_arima_predict_mle_dates():
cpi = datasets.macrodata.load_pandas().data['cpi'].values
res1 = ARIMA(cpi, (4, 1, 1), dates=cpi_dates, freq='Q').fit(disp=-1)
path = os.path.join(current_path, 'results',
'results_arima_forecasts_all_mle.csv')
arima_forecasts = pd.read_csv(path).values
fc = arima_forecasts[:, 0]
fcdyn = arima_forecasts[:, 1]
fcdyn2 = arima_forecasts[:, 2]
start, end = 2, 51
fv = res1.predict('1959Q3', '1971Q4', typ='levels')
assert_almost_equal(fv, fc[start:end + 1], DECIMAL_4)
tm.assert_index_equal(res1.data.predict_dates,
cpi_dates[start:end + 1])
start, end = 202, 227
fv = res1.predict('2009Q3', '2015Q4', typ='levels')
assert_almost_equal(fv, fc[start:end + 1], DECIMAL_4)
tm.assert_index_equal(res1.data.predict_dates,
cpi_predict_dates)
# make sure dynamic works
start, end = '1960q2', '1971q4'
fv = res1.predict(start, end, dynamic=True, typ='levels')
assert_almost_equal(fv, fcdyn[5:51 + 1], DECIMAL_4)
start, end = '1965q1', '2015q4'
fv = res1.predict(start, end, dynamic=True, typ='levels')
assert_almost_equal(fv, fcdyn2[24:227 + 1], DECIMAL_4)
@pytest.mark.not_vetted
def test_arma_predict_mle_dates():
sunspots = datasets.sunspots.load_pandas().data['SUNACTIVITY'].values
mod = ARMA(sunspots, (9, 0), dates=sun_dates, freq='A')
mod.method = 'mle'
with pytest.raises(ValueError):
mod._get_prediction_index('1701', '1751', True)
start, end = 2, 51
mod._get_prediction_index('1702', '1751', False)
tm.assert_index_equal(mod.data.predict_dates, sun_dates[start:end + 1])
start, end = 308, 333
mod._get_prediction_index('2008', '2033', False)
tm.assert_index_equal(mod.data.predict_dates, sun_predict_dates)
@pytest.mark.not_vetted
def test_arima_predict_css_dates():
cpi = datasets.macrodata.load_pandas().data['cpi'].values
res1 = ARIMA(cpi, (4, 1, 1), dates=cpi_dates, freq='Q').fit(disp=-1,
method='css',
trend='nc')
params = np.array([1.231272508473910,
-0.282516097759915,
0.170052755782440,
-0.118203728504945,
-0.938783134717947])
path = os.path.join(current_path, 'results',
'results_arima_forecasts_all_css.csv')
arima_forecasts = pd.read_csv(path).values
fc = arima_forecasts[:, 0]
fcdyn = arima_forecasts[:, 1]
fcdyn2 = arima_forecasts[:, 2]
start, end = 5, 51
fv = res1.model.predict(params, '1960Q2', '1971Q4', typ='levels')
assert_almost_equal(fv, fc[start:end + 1], DECIMAL_4)
tm.assert_index_equal(res1.data.predict_dates, cpi_dates[start:end + 1])
start, end = 202, 227
fv = res1.model.predict(params, '2009Q3', '2015Q4', typ='levels')
assert_almost_equal(fv, fc[start:end + 1], DECIMAL_4)
tm.assert_index_equal(res1.data.predict_dates, cpi_predict_dates)
# make sure dynamic works
start, end = 5, 51
fv = res1.model.predict(params, '1960Q2', '1971Q4', typ='levels',
dynamic=True)
assert_almost_equal(fv, fcdyn[start:end + 1], DECIMAL_4)
start, end = '1965q1', '2015q4'
fv = res1.model.predict(params, start, end, dynamic=True, typ='levels')
assert_almost_equal(fv, fcdyn2[24:227 + 1], DECIMAL_4)
@pytest.mark.not_vetted
def test_arma_predict_css_dates():
# TODO: GH reference?
sunspots = datasets.sunspots.load_pandas().data['SUNACTIVITY'].values
mod = ARMA(sunspots, (9, 0), dates=sun_dates, freq='A')
mod.method = 'css'
with pytest.raises(ValueError):
mod._get_prediction_index('1701', '1751', False)
def test_arima_wrapper():
# test that names get attached to res.params correctly
# TODO: GH reference?
cpi = datasets.macrodata.load_pandas().data['cpi']
cpi.index = pd.Index(cpi_dates)
res = ARIMA(cpi, (4, 1, 1), freq='Q').fit(disp=-1)
expected_index = pd.Index(['const', 'ar.L1.D.cpi', 'ar.L2.D.cpi',
'ar.L3.D.cpi', 'ar.L4.D.cpi',
'ma.L1.D.cpi'])
assert expected_index.equals(res.params.index)
tm.assert_index_equal(res.params.index, expected_index)
assert res.model.endog_names == 'D.cpi'
@pytest.mark.not_vetted
@pytest.mark.smoke
def test_1dexog():
# smoke test, this will raise an error if broken
dta = datasets.macrodata.load_pandas().data
endog = dta['realcons'].values
exog = dta['m1'].values.squeeze()
with warnings.catch_warnings():
warnings.simplefilter("ignore")
mod = ARMA(endog, (1, 1), exog).fit(disp=-1)
mod.predict(193, 203, exog[-10:])
# check for dynamic is true and pandas Series see GH#2589
mod.predict(193, 202, exog[-10:], dynamic=True)
dta.index = pd.Index(cpi_dates)
mod = ARMA(dta['realcons'], (1, 1), dta['m1'])
res = mod.fit(disp=-1)
res.predict(dta.index[-10], dta.index[-1],
exog=dta['m1'][-10:], dynamic=True)
mod = ARMA(dta['realcons'], (1, 1), dta['m1'])
res = mod.fit(trend='nc', disp=-1)
res.predict(dta.index[-10], dta.index[-1],
exog=dta['m1'][-10:], dynamic=True)
@pytest.mark.not_vetted
def test_arima_predict_bug():
# predict_start_date wasn't getting set on start = None
# TODO: GH reference?
dta = datasets.sunspots.load_pandas().data['SUNACTIVITY']
dta.index = pd.DatetimeIndex(start='1700', end='2009', freq='A')[:309]
arma_mod20 = ARMA(dta, (2, 0)).fit(disp=-1)
arma_mod20.predict(None, None)
# test prediction with time stamp, see GH#2587
predict = arma_mod20.predict(dta.index[-20], dta.index[-1])
assert predict.index.equals(dta.index[-20:])
predict = arma_mod20.predict(dta.index[-20], dta.index[-1], dynamic=True)
assert predict.index.equals(dta.index[-20:])
# partially out of sample
predict_dates = pd.DatetimeIndex(start='2000', end='2015', freq='A')
predict = arma_mod20.predict(predict_dates[0], predict_dates[-1])
assert predict.index.equals(predict_dates)
@pytest.mark.not_vetted
def test_arima_predict_q2():
# bug with q > 1 for arima predict
# TODO: GH reference?
inv = datasets.macrodata.load().data['realinv']
arima_mod = ARIMA(np.log(inv), (1, 1, 2)).fit(start_params=[0, 0, 0, 0],
disp=-1)
fc, stderr, conf_int = arima_mod.forecast(5)
# values copy-pasted from gretl
assert_almost_equal(fc,
[7.306320, 7.313825, 7.321749, 7.329827, 7.337962],
5)
@pytest.mark.not_vetted
def test_arima_predict_pandas_nofreq():
# GH#712
dates = ["2010-01-04", "2010-01-05", "2010-01-06", "2010-01-07",
"2010-01-08", "2010-01-11", "2010-01-12", "2010-01-11",
"2010-01-12", "2010-01-13", "2010-01-17"]
close = [626.75, 623.99, 608.26, 594.1, 602.02, 601.11, 590.48, 587.09,
589.85, 580.0, 587.62]
data = pd.DataFrame(close, index=pd.DatetimeIndex(dates),
columns=["close"])
# TODO: fix this names bug for non-string names names
arma = ARMA(data, order=(1, 0)).fit(disp=-1)
# first check that in-sample prediction works
predict = arma.predict()
assert predict.index.equals(data.index)
# check that this raises an exception when date not on index
with pytest.raises(KeyError):
arma.predict(start="2010-1-9", end=10)
with pytest.raises(KeyError):
arma.predict(start="2010-1-9", end="2010-1-17")
# raise because end not on index
with pytest.raises(KeyError):
arma.predict(start="2010-1-4", end="2010-1-10")
# raise because end not on index
with pytest.raises(KeyError):
arma.predict(start=3, end="2010-1-10")
predict = arma.predict(start="2010-1-7", end=10) # should be of length 10
assert len(predict) == 8
assert predict.index.equals(data.index[3:10 + 1])
predict = arma.predict(start="2010-1-7", end=14)
assert predict.index.equals(pd.Index(range(3, 15)))
predict = arma.predict(start=3, end=14)
assert predict.index.equals(pd.Index(range(3, 15)))
# end can be a date if it's in the sample and on the index
# predict dates is just a slice of the dates index then
predict = arma.predict(start="2010-1-6", end="2010-1-13")
assert predict.index.equals(data.index[2:10])
predict = arma.predict(start=2, end="2010-1-13")
assert predict.index.equals(data.index[2:10])
@pytest.mark.not_vetted
def test_arima_predict_exog():
# check GH#625 and GH#626
# Note: upstream there is a bunch of commented-out code after this point;
# I have not been able to get an explanation as to if/why it is worth
# keeping.
# TODO: At some point check back to see if it has been addressed.
path = os.path.join(current_path, 'results',
'results_arima_exog_forecasts_mle.csv')
arima_forecasts = pd.read_csv(path)
y = arima_forecasts["y"].dropna()
X = np.arange(len(y) + 25) / 20.
predict_expected = arima_forecasts["predict"]
arma_res = ARMA(y.values, order=(2, 1), exog=X[:100]).fit(trend="c",
disp=-1)
# params from gretl
params = np.array([2.786912485145725, -0.122650190196475,
0.533223846028938, -0.319344321763337,
0.132883233000064])
assert_almost_equal(arma_res.params, params, 5)
# no exog for in-sample
predict = arma_res.predict()
assert_almost_equal(predict, predict_expected.values[:100], 5)
# check GH#626
assert len(arma_res.model.exog_names) == 5
# exog for out-of-sample and in-sample dynamic
predict = arma_res.model.predict(params, end=124, exog=X[100:])
assert_almost_equal(predict, predict_expected.values, 6)
# conditional sum of squares
#arima_forecasts = pd.read_csv(current_path + "/results/"
# "results_arima_exog_forecasts_css.csv")
#predict_expected = arima_forecasts["predict"].dropna()
#arma_res = ARMA(y.values, order=(2, 1), exog=X[:100]).fit(trend="c",
# method="css",
# disp=-1)
#params = np.array([2.152350033809826, -0.103602399018814,
# 0.566716580421188, -0.326208009247944,
# 0.102142932143421])
#predict = arma_res.model.predict(params)
# in-sample
#assert_almost_equal(predict, predict_expected.values[:98], 6)
#predict = arma_res.model.predict(params, end=124, exog=X[100:])
# exog for out-of-sample and in-sample dynamic
#assert_almost_equal(predict, predict_expected.values, 3)
@pytest.mark.not_vetted
def test_arimax():
dta = datasets.macrodata.load_pandas().data
dta.index = cpi_dates
dta = dta[["realdpi", "m1", "realgdp"]]
y = dta.pop("realdpi")
# 1 exog
#X = dta.iloc[1:]["m1"]
#res = ARIMA(y, (2, 1, 1), X).fit(disp=-1)
#params = [23.902305009084373, 0.024650911502790, -0.162140641341602,
# 0.165262136028113, -0.066667022903974]
#assert_almost_equal(res.params.values, params, 6)
# 2 exog
X = dta
res = ARIMA(y, (2, 1, 1), X).fit(disp=False, solver="nm", maxiter=1000,
ftol=1e-12, xtol=1e-12)
# from gretl; we use the versions from stata below instead
# params = [13.113976653926638, -0.003792125069387, 0.004123504809217,
# -0.199213760940898, 0.151563643588008, -0.033088661096699]
# from stata using double
stata_llf = -1076.108614859121
params = [13.1259220104, -0.00376814509403812, 0.00411970083135622,
-0.19921477896158524, 0.15154396192855729, -0.03308400760360837]
# we can get close
assert_almost_equal(res.params.values, params, 4)
# This shows that it's an optimizer problem and not a problem in the code
assert_almost_equal(res.model.loglike(np.array(params)), stata_llf, 6)
X = dta.diff()
X.iloc[0] = 0
res = ARIMA(y, (2, 1, 1), X).fit(disp=False)
# gretl won't estimate this - looks like maybe a bug on their part,
# but we can just fine, we're close to Stata's answer
# from Stata
params = [19.5656863783347, 0.32653841355833396198,
0.36286527042965188716, -1.01133792126884,
-0.15722368379307766206, 0.69359822544092153418]
assert_almost_equal(res.params.values, params, 3)
@pytest.mark.not_vetted
def test_bad_start_params():
# TODO: what is bad about these params??
# TODO: GH reference?
endog = np.array([
820.69093, 781.0103028, 785.8786988, 767.64282267,
778.9837648, 824.6595702, 813.01877867, 751.65598567,
753.431091, 746.920813, 795.6201904, 772.65732833,
793.4486454, 868.8457766, 823.07226547, 783.09067747,
791.50723847, 770.93086347, 835.34157333, 810.64147947,
738.36071367, 776.49038513, 822.93272333, 815.26461227,
773.70552987, 777.3726522, 811.83444853, 840.95489133,
777.51031933, 745.90077307, 806.95113093, 805.77521973,
756.70927733, 749.89091773, 1694.2266924, 2398.4802244,
1434.6728516, 909.73940427, 929.01291907, 769.07561453,
801.1112548, 796.16163313, 817.2496376, 857.73046447,
838.849345, 761.92338873, 731.7842242, 770.4641844])
mod = ARMA(endog, (15, 0))
with pytest.raises(ValueError):
mod.fit()
inv = datasets.macrodata.load().data['realinv']
arima_mod = ARIMA(np.log(inv), (1, 1, 2))
with pytest.raises(ValueError):
# TODO: Upstream this incorrectly re-tries `mod.fit()`
arima_mod.fit()
@pytest.mark.not_vetted
def test_armax_predict_no_trend():
# GH#1123 test ARMAX predict doesn't ignore exog when trend is none
arparams = np.array([.75, -.25])
maparams = np.array([.65, .35])
nobs = 20
np.random.seed(12345)
y = arma_generate_sample(arparams, maparams, nobs)
X = np.random.randn(nobs)
y += 5 * X
mod = ARMA(y[:-1], order=(1, 0), exog=X[:-1])
res = mod.fit(trend='nc', disp=False)
fc = res.forecast(exog=X[-1:])
# results from gretl
assert_almost_equal(fc[0], 2.200393, 6)
assert_almost_equal(fc[1], 1.030743, 6)
assert_almost_equal(fc[2][0, 0], 0.180175, 6)
assert_almost_equal(fc[2][0, 1], 4.220611, 6)
mod = ARMA(y[:-1], order=(1, 1), exog=X[:-1])
res = mod.fit(trend='nc', disp=False)
fc = res.forecast(exog=X[-1:])
assert_almost_equal(fc[0], 2.765688, 6)
assert_almost_equal(fc[1], 0.835048, 6)
assert_almost_equal(fc[2][0, 0], 1.129023, 6)
assert_almost_equal(fc[2][0, 1], 4.402353, 6)
# make sure this works to. code looked fishy.
mod = ARMA(y[:-1], order=(1, 0), exog=X[:-1])
res = mod.fit(trend='c', disp=False)
fc = res.forecast(exog=X[-1:])
assert_almost_equal(fc[0], 2.481219, 6)
assert_almost_equal(fc[1], 0.968759, 6)
assert_almost_equal(fc[2][0], [0.582485, 4.379952], 6)
@pytest.mark.not_vetted
def test_small_data():
# GH#1146
y = [-1214.360173, -1848.209905, -2100.918158, -3647.483678, -4711.186773]
# refuse to estimate these
with pytest.raises(ValueError):
ARIMA(y, (2, 0, 3))
with pytest.raises(ValueError):
ARIMA(y, (1, 1, 3))
mod = ARIMA(y, (1, 0, 3))
with pytest.raises(ValueError):
mod.fit(trend="c")
# TODO: mark these as smoke?
# try to estimate these...leave it up to the user to check for garbage
# and be clear, these are garbage parameters.
# X-12 arima will estimate, gretl refuses to estimate likely a problem
# in start params regression.
mod.fit(trend="nc", disp=0, start_params=[.1, .1, .1, .1])
mod = ARIMA(y, (1, 0, 2))
with warnings.catch_warnings():
warnings.simplefilter("ignore")
mod.fit(disp=0, start_params=[np.mean(y), .1, .1, .1])
@pytest.mark.not_vetted
class TestARMA00(object):
@classmethod
def setup_class(cls):
sunspots = datasets.sunspots.load_pandas().data['SUNACTIVITY'].values
cls.y = y = sunspots
cls.arma_00_model = ARMA(y, order=(0, 0))
cls.arma_00_res = cls.arma_00_model.fit(disp=-1)
def test_parameters(self):
params = self.arma_00_res.params
assert_almost_equal(self.y.mean(), params)
def test_predictions(self):
predictions = self.arma_00_res.predict()
assert_almost_equal(self.y.mean() * np.ones_like(predictions),
predictions)
def test_arroots(self): # TODO: Belongs in test_wold?
# GH#4559
# regression test; older implementation of arroots returned None
# instead of en empty array
roots = self.arma_00_res.arroots
assert roots.size == 0
def test_maroots(self): # TODO: Belongs in test_wold?
# GH#4559
# regression test; older implementation of arroots returned None
# instead of en empty array
roots = self.arma_00_res.maroots
assert roots.size == 0
@pytest.mark.skip(reason=' This test is invalid since the ICs differ due '
'to df_model differences between OLS and ARIMA')
def test_information_criteria(self):
# This test is invalid since the ICs differ due to df_model differences
# between OLS and ARIMA
res = self.arma_00_res
y = self.y
ols_res = OLS(y, np.ones_like(y)).fit(disp=-1)
ols_ic = np.array([ols_res.aic, ols_res.bic])
arma_ic = np.array([res.aic, res.bic])
assert_almost_equal(ols_ic, arma_ic, DECIMAL_4)
def test_arma_00_nc(self):
arma_00 = ARMA(self.y, order=(0, 0))
with pytest.raises(ValueError):
arma_00.fit(trend='nc', disp=-1)
def test_css(self):
arma = ARMA(self.y, order=(0, 0))
fit = arma.fit(method='css', disp=-1)
predictions = fit.predict()
assert_almost_equal(self.y.mean() * np.ones_like(predictions),
predictions)
def test_arima(self):
yi = np.cumsum(self.y)
arima = ARIMA(yi, order=(0, 1, 0))
fit = arima.fit(disp=-1)
assert_almost_equal(np.diff(yi).mean(),
fit.params,
DECIMAL_4)
def test_arma_ols(self):
y = self.y
y_lead = y[1:]
y_lag = y[:-1]
T = y_lag.shape[0]
X = np.hstack((np.ones((T, 1)), y_lag[:, None]))
ols_res = OLS(y_lead, X).fit()
arma_res = ARMA(y_lead, order=(0, 0), exog=y_lag).fit(trend='c',
disp=-1)
assert_almost_equal(ols_res.params, arma_res.params)
def test_arma_exog_no_constant(self):
y = self.y
y_lead = y[1:]
y_lag = y[:-1]
X = y_lag[:, None]
ols_res = OLS(y_lead, X).fit()
arma_res = ARMA(y_lead, order=(0, 0), exog=y_lag).fit(trend='nc',
disp=-1)
assert_almost_equal(ols_res.params, arma_res.params)
@pytest.mark.not_vetted
def test_arima_dates_startatend():
# TODO: GH reference?
np.random.seed(18)
x = pd.Series(np.random.random(36),
index=pd.DatetimeIndex(start='1/1/1990',
periods=36, freq='M'))
res = ARIMA(x, (1, 0, 0)).fit(disp=0)
pred = res.predict(start=len(x), end=len(x))
assert pred.index[0] == x.index.shift(1)[-1]
fc = res.forecast()[0]
assert_almost_equal(pred.values[0], fc)
@pytest.mark.not_vetted
def test_arima_diff2():
dta = datasets.macrodata.load_pandas().data['cpi']
dta.index = cpi_dates
mod = ARIMA(dta, (3, 2, 1)).fit(disp=-1)
fc, fcerr, conf_int = mod.forecast(10)
# forecasts from gretl
conf_int_res = [(216.139, 219.231),
(216.472, 221.520),
(217.064, 223.649),
(217.586, 225.727),
(218.119, 227.770),
(218.703, 229.784),
(219.306, 231.777),
(219.924, 233.759),
(220.559, 235.735),
(221.206, 237.709)]
fc_res = [217.685, 218.996, 220.356, 221.656, 222.945,
224.243, 225.541, 226.841, 228.147, 229.457]
fcerr_res = [0.7888, 1.2878, 1.6798, 2.0768, 2.4620,
2.8269, 3.1816, 3.52950, 3.8715, 4.2099]
assert_almost_equal(fc, fc_res, 3)
assert_almost_equal(fcerr, fcerr_res, 3)
assert_almost_equal(conf_int, conf_int_res, 3)
predicted = mod.predict('2008Q1', '2012Q1', typ='levels')
predicted_res = [214.464, 215.478, 221.277, 217.453, 212.419, 213.530,
215.087, 217.685, 218.996, 220.356, 221.656, 222.945,
224.243, 225.541, 226.841, 228.147, 229.457]
assert_almost_equal(predicted, predicted_res, 3)
@pytest.mark.not_vetted
def test_arima111_predict_exog_2127():
# regression test for issue GH#2127
ef = [0.03005, 0.03917, 0.02828, 0.03644, 0.03379, 0.02744,
0.03343, 0.02621, 0.03050, 0.02455, 0.03261, 0.03507,
0.02734, 0.05373, 0.02677, 0.03443, 0.03331, 0.02741,
0.03709, 0.02113, 0.03343, 0.02011, 0.03675, 0.03077,
0.02201, 0.04844, 0.05518, 0.03765, 0.05433, 0.03049,
0.04829, 0.02936, 0.04421, 0.02457, 0.04007, 0.03009,
0.04504, 0.05041, 0.03651, 0.02719, 0.04383, 0.02887,
0.03440, 0.03348, 0.02364, 0.03496, 0.02549, 0.03284,
0.03523, 0.02579, 0.03080, 0.01784, 0.03237, 0.02078,
0.03508, 0.03062, 0.02006, 0.02341, 0.02223, 0.03145,
0.03081, 0.02520, 0.02683, 0.01720, 0.02225, 0.01579,
0.02237, 0.02295, 0.01830, 0.02356, 0.02051, 0.02932,
0.03025, 0.02390, 0.02635, 0.01863, 0.02994, 0.01762,
0.02837, 0.02421, 0.01951, 0.02149, 0.02079, 0.02528,
0.02575, 0.01634, 0.02563, 0.01719, 0.02915, 0.01724,
0.02804, 0.02750, 0.02099, 0.02522, 0.02422, 0.03254,
0.02095, 0.03241, 0.01867, 0.03998, 0.02212, 0.03034,
0.03419, 0.01866, 0.02623, 0.02052]
ue = [4.9, 5.0, 5.0, 5.0, 4.9, 4.7, 4.8, 4.7, 4.7,
4.6, 4.6, 4.7, 4.7, 4.5, 4.4, 4.5, 4.4, 4.6,
4.5, 4.4, 4.5, 4.4, 4.6, 4.7, 4.6, 4.7, 4.7,
4.7, 5.0, 5.0, 4.9, 5.1, 5.0, 5.4, 5.6, 5.8,
6.1, 6.1, 6.5, 6.8, 7.3, 7.8, 8.3, 8.7, 9.0,
9.4, 9.5, 9.5, 9.6, 9.8, 10., 9.9, 9.9, 9.7,
9.8, 9.9, 9.9, 9.6, 9.4, 9.5, 9.5, 9.5, 9.5,
9.8, 9.4, 9.1, 9.0, 9.0, 9.1, 9.0, 9.1, 9.0,
9.0, 9.0, 8.8, 8.6, 8.5, 8.2, 8.3, 8.2, 8.2,
8.2, 8.2, 8.2, 8.1, 7.8, 7.8, 7.8, 7.9, 7.9,
7.7, 7.5, 7.5, 7.5, 7.5, 7.3, 7.2, 7.2, 7.2,
7.0, 6.7, 6.6, 6.7, 6.7, 6.3, 6.3]
ue = np.array(ue) / 100
model = ARIMA(ef, (1, 1, 1), exog=ue)
res = model.fit(transparams=False, pgtol=1e-8, iprint=0, disp=0)
assert res.mle_retvals['warnflag'] == 0
predicts = res.predict(start=len(ef), end=len(ef) + 10,
exog=ue[-11:], typ='levels')
# regression test, not verified numbers
predicts_res = np.array([
0.02591095, 0.02321325, 0.02436579, 0.02368759, 0.02389753,
0.02372, 0.0237481, 0.0236738, 0.023644, 0.0236283,
0.02362267])
assert_allclose(predicts, predicts_res, atol=5e-6)
@pytest.mark.not_vetted
def test_arima_exog_predict():
# TODO: break up giant test
# test forecasting and dynamic prediction with exog against Stata
dta = datasets.macrodata.load_pandas().data
cpi_dates = pd.PeriodIndex(start='1959Q1', end='2009Q3', freq='Q')
dta.index = cpi_dates
data = dta
data['loginv'] = np.log(data['realinv'])
data['loggdp'] = np.log(data['realgdp'])
data['logcons'] = np.log(data['realcons'])
forecast_period = pd.PeriodIndex(start='2008Q2', end='2009Q4', freq='Q')
end = forecast_period[0]
data_sample = data.loc[dta.index < end]
exog_full = data[['loggdp', 'logcons']]
# pandas
mod = ARIMA(data_sample['loginv'], (1, 0, 1),
exog=data_sample[['loggdp', 'logcons']])
with warnings.catch_warnings():
warnings.simplefilter("ignore")
res = mod.fit(disp=0, solver='bfgs', maxiter=5000)
predicted_arma_fp = res.predict(start=197, end=202,
exog=exog_full.values[197:]).values
predicted_arma_dp = res.predict(start=193, end=202,
exog=exog_full[197:], dynamic=True)
# numpy
mod2 = ARIMA(np.asarray(data_sample['loginv']),
(1, 0, 1),
exog=np.asarray(data_sample[['loggdp', 'logcons']]))
res2 = mod2.fit(start_params=res.params, disp=0,
solver='bfgs', maxiter=5000)
exog_full = data[['loggdp', 'logcons']]
predicted_arma_f = res2.predict(start=197, end=202,
exog=exog_full.values[197:])
predicted_arma_d = res2.predict(start=193, end=202,
exog=exog_full[197:], dynamic=True)
endog_scale = 100
ex_scale = 1000
# ARIMA(1, 1, 1)
ex = ex_scale * np.asarray(data_sample[['loggdp', 'logcons']].diff())
# The first obsevation is not (supposed to be) used, but I get
# a Lapack problem
# Intel MKL ERROR: Parameter 5 was incorrect on entry to DLASCL.
ex[0] = 0
mod111 = ARIMA(100 * np.asarray(data_sample['loginv']),
(1, 1, 1),
# Stata differences also the exog
exog=ex)
res111 = mod111.fit(disp=0, solver='bfgs', maxiter=5000)
exog_full_d = ex_scale * data[['loggdp', 'logcons']].diff()
res111.predict(start=197, end=202, exog=exog_full_d.values[197:])
predicted_arima_f = res111.predict(start=196, end=202,
exog=exog_full_d.values[197:],
typ='levels')
predicted_arima_d = res111.predict(start=193, end=202,
exog=exog_full_d.values[197:],
typ='levels', dynamic=True)
res_f101 = np.array([
7.73975859954, 7.71660108543, 7.69808978329, 7.70872117504,
7.6518392758, 7.69784279784, 7.70290907856, 7.69237782644,
7.65017785174, 7.66061689028, 7.65980022857, 7.61505314129,
7.51697158428, 7.5165760663, 7.5271053284])
res_f111 = np.array([
7.74460013693, 7.71958207517, 7.69629561172, 7.71208186737,
7.65758850178, 7.69223472572, 7.70411775588, 7.68896109499,
7.64016249001, 7.64871881901, 7.62550283402, 7.55814609462,
7.44431310053, 7.42963968062, 7.43554675427])
res_d111 = np.array([
7.74460013693, 7.71958207517, 7.69629561172, 7.71208186737,
7.65758850178, 7.69223472572, 7.71870821151, 7.7299430215,
7.71439447355, 7.72544001101, 7.70521902623, 7.64020040524,
7.5281927191, 7.5149442694, 7.52196378005])
res_d101 = np.array([
7.73975859954, 7.71660108543, 7.69808978329, 7.70872117504,
7.6518392758, 7.69784279784, 7.72522142662, 7.73962377858,
7.73245950636, 7.74935432862, 7.74449584691, 7.69589103679,
7.5941274688, 7.59021764836, 7.59739267775])
assert_allclose(predicted_arma_dp,
res_d101[-len(predicted_arma_d):],
atol=1e-4)
assert_allclose(predicted_arma_fp,
res_f101[-len(predicted_arma_f):],
atol=1e-4)
assert_allclose(predicted_arma_d,
res_d101[-len(predicted_arma_d):],
atol=1e-4)
assert_allclose(predicted_arma_f,
res_f101[-len(predicted_arma_f):],
atol=1e-4)
assert_allclose(predicted_arima_d / endog_scale,
res_d111[-len(predicted_arima_d):],
rtol=1e-4, atol=1e-4)
assert_allclose(predicted_arima_f / endog_scale,
res_f111[-len(predicted_arima_f):],
rtol=1e-4, atol=1e-4)
# test for forecast with 0 ar fix in GH#2457 numbers again from Stata
res_f002 = np.array([
7.70178181209, 7.67445481224, 7.6715373765, 7.6772915319,
7.61173201163, 7.67913499878, 7.6727609212, 7.66275451925,
7.65199799315, 7.65149983741, 7.65554131408, 7.62213286298,
7.53795983357, 7.53626130154, 7.54539963934])
res_d002 = np.array([
7.70178181209, 7.67445481224, 7.6715373765, 7.6772915319,
7.61173201163, 7.67913499878, 7.67306697759, 7.65287924998,
7.64904451605, 7.66580449603, 7.66252081172, 7.62213286298,
7.53795983357, 7.53626130154, 7.54539963934])
mod_002 = ARIMA(np.asarray(data_sample['loginv']), (0, 0, 2),
exog=np.asarray(data_sample[['loggdp', 'logcons']]))
# doesn't converge with default starting values
start_params = np.concatenate((res.params[[0, 1, 2, 4]], [0]))
res_002 = mod_002.fit(start_params=start_params,
disp=0, solver='bfgs', maxiter=5000)
# forecast
fpredict_002 = res_002.predict(start=197, end=202,
exog=exog_full.values[197:])
forecast_002 = res_002.forecast(steps=len(exog_full.values[197:]),
exog=exog_full.values[197:])
forecast_002 = forecast_002[0]
# TODO: we are not checking the other results
assert_allclose(fpredict_002,
res_f002[-len(fpredict_002):],
rtol=1e-4, atol=1e-6)
assert_allclose(forecast_002,
res_f002[-len(forecast_002):],
rtol=1e-4, atol=1e-6)
# dynamic predict
dpredict_002 = res_002.predict(start=193, end=202,
exog=exog_full.values[197:],
dynamic=True)
assert_allclose(dpredict_002,
res_d002[-len(dpredict_002):],
rtol=1e-4, atol=1e-6)
# GH#4497
# in-sample dynamic predict should not need exog, #2982
predict_3a = res_002.predict(start=100, end=120, dynamic=True)
predict_3b = res_002.predict(start=100, end=120,
exog=exog_full.values[100:120], dynamic=True)
assert_allclose(predict_3a, predict_3b, rtol=1e-10)
# TODO: break this out into a specific non-smoke test
# GH#4915 invalid exogs passed to forecast should raise
h = len(exog_full.values[197:])
with pytest.raises(ValueError):
res_002.forecast(steps=h)
with pytest.raises(ValueError):
res_002.forecast(steps=h, exog=np.empty((h, 20)))
with pytest.raises(ValueError):
res_002.forecast(steps=h, exog=np.empty(20))
@pytest.mark.not_vetted
def test_arima_fit_multiple_calls():
y = [-1214.360173, -1848.209905, -2100.918158, -3647.483678, -4711.186773]
mod = ARIMA(y, (1, 0, 2))
# Make multiple calls to fit
with warnings.catch_warnings(record=True):
mod.fit(disp=0, start_params=[np.mean(y), .1, .1, .1])
assert mod.exog_names == ['const', 'ar.L1.y', 'ma.L1.y', 'ma.L2.y']
with warnings.catch_warnings(record=True):
mod.fit(disp=0, start_params=[np.mean(y), .1, .1, .1])
assert mod.exog_names == ['const', 'ar.L1.y', 'ma.L1.y', 'ma.L2.y']
# test multiple calls when there is only a constant term
mod = ARIMA(y, (0, 0, 0))
# Make multiple calls to fit
with warnings.catch_warnings(record=True):
mod.fit(disp=0, start_params=[np.mean(y)])
assert mod.exog_names == ['const']
with warnings.catch_warnings(record=True):
mod.fit(disp=0, start_params=[np.mean(y)])
assert mod.exog_names == ['const']
@pytest.mark.not_vetted
def test_long_ar_start_params():
arparams = np.array([1, -.75, .25])
maparams = np.array([1, .65, .35])
nobs = 30
np.random.seed(12345)
y = arma_generate_sample(arparams, maparams, nobs)
model = ARMA(y, order=(2, 2))
model.fit(method='css', start_ar_lags=10, disp=0)
model.fit(method='css-mle', start_ar_lags=10, disp=0)
model.fit(method='mle', start_ar_lags=10, disp=0)
with pytest.raises(ValueError):
model.fit(start_ar_lags=nobs + 5, disp=0)
# ----------------------------------------------------------------
# `predict` tests
@pytest.mark.not_vetted
def test_arima_predict_mle():
cpi = datasets.macrodata.load_pandas().data['cpi'].values
res1 = ARIMA(cpi, (4, 1, 1)).fit(disp=-1)
# fit the model so that we get correct endog length but use
path = os.path.join(current_path, 'results',
'results_arima_forecasts_all_mle.csv')
arima_forecasts = pd.read_csv(path).values
fc = arima_forecasts[:, 0]
fcdyn = arima_forecasts[:, 1]
fcdyn2 = arima_forecasts[:, 2]
fcdyn3 = arima_forecasts[:, 3]
fcdyn4 = arima_forecasts[:, 4]
# 0 indicates the first sample-observation below
# ie., the index after the pre-sample, these are also differenced once
# so the indices are moved back once from the cpi in levels
# start < p, end <p 1959q2 - 1959q4
start, end = 1, 3
fv = res1.predict(start, end, typ='levels')
assert_almost_equal(fv, fc[start:end + 1], DECIMAL_4)
# start < p, end 0 1959q3 - 1960q1
start, end = 2, 4
fv = res1.predict(start, end, typ='levels')
assert_almost_equal(fv, fc[start:end + 1], DECIMAL_4)
# start < p, end >0 1959q3 - 1971q4
start, end = 2, 51
fv = res1.predict(start, end, typ='levels')
assert_almost_equal(fv, fc[start:end + 1], DECIMAL_4)
# start < p, end nobs 1959q3 - 2009q3
start, end = 2, 202
fv = res1.predict(start, end, typ='levels')
assert_almost_equal(fv, fc[start:end + 1], DECIMAL_4)
# start < p, end >nobs 1959q3 - 2015q4
start, end = 2, 227
fv = res1.predict(start, end, typ='levels')
assert_almost_equal(fv, fc[start:end + 1], DECIMAL_4)
# start 0, end >0 1960q1 - 1971q4
start, end = 4, 51
fv = res1.predict(start, end, typ='levels')
assert_almost_equal(fv, fc[start:end + 1], DECIMAL_4)
# start 0, end nobs 1960q1 - 2009q3
start, end = 4, 202
fv = res1.predict(start, end, typ='levels')
assert_almost_equal(fv, fc[start:end + 1], DECIMAL_4)
# start 0, end >nobs 1960q1 - 2015q4
start, end = 4, 227
fv = res1.predict(start, end, typ='levels')
assert_almost_equal(fv, fc[start:end + 1], DECIMAL_4)
# start >p, end >0 1965q1 - 1971q4
start, end = 24, 51
fv = res1.predict(start, end, typ='levels')
assert_almost_equal(fv, fc[start:end + 1], DECIMAL_4)
# start >p, end nobs 1965q1 - 2009q3
start, end = 24, 202
fv = res1.predict(start, end, typ='levels')
| assert_almost_equal(fv, fc[start:end + 1], DECIMAL_4) | numpy.testing.assert_almost_equal |
import matplotlib.pyplot as plt
import matplotlib
import numpy as np
from matplotlib.pyplot import *
from PIL import Image
colors = [ 'xkcd:blue',
'xkcd:red',
'xkcd:purple',
'xkcd:orchid',
'xkcd:orange',
'xkcd:grey',
'xkcd:teal',
'xkcd:sienna',
'xkcd:azure',
'xkcd:green',
'xkcd:black',
'xkcd:goldenrod']
def plot_curves(curves,
xlabel='% Dataset Labeled\n(ScanNet-5-Recon)',
xlim=[4, 36],
xticks= | np.arange(5, 35, 5) | numpy.arange |
import numpy as np
import pyspark.sql.functions as F
import pyspark.sql.types as T
from pyspark.ml.feature import IDF, Tokenizer, CountVectorizer
def isin(element, test_elements, assume_unique=False, invert=False):
"""
Impliments the numpy function isin() for legacy versions of
the library
"""
element = | np.asarray(element) | numpy.asarray |
#!/usr/bin/env python
"""
@package ion_functions.data.wav_functions
@file ion_functions/data/wav_functions.py
@author <NAME>
@brief Module containing WAVSS wave statistics data-calculations.
"""
import numpy as np
from ion_functions.data.generic_functions import magnetic_declination
from ion_functions.utils import fill_value
def wav_triaxys_dir_freq(nfreq_nondir, nfreq_dir, freq0, delta_freq):
"""
FLAG:
The variable nfreq_dir put out by the WAVSS instrument and therefore
also the data product WAVSTAT-FDS_L1 can vary within each datapacket
based solely on measured ocean conditions (with unchanged instrument
settings). The numbers of values in the L0 data products WAVSTAT_PDS
and WAVSTAT_SDS for each datapacket are also determined by the nfreq_dir
values, as is true with the WAVSTAT-DDS_L2 data product (see function
def wav_triaxys_correct_directional_wave_direction).
Description:
Function to compute the WAVSTAT-FDS_L1 data product (frequency values for
directional wave spectral bins) for the WAVSS instrument class (TRIAXYS
Wave Sensor, manufactured by AXYS Technologies).
Implemented by:
2014-04-03: <NAME>. Initial code.
Usage:
fds = wav_triaxys_dir_freq(nfreq_nondir, nfreq_dir, freq0, delta_freq)
where
fds = frequency values for directional wave spectral bins (WAVSTAT-FDS_L1) [Hz]
nfreq_nondir = number of non-directional wave frequency bins from the value specified in the
WAVSS $TSPNA (not $TSPMA) data sentence.
nfreq_dir = number of directional wave frequency bins from the value specified in the WAVSS
$TSPMA data sentence.
freq0 = initial frequency value from the value specified in the WAVSS $TSPMA data sentence.
delta_freq = frequency spacing from the value specified in the WAVSS $TSPMA data sentence.
References:
OOI (2012). Data Product Specification for Wave Statistics. Document Control
Number 1341-00450. https://alfresco.oceanobservatories.org/ (See:
Company Home >> OOI >> Controlled >> 1000 System Level >>
1341-00450_Data_Product_WAVE_STATISTICS_OOI.pdf)
"""
# condition input variables.
# all delta_freq and freq0 values will be floats.
nfreq_nondir = np.array(nfreq_nondir, ndmin=1)
nfreq_dir = np.array(nfreq_dir, ndmin=1)
freq0 = np.array(freq0, ndmin=1)
delta_freq = np.array(delta_freq, ndmin=1)
# each data packet may call for a different number of directional frequency values nfreq_dir.
# however, this number will always be <= nfreq_nondir, and all the nfreq_nondir values will be identical.
npackets = nfreq_nondir.shape[0]
fds = np.zeros((npackets, int(nfreq_nondir[0]))) + fill_value
# for the linspace calculation, which is slightly slower than using arange.
#freq_end = freq0 + (nfreq_dir - 1) * delta_freq
for ii in range(npackets):
#fds[ii, 0:nfreq_dir[ii]] = np.linspace(freq0[ii], freq_end[ii], num=nfreq_dir[ii])
fds[ii, 0:nfreq_dir[ii]] = freq0[ii] + np.arange(nfreq_dir[ii]) * delta_freq[ii]
## return a "rank 1 vector" if fds is a 2D row vector
#if fds.shape[0] == 1:
# fds = np.reshape(fds, (fds.shape[1],))
return fds
def wav_triaxys_nondir_freq(nfreq, freq0, delta_freq):
"""
Description:
Function to compute the WAVSTAT-FND_L1 data product (frequency values for
non-directional wave spectral bins) for the WAVSS instrument class (TRIAXYS
Wave Sensor, manufactured by AXYS Technologies).
Implemented by:
2014-04-03: <NAME>. Initial code.
Usage:
fnd = wav_triaxys_nondir_freq(nfreq, freq0, delta_freq)
where
fnd = frequency values for non-directional wave spectral bins (WAVSTAT-FND_L1) [Hz]
nfreq = number of frequency bins from the value specified in the WAVSS $TSPNA data sentence.
freq0 = initial frequency value from the value specified in the WAVSS $TSPNA data sentence.
delta_freq = frequency spacing from the value specified in the WAVSS $TSPNA data sentence.
References:
OOI (2012). Data Product Specification for Wave Statistics. Document Control
Number 1341-00450. https://alfresco.oceanobservatories.org/ (See:
Company Home >> OOI >> Controlled >> 1000 System Level >>
1341-00450_Data_Product_WAVE_STATISTICS_OOI.pdf)
"""
# condition input variables
nfreq = np.array(nfreq, ndmin=1)
freq0 = np.array(freq0, ndmin=1)
delta_freq = np.array(delta_freq, ndmin=1)
# each set of data inputs will call for the same number of frequency values nfreq.
# therefore can vectorize (without using forloop as had to be done for the
# directional frequencies case) by setting up all variables as 2D arrays
# of size(npackets, nfreq).
npackets = nfreq.shape[0]
n_freqs = nfreq[0]
# orient arrays such that lead index indexes each set of data inputs
freq0_2d = np.tile(freq0, (n_freqs, 1)).transpose()
delta_freq_2d = np.tile(delta_freq, (n_freqs, 1)).transpose()
steps_2d = np.tile(np.arange(n_freqs), (npackets, 1))
fnd = freq0_2d + steps_2d * delta_freq_2d
## return a "rank 1 vector" if fnd is a 2D row vector
#if fnd.shape[0] == 1:
# fnd = np.reshape(fnd, (fnd.shape[1],))
return fnd
def wav_triaxys_buoymotion_time(ntp_timestamp, ntime, time0, delta_time):
"""
Description:
Function to compute the WAVSTAT-MOTT_L1 data product (time values associated with
buoy displacement measurements WAVSTAT-MOT[X,Y,Z]) for the WAVSS instrument class
(TRIAXYS Wave Sensor, manufactured by AXYS Technologies).
Implemented by:
2014-04-07: <NAME>. Initial code.
Usage:
mott = wav_triaxys_buoymotion_time(ntp_timestamp, ntime, time0, delta_time):
where
mott = NTP times corresponding to buoy displacement data measurements (WAVSTAT-MOTT_L1)
[secs since 1900-01-01].
ntp_timestamp = NTP time stamp corresponding to the date and time specified in
the $TSPHA data sentence [secs since 1900-01-01].
ntime = number of time values from the value specified in the WAVSS $TSPHA data sentence.
time0 = time elapsed between ntp_timestamp and time of first WAVSTAT-MOT[XYZ] data point,
from the value specified in the WAVSS $TSPHA data sentence ("Initial Time") [sec].
delta_time = time intervals between subsequent buoydisplacement measurement times,
from the value specified in the WAVSS $TSPHA data sentence ("Time Spacing") [sec].
References:
OOI (2012). Data Product Specification for Wave Statistics. Document Control
Number 1341-00450. https://alfresco.oceanobservatories.org/ (See:
Company Home >> OOI >> Controlled >> 1000 System Level >>
1341-00450_Data_Product_WAVE_STATISTICS_OOI.pdf)
"""
# condition input variables;
# make sure time interval is not type integer
ntime = np.array(ntime, ndmin=1)
time0 = np.array(time0, ndmin=1)
delta_time = np.array(delta_time, dtype='float', ndmin=1)
# this algorithm is almost identical to that contained in def wav_wavss_nondir_freq above.
# these are the dimensions of all the 2D arrays used in the calculation
npackets = ntime.shape[0]
n_time_values = ntime[0]
# orient the lead index to iterate over the data packet number
ntp0_2d = np.tile(ntp_timestamp + time0, (n_time_values, 1)).transpose()
delta_time_2d = np.tile(delta_time, (n_time_values, 1)).transpose()
steps_2d = np.tile(np.arange(n_time_values), (npackets, 1))
mott = ntp0_2d + steps_2d * delta_time_2d
## return a "rank 1 vector" if fnd is a 2D row vector
#if mott.shape[0] == 1:
# mott = np.reshape(mott, (mott.shape[1],))
return mott
def wav_triaxys_correct_mean_wave_direction(dir_raw, lat, lon, ntp_ts):
"""
Description:
Function to compute the WAVSTAT-D_L2 data product (mean wave direction corrected for magnetic
declination) for the WAVSS instrument class (TRIAXYS Wave Sensor, manufactured by AXYS Technologies).
Implemented by:
2014-04-08: <NAME>. Initial code.
Usage:
dir_cor = wav_triaxys_correct_mean_wave_direction(dir_raw, lat, lon, ntp_ts)
where
dir_cor = mean wave direction corrected for magnetic declination (WAVSTAT-D_L2) [deg, [0 360)].
dir_raw = uncorrected mean wave direction (WAVSTAT-D_L0) [deg, [0 360)].
lat = latitude of the instrument [decimal degrees]. North is positive, South negative.
lon = longitude of the instrument [decimal degrees]. East is positive, West negative.
ntp_ts = NTP time stamp from a data particle [secs since 1900-01-01].
References:
OOI (2012). Data Product Specification for Wave Statistics. Document Control
Number 1341-00450. https://alfresco.oceanobservatories.org/ (See:
Company Home >> OOI >> Controlled >> 1000 System Level >>
1341-00450_Data_Product_WAVE_STATISTICS_OOI.pdf)
"""
# calculate the magnetic declination using the WWM2010 model
# the WAVSS is a surface wave sensor, so that height above sealevel = 0,
# which is the default value used in the magnetic_declination calculation.
theta = magnetic_declination(lat, lon, ntp_ts)
# directions are [0,360) degrees; and magnetic declinations can be positive or negative
dir_cor = np.mod(dir_raw + theta + 360, 360)
# return corrected direction
return dir_cor
def wav_triaxys_correct_directional_wave_direction(dir_raw, lat, lon, ntp_ts):
"""
FLAG:
The numbers of values in the L0 and L2 data product WAVSTAT_DDS for each datapacket
are determined by the values of the nfreq_dir variable, which can vary as a function
of measured ocean conditions at fixed instrument setting. See also the FLAG note for
function def wav_triaxys_dir_freq.
Description:
Function to compute the WAVSTAT-DDS_L2 data product (directional wave
directions corrected for magnetic declination) for the WAVSS instrument
class (TRIAXYS Wave Sensor, manufactured by AXYS Technologies).
Implemented by:
2014-04-09: <NAME>. Initial code.
Usage:
dir_cor = wav_triaxys_correct_directional_wave_direction(dir_raw, lat, lon, ntp_ts)
where
dir_cor = directional waves' directions corrected for magnetic declination
(WAVSTAT-DDS_L2) [deg, [0 360)].
dir_raw = uncorrected directional waves' directions (WAVSTAT-DDS_L0) [deg, [0 360)].
lat = latitude of the instrument [decimal degrees]. North is positive, South negative.
lon = longitude of the instrument [decimal degrees]. East is positive, West negative.
ntp_ts = NTP time stamp from a data particle [secs since 1900-01-01].
References:
OOI (2012). Data Product Specification for Wave Statistics. Document Control
Number 1341-00450. https://alfresco.oceanobservatories.org/ (See:
Company Home >> OOI >> Controlled >> 1000 System Level >>
1341-00450_Data_Product_WAVE_STATISTICS_OOI.pdf)
"""
# assume that the dir_raw data product comes in as a 2D numpy array with fill values
# appropriately placed to account for the cases in which the number of reported
# directional wave frequency bins differs from data packet to data packet (and is
# less than the number of reported non-directional frequency bins).
dir_raw = np.array(dir_raw, ndmin=2)
# change fill values to Nans, so that subsequent array operations will leave the
# Nan entries unchanged.
dir_raw[dir_raw == fill_value] = np.nan
# calculate the magnetic declination using the WWM2010 model
# the WAVSS is a surface wave sensor, so that height above sealevel = 0,
# which is the default value used in the magnetic_declination calculation.
theta = magnetic_declination(lat, lon, ntp_ts)
# theta in general will be a vector, so replicate it into a matrix to match the dir_raw dimensions.
theta = np.tile(theta, (dir_raw.shape[1], 1)).transpose()
# directions are [0,360) degrees; and magnetic declinations can be positive or negative
dir_cor = np.mod(dir_raw + theta + 360, 360)
# replace Nans with fills
dir_cor[np.isnan(dir_cor)] = fill_value
# return corrected directions
return dir_cor
def wav_triaxys_magcor_buoymotion_x(x, y, lat, lon, ntp_timestamp):
"""
Description:
Function to compute the WAVSTAT-MOTX_L1 data product (eastward buoy displacement)
for the WAVSS instrument class (TRIAXYS Wave Sensor, manufactured by AXYS Technologies)
from the WAVSTAT-MOTX_L0 and WAVSTAT-MOTY_L0 data products. All that is required is to
correct for magnetic declination (variation).
Implemented by:
2014-04-10: <NAME>. Initial code. Uses magnetic declination values calculated
using the WMM 2010 model. WAVSS is a surface sensor, so
that the depth variable for calculating declination is 0
(default value for the magnetic_declination function).
Usage:
motx = wav_triaxys_magcor_buoymotion_x(x, y, lat, lon, ntp_timestamp)
where
motx = East displacement of the buoy on which the WAVSS is mounted, corrected for
magnetic declination (WAVSTAT-MOTX_L1) [m]
x = uncorrected eastward displacement (WAVSTAT-MOTX_L0) [m]
y = uncorrected northward displacement (WAVSTAT-MOTY_L0) [m]
lat = instrument's deployment latitude [decimal degrees]
lon = instrument's deployment longitude [decimal degrees]
ntp_timestamp = NTP time stamp corresponding to the date and time specified in
the $TSPHA data sentence [secs since 1900-01-01].
Note as to the values of ntp_timestamp used in the calculation:
The maximum sampling period for this instrument is 35 minutes, during which time
the magnetic declination will not change. Therefore, to correct for magnetic
declinaton only one timestamp is required for each ensemble of (x,y) values acquired
during any given sampling period. All that is necessary, then, is the ntp_timestamp
specified above, which is the same input ntp_timestamp parameter used in the function
wav_triaxys_buoymotion_time; it is not necessary to use the vector timestamps in the
WAVSTAT-MOTT_L1 data product.
References:
OOI (2012). Data Product Specification for Wave Statistics. Document Control
Number 1341-00450. https://alfresco.oceanobservatories.org/ (See:
Company Home >> OOI >> Controlled >> 1000 System Level >>
1341-00450_Data_Product_WAVE_STATISTICS_OOI.pdf)
"""
# force shapes of inputs to arrays
x = np.atleast_2d(x)
y = np.atleast_2d(y)
lat = np.atleast_1d(lat)
lon = np.atleast_1d(lon)
ntp_timestamp = np.atleast_1d(ntp_timestamp)
# calculate the magnetic declination using the WWM2010 model.
# the WAVSS surface wave sensor is at sealevel, which is the default z value for mag dec.
theta = magnetic_declination(lat, lon, ntp_timestamp)
# correct for declination by rotating coordinates.
# the function magnetic_correction_einsum was written to correct (u,v) velocities, but
# it also applies to (E,N) coordinates.
motx, _ = magnetic_correction_einsum(theta, x, y)
# return corrected Eastward buoy displacement(s)
return motx
def wav_triaxys_magcor_buoymotion_y(x, y, lat, lon, ntp_timestamp):
"""
Description:
Function to compute the WAVSTAT-MOTY_L1 data product (northward buoy displacement)
for the WAVSS instrument class (TRIAXYS Wave Sensor, manufactured by AXYS Technologies)
from the WAVSTAT-MOTX_L0 and WAVSTAT-MOTY_L0 data products. All that is required is to
correct for magnetic declination (variation).
Implemented by:
2014-04-10: <NAME>. Initial code. Uses magnetic declination values calculated
using the WMM 2010 model. WAVSS is a surface sensor, so
that the depth variable for calculating declination is 0
(default value for the magnetic_declination function).
Usage:
moty = wav_triaxys_magcor_buoymotion_y(x, y, lat, lon, dt)
where
moty = North displacement of the buoy on which the WAVSS is mounted, corrected for
magnetic declination (WAVSTAT-MOTY_L1) [m]
x = uncorrected eastward displacement (WAVSTAT-MOTX_L0) [m]
y = uncorrected northward displacement (WAVSTAT-MOTY_L0) [m]
lat = instrument's deployment latitude [decimal degrees]
lon = instrument's deployment longitude [decimal degrees]
ntp_timestamp = NTP time stamp corresponding to the date and time specified in
the $TSPHA data sentence [secs since 1900-01-01].
Note as to the values of ntp_timestamp used in the calculation:
See Note in Usage section of wav_triaxys_magcor_buoymotion_x.
References:
OOI (2012). Data Product Specification for Wave Statistics. Document Control
Number 1341-00450. https://alfresco.oceanobservatories.org/ (See:
Company Home >> OOI >> Controlled >> 1000 System Level >>
1341-00450_Data_Product_WAVE_STATISTICS_OOI.pdf)
"""
# force shapes of inputs to arrays
x = np.atleast_2d(x)
y = np.atleast_2d(y)
lat = np.atleast_1d(lat)
lon = np.atleast_1d(lon)
ntp_timestamp = np.atleast_1d(ntp_timestamp)
# calculate the magnetic declination using the WWM2010 model.
# the WAVSS surface wave sensor is at sealevel, which is the default z value for mag dec.
theta = magnetic_declination(lat, lon, ntp_timestamp)
# correct for declination by rotating coordinates.
# the function magnetic_correction_einsum was written to correct (u,v) velocities, but
# it also applies to (E,N) coordinates.
_, moty = magnetic_correction_einsum(theta, x, y)
# return corrected Northward buoy displacement(s)
return moty
def magnetic_correction_einsum(theta, u, v):
"""
Description:
The executable code in this function is identical to that in the function
magnetic_correction_vctrzd in the module adcp_functions. At some point in
the future the function magnetic_correction in generic_functions may be
deprecated and replaced with this vectorized and much faster version.
This function corrects velocity profiles for the magnetic variation
(declination) at the measurement location. The magnetic declination
is obtained from the 2010 World Magnetic Model (WMM2010) provided by
NOAA (see wmm_declination).
This version handles 'vectorized' input variables without using for
loops. It was specifically written to handle the case of a 1D array of
theta values, theta=f(i), with corresponding sets of 'u' and 'v' values
such that u=f(i,j) and v=f(i,j), where there are j 'u' and 'v' values
for each theta(i).
Implemented by:
2014-04-04: <NAME>. Initial code. This function is used to
calculate magnetic corrections by the functions contained
in this module instead of the function magnetic_correction
found in ion_functions.data.generic_functions.
Usage:
u_cor, v_cor = magnetic_correction(theta, u, v)
where
u_cor = eastward velocity profiles, in earth coordinates, with
the correction for magnetic variation applied.
v_cor = northward velocity profiles, in earth coordinates,
with the correction for magnetic variation applied.
theta = magnetic variation based on location (latitude, longitude and
altitude) and date; units of theta are [degrees]
u = uncorrected eastward velocity profiles in earth coordinates
v = uncorrected northward velocity profiles in earth coordinates
References:
OOI (2012). Data Product Specification for Velocity Profile and Echo
Intensity. Document Control Number 1341-00750.
https://alfresco.oceanobservatories.org/ (See: Company Home >> OOI
>> Controlled >> 1000 System Level >>
1341-00750_Data_Product_SPEC_VELPROF_OOI.pdf)
OOI (2013). Data Product Specification for Turbulent Velocity Profile
and Echo Intensity. Document Control Number 1341-00760.
https://alfresco.oceanobservatories.org/ (See: Company Home >> OOI
>> Controlled >> 1000 System Level >>
1341-00760_Data_Product_SPEC_VELPROF_OOI.pdf)
"""
# force shapes of inputs to arrays
theta = np.atleast_1d(theta)
uv = np.atleast_2d(u)
v = | np.atleast_2d(v) | numpy.atleast_2d |
# coding=utf-8
# Copyright 2021 The init2winit 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.
"""Trainer for the init2winit project."""
import collections
import functools
import itertools
import json
import os
import struct
import time
from typing import Any, Dict, Optional, Sequence
from absl import flags
from absl import logging
from flax import jax_utils
from init2winit import callbacks
from init2winit import checkpoint
from init2winit import hyperparameters
from init2winit import schedules
from init2winit import utils
from init2winit.dataset_lib import data_utils
from init2winit.dataset_lib import datasets
from init2winit.init_lib import initializers
from init2winit.model_lib import model_utils
from init2winit.model_lib import models
from init2winit.optimizer_lib import optimizers
import jax
from jax import lax
import jax.numpy as jnp
import numpy as np
import optax
from tensorflow.io import gfile
FLAGS = flags.FLAGS
_GRAD_CLIP_EPS = 1e-6
def evaluate(
params,
batch_stats,
batch_iter,
evaluate_batch_pmapped):
"""Compute aggregated metrics on the given data iterator.
WARNING: The caller is responsible for synchronizing the batch norm statistics
before calling this function!
Assumed API of evaluate_batch_pmapped:
metrics = evaluate_batch_pmapped(params, batch_stats, batch)
where batch is yielded by the batch iterator, and metrics is a dictionary
mapping metric name to a vector of per example measurements. The metric
'denominator' must also be defined. evaluate will aggregate (by summing)
all per example measurements and divide by the aggregated denominator.
For each given metric we compute
1/N sum_{b in batch_iter} metric(b).
Where N will be the sum of 'denominator' over all batches. See
classification_metrics.py for a definition of evaluate_batch.
Args:
params: a dict of trainable model parameters. Passed as {'params': params}
into flax_module.apply().
batch_stats: a dict of non-trainable model state. Passed as
{'batch_stats': batch_stats} into flax_module.apply().
batch_iter: Generator which yields batches. Must support the API
for b in batch_iter:
evaluate_batch_pmapped: A function with API
evaluate_batch_pmapped(params, batch_stats, batch). Returns a dictionary
mapping keys to the summed metric across the sharded batch. The key
'denominator' is required, as this indicates how many real samples were
in the sharded batch.
Returns:
A dictionary of aggregated metrics. The keys will match the keys returned by
evaluate_batch_pmapped.
"""
# TODO(gilmer) Currently we only support metrics of the form 1/N sum f(x_i).
# May need a more general framework to stuff like precision and recall.
# np allows for the total_losses += syntax to work (array assignment).
total_metrics = collections.defaultdict(float)
for batch in batch_iter:
batch = data_utils.shard(batch)
computed_metrics = evaluate_batch_pmapped(
params=params, batch_stats=batch_stats, batch=batch)
for key in computed_metrics:
# The shape of computed_metrics[key] is [n_local_devices]. However,
# because evaluate_batch_pmapped has a psum, we have already summed
# across the whole sharded batch, and what's returned is n_local_devices
# copies of the same summed metric. So here we just grab the 0'th entry.
total_metrics[key] += np.float32(computed_metrics[key][0])
# For data splits with no data (e.g. Imagenet no test set) no values
# will appear for that split.
for key in total_metrics:
# Convert back to numpy
if np.isnan(total_metrics[key]):
raise utils.TrainingDivergedError('NaN detected in {}'.format(key))
if key != 'denominator':
total_metrics[key] = total_metrics[key] / np.float32(
total_metrics['denominator'])
return total_metrics
def _inject_learning_rate(optimizer_state, lr):
"""Inject the given LR into any optimizer state that will accept it."""
# The optimizer state should always be an InjectHyperparamsState, and we
# inject the learning rate into all states that will accept it. We need to do
# this to allow arbitrary (non-jittable) LR schedules.
if isinstance(optimizer_state, optax.InjectHyperparamsState):
if 'learning_rate' in optimizer_state.hyperparams:
optimizer_state.hyperparams['learning_rate'] = lr
else:
raise ValueError(
'Unsupported optimizer_state type given when trying to inject the '
'learning rate:\n\n{}.'.format(optimizer_state))
def update(
optimizer_state,
params,
batch_stats,
batch,
step,
lr,
rng,
local_device_index,
training_metrics_grabber,
training_cost,
grad_clip,
optimizer_update_fn):
"""Single step of the training loop.
Args:
optimizer_state: the optax optimizer state.
params: a dict of trainable model parameters. Passed into training_cost(...)
which then passes into flax_module.apply() as {'params': params} as part
of the variables dict.
batch_stats: a dict of non-trainable model state. Passed into
training_cost(...) which then passes into flax_module.apply() as
{'batch_stats': batch_stats} as part of the variables dict.
batch: the per-device batch of data to process.
step: the current global step of this update. Used to fold in to `rng` to
produce a unique per-device, per-step RNG.
lr: the floating point learning rate for this step.
rng: the RNG used for calling the model. `step` and `local_device_index`
will be folded into this to produce a unique per-device, per-step RNG.
local_device_index: an integer that is unique to this device amongst all
devices on this host, usually in the range [0, jax.local_device_count()].
It is folded in to `rng` to produce a unique per-device, per-step RNG.
training_metrics_grabber: See the TrainingMetricsGrabber in utils.py
training_cost: a function used to calculate the training objective that will
be differentiated to generate updates. Takes
(`params`, `batch`, `batch_stats`, `dropout_rng`) as inputs.
grad_clip: Clip the l2 norm of the gradient at the specified value. For
minibatches with gradient norm ||g||_2 > grad_clip, we rescale g to the
value g / ||g||_2 * grad_clip. If None, then no clipping will be applied.
optimizer_update_fn: the optimizer update function.
Returns:
A tuple of the new optimizer, the new batch stats, the scalar training cost,
and the updated metrics_grabber.
"""
# `jax.random.split` is very slow outside the train step, so instead we do a
# `jax.random.fold_in` here.
rng = jax.random.fold_in(rng, step)
rng = jax.random.fold_in(rng, local_device_index)
_inject_learning_rate(optimizer_state, lr)
def opt_cost(params):
return training_cost(
params, batch=batch, batch_stats=batch_stats, dropout_rng=rng)
grad_fn = jax.value_and_grad(opt_cost, has_aux=True)
(cost_value, new_batch_stats), grad = grad_fn(params)
new_batch_stats = new_batch_stats.get('batch_stats', None)
cost_value, grad = lax.pmean((cost_value, grad), axis_name='batch')
grad_norm = jnp.sqrt(model_utils.l2_regularization(grad, 0))
# TODO(znado): move to inside optax gradient clipping.
if grad_clip:
scaled_grad = jax.tree_map(
lambda x: x / (grad_norm + _GRAD_CLIP_EPS) * grad_clip, grad)
grad = jax.lax.cond(grad_norm > grad_clip, lambda _: scaled_grad,
lambda _: grad, None)
model_updates, new_optimizer_state = optimizer_update_fn(
grad,
optimizer_state,
params=params,
batch=batch,
batch_stats=new_batch_stats)
new_params = optax.apply_updates(params, model_updates)
new_metrics_grabber = None
if training_metrics_grabber:
new_metrics_grabber = training_metrics_grabber.update(
grad, params, new_params)
return (new_optimizer_state, new_params, new_batch_stats, cost_value,
new_metrics_grabber, grad_norm)
def _merge_and_apply_prefix(d1, d2, prefix):
d1 = d1.copy()
for key in d2:
d1[prefix+key] = d2[key]
return d1
@utils.timed
def eval_metrics(params, batch_stats, dataset, eval_num_batches,
eval_train_num_batches, evaluate_batch_pmapped):
"""Evaluates the given network on the train, validation, and test sets.
WARNING: we assume that `batch_stats` has already been synchronized across
devices before being passed to this function! See
`_maybe_sync_batchnorm_stats`.
The metric names will be of the form split/measurement for split in the set
{train, valid, test} and measurement in the set {loss, error_rate}.
Args:
params: a dict of trainable model parameters. Passed as {'params': params}
into flax_module.apply().
batch_stats: a dict of non-trainable model state. Passed as
{'batch_stats': batch_stats} into flax_module.apply().
dataset: Dataset returned from datasets.get_dataset. train, validation, and
test sets.
eval_num_batches: (int) The batch size used for evaluating on validation,
and test sets. Set to None to evaluate on the whole test set.
eval_train_num_batches: (int) The batch size used for evaluating on train
set. Set to None to evaluate on the whole training set.
evaluate_batch_pmapped: Computes the metrics on a sharded batch.
Returns:
A dictionary of all computed metrics.
"""
train_iter = dataset.eval_train_epoch(eval_train_num_batches)
valid_iter = dataset.valid_epoch(eval_num_batches)
test_iter = dataset.test_epoch(eval_num_batches)
metrics = {}
for split_iter, split_name in zip([train_iter, valid_iter, test_iter],
['train', 'valid', 'test']):
split_metrics = evaluate(params, batch_stats, split_iter,
evaluate_batch_pmapped)
metrics = _merge_and_apply_prefix(metrics, split_metrics,
(split_name + '/'))
return metrics
def initialize(flax_module,
initializer,
loss_fn,
input_shape,
output_shape,
hps,
rng,
metrics_logger,
fake_batch=None):
"""Run the given initializer.
We initialize in 3 phases. First we run the default initializer that is
specified by the model constructor. Next we apply any rescaling as specified
by hps.layer_rescale_factors. Finally we run the black box initializer
provided by the initializer arg (the default is noop).
Args:
flax_module: The Flax nn.Module.
initializer: An initializer defined in init_lib.
loss_fn: A loss function.
input_shape: The input shape of a single data example.
output_shape: The output shape of a single data example.
hps: A dictionary specifying the model and initializer hparams.
rng: An rng key to seed the initialization.
metrics_logger: Used for black box initializers that have learning curves.
fake_batch: Fake input used to intialize the network or None if using
init_by_shape.
Returns:
A tuple (model, batch_stats), where model is the initialized
flax.nn.Model and batch_stats is the collection used for batch norm.
"""
model_dtype = utils.dtype_from_str(hps.model_dtype)
# init_by_shape should either pass in a tuple or a list of tuples.
# For example, for vision tasks typically input_shape is (image_shape)
# For seq2seq tasks, shape can be a list of two tuples corresponding to
# input_sequence_shape for encoder and output_sequence_shape for decoder.
# TODO(gilmer,ankugarg): Support initializers for list of tuples.
#
# Note that this fake input batch will be optimized away because the init
# function is jitted. However, this can still cause memory issues if it is
# large because it is passed in as an XLA argument. Therefore we use a fake
# batch size of 2 (we do not want to use 1 in case there is any np.squeeze
# calls that would remove it), because we assume that there is no dependence
# on the batch size with the model (batch norm reduces across a batch dim of
# any size). This is similar to how the Flax examples initialize models:
# https://github.com/google/flax/blob/44ee6f2f4130856d47159dc58981fb26ea2240f4/examples/imagenet/train.py#L70.
if fake_batch:
fake_input_batch = fake_batch
elif isinstance(input_shape, list): # Typical case for seq2seq models
fake_input_batch = [
| np.zeros((2, *x), model_dtype) | numpy.zeros |
# -*- coding: utf-8 -*-
#以捕捉手指上系的蓝色便签条为例
#摄像头480p,ubuntu 18.10
#macbook air BIG SUR
#拍摄图片中不能出现其他作为标志色的物品啦。
import random
import time
import cv2
import numpy as np
#import matplotlib.pyplot as plt
from turtle import *
from time import ctime,sleep
#import threading
delay(delay=None)
color('red', 'blue')
cap = cv2.VideoCapture(0) # 或传入0,使用摄像头
def getpicture():
# 读取一帧
_, frame = cap.read()
# 把 BGR 转为 HSV
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
# HSV中标记色范围
lower_mark = | np.array([100,90,99]) | numpy.array |
"""Definitions for the `Kernel` class."""
from collections import OrderedDict
import numpy as np
from six import string_types
from mosfit.constants import ANG_CGS, C_CGS
from mosfit.modules.arrays.array import Array
# Important: Only define one ``Module`` class per file.
class Kernel(Array):
"""Calculate the kernel for use in computing the likelihood score."""
MIN_COV_TERM = 1.0e-30
def __init__(self, **kwargs):
"""Initialize module."""
super(Kernel, self).__init__(**kwargs)
self._times = np.array([])
self._codeltatime = -1
self._codeltalambda = -1
self._type = kwargs.get('type', False)
def process(self, **kwargs):
"""Process module."""
self.preprocess(**kwargs)
ret = OrderedDict()
# If we are trying to krig between observations, we need an array with
# dimensions equal to the number of intermediate observations.
if self._type == 'full':
kskey = 'kfmat'
elif self._type == 'oa':
kskey = 'koamat'
elif self._type == 'ao':
kskey = 'kaomat'
else:
kskey = 'kmat'
# Get band variances
self._variance = kwargs.get(self.key('variance'), 0.0)
# Get array of real observations.
self._observations = np.array([
ct if (t == 'countrate' or t == 'magcount') else y if (
t == 'magnitude') else fd if t == 'fluxdensity' else None
for y, ct, fd, t in zip(
self._mags, self._cts, self._fds, self._o_otypes)
])
# Get array of model observations.
self._model_observations = kwargs.get('model_observations', [])
# Handle band-specific variances if that option is enabled.
self._band_v_vars = OrderedDict()
for key in kwargs:
if key.startswith('variance-band-'):
self._band_v_vars[key.split('-')[-1]] = kwargs[key]
if self._variance_bands:
self._o_variance_bands = [
self._variance_bands[i] for i in self._all_band_indices]
self._band_vs = np.array([
self._band_v_vars.get(i, self._variance) if
isinstance(i, string_types)
else (i[0] * self._band_v_vars.get(i[1][0], self._variance) +
(1.0 - i[0]) * self._band_v_vars.get(
i[1][0], self._variance))
for i in self._o_variance_bands])
else:
self._band_vs = np.full(
len(self._all_band_indices), self._variance)
# Compute relative errors for count-based observations.
self._band_vs[self._count_inds] = (
10.0 ** (self._band_vs[self._count_inds] / 2.5) - 1.0
) * self._model_observations[self._count_inds]
self._o_band_vs = self._band_vs[self._observed]
if self._type == 'full':
self._band_vs_1 = self._band_vs
self._band_vs_2 = self._band_vs
elif self._type == 'oa':
self._band_vs_1 = self._o_band_vs
self._band_vs_2 = self._band_vs
elif self._type == 'ao':
self._band_vs_1 = self._band_vs
self._band_vs_2 = self._o_band_vs
else:
self._band_vs_1 = self._o_band_vs
self._band_vs_2 = self._o_band_vs
if self._codeltatime >= 0 or self._codeltalambda >= 0:
kmat = np.outer(self._band_vs_1, self._band_vs_2)
if self._codeltatime >= 0:
kmat *= np.exp(self._dt2mat / self._codeltatime ** 2)
if self._codeltalambda >= 0:
kmat *= np.exp(self._dl2mat / self._codeltalambda ** 2)
ret[kskey] = kmat
else:
ret['abandvs'] = self._band_vs
ret['obandvs'] = self._o_band_vs
return ret
def receive_requests(self, **requests):
"""Receive requests from other ``Module`` objects."""
self._average_wavelengths = requests.get('average_wavelengths', [])
self._variance_bands = requests.get('variance_bands', [])
def preprocess(self, **kwargs):
"""Construct kernel distance arrays."""
new_times = np.array(kwargs.get('all_times', []), dtype=float)
self._codeltatime = kwargs.get(self.key('codeltatime'), -1)
self._codeltalambda = kwargs.get(self.key('codeltalambda'), -1)
if np.array_equiv(new_times, self._times) and self._preprocessed:
return
self._times = new_times
self._all_band_indices = kwargs.get('all_band_indices', [])
self._are_bands = | np.array(self._all_band_indices) | numpy.array |
# code to calculate fundamental stellar parameters and distances using
# a "direct method", i.e. adopting a fixed reddening map and bolometric
# corrections
import astropy.units as units
from astropy.coordinates import SkyCoord
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from scipy.interpolate import RegularGridInterpolator
import pdb
def distance_likelihood(plx, plxe, ds):
"""Distance Likelihood
Likelihood of distance given measured parallax
Args:
plx (float): parallax
plxe (float): parallax uncertainty
ds (array): distance in parsecs
Returns:
array: likelihood (not log-likelihood)
"""
lh = ((1.0/(np.sqrt(2.0*np.pi)*plxe))
* np.exp( (-1.0/(2.0*plxe**2))*(plx - 1.0/ds)**2))
return lh
def distance_prior(ds, L):
"""Distance prior
Exponetial decreasing vol density prior
Returns:
array: prior probability (not log-prior)
"""
prior = ds**2/(2.0*L**3.0)*np.exp(-ds/L)
return prior
def stparas(input, dnumodel=-99, bcmodel=-99, dustmodel=-99, dnucor=-99,
useav=-99, plot=0, band='k', ext=-99):
# IAU XXIX Resolution, Mamajek et al. (2015)
r_sun = 6.957e10
gconst = 6.67408e-8
gm = 1.3271244e26
m_sun = gm/gconst
rho_sun = m_sun/(4./3.*np.pi*r_sun**3)
g_sun = gconst*m_sun/r_sun**2.
# solar constants
numaxsun = 3090.
dnusun = 135.1
teffsun = 5777.
Msun = 4.74 # NB this is fixed to MESA BCs!
# assumed uncertainty in bolometric corrections
err_bc=0.02
# assumed uncertainty in extinction
err_ext=0.02
# object containing output values
out = resdata()
## extinction coefficients
extfactors=ext
if (len(band) == 4):
bd=band[0:1]
else:
bd=band[0:2]
######################################
# case 1: input is parallax + colors #
######################################
#with h5py.File(bcmodel,'r') as h5:
teffgrid = bcmodel['teffgrid'][:]
logggrid = bcmodel['logggrid'][:]
fehgrid = bcmodel['fehgrid'][:]
avgrid = bcmodel['avgrid'][:]
bc_band = bcmodel['bc_'+bd][:]
if ((input.plx > 0.)):
# load up bolometric correction grid
# only K-band for now
points = (teffgrid,logggrid,fehgrid,avgrid)
values = bc_band
interp = RegularGridInterpolator(points,values)
### Monte Carlo starts here
# number of samples
nsample = int(1e5)
# length scale for exp decreasing vol density prior in pc
L = 1350.0
# maximum distance to sample (in pc)
maxdis = 1e5
# get a rough maximum and minimum distance
tempdis = 1.0/input.plx
tempdise = input.plxe/input.plx**2
maxds = tempdis + 5.0*tempdise
minds = tempdis - 5.0*tempdise
ds = np.arange(1.0, maxdis, 1.0)
lh = distance_likelihood(input.plx, input.plxe, ds)
prior = distance_prior(ds, L)
dis = lh*prior
dis2 = dis/np.sum(dis)
norm = dis2/np.max(dis2)
# Deal with negative and positive parallaxes differently:
if tempdis > 0:
# Determine maxds based on posterior:
um = np.where((ds > tempdis) & (norm < 0.001))[0]
# Determine minds just like maxds:
umin = np.where((ds < tempdis) & (norm < 0.001))[0]
else:
# Determine maxds based on posterior, taking argmax
# instead of tempdis which is wrong:
um = np.where((ds > np.argmax(norm)) & (norm < 0.001))[0]
# Determine minds just like maxds:
umin = np.where((ds < np.argmax(norm)) & (norm < 0.001))[0]
if (len(um) > 0):
maxds = np.min(ds[um])
else:
maxds = 1e5
if (len(umin) > 0):
minds = np.max(ds[umin])
else:
minds = 1.0
print('using max distance:', maxds)
print('using min distance:', minds)
ds = np.linspace(minds,maxds,nsample)
lh = distance_likelihood(input.plx, input.plxe, ds)
prior = distance_prior(ds, L)
dis = lh*prior
dis2=dis/np.sum(dis)
# sample distances following the discrete distance posterior
np.random.seed(seed=10)
dsamp = np.random.choice(ds, p=dis2, size=nsample)
# interpolate dustmodel dataframe to determine values of reddening.
if (isinstance(dustmodel,pd.DataFrame) == False):
ebvs = np.zeros(len(dsamp))
avs = ebvs
else:
xp = np.concatenate(
([0.0], np.array(dustmodel.columns[2:].str[3:], dtype='float'))
)
fp = np.concatenate(([0.0],np.array(dustmodel.iloc[0][2:])))
ebvs=np.interp(x=dsamp, xp=xp, fp=fp)
avs = extfactors['av']*ebvs
# NB the next line means that useav is not actually working yet
if (useav > -99):
ebvs = np.zeros(len(dsamp)) + useav
ext = extfactors['a'+bd]*ebvs
map = input.mag
mape = input.mage
np.random.seed(seed=12)
map_samp = map + np.random.randn(nsample)*mape
# NB no extinction correction here yet since it is either:
# - already taken into account in ATLAS BCs below
# - corrected for M dwarfs further below
absmag = -5.0*np.log10(dsamp) + map_samp + 5.
# assume solar metallicity if no input feh is provided
if (input.feh == -99.0):
feh = 0.0
else:
feh = input.feh
# if no Teff is provided, use color-Teff relations:
### A and earlier: Flower et al.
### FGK dwarfs: Casagrande et al. 2010
### M dwarfs: Mann et al. 2015
if (input.teff == -99.0):
if ((input.bmag > -99.0) & (input.vmag > -99.0)):
bvmag = ((input.bmag-np.median(ebvs*extfactors['ab']))
- (input.vmag-np.median(ebvs*extfactors['av'])))
print(bvmag)
col=((input.bmag-ebvs*extfactors['ab'])-(input.vmag-ebvs*extfactors['av']))
#pdb.set_trace()
if ((bvmag >= 0.18) & (bvmag <= 1.29)):
input.teff=casagrande_bv(bvmag,feh)
print('using Casagrande B-V for Teff')
if (bvmag < 0.19):
input.teff=torres_bv(bvmag,feh)
print('using Flower/Torres B-V for Teff')
print(input.teff)
if ((input.btmag > -99.0) & (input.vtmag > -99.0)):
bvtmag = ((input.btmag-np.median(ebvs*extfactors['abt']))
- (input.vtmag-np.median(ebvs*extfactors['avt'])))
if ((bvmag >= 0.19) & (bvmag <= 1.49)):
input.teff = casagrande_bvt(bvtmag, feh)
print('using Casagrande Bt-Vt for Teff')
if ((input.jmag > -99.0) & (input.kmag > -99.0)):
jkmag = ((input.jmag-np.median(ebvs*extfactors['aj']))
- (input.kmag-np.median(ebvs*extfactors['ak'])))
if ((jkmag >= 0.07) & (jkmag <= 0.8)):
input.teff=casagrande_jk(jkmag,feh)
print('using Casagrande J-K for Teff')
if (jkmag > 0.8):
input.teff=mist_jk(jkmag)
print('using MIST J-K for Teff')
input.teffe = input.teff*0.02
# M dwarfs
if ((input.jmag > -99.0) & (input.bpmag > -99.0) & (input.hmag > -99.0)):
if (input.bpmag-input.rpmag > 1.5) & (np.median(absmag - ext) > 3.):
bprpmag=input.bpmag-input.rpmag
jhmag=((input.jmag-np.median(ebvs*extfactors['aj']))
- (input.hmag-np.median(ebvs*extfactors['ah'])))
input.teff = mann_bprpjh(bprpmag, jhmag)
input.teffe = np.sqrt(49.**2 + 60.**2)
print('using Mann Bp-Rp,J-H for Teff')
if ((input.jmag > -99.0) & (input.vmag > -99.0) & (input.hmag > -99.0)):
if (input.vmag-input.jmag > 2.7) & (np.median(absmag - ext) > 3.):
vjmag=((input.vmag-np.median(ebvs*extfactors['av']))
- (input.jmag-np.median(ebvs*extfactors['aj'])))
jhmag=((input.jmag-np.median(ebvs*extfactors['aj']))
- (input.hmag-np.median(ebvs*extfactors['ah'])))
input.teff = mann_vjh(vjmag, jhmag)
input.teffe = np.sqrt(48.**2 + 60.**2)
print('using Mann V-J,J-H for Teff')
if ((input.jmag > -99.0) & (input.rmag > -99.0) & (input.hmag > -99.0)):
if (input.rmag-input.jmag > 2.0) & (np.median(absmag - ext) > 3.):
rjmag=((input.rmag-np.median(ebvs*extfactors['ar']))
- (input.jmag-np.median(ebvs*extfactors['aj'])))
jhmag=((input.jmag-np.median(ebvs*extfactors['aj']))
- (input.hmag-np.median(ebvs*extfactors['ah'])))
input.teff = mann_rjh(rjmag, jhmag)
input.teffe = np.sqrt(52.**2 + 60.**2)
print('using Mann r-J,J-H for Teff')
if (input.teff == -99.0):
print('no valid Teff provided or calculated, skipping')
return out
np.random.seed(seed=11)
teffsamp = input.teff + np.random.randn(nsample)*input.teffe
# hack to avoid crazy Teff samples
teffsamp[teffsamp < 1000.0] = 1000.0
# if no logg is provided, take guess from absolute mag-logg
# fit to solar-metallicity MIST isochrones NB these coeffs are
# dodgy in Mv, but pretty good in Mk
if (input.logg == -99.):
if ((band == 'vmag') | (band == 'vtmag')):
fitv = np.poly1d(
[ 0.00255731, -0.07991211, 0.85140418, 1.82465197]
)
input.logg = fitv(np.median(absmag-ext))
print('no input logg provided, guessing (using Mv):', input.logg)
#pdb.set_trace()
# should really be done filter by filter with a dictionary; TODO
else:
fitk = np.poly1d([-0.01234736, 0.36684517, 3.1477089 ])
input.logg = fitk(np.median(absmag-ext))
msg = 'no input logg provided, guessing (using Mk): {}'.format(
input.logg
)
print(msg)
# ATLAS BCs are inaccurate for M dwarfs; use Mann et al. 2015
# Mks-R relation instead
if ((input.teff < 4100.) & (np.median(absmag-ext) > 3.)):
sampMabs = absmag - ext
if (input.feh > -99.):
rad = ((1.9305 - 0.3466*(absmag-ext) + 0.01647*(absmag-ext)**2)
* (1.+0.04458*input.feh))
else:
rad = 1.9515 - 0.3520*(absmag - ext) + 0.01680*(absmag - ext)**2
# add 3% scatter in Mks-R relation
rad = rad + np.random.randn(len(rad))*np.median(rad)*0.03
lum = rad**2 * (teffsamp/teffsun)**4
# Also compute M-dwarf masses:
sampMabsZP = sampMabs - 7.5 #7.5 is the ZP defined in Mann et al. (2019)
if (input.feh > -99.):
mass = (1. - 0.0035*input.feh) * 10.**(-0.647 - 0.207 * (sampMabsZP)
- 6.53*10**(-4) * (sampMabsZP)**2
+ 7.13*10**(-3) * (sampMabsZP)**3
+ 1.84*10**(-4) * (sampMabsZP)**4
- 1.60*10**(-4) * (sampMabsZP)**5)
else:
mass = 10.**(-0.647 - 0.207 * (sampMabsZP)
- 6.53*10**(-4) * (sampMabsZP)**2
+ 7.13*10**(-3) * (sampMabsZP)**3
+ 1.84*10**(-4) * (sampMabsZP)**4
- 1.60*10**(-4) * (sampMabsZP)**5)
# Add 4% scatter in Mks-M relation
mass = mass + np.random.randn(len(mass))*np.median(mass)*0.04
# Now compute density with the mass and radius relations given here:
rho = mass/rad**3
# Output mass and densities:
out.mass,out.massep,out.massem = getstat(mass)
out.rho,out.rhoep,out.rhoem = getstat(rho)
# for everything else, interpolate ATLAS BCs
else:
if (input.teff < np.min(teffgrid)):
return out
if (input.teff > np.max(teffgrid)):
return out
if ((input.logg > -99.0) & (input.logg < np.min(logggrid))):
return out
if ((input.logg > -99.0) & (input.logg > np.max(logggrid))):
return out
if ((input.feh > -99.0) & (input.feh < np.min(fehgrid))):
return out
if ((input.feh > -99.0) & (input.feh > | np.max(fehgrid) | numpy.max |
import numpy as np
from scipy import signal
from scipy import ndimage
import preprocessing.image2D.preprocess_2D as pre
import preprocessing.image2D.convolution as conv
import preprocessing.image2D.iterative_point_processing as itproc
def fl_linear(data, kernel):
return signal.convolve2d(data, kernel, 'same')
def fl_isotropic(data, c, its):
for _ in range(its):
grad_x = | np.gradient(data, axis=0) | numpy.gradient |
import sys
import os
import string
import math
from math import pi
from matplotlib import pyplot as plt
import numpy as nm
from datetime import datetime
import array
script_dir=os.path.dirname(os.path.abspath(__file__));
auto_time=[];
auto_time2=[];
auto_time_raw=[]; # offset time;
create_time=[];
create_time.append(0);
auto_x=[]; # X pose in each step;
auto_y=[];
auto_h=[];
auto_x1=[]; # X pose in each step;
auto_y1=[];
auto_h1=[];
last_time_offset = 0;
start_time=datetime.now();
end_time=start_time;
init_time=start_time;
last_time=start_time;
heading_imu=[];
heading_odom=[];
imu_time=[];
data=[];
data_time=[];
data_time_str=[]
data_x=[]; # xError in follower;
data_x_raw=[]; # current Pose
data_y=[];
data_y_raw=[]
data_h=[]; # headingError
data_h_rad=[];
data_h_raw=[];
data_h_raw_rad=[];
data_v_err=[];
data_v_target=[];
data_v_actual=[];
data_power=[];
power_time=[];
max_power=0;
max_x_err=0;
max_y_err=0;
max_heading_err=0;
max_final_x_err=0;
max_final_y_err=0;
max_final_heading_err=0;
max_v=0;
p_name='unknown';
max_power_time = 0;
print_summary=0;
last_x_err=0;
last_y_err=0;
last_h_err=0;
filepath = sys.argv[1];
arg_c = len(sys.argv);
if (arg_c>=3):
print_summary = 1;
def get_time(t):
t = t.split(' ')
#print(t)
t_s = ' ';
t_s = t_s.join(t[:2])
#print(t_s)
t = datetime.strptime(t_s, '%m-%d %H:%M:%S.%f')
return t;
with open(filepath) as fp:
line = fp.readline()
#print(line)
while line:
line = fp.readline();
#print(line)
if ("StandardTrackingWheelLocalizer: using IMU:" in line):
t = line.split("StandardTrackingWheelLocalizer");
t = get_time(t[0]);
t_delta = t-start_time;
imu_time.append(t_delta.total_seconds());
t = line.strip().split('StandardTrackingWheelLocalizer');
t = t[1].split(' ');
#print(t)
#print(t[12], t[15]);
t1 = float(t[5]);
t2 = float(t[8]);
if (t2>pi):
t2 = (-1.0) * (2*pi - t2);
#if (t1 < 0):
# t1 = t1 + 2 * pi;
#heading_imu.append(math.degrees(t1));
#heading_odom.append(math.degrees(t2));
heading_imu.append(t1);
heading_odom.append(t2);
if (("SampleMecanumDriveBase" in line) or ("BaseClass" in line)) and ("update: x" in line):
#print(line)
t1 = line.split("update: x");
t2 = t1[1].strip();
t3 = t2.split(' ');
t = float(t3[0]);
data_x_raw.append(t);
curr_time = get_time(t1[0])
delta = curr_time - start_time;
data_time.append(delta.total_seconds());
data_time_str.append(curr_time)
last_time_offset = delta.total_seconds();
end_time = curr_time;
if (("SampleMecanumDriveBase" in line) or ("BaseClass" in line)) and (" y " in line):
t1 = line.split(" y ");
t2 = t1[1].strip();
t3 = t2.split(' ');
t = t3[0];
data_y_raw.append(float(t));
#print("y: ", t);
if (("SampleMecanumDriveBase" in line) or ("BaseClass" in line)) and (": heading " in line):
t1 = line.split(" heading ");
t2 = t1[1].strip();
t3 = t2.split(' ');
#print(t3)
t = t3[0];
data_h_raw_rad.append(float(t));
data_h_raw.append(math.degrees(float(t)));
#print("y: ", t);
if (("SampleMecanumDriveBase" in line) or ("BaseClass" in line)) and ("Error" in line):
#t = line.strip();
if ("xError" in line):
t1 = line.split('xError')
#print(t1)
t2 = t1[1]
t = float(t2)
data_x.append(t)
last_x_err = t;
if t > max_x_err:
max_x_err = t;
if ("yError" in line):
t1 = line.split('yError')
t2 = t1[1]
t = float(t2)
data_y.append(t)
last_y_err = t;
if t > max_y_err:
max_y_err = t;
if ("headingError" in line):
t1 = line.split('headingError')
t2 = t1[1]
data_h_rad.append(float(t2))
t = math.degrees(float(t2));
last_h_err = t;
data_h.append(t)
if t > max_heading_err:
max_heading_err = t;
#####################################
if ("DriveVelocityPIDTuner: error 0" in line):
#print(t);
t1 = line.split('error 0');
data_v_err.append(float(t1[1]))
if ("DriveVelocityPIDTuner: targetVelocity" in line):
t1 = line.split('targetVelocity')
data_v_target.append(float(t1[1]))
if ("DriveVelocityPIDTuner: velocity 0" in line):
t1 = line.split('velocity 0');
t2 = t1[1];
data_v_actual.append(float(t2))
t = float(t2.strip());
t = abs(t)
if t > max_v:
max_v = t;
#############################################
if ("setMotorPowers" in line) and ("leftFront" in line):
#print(line)
t = line.split('setMotorPowers');
t1 = t[1].strip().split(' ');
#print(t1)
t2 = t1[1]
t3 = float(t2)
data_power.append(t3)
t_time = get_time(t[0])
d = t_time - start_time;
power_time.append(d.total_seconds());
#print(t3)
if abs(t3)>abs(max_power):
max_power=t3;
max_power_time = t_time;
t = max_power_time-start_time
max_power_delta = t.total_seconds()
###########################################
if ("AutonomousPath: start new step: step" in line):
#print(line.rstrip())
t = line.split('currentPos (');
t1 = get_time(t[0]);
last_time = t1;
auto_time_raw.append(t1);
t_delta = t1-start_time;
auto_time2.append(t_delta.total_seconds());
auto_time.append(last_time_offset);
t = t[1].split(', ');
#print(t)
auto_x.append(float(t[0].rstrip()));
auto_y.append(float(t[1].rstrip()));
t2 = line.split('errorPos (');
t3 = t2[1].split(', ');
#print(t3);
auto_x1.append(float(t3[0].rstrip()));
auto_y1.append(float(t3[1].rstrip()));
t=t[2];
t=t[:-3].strip();
auto_h.append(float(t));
t = line.split("errorPos (");
t = (t[1][:-4]);
t = t.split(', ');
x = float(t[0]);
y = float(t[1]);
z = float(t[2]);
#print(x, y, z);
if (abs(x) > abs(max_final_x_err)):
max_final_x_err = x;
if (abs(y) > abs(max_final_y_err)):
max_final_y_err = y;
if (abs(z) > abs(max_final_heading_err)):
max_final_heading_err = z;
if ("AutonomousPath: drive and builder created, initialized with pose" in line) or ("AutonomousPath: drive and builder reset, initialized with pose" in line):
#print(line.rstrip())
t = line.split('AutonomousPath');
t1 = get_time(t[0]);
t_delta = t1-last_time
#print("drive reset takes: ", t_delta.total_seconds());
create_time.append(t_delta.total_seconds());
###########################################
if ("Robocol : received command: CMD_RUN_OP_MODE" in line):
t = line.strip().split(' ');
p_name=t[-1]
t = line.strip().split('Robotcol')
init_time = get_time(t[0])
#print(start_time)
if ("received command: CMD_RUN_OP_MODE" in line):
t = line.split('CMD_RUN_OP_MODE');
start_time = get_time(t[0])
# print(start_time)
if ("RobotCore" in line) and ("STOP - OPMODE" in line):
break;
for i in range(len(data_x)):
if (i%10==0):
print("time\t\t\ttime offset\t xErr\t\t\t X \t\t yErr\t\t \t\tY \t\t headingErr\tHeading(degree)\t\t headingErr(rad) \t heading(rad)");
print(data_time_str[i], " ", data_time[i], " ", data_x[i], " ", data_x_raw[i], " ", data_y[i], " ", data_y_raw[i], " ", data_h[i], " ", data_h_raw[i], " ", data_h_rad[i], " ", data_h_raw_rad[i]);
print("-----------------moving steps in autonomous------------------------");
for i in range(len(auto_time)):
if (i==0):
print("time\t\t\ttime offset X\t\tY\theading reset_time duration");
print(auto_time_raw[i], " ", auto_time[i], " ", auto_x[i], " ", auto_y[i], " ", auto_h[i], " ", create_time[i], "\t 0");
else:
print(auto_time_raw[i], " ", auto_time[i], " ", auto_x[i], " ", auto_y[i], " ", auto_h[i], " ", create_time[i], "\t", auto_time[i]-auto_time[i-1]);
for i in range(len(data_v_err)):
if (i%10==0):
print("data_v, data_v_target, data_v_actual");
print(data_v_err[i].strip(), " ", data_v_target[i].strip(), " ", data_v_actual[i].strip());
fp.close();
t = len(data_x);
if (t!=len(data_y) or t!=len(data_h) or t!=len(data_h_raw)) or (t==0):
print("double check the parsing!!!", t, " ", len(data_h_raw), " ", len(data_h), " ", len(data_time));
sys.exit()
else:
print("parsing looks good, len: ", t);
#os.system('cat ' + filepath + ' |grep SampleMecanumDriveBase | grep update |grep x');
print("-----------------moving steps in autonomous------------------------");
with open(filepath) as fp:
line = fp.readline()
while line:
line = fp.readline();
if (("start new step: step" in line) or ("pose correction" in line)):
print(line.strip())
fp.close();
############### better than grep
with open(filepath) as fp:
line = fp.readline()
while line:
line = fp.readline();
if ("IMUBufferReader: IMU gyro time delta" in line):
print(line.strip())
fp.close();
print("===============summary==========================")
t = max_power_time.strftime('%H:%M:%S.%f');
max_power_time = t[:-3];
print("max power to wheel: ", max_power, " timestamp: ", max_power_time, " timeoffset: ", max_power_delta)
print("max_x_err (inches): ", max_x_err)
print("max_y_err (inches): ", max_y_err)
print("max_heading_err (degrees) ", max_heading_err)
print("max_velocity : ", max_v)
duration = end_time - start_time;
print("init time: ", init_time);
print("start time: ", start_time, " end time: ", end_time, " run duration(seconds): ", duration.total_seconds());
print("\nDrivetrain parameters:");
print("program : ", p_name)
with open(filepath) as fp:
line = fp.readline()
while line:
line = fp.readline();
if (("DriveConstants" in line) and ("maxVel" in line) and ("maxAccel" in line)):
print(line.strip())
if (("DriveConstants: Strafing paramters" in line)):
print(line.strip())
if (("DriveConstants: test distance" in line)):
print(line.strip())
if (("DriveConstants" in line) and ("PID" in line)):
print(line.strip())
if (("DriveConstants: using IMU in localizer?" in line)):
print(line.strip())
if (("DriveConstants: debug.ftc.brake" in line)):
print(line.strip())
if (("DriveConstants: debug.ftc.resetfollow" in line)):
print(line.strip())
if (("DriveConstants: using Odometry" in line)):
print(line.strip())
if (("currentPos" in line) and ("errorPos" in line)):
print(line.strip())
if (("AutonomousPath:" in line) and ("xml" in line)):
print(line.strip())
fp.close();
print("max error: ", max_final_x_err, max_final_y_err, max_final_heading_err);
print("last error: ", last_x_err, last_y_err, last_h_err);
#print("start time(in miliseconds): ", start_time.timestamp() * 1000, " end time: ", end_time.timestamp() * 1000);
print(filepath);
if print_summary != 0:
plt.style.use('ggplot')
#plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc='lower left', ncol=3, mode="expand", borderaxespad=0.);
plt.plot(data_time, data_x, label="xError");
plt.plot(data_time, data_y, label="yError");
plt.plot(data_time, data_h, label="headingError");
plt.scatter(auto_time, [0 for i in range(len(auto_time))], zorder=2); # mark the drive reset;
plt.xlabel('time(seconds)');
plt.ylabel('inches for x, y, degrees for heading');
plt.legend();
plt.figure();
plt.plot(data_time, | nm.add(data_x, data_x_raw) | numpy.add |
#!/usr/bin/env python
import argparse
import os
import sys
import numpy as np
from pprint import pprint
import progressbar
from utilities import is_valid_path
from utilities import ModelData
from utilities import TrackData
from utilities import get_image
import functools
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="Displays pairs of images and reidentification " +
"output.")
parser.add_argument("data_dir",
type=lambda x: is_valid_path(parser, x),
help="Directory containing reidentification data.")
parser.add_argument("--data",
type=str,
default="validate",
help="Which data to display, must be 'training' or 'validate'.")
args = parser.parse_args()
model_data = ModelData(args.data_dir)
mean_img = model_data.mean_image()
extractor = model_data.appearance_extractor()
comparator = model_data.appearance_comparator()
if args.data == "validate":
test_data = model_data.cnn_validate()
elif args.data == "training":
test_data = model_data.cnn_training()
dir_idx_list = []
idx_list = []
tdata_list = [TrackData(os.path.join(args.data_dir,d)) for d in model_data.track_dirs()]
for dir_idx, track_data in enumerate(tdata_list):
num_img = track_data.num_detection_images()
dir_idx_list += [dir_idx for _ in range(num_img)]
idx_list += range(num_img)
mapping = | np.transpose([dir_idx_list, idx_list]) | numpy.transpose |
import time
import unittest
import numpy as np
from cctpy.baseutils import Vectors, Equal, Scalar
from cctpy.cuda.cuda_cross import cross
from cctpy.cuda.cuda_dot_a_v import dot_a_v
from cctpy.cuda.cuda_dot_v_v import dot_v_v
from cctpy.cuda.cuda_add3d_local import add3d_local
from cctpy.cuda.cuda_add3d import add3d
from cctpy.cuda.cuda_neg3d import neg3d
from cctpy.cuda.cuda_copy3d import copy3d
from cctpy.cuda.cuda_length3d import len3d
from cctpy.cuda.cuda_global import use_global
from cctpy.cuda.cuda_dB import dB
from cctpy.cuda.cuda_magnet_at_point import magnet_at_point
from cctpy.cuda.cuda_run_one_line import particle_run_len_one_line
from cctpy.cuda.cuda_add3d_local_float_and_double import add3d_local_double, add3d_local_foult
from cctpy.cuda.cuda_compute_and_table import sin_sum_tb, sin_sum_compute
from cctpy.cct import SoleLayerCct
from cctpy.abstract_classes import LocalCoordinateSystem
class CudaTest(unittest.TestCase):
def test_cross(self):
for ig in range(10):
a = Vectors.random_float32()
b = Vectors.random_float32()
ans_d = Vectors.empty_float32()
ans_h = Vectors.cross(a, b)
cross(a, b, ans_d)
self.assertTrue(Equal.equal_vector(ans_h, ans_d, err=1e-5))
def test_dot_a_v(self):
for ig in range(10):
a = Scalar.random_float32()
v = Vectors.random_float32()
ans_h = a * v
dot_a_v(a, v)
self.assertTrue(Equal.equal_vector(ans_h, v, err=1e-5))
def test_dot_v_v(self):
for ig in range(10):
v1 = Vectors.random_float32()
v2 = Vectors.random_float32()
a = Scalar.empty_float32()
a_h = | np.inner(v1, v2) | numpy.inner |
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import animation
import json
from tqdm import tqdm
from collections import deque
from fourier_transform import FourierTransform
from epicycle_frame import EpicycleFrame
from draw_it_yourself import draw_it_yourself
# Draw it yourself
diy_or_not = input("Draw image by yourself ? (y/n) ")
if diy_or_not == 'y':
draw_it_yourself()
# Show original sample points
fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_axis_off()
ax.set_aspect('equal') # To have symmetric axes
# Load coords
f = open('input/coords', 'r')
coords = json.load(f)
f.close()
x_list = [coord[0] for coord in coords]
x_list = x_list - np.mean(x_list)
y_list = [-coord[1] for coord in coords]
y_list = y_list - | np.mean(y_list) | numpy.mean |
from collections import defaultdict
import numpy as np
from pyNastran.bdf.bdf_interface.assign_type import (
integer, integer_or_blank, double_or_blank)
from pyNastran.bdf.field_writer_8 import print_card_8, set_blank_if_default
from pyNastran.bdf.cards.base_card import _format_comment
class Rods:
"""intializes the Rods"""
def __init__(self, model):
self.model = model
self.conrod = model.conrod
self.crod = model.crod
self.ctube = model.ctube
self._eids = set()
def add(self, eid):
if eid not in self._eids:
self._eids.add(eid)
else:
raise RuntimeError('eid=%s is duplicated' % eid)
def write_card(self, size=8, is_double=False, bdf_file=None):
assert bdf_file is not None
if len(self.conrod):
self.conrod.write_card(size, is_double, bdf_file)
if len(self.crod):
self.crod.write_card(size, is_double, bdf_file)
if len(self.ctube):
self.ctube.write_card(size, is_double, bdf_file)
def make_current(self):
self.conrod.make_current()
self.crod.make_current()
self.ctube.make_current()
def __len__(self):
return len(self.conrod) + len(self.crod) + len(self.ctube)
def repr_indent(self, indent=' '):
msg = '%s<Rods> : nelements=%s\n' % (indent, len(self))
msg += '%s CONROD: %s\n' % (indent, len(self.conrod))
msg += '%s CROD : %s\n' % (indent, len(self.crod))
msg += '%s CTUBE : %s\n' % (indent, len(self.ctube))
return msg
def __repr__(self):
return self.repr_indent(indent='')
class RodElement:
"""base class for CONROD, CROD, and CTUBE"""
card_name = ''
def check_if_current(self, eid, eids):
"""we split this up to reason about it easier"""
if self.is_current:
if eid in eids:
# card exists, so we use that slot
add_card = False
else:
add_card = True
else:
add_card = True
return add_card
def cross_reference(self, model):
"""does this do anything?"""
self.make_current()
def __len__(self):
"""returns the number of elements"""
return len(self.eid) + len(self._eid)
def repr_indent(self, indent=''):
self.make_current()
neids = len(self.eid)
if neids == 0:
return '%s%sv; nelements=%s' % (indent, self.card_name, neids)
msg = '%s%sv; nelements=%s\n' % (indent, self.card_name, neids)
msg += '%s eid = %s\n' % (indent, self.eid)
if hasattr(self, 'pid'):
upid = np.unique(self.pid)
if len(upid) == 1:
msg += '%s upid = %s\n' % (indent, upid)
else:
msg += '%s pid = %s\n' % (indent, self.pid)
else:
msg += '%s A = %s\n' % (indent, self.A)
msg += '%s j = %s\n' % (indent, self.j)
msg += '%s c = %s\n' % (indent, self.c)
msg += '%s nsm = %s\n' % (indent, self.nsm)
return msg
#umcid = np.unique(self.mcid)
#if len(umcid) == 1 and umcid[0] == 0:
#msg += ' umcid = %s\n' % umcid
#else:
#msg += ' umcid = %s\n' % umcid
#msg += ' mcid = %s\n' % self.mcid
#utheta = np.unique(self.theta)
#if len(utheta) == 1 and umcid[0] == 0:
#msg += ' utheta = %s\n' % utheta
#else:
#msg += ' theta = %s\n' % self.theta
#msg += ' is_theta = %s\n' % self.is_theta
#msg += ' nid =\n%s' % self.nid
#return msg
def __repr__(self):
return self.repr_indent(indent='')
class CONRODv(RodElement):
"""
+--------+-----+-----+----+-----+---+---+---+-----+
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
+========+=====+=====+====+=====+===+===+===+=====+
| CONROD | EID | N1 | N2 | MID | A | J | C | NSM |
+--------+-----+-----+----+-----+---+---+---+-----+
"""
card_name = 'CONROD'
def __init__(self, model):
self.model = model
self.is_current = True
self.eid = np.array([], dtype='int32')
self.nids = np.array([], dtype='int32')
self.mid = np.array([], dtype='int32')
self.A = | np.array([], dtype='float64') | numpy.array |
import numpy
from . tile_struct import UdimMipAddress
class UdimIndirectionBuilder(object):
def __init__(self, udim_entries):
self._udim_entries = udim_entries
self._init_data()
self._allocate_mip_indirections()
def _init_data(self):
# First determine the bounds we're going to need for the UdimInfoStart texture
udim_entries_iter = iter(self._udim_entries)
entry = next(udim_entries_iter)
min_x = entry.udim_xy[0]
max_x = entry.udim_xy[0]
min_y = entry.udim_xy[1]
max_y = entry.udim_xy[1]
for entry in udim_entries_iter:
x = entry.udim_xy[0]
y = entry.udim_xy[1]
if x < min_x:
min_x = x
elif x > max_x:
max_x = x
if y < min_y:
min_y = y
elif y > max_y:
max_y = y
self.udim_offset = (min_x, min_y)
self.udim_info_start = numpy.full(
(
(max_y-min_y + 1),
(max_x-min_x + 1),
),
0xffffffff,
dtype=numpy.uint32
)
# Allocate the udim info here (even if it's populated later)
# and write back into udim_info_start
udim_info = []
self.offset_udim_to_image = {}
for entry in self._udim_entries:
x = entry.udim_xy[0] - min_x
y = entry.udim_xy[1] - min_y
self.offset_udim_to_image[(x << 16) | y] = entry
self.udim_info_start[y, x] = len(udim_info)
image = entry.image
width = image.size[0]
height = image.size[1]
mips = image.mips
udim_info.extend((width, height, mips))
udim_info.extend([0] * mips)
# If GLSL supported uint16, this could be that
# realistically we COULD make this a 1d texture
self.udim_info = numpy.array(udim_info, dtype=numpy.uint32)
def _allocate_mip_indirections(self):
pages = [_UdimPage()]
# Add things to the layers, starting from the biggest mips (dimension wise),
# to the lowest.
# Were doing this by unrolling the mips into a single sequence and sorting them
# (there is probably a smarter way to do this)
expanded_mips = []
for entry in self._udim_entries:
width = entry.image.size[0]
height = entry.image.size[1]
mips = entry.image.mips
for mip in range(entry.image.mips):
expanded_mips.append(
(
# Store the tile size, not pixel size
(width + 63)//64,
(height + 63)//64,
mip,
entry
)
)
width = max(1, width >> 1)
height = max(1, height >> 1)
# Sort by tile count
expanded_mips.sort(
key = lambda x: x[0] * x[1],
reverse = True
)
for tile_w, tile_h, mip, entry in expanded_mips:
alloc = None
layer = 0
for layer, page in enumerate(pages):
alloc = page.allocate(tile_w, tile_h)
if alloc is not None:
break
# Need to add a new page
if not alloc:
page = _UdimPage()
layer = len(pages)
pages.append(page)
alloc = page.allocate(tile_w, tile_h)
# Write back to the info table!
udim_start = self.udim_info_start[
entry.udim_xy[1] - self.udim_offset[1],
entry.udim_xy[0] - self.udim_offset[0],
]
self.udim_info[udim_start + 3 + mip] = UdimMipAddress(
startX = alloc[0],
startY = alloc[1],
layer = layer,
).pack()
self.mip_indirection_size = (
max(page.max_written_x for page in pages),
max(page.max_written_y for page in pages),
len(pages)
)
class UdimEntry(object):
def __init__(self, udim_xy, image):
self.udim_xy = udim_xy
self.image = image
class _UdimPage(object):
def __init__(self, max_dimension=4096):
# Start off with a 1x1
self._page = numpy.zeros((max_dimension, max_dimension), dtype=numpy.uint8)
# Keep track of free space for rows and cols
self._space_x = numpy.full(max_dimension, max_dimension)
self._space_y = | numpy.full(max_dimension, max_dimension) | numpy.full |
# Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved.
#
# 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 NVIDIA CORPORATION 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 ``AS IS'' AND ANY
# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
# OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from abc import ABC, abstractmethod
import time
import pandas as pd
import numpy as np
import dask.dataframe as dd
import dask.array as da
from dask.distributed import Client
from dask_cuda import LocalCUDACluster
import xgboost as xgb
import cudf
try:
import catboost as cat
except ImportError:
cat = None
try:
import lightgbm as lgb
except (ImportError, OSError):
lgb = None
try:
import dask_xgboost as dxgb
except ImportError:
dxgb = None
try:
from sklearn.experimental import enable_hist_gradient_boosting
from sklearn.ensemble import HistGradientBoostingClassifier as skhgb
except ImportError:
skhgb = None
try:
from sklearn.experimental import enable_hist_gradient_boosting
from sklearn.ensemble import HistGradientBoostingRegressor as skhgb_r
except ImportError:
skhgb_r = None
try:
from sklearn.ensemble import GradientBoostingClassifier as skgb
except ImportError:
skgb = None
try:
from sklearn.ensemble import GradientBoostingRegressor as skgb_r
except ImportError:
skgb_r = None
try:
from sklearn.ensemble import RandomForestClassifier as skrf
except ImportError:
skrf = None
try:
from sklearn.ensemble import RandomForestRegressor as skrf_r
except ImportError:
skrf_r = None
try:
from cuml.ensemble import RandomForestClassifier as cumlrf
except ImportError:
cumlrf = None
try:
from cuml.ensemble import RandomForestRegressor as cumlrf_r
except ImportError:
cumlrf_r = None
from datasets import LearningTask
class Timer:
def __init__(self):
self.start = None
self.end = None
self.interval = None
def __enter__(self):
self.start = time.perf_counter()
return self
def __exit__(self, *args):
self.end = time.perf_counter()
self.interval = self.end - self.start
class Algorithm(ABC):
@staticmethod
def create(name): # pylint: disable=too-many-return-statements
if name == 'xgb-gpu':
return XgbGPUHistAlgorithm()
if name == 'xgb-gpu-dask':
return XgbGPUHistDaskAlgorithm()
if name == 'xgb-gpu-dask-old':
return XgbGPUHistDaskOldAlgorithm()
if name == 'xgb-cpu':
return XgbCPUHistAlgorithm()
if name == 'lgbm-cpu':
return LgbmCPUAlgorithm()
if name == 'lgbm-gpu':
return LgbmGPUAlgorithm()
if name == 'cat-cpu':
return CatCPUAlgorithm()
if name == 'cat-gpu':
return CatGPUAlgorithm()
if name == 'skhgb':
return SkHistAlgorithm()
if name == 'skgb':
return SkGradientAlgorithm()
if name == 'skrf':
return SkRandomForestAlgorithm()
if name == 'cumlrf':
return CumlRfAlgorithm()
raise ValueError("Unknown algorithm: " + name)
def __init__(self):
self.model = None
@abstractmethod
def fit(self, data, args):
pass
@abstractmethod
def test(self, data):
pass
def __enter__(self):
pass
@abstractmethod
def __exit__(self, exc_type, exc_value, traceback):
pass
# learning parameters shared by all algorithms, using the xgboost convention
shared_params = {"max_depth": 8, "learning_rate": 0.1,
"reg_lambda": 1}
class CumlRfAlgorithm(Algorithm):
def configure(self, data, args):
params = shared_params.copy()
del params["reg_lambda"]
del params["learning_rate"]
params["n_estimators"] = args.ntrees
params.update(args.extra)
return params
def fit(self, data, args):
params = self.configure(data, args)
if data.learning_task == LearningTask.REGRESSION:
with Timer() as t:
self.model = cumlrf_r(**params).fit(data.X_train, data.y_train)
return t.interval
else:
with Timer() as t:
self.model = cumlrf(**params).fit(data.X_train, data.y_train)
return t.interval
def test(self, data):
return self.model.predict(data.X_test)
def __exit__(self, exc_type, exc_value, traceback):
del self.model
class XgbAlgorithm(Algorithm):
def configure(self, data, args):
params = shared_params.copy()
params.update({"max_leaves": 256,
"nthread": args.cpus})
if data.learning_task == LearningTask.REGRESSION:
params["objective"] = "reg:squarederror"
elif data.learning_task == LearningTask.CLASSIFICATION:
params["objective"] = "binary:logistic"
params["scale_pos_weight"] = len(data.y_train) / np.count_nonzero(data.y_train)
elif data.learning_task == LearningTask.MULTICLASS_CLASSIFICATION:
params["objective"] = "multi:softmax"
params["num_class"] = np.max(data.y_test) + 1
params.update(args.extra)
return params
def fit(self, data, args):
dtrain = xgb.DMatrix(data.X_train, data.y_train)
params = self.configure(data, args)
with Timer() as t:
self.model = xgb.train(params, dtrain, args.ntrees)
return t.interval
def test(self, data):
dtest = xgb.DMatrix(data.X_test, data.y_test)
return self.model.predict(dtest)
def __exit__(self, exc_type, exc_value, traceback):
del self.model
class XgbGPUHistAlgorithm(XgbAlgorithm):
def configure(self, data, args):
params = super(XgbGPUHistAlgorithm, self).configure(data, args)
params.update({"tree_method": "gpu_hist", "gpu_id": 0})
return params
class SkRandomForestAlgorithm(Algorithm):
def configure(self, data, args):
params = shared_params.copy()
del params["reg_lambda"]
del params["learning_rate"]
params["n_estimators"] = args.ntrees
params.update(args.extra)
return params
def fit(self, data, args):
params = self.configure(data, args)
if data.learning_task == LearningTask.REGRESSION:
with Timer() as t:
self.model = skrf_r(**params).fit(data.X_train, data.y_train)
return t.interval
else:
with Timer() as t:
self.model = skrf(**params).fit(data.X_train, data.y_train)
return t.interval
def test(self, data):
return self.model.predict(data.X_test)
def __exit__(self, exc_type, exc_value, traceback):
del self.model
class SkGradientAlgorithm(Algorithm):
def configure(self, data, args):
params = shared_params.copy()
del params["reg_lambda"]
del params["learning_rate"]
params["n_estimators"] = args.ntrees
params.update(args.extra)
return params
def fit(self, data, args):
params = self.configure(data, args)
if data.learning_task == LearningTask.REGRESSION:
with Timer() as t:
self.model = skgb_r(**params).fit(data.X_train, data.y_train)
return t.interval
else:
with Timer() as t:
self.model = skgb(**params).fit(data.X_train, data.y_train)
return t.interval
def test(self, data):
return self.model.predict(data.X_test)
def __exit__(self, exc_type, exc_value, traceback):
del self.model
class SkHistAlgorithm(Algorithm):
def configure(self, data, args):
params = shared_params.copy()
del params["reg_lambda"]
del params["learning_rate"]
params["n_estimators"] = args.ntrees
params.update(args.extra)
return params
def fit(self, data, args):
params = self.configure(data, args)
if data.learning_task == LearningTask.REGRESSION:
with Timer() as t:
self.model = skhgb_r(**params).fit(data.X_train, data.y_train)
return t.interval
else:
with Timer() as t:
self.model = skhgb(**params).fit(data.X_train, data.y_train)
return t.interval
def test(self, data):
return self.model.predict(data.X_test)
def __exit__(self, exc_type, exc_value, traceback):
del self.model
class XgbGPUHistDaskAlgorithm(XgbAlgorithm):
def configure(self, data, args):
params = super(XgbGPUHistDaskAlgorithm, self).configure(data, args)
params.update({"tree_method": "gpu_hist"})
del params['nthread'] # This is handled by dask
return params
def get_slices(self, n_slices, X, y):
n_rows_worker = int(np.ceil(len(y) / n_slices))
indices = []
count = 0
for _ in range(0, n_slices - 1):
indices.append(min(count + n_rows_worker, len(y)))
count += n_rows_worker
return np.split(X, indices), np.split(y, indices)
def fit(self, data, args):
params = self.configure(data, args)
n_workers = None if args.gpus < 0 else args.gpus
cluster = LocalCUDACluster(n_workers=n_workers,
local_directory=args.root)
client = Client(cluster)
n_partitions = len(client.scheduler_info()['workers'])
X_sliced, y_sliced = self.get_slices(n_partitions,
data.X_train, data.y_train)
X = da.concatenate([da.from_array(sub_array) for sub_array in X_sliced])
X = X.rechunk((X_sliced[0].shape[0], data.X_train.shape[1]))
y = da.concatenate([da.from_array(sub_array) for sub_array in y_sliced])
y = y.rechunk(X.chunksize[0])
dtrain = xgb.dask.DaskDMatrix(client, X, y)
with Timer() as t:
output = xgb.dask.train(client, params, dtrain, num_boost_round=args.ntrees)
self.model = output['booster']
client.close()
cluster.close()
return t.interval
def test(self, data):
dtest = xgb.DMatrix(data.X_test, data.y_test)
self.model.set_param({'predictor': 'gpu_predictor'})
return self.model.predict(dtest)
def __exit__(self, exc_type, exc_value, traceback):
del self.model
class XgbGPUHistDaskOldAlgorithm(XgbAlgorithm):
def configure(self, data, args):
params = super(XgbGPUHistDaskOldAlgorithm, self).configure(data, args)
params.update({"tree_method": "gpu_hist", "nthread": 1})
return params
def fit(self, data, args):
params = self.configure(data, args)
cluster = LocalCUDACluster(n_workers=None if args.gpus < 0 else args.gpus,
local_directory=args.root)
client = Client(cluster)
partition_size = 1000
if isinstance(data.X_train, np.ndarray):
X = dd.from_array(data.X_train, partition_size)
y = dd.from_array(data.y_train, partition_size)
else:
X = dd.from_pandas(data.X_train, partition_size)
y = dd.from_pandas(data.y_train, partition_size)
X.columns = [str(i) for i in range(0, X.shape[1])]
with Timer() as t:
self.model = dxgb.train(client, params, X, y, num_boost_round=args.ntrees)
client.close()
return t.interval
def test(self, data):
if isinstance(data.X_test, np.ndarray):
data.X_test = pd.DataFrame(data=data.X_test, columns=np.arange(0,
data.X_test.shape[1]),
index=np.arange(0, data.X_test.shape[0]))
data.X_test.columns = [str(i) for i in range(0, data.X_test.shape[1])]
dtest = xgb.DMatrix(data.X_test, data.y_test)
return self.model.predict(dtest)
def __exit__(self, exc_type, exc_value, traceback):
del self.model
class XgbCPUHistAlgorithm(XgbAlgorithm):
def configure(self, data, args):
params = super(XgbCPUHistAlgorithm, self).configure(data, args)
params.update({"tree_method": "hist"})
return params
class LgbmAlgorithm(Algorithm):
def configure(self, data, args):
params = shared_params.copy()
params.update({"max_leaves": 256,
"nthread": args.cpus})
if data.learning_task == LearningTask.REGRESSION:
params["objective"] = "regression"
elif data.learning_task == LearningTask.CLASSIFICATION:
params["objective"] = "binary"
params["scale_pos_weight"] = len(data.y_train) / np.count_nonzero(data.y_train)
elif data.learning_task == LearningTask.MULTICLASS_CLASSIFICATION:
params["objective"] = "multiclass"
params["num_class"] = np.max(data.y_test) + 1
params.update(args.extra)
return params
def fit(self, data, args):
dtrain = lgb.Dataset(data.X_train, data.y_train,
free_raw_data=False)
params = self.configure(data, args)
with Timer() as t:
self.model = lgb.train(params, dtrain, args.ntrees)
return t.interval
def test(self, data):
if data.learning_task == LearningTask.MULTICLASS_CLASSIFICATION:
prob = self.model.predict(data.X_test)
return | np.argmax(prob, axis=1) | numpy.argmax |
import time
import warnings
import numpy as np
from scipy import signal
from tikreg import models, utils as tikutils
from tikreg import models
from tikreg import spatial_priors, temporal_priors
from fusilib.config import DATA_ROOT
def get_peak_info(time, data, sumfunc=np.median):
'''
time : 1D np.array
data : 1D np.array
'''
assert data.ndim == 1
data = np.atleast_2d(data)
peak_location = np.argmax(sumfunc(data, 0))
peak_time = time[peak_location]
peak_width = signal.peak_widths(
sumfunc(data, 0), [peak_location], rel_height=0.5)[0]
peak_fwhm = peak_width*0.3 # fUSI dt = 0.3 sec
return peak_time, float(peak_fwhm)
def summarize_peaks(time, data, **kwargs):
'''
'''
peak_time, peak_fwhm = np.asarray(
[get_peak_info(time, dat, **kwargs) for dat in data]).T
return peak_time, peak_fwhm
def MAD(data, axis=0):
'''
'''
med = np.median(data, axis=axis, keepdims=True)
mad = np.median(np.abs(data - med), axis=axis)
return mad
def pct_signal_change(data):
pct = ((data/data.mean(0)) - 1.0)*100.0
return pct
def glob_loader(pattern, **kwargs):
'''
subject='CR017',
session='2019-11-13',
stimulus_condition='kalatsky',
block_numbers=None,
results_version='results_v03',
data_root=DATA_ROOT
'''
from fusilib.extras import readers
for fl, key in glob_local(pattern, **kwargs):
yield readers.hdf_load(fl, key)
def load_fusinpx_results(prefix='regression',
data_pattern='halfidx-1*weights',
time_pattern='halfidx-1*delaysec',
area_name='V1',
probe_names=['probe00', 'probe01'],
res_transform=lambda x: x,
flatten=False,
verbose=False,
**kwargs):
'''
Parameters
----------
probe_names : str or None
time_pattern : str or none
flatten : bool
True: Useful when arrays are of different size, (dataset*samples)
False: Output shape is (dataset, nsamples)
res_transform : function
Function applied to each dataset after squeezing.
kwargs : dict
Passed to glob_pattern() for finer selection:
* subject='*'
* session='*'
* stimulus_condition='*'
* block_numbers=None
* results_version='results_v03'
* exclude_patterns=[('2019-11-26', None)],
Available patterns
------------------
`prefix`, followed by relelevant key in `data_pattern`
* shuffcoh: {freq, coherence_boot, coherece_median, coherence_mean}
* slicesview: {mean,std,tsnr}_methodC.hdf
* timecourses: frunits{spksec,zscore,pctchg}_{probe00,probe01}_{fusi,ephys}
* regression: {probe00,probe01}_{halfidx0,halfidx-1}_fitl2_{performance,predictions,weights,Ytest}_methodC.hdf
* crosscorrelation: {probe00, probe00}_{delaysecs,tpcorr}_methodC.hdf
* coherence: {probe00,probe01}_{freq,coherence}_methodC.hdf
subject='CR017',
session='2019-11-13',
stimulus_condition='kalatsky',
block_numbers=None,
results_version='results_v03',
data_root=DATA_ROOT
'''
results = []
time = None
if probe_names is None:
# future-proofing
probe_name = ''
raise ValueError('Untested for non-probe data')
for probe_name in probe_names:
matcher = f'*{prefix}*{probe_name}*{data_pattern}*'
print(matcher, kwargs)
res = list(glob_pattern(matcher,
probe_name=probe_name,
area_name=area_name,
verbose=verbose,
do_loading=True, **kwargs))
if len(res) > 0:
res = [res_transform(t.squeeze()) for t in res]
res = np.asarray(res) if flatten is False else np.hstack(res)
results.append(res.squeeze())
if time_pattern is not None and time is None:
# Only load time information once
time_matcher = f'*{prefix}*{probe_name}*{time_pattern}*'
print(time_matcher)
time = np.asarray(list(glob_pattern(
time_matcher,
probe_name=probe_name,
area_name=area_name,
verbose=verbose,
do_loading=True,
**kwargs)))
if len(time) == 0:
raise ValueError('No time info found!')
if len(results) == 0:
print('Nothing found: %s' % matcher, kwargs)
return None, None
if len(results) == 1:
results = results[0]
else:
results = np.vstack(
results) if flatten is False else np.hstack(results)
# time-vector is the same for all
if time is not None:
assert time.shape[-1] == results.shape[-1]
time = time[0]
print('shapes: times, data:', time.shape, results.shape)
else:
print('shapes:', results.shape)
return time, results
def glob_pattern(pattern,
subject='*',
session='*',
stimulus_condition='*',
block_numbers=None,
results_version='results_v03',
exclude_patterns=None, # [('2019-11-26', None)],
data_root=DATA_ROOT,
verbose=False,
probe_name=None,
area_name=None,
do_loading=False):
'''
Patterns
--------
* slicesview: {mean,std,tsnr}_methodC.hdf
* timecourses: frunits{spksec,zscore,pctchg}_{probe00,probe01}_{fusi,ephys}
* regression: {probe00,probe01}_{halfidx0,halfidx-1}_fitl2_{performance,predictions,weights,Ytest}_methodC.hdf
* crosscorrelation: {probe00, probe00}_{delaysecs,tpcorr}_methodC.hdf
* coherence: {probe00,probe01}_{freq,coherence}_methodC.hdf
subject='CR017',
session='2019-11-13',
stimulus_condition='kalatsky',
block_numbers=None,
results_version='results_v03',
data_root=DATA_ROOT
'''
from fusilib.extras import readers
from fusilib import handler2 as handler
EXPERIMENTS = {'CR017': ['2019-11-13', '2019-11-14'],
'CR020': ['2019-11-20', '2019-11-21', '2019-11-22'],
'CR019': ['2019-11-26', '2019-11-27'],
'CR022': ['2020-10-07', '2020-10-11'],
'CR024': ['2020-10-29']}
if stimulus_condition != '*':
assert stimulus_condition in [
'kalatsky', 'checkerboard', 'spontaneous']
if subject == '*':
# Use all subjects
pass
elif isinstance(subject, (list, str)):
# select some subjects
EXPERIMENTS = {k: v for k, v in EXPERIMENTS.items() if k in subject}
for sub, sessions in EXPERIMENTS.items():
if session == '*':
# Use all sesssions
pass
else:
# select requested sessions only
sessions = [sess for sess in sessions if sess in session]
# iterate thru sessions
for sess in sessions:
matches = glob_local(pattern,
subject=sub,
session=sess,
stimulus_condition=stimulus_condition,
block_numbers=block_numbers,
results_version=results_version,
probe_name=probe_name,
area_name=area_name,
exclude_patterns=exclude_patterns,
verbose=verbose,
data_root=data_root)
# iterate thru matches
for (fl, key) in matches:
if do_loading:
if verbose:
print('%s : %s' % (fl, key), sub,
sess, stimulus_condition)
data = readers.hdf_load(fl, key, verbose=False)
if np.allclose(data, 0):
print('Data is all zeros:', fl, key)
yield data
else:
yield fl, key
def glob_local(pattern,
subject='CR017',
session='2019-11-13',
stimulus_condition='kalatsky',
block_numbers=None,
results_version='results_v03',
probe_name=None,
area_name=None,
exclude_patterns=None,
verbose=False,
analysis_valid_only=True,
data_root=DATA_ROOT):
'''
valid_only : bool
Use only data defined as good from the subject LOG.INI
Example
-------
>>> pattern = '*frunitzscore*probe00*ephys*'
>>> files = glob_local(pattern)
'''
from pathlib import Path
from fusilib.extras import readers
from fusilib import handler2 as handler
path = Path(data_root).joinpath(subject, session, results_version)
files = path.glob(pattern)
for fl in files:
contents = readers.hdf_load(fl, verbose=False)
block_mapper = {
int(t.split('_')[1].strip('block')): t for t in contents}
if block_numbers is not None:
# In case we want to restrict to a subset of blocks
block_mapper = [b for b in block_mapper if b in block_numbers]
if analysis_valid_only:
block_mapper = {k: v for k, v in block_mapper.items() if k in handler.MetaSession(
subject, session, verbose=False).analysis_blocks}
if stimulus_condition is not None and stimulus_condition != '*':
block_mapper = {blk_number: key for idx, (blk_number, key) in enumerate(block_mapper.items())
if handler.MetaBlock(subject, session, blk_number, verbose=False).task_name == stimulus_condition}
if area_name is not None and area_name != '*':
assert probe_name is not None
block_mapper = {blk_number: key for idx, (blk_number, key) in enumerate(block_mapper.items())
if (handler.MetaBlock(subject, session, blk_number, verbose=False).fusi_get_probe_allen_mask(
probe_name, allen_area_name=area_name) is not None)}
for block_number, block_key in sorted(block_mapper.items()):
if exclude_patterns is not None:
is_valid = True
for exclude_fl, exclude_key in exclude_patterns:
if (exclude_fl in str(fl)) and (str(exclude_key) in block_key):
if verbose:
print('Skipping:', exclude_fl, exclude_key)
is_valid = False
continue
if is_valid:
yield fl, block_key
else:
yield fl, block_key
def roiwise_pctsignalchange(data,
population_mean=False,
clip_value=75,
trim_beg=0, trim_end=None):
'''data is time by units
pct signal change per pixel, then mean across pixels
'''
data = data[trim_beg:trim_end].mean(-1, keepdims=True)
data /= data.mean(0)
data -= 1.0
data *= 100
# clip this
data = np.clip(data, -75, 75)
return data
def pixelwise_pctsignalchange_median(data, **kwargs):
return pixelwise_pctsignalchange(data, normfunc=np.median, **kwargs)
def pixelwise_pctsignalchange(data,
population_mean=False,
clip_value=None,
clip_sd=None,
normfunc=np.mean,
trim_beg=0, trim_end=None):
'''Compute the percent signal change per unit.
Parameters
----------
data : np.ndarray, (ntimepoints, ..., nunits)
clip_value : scalar
Threshold for % signal changes
population_mean : bool
Mean across last dimension
trim_beg, trim_end:
Ignore these samples when computing % signal change
Returns
-------
pct_signal_change : np.ndarray, (ntimepoints, ..., nunits)
Signals in units of % (ie 10% not 0.1) in the
range (-clip_value, clip_value), mean=0.
'''
data /= normfunc(data[trim_beg:trim_end], axis=0)
data -= 1.0
data *= 100
# clip this
sdvals = data.std(0)
if clip_value is not None:
data = np.clip(data, -clip_value, clip_value)
if clip_sd is not None:
data = np.clip(data, -(sdvals*clip_sd), sdvals*clip_sd)
if population_mean:
data = data.mean(-1, keepdims=True)
return data
def normalize_fusi(data_matrix):
'''
'''
return pct_signal_change(np.sqrt(data_matrix))
def fast_find_between(continuous_times, discrete_times, window=0.050):
'''A parallel implementation of::
markers = np.logical_and(continuous_units >= discrete_units[0],
continuous_units < discrete_units[0] + window)
for all elements of `discrete_units`.
Parameters
----------
continuous_units (1D np.ndarray) : (n,) vector of unit sampling (e.g. secs, mm]
discrete_units (1D np.ndarray) : (m,) Vector of new unit-stamps
window (scalar) : Window of unit after unit (e.g. secs, mm]
Returns
-------
markers (list of `m` arrays) :
Each element of the list contains the mask (n,)
Examples
--------
>>> fast_ratehz, new_ratehz = 100, 10
>>> times = np.arange(10000)/fast_ratehz + np.random.rand(10000)/fast_ratehz
>>> new_times = np.linspace(0, times.max(), len(times)/(fast_ratehz/new_ratehz))
>>> markers = fast_find_times_between(times, new_times, window=1./new_ratehz)
'''
from fusilib import mp
def find_between(vec, before, window=0.050):
'''
'''
matches = np.logical_and(vec >= before, vec < before+window)
matches = matches.nonzero()[0]
# # Same speed
# matches = (vec >= before)*(vec < before+window).nonzero()[0]
# # Same speed-ish
# greater = (vec >= before).nonzero()[0]
# matches = greater[vec[greater] < (before + window)]
return matches
def func(x): return find_between(continuous_times, x, window=window)
res = mp.map(func, discrete_times, procs=10)
return res
def spikes_at_times(event_times, post_event_time,
spike_times, spike_clusters,
nclusters=None):
'''
'''
from fusilib.mp import map as parallelmap
from scipy import sparse
if nclusters is None:
# use highest cluster index
nclusters = spike_clusters.max() + 1
shape = (len(spike_times), nclusters)
sparse_spike_matrix = sparse.csr_matrix((np.ones_like(spike_times),
(np.arange(len(spike_times)), spike_clusters)),
shape, dtype=np.bool)
spike_bins = fast_find_between(
spike_times, event_times, window=post_event_time)
def func(x): return np.asarray(
sparse_spike_matrix[x]) # spike counter function
spike_matrix = np.asarray(parallelmap(
func, spike_bins, procs=10)).squeeze()
return spike_matrix
def sparse_spike_matrix(spike_times, spike_clusters, nclusters=None):
'''
'''
from scipy import sparse
if nclusters is None:
# use highest cluster index
nclusters = spike_clusters.max() + 1
shape = (len(spike_times), nclusters)
sparse_spike_matrix = sparse.csr_matrix((np.ones_like(spike_times),
(np.arange(len(spike_times)), spike_clusters)),
shape, dtype=np.bool)
return sparse_spike_matrix
def bin_spikes(new_onsets, window,
spike_times, spike_clusters,
nclusters=None):
'''Construct a spike counts matrix at the temporal resolution requested.
Parameters
----------
new_onsets : 1D np.ndarray (m,)
Times at which to start counting spikes [seconds]
window : scalar
Bin size in [seconds]
spike_times : 1D np.ndarray (n,)
Vector of spike time-stamps in [seconds]
spike_clusters : 1D np.ndarray (n,)
Vector of cluster indexes
nclusters (optional) : scalar
total number of clusters `k`.
if not given, `nclusters = spike_clusters.max() + 1`
Returns
-------
spike_matrix : 2D np.ndarray (m, k)
'''
from fusilib.io import spikes
spike_matrix = spikes.time_locked_spike_matrix(spike_times,
spike_clusters,
new_onsets,
window,
nclusters=nclusters)
return spike_matrix
def bin_spikes_turbo(window,
spike_times, spike_clusters,
nclusters=None,
first_bin_onset=0.0):
'''Construct a spike counts matrix at the temporal resolution requested.
Parameters
----------
window : scalar
Bin size in [seconds]
spike_times : 1D np.ndarray (n,)
Vector of spike time-stamps in [seconds]
spike_clusters : 1D np.ndarray (n,)
Vector of cluster indexes
nclusters (optional) : scalar
total number of clusters `k`.
if not given, `nclusters = spike_clusters.max() + 1`
first_bin_onset : scalar-like
Onset of first bin [seconds]
Returns
-------
spike_matrix : 2D np.ndarray (m, k)
'''
from fusilib.mp import map as parallelmap
from scipy import sparse
if nclusters is None:
# use highest cluster index
nclusters = spike_clusters.max() + 1
shape = (len(spike_times), nclusters)
sparse_spike_matrix = sparse.csr_matrix((np.ones_like(spike_times),
(np.arange(len(spike_times)), spike_clusters)),
shape, dtype=np.bool)
spike_bins = (spike_times - first_bin_onset) // window
nbins = int(np.ceil(spike_bins.max())) + 1
unique_bins = np.unique(spike_bins)
spike_matrix = np.zeros((nbins, nclusters), dtype=np.int32)
def func(uqbin): return np.asarray(
sparse_spike_matrix[spike_bins == uqbin, :].sum(0)).squeeze()
spike_counts = parallelmap(func, unique_bins)
for idx, scount in zip(unique_bins, spike_counts):
spike_matrix[int(idx)] = scount
matrix_times = np.arange(nbins)*window + first_bin_onset
return matrix_times, spike_matrix
class Bunch(dict):
"""A subclass of dictionary with an additional dot syntax."""
def __init__(self, *args, **kwargs):
super(Bunch, self).__init__(*args, **kwargs)
self.__dict__ = self
def copy(self):
"""Return a new Bunch instance which is a copy of the current Bunch instance."""
return Bunch(super(Bunch, self).copy())
def mk_log_fusi(raw_mean_image):
img = raw_mean_image.copy()
img -= img.min()
img /= img.max()
img *= 1000
img = np.log(img + 1)
return img
def brain_mask(raw_mean_image):
'''
'''
from skimage.filters import threshold_otsu
thresh = threshold_otsu(img)
binary = img > thresh
return binary
def cvridge_nodelays(Xfull, Yfull,
Xtest=None,
Ytest=None,
ridges=np.logspace(0, 3, 10), chunklen=10,
metric='rsquared', population_optimal=False, delays_mean=True,
performance=True, weights=False, predictions=False, verbose=2):
'''
'''
if Xtest is None and Ytest is None:
ntrain = int(Xfull.shape[0]/2)
Xtrain, Xtest = Xfull[:ntrain], Xfull[ntrain:]
Ytrain, Ytest = Yfull[:ntrain], Yfull[ntrain:]
else:
Xtrain, Ytrain = Xfull, Yfull
nfeatures = Xtrain.shape[1]
feature_prior = spatial_priors.SphericalPrior(nfeatures)
temporal_prior = temporal_priors.SphericalPrior(delays=[0])
fit_spherical = models.estimate_stem_wmvnp([Xtrain], Ytrain,
[Xtest], Ytest,
feature_priors=[feature_prior],
temporal_prior=temporal_prior,
ridges=ridges,
folds=(2, 5),
verbosity=verbose,
performance=performance,
weights=weights,
predictions=predictions,
population_optimal=population_optimal, # pop opt is more stable
metric=metric,
chunklen=chunklen) # correlation is more stable
if weights is True:
kernel_weights = np.nan_to_num(fit_spherical['weights'])
voxels_ridge = fit_spherical['optima'][:, -1]
weights_mean = models.dual2primal_weights_banded(kernel_weights,
Xtrain,
np.ones_like(
voxels_ridge),
temporal_prior,
delays_mean=delays_mean,
verbose=True)
fit_spherical['weights'] = weights_mean
return fit_spherical
def generate_bootstrap_samples(data_size, subsample_size=100,
chunk_size=20, nresamples=1000):
'''sample 1000 sequences `s` long from the full dataset `data_size`
data_size : int
n-samples in the full dataset
subsample_size : int
sample `s` samples from the full dataset
chunks_size : int
Break data into non-overlapping chunks
of this size before bootstrapping samples
nresamples : int
Number of bootstrap resamples
'''
assert data_size < 2**16 # this will be soooo slow
dtype = np.uint16
nsplits = int(data_size / chunk_size)
nchunks = int(subsample_size / chunk_size)
print(nsplits, nchunks)
for idx in range(nresamples):
start = np.random.randint(0, chunk_size, dtype=dtype)
indices = np.arange(start, data_size, dtype=dtype)
splits = np.array_split(indices, nsplits)
# gidx = sorted(np.random.permutation(nsplits)[:nchunks]) # w/o replacement
gidx = np.random.randint(0, nsplits, size=nchunks) # w/ replacement
sample = np.hstack([splits[t] for t in gidx])
yield sample
def bootstrap_ols_fit(xtrain, ytrain, bootsamples,
include_constant=False):
'''bootstrap the bhat estimate with OLS
'''
nboot = len(bootsamples)
if include_constant:
xtrain = np.hstack([np.ones((xtrain.shape[0], 1), dtype=xtrain.dtype),
xtrain])
boot_weights = np.zeros(
(nboot, xtrain.shape[1], ytrain.shape[1]), dtype=xtrain.dtype)
for bdx, samplesidx in enumerate(bootsamples):
bhat = models.ols(xtrain[samplesidx], ytrain[samplesidx])
boot_weights[bdx] = bhat
if bdx % 500 == 0:
print(bdx, bhat.shape)
return boot_weights
def bootstrap_sta_fit(xtrain, ytrain, bootsamples,
include_constant=False):
'''bootstrap the bhat estimate with OLS
'''
nboot = len(bootsamples)
if include_constant:
xtrain = np.hstack([np.ones((xtrain.shape[0], 1), dtype=xtrain.dtype),
xtrain])
boot_weights = np.zeros(
(nboot, xtrain.shape[1], ytrain.shape[1]), dtype=xtrain.dtype)
for bdx, samplesidx in enumerate(bootsamples):
bhat = np.dot(xtrain[samplesidx].T, ytrain[samplesidx])/len(samplesidx)
boot_weights[bdx] = bhat
if bdx % 500 == 0:
print(bdx, bhat.shape)
return boot_weights
def bootstrap_ridge_fit(xtrain, ytrain, bootsamples,
include_constant=False,
ridges=np.logspace(0, 4, 10)):
'''bootstrap the bhat estimate with OLS
'''
nboot = len(bootsamples)
if include_constant:
xtrain = np.hstack([np.ones((xtrain.shape[0], 1), dtype=xtrain.dtype),
xtrain])
boot_weights = np.zeros(
(nboot, xtrain.shape[1], ytrain.shape[1]), dtype=xtrain.dtype)
solver = models.solve_l2_primal if xtrain.shape[0] > xtrain.shape[1] \
else models.solve_l2_dual
for bdx, samplesidx in enumerate(bootsamples):
fit = solver(xtrain[samplesidx], ytrain[samplesidx],
xtrain[samplesidx], ytrain[samplesidx],
performance=True,
ridges=ridges,
metric='rsquared',
verbose=True if bdx % 1000 == 0 else False,
)
# population best
perf = np.nanmean(fit['performance'], -1)
ridgeperf, ridgeopt = np.max(perf), ridges[np.argmax(perf)]
if np.isnan(ridgeperf):
ridgeopt = np.inf
fit = solver(xtrain[samplesidx], ytrain[samplesidx],
xtrain[samplesidx], ytrain[samplesidx],
weights=True,
ridges=[ridgeopt],
metric='rsquared')
bhat = fit['weights']
boot_weights[bdx] = bhat
if bdx % 500 == 0:
print(bdx, bhat.shape)
return boot_weights
def detrend_secs2oddwindow(secs, dt):
'''Valid window length for detrending
Parameters
----------
secs : scalar, [seconds]
dt : scalar, [seconds]
'''
window_size = int(secs/dt)
window_size += (window_size - 1) % 2
return window_size
def detrend_signal(data,
window_size=5,
detrend_type='median',
**kwargs):
'''Detrend a signal
Parameters
----------
data : np.ndarray, (ntimepoints, ...)
window_size : scalar, (k,)
detrend_type : str
* median: Median filter
* mean: Moving average filter
* macausal: Causal moving average filter
* bandpass: Bandpass signal
* sg: savitsky-golay filter
**kwargs : for sg detrending
Returns
-------
detrended_data : np.ndarray, (ntimepoints, ...)
'''
shape = data.shape
data = data.reshape(data.shape[0], -1)
detdat = temporal_filter(
data, window_size=window_size, ftype=detrend_type, **kwargs)
detdat = detdat.reshape(shape)
return detdat
def temporal_filter(fusi, window_size=5,
ftype='median', **fkwargs):
'''Estimate low-frequency trend and removes it from signal
Parameters
----------
fusi (ntimepoints, voxels): np.ndarray
'''
assert ftype in ['median', 'sg', 'ma', 'macausal', 'bandpass']
if fusi.ndim == 1:
fusi = fusi[..., None]
fusi_filt = np.zeros_like(fusi)
for chidx in range(fusi.shape[1]):
pixel_data = fusi[:, chidx] # .copy()
pixel_mean = pixel_data.mean()
pixel_data = pixel_data - pixel_mean
if ftype == 'median':
temporal_filter = signal.medfilt(pixel_data, window_size)
elif ftype == 'sg':
polyorder = 3 if 'polyorder' not in fkwargs else fkwargs.pop(
'polyorder')
temporal_filter = signal.savgol_filter(pixel_data,
window_size,
polyorder,
**fkwargs)
elif ftype == 'ma':
delays = range(-window_size, window_size+1)
temporal_filter = tikutils.delay_signal(
pixel_data, delays).mean(-1)
elif ftype == 'macausal':
delays = range(window_size+1)
temporal_filter = tikutils.delay_signal(
pixel_data, delays).mean(-1)
elif ftype == 'bandpass':
temporal_filter = band_pass_signal(pixel_data, **kwargs)
# add mean back
new_signal = (pixel_data - temporal_filter) + pixel_mean
fusi_filt[:, chidx] = new_signal
if chidx % 1000 == 0:
print(ftype, window_size, chidx,
new_signal.sum(), pixel_mean, fkwargs)
return fusi_filt
def get_centered_samples(data, outsamples):
'''Extract "N" samples from the middle of the data.
'''
oldsamples = data.shape[0]
window_left = int((oldsamples - outsamples)/2)
#window_left = int((oldsamples - window_center)/2)
newdata = data[window_left:window_left + outsamples]
assert newdata.shape[0] == outsamples
return newdata
def get_temporal_filters(fusi, window_size=5,
ftype='median', **fkwargs):
'''fusi (ntimepoints, pixels)
estimates and returns a filter
'''
assert ftype in ['median', 'sg', 'ma', 'macausal', 'bandpass']
if fusi.ndim == 1:
fusi = fusi[..., None]
fusi_filt = np.zeros_like(fusi)
for chidx in range(fusi.shape[1]):
pixel_data = fusi[:, chidx].copy()
pixel_mean = pixel_data.mean()
pixel_data = pixel_data - pixel_mean
if ftype == 'median':
temporal_filter = signal.medfilt(pixel_data, window_size)
elif ftype == 'sg':
polyorder = 3 if 'polyorder' not in fkwargs else fkwargs.pop(
'polyorder')
temporal_filter = signal.savgol_filter(pixel_data,
window_size,
polyorder,
**fkwargs)
elif ftype == 'ma':
delays = range(-window_size, window_size+1)
temporal_filter = tikutils.delay_signal(
pixel_data, delays).mean(-1)
elif ftype == 'macausal':
delays = range(window_size+1)
temporal_filter = tikutils.delay_signal(
pixel_data, delays).mean(-1)
elif ftype == 'bandpass':
temporal_filter = band_pass_signal(pixel_data, **fkwargs)
# add mean back
new_signal = temporal_filter + pixel_mean
fusi_filt[:, chidx] = new_signal
if chidx % 1000 == 0:
print(ftype, window_size, chidx,
new_signal.sum(), pixel_mean, fkwargs)
return fusi_filt.squeeze()
def autocorr(y, yy=None, nlags=1):
'''
Auto-correlation function for `y` a 1D-array
`nlags` is in sample units.
Parameters
----------
y : 1D np.ndarray
The signal
yy : optional
nlags : int
Number of lags to return (0 - N)
Returns
-------
rho : 1D np.ndarray
The auto-correlation values upto `nlags` including zero
'''
assert y.ndim == 1
if yy is None:
yy = y
assert yy.ndim == 1
acorr = np.correlate(y, yy, 'same')
acorr /= acorr.max() # normalized
n = int(acorr.shape[0]/2)
# lags = np.arange(acorr.shape[0]) - n
# return acorr[np.where(np.logical_and(lags >= 0, lags <= nlags))]
# Minutely faster
return acorr[n:n+nlags+1]
def make_mask(superior_top, superior_bottom,
coronal_medial, coronal_lateral,
shape):
mask = np.zeros(shape, dtype=np.bool)
mask[min(coronal_medial, coronal_lateral):max(coronal_medial, coronal_lateral),
min(superior_bottom, superior_top):max(superior_bottom, superior_top)] = True
return mask
def band_pass_signal(data, sample_rate=1.0, ntaps=5, cutoff=[24.0, 48.0]):
'''Band-pass a signal with a FIR filter.
data (np.ndarray) :
sample_rate (float-like): in Hz
cutoff (list-like) : (low, high) frequency cutoffs
'''
# filter photo signal
from scipy import signal
ntaps = max(int(sample_rate/float(ntaps)), 1)
cutoff = | np.asarray(cutoff) | numpy.asarray |
import os
import subprocess
import pickle
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import scipy as sc
import pathlib
import threading
import concurrent.futures as cf
from scipy.signal import medfilt
import csv
import tikzplotlib
import encoders_comparison_tool as enc
import video_info as vi
from bj_delta import bj_delta, bj_delta_akima
# Colors in terminal
class bcolors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKCYAN = '\033[96m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
useage_log_suffix = "_useage.log"
psnr_log_suffix = "-psnr_logfile.txt"
ssim_log_suffix = "-ssim_logfile.txt"
vmaf_log_suffix = "-vmaf_logfile.txt"
videofiles = []
codecs = ["av1", "svtav1", "vp9", "x264", "x265", "vvc"]
codecs_short = {"av1": "AV1", "svtav1": "SVT-AV1", "vp9": "VP9", "x264": "x264", "x265": "x265", "vvc": "VVenC",}
sequences = ["Netflix Aerial yuv420p10le 60fps",
"ShakeNDry yuv420p 30fps",
"SunBath yuv420p10le 50fps",
"Tree Shade yuv420p10le 30fps",
"Sintel2 yuv420p10le 24fps",
]
preset = ["preset"]
top_dir = "/run/media/ondra/video/test2/"
# top_dir = "/run/media/ondra/61597e72-9c9f-4edd-afab-110602521f55/test2/"
graphics_dir = "graphs/"
sequences_short = {
"Netflix Aerial yuv420p10le 60fps": "Aerial",
"ShakeNDry yuv420p 30fps": "ShakeNDry",
"SunBath yuv420p10le 50fps": "SunBath",
"Tree Shade yuv420p10le 30fps": "Tree Shade",
"Sintel2 yuv420p10le 24fps": "Sintel2",
}
series_labels = {
'av1-cpu-used_3-': "AV1 cpu-used 3",
'av1-cpu-used_4-': "AV1 cpu-used 4",
'av1-cpu-used_5-': "AV1 cpu-used 5",
'av1-cpu-used_6-': "AV1 cpu-used 6",
'svtav1-preset_3-': "SVT-AV1 preset 3",
'svtav1-preset_5-': "SVT-AV1 preset 5",
'svtav1-preset_7-': "SVT-AV1 preset 7",
'svtav1-preset_9-': "SVT-AV1 preset 9",
'svtav1-preset_11-': "SVT-AV1 preset 11",
'svtav1-preset_13-': "SVT-AV1 preset 13",
'vp9-rc_0-': "VP9 RC 0",
'vp9-cpu-used_0-': "VP9 cpu-used 0",
'vp9-cpu-used_2-': "VP9 cpu-used 2",
'vp9-cpu-used_4-': "VP9 cpu-used 4",
# 'x264-preset_ultrafast-': "x264 ultrafast",
'x264-preset_fast-': "x264 fast",
'x264-preset_medium-': "x264 medium",
'x264-preset_slow-': "x264 slow",
'x264-preset_veryslow-': "x264 veryslow",
'x264-preset_placebo-': "x264 placebo",
'x265-preset_ultrafast-': "x265 ultrafast",
'x265-preset_fast-': "x265 fast",
'x265-preset_medium-': "x265 medium",
'x265-preset_slow-': "x265 slow",
'x265-preset_veryslow-': "x265 veryslow",
'vvc-preset_faster-': "VVenC faster",
'vvc-preset_fast-': "VVenC fast",
'vvc-preset_medium-': "VVenC medium",
}
psnr_lim = {
"Netflix Aerial yuv420p10le 60fps": (33, 47),
"ShakeNDry yuv420p 30fps": (33, 44),
"Sintel2 yuv420p10le 24fps": (40, 60),
"SunBath yuv420p10le 50fps": (35, 55),
"Tree Shade yuv420p10le 30fps": (35, 45),
}
ssim_lim = {
"Netflix Aerial yuv420p10le 60fps": (0.9, 1),
"ShakeNDry yuv420p 30fps": (0.9, 0.98),
"Sintel2 yuv420p10le 24fps": (0.98, 1),
"SunBath yuv420p10le 50fps": (0.94, 1),
"Tree Shade yuv420p10le 30fps": (0.92, 0.99),
}
msssim_lim = {
"Netflix Aerial yuv420p10le 60fps": (0.9, 1),
"ShakeNDry yuv420p 30fps": (0.92, 1),
"Sintel2 yuv420p10le 24fps": (0.98, 1),
"SunBath yuv420p10le 50fps": (0.94, 1),
"Tree Shade yuv420p10le 30fps": (0.96, 1),
}
vmaf_lim = {
"Netflix Aerial yuv420p10le 60fps": (60, 100),
"ShakeNDry yuv420p 30fps": (70, 100),
"Sintel2 yuv420p10le 24fps": (70, 100),
"SunBath yuv420p10le 50fps": (70, 100),
"Tree Shade yuv420p10le 30fps": (80, 100),
}
bitrate_lim = {
"Netflix Aerial yuv420p10le 60fps": (0, 150),
"ShakeNDry yuv420p 30fps": (0, 200),
"Sintel2 yuv420p10le 24fps": (0, 45),
"SunBath yuv420p10le 50fps": (0, 150),
"Tree Shade yuv420p10le 30fps": (0, 200),
}
bitrate_lim_log = {
"Netflix Aerial yuv420p10le 60fps": (0.1, 1000),
"ShakeNDry yuv420p 30fps": (0.1, 1000),
"SunBath yuv420p10le 50fps": (0.1, 1000),
"Tree Shade yuv420p10le 30fps": (0.1, 1000),
"Sintel2 yuv420p10le 24fps": (0.1, 100),
}
processing_lim = {
"Netflix Aerial yuv420p10le 60fps": (0, 50000),
"ShakeNDry yuv420p 30fps": (0, 8000),
"SunBath yuv420p10le 50fps": (0, 5000),
"Tree Shade yuv420p10le 30fps": (0, 12000),
"Sintel2 yuv420p10le 24fps": (0, 12000),
}
processing_lim_log = {
"Netflix Aerial yuv420p10le 60fps": (1, 1000),
"ShakeNDry yuv420p 30fps": (1, 10000),
"SunBath yuv420p10le 50fps": (1, 1000),
"Tree Shade yuv420p10le 30fps": (1, 1000),
"Sintel2 yuv420p10le 24fps": (1, 1000),
}
cpu_time_lim = {
"Netflix Aerial yuv420p10le 60fps": (0, 200000),
"ShakeNDry yuv420p 30fps": (0, 60000),
"SunBath yuv420p10le 50fps": (0, 35000),
"Tree Shade yuv420p10le 30fps": (0, 70000),
"Sintel2 yuv420p10le 24fps": (0, 70000),
}
cpu_time_lim_log = {
"Netflix Aerial yuv420p10le 60fps": (0.1, 1000),
"ShakeNDry yuv420p 30fps": (0.1, 10000),
"SunBath yuv420p10le 50fps": (0.1, 1000),
"Tree Shade yuv420p10le 30fps": (0.1, 1000),
"Sintel2 yuv420p10le 24fps": (0.1, 1000),
}
cpu_fps_lim = {
"Netflix Aerial yuv420p10le 60fps": (0, 200),
"ShakeNDry yuv420p 30fps": (0, 200),
"SunBath yuv420p10le 50fps": (0, 200),
"Tree Shade yuv420p10le 30fps": (0, 200),
"Sintel2 yuv420p10le 24fps": (0, 200),
}
decode_fps_lim = {
"Netflix Aerial yuv420p10le 60fps": (0, None),
"ShakeNDry yuv420p 30fps": (0, 60),
"SunBath yuv420p10le 50fps": (0, 60),
"Tree Shade yuv420p10le 30fps": (0, 60),
"Sintel2 yuv420p10le 24fps": (0, 60),
}
BJ1_serie = "x264-preset_placebo-"
BD_xname = "avg_bitrate_mb"
BD_ynames = ["psnr_avg", "ssim_avg", "msssim_avg", "vmaf_avg"]
BD_names = []
for n in BD_ynames:
# BD_names.append("bd_" + n)
BD_names.append("bd_rate_" + n)
encode_excluded_states = ["measuring decode"]
speeds_table = {
"placebo": 0,
"slow": 3,
"slower": 2,
"veryslow": 1,
"medium": 4,
"fast": 5,
"faster": 6,
"veryfast": 7,
"superfast": 8,
"ultrafast": 9,
}
binaries = {
"ffprobe": "/usr/bin/ffprobe",
"ffmpeg": "/usr/bin/ffmpeg"
}
vi.set_defaults(binaries)
def video_stream_size(videofile_path):
if videofile_path.endswith(".266"):
return os.path.getsize(videofile_path[0:-4] + ".266") / 1024 #in KiB
log = videofile_path + ".stream_size"
if os.path.exists(log):
with open(log, "r") as f:
s = f.readline()
print("stream size hit!")
return float(s)
result = subprocess.run(
[
"ffmpeg",
"-hide_banner",
"-i", videofile_path,
"-map", "0:v:0",
"-c", "copy",
"-f", "null", "-"
],
capture_output=True,
text=True,
)
try:
size = (result.stderr.rsplit("\n")[-2].rsplit(" ")[0].rsplit(":")[1][0: -2])
s = float(size) # in KiB
with open(log, "w") as f:
f.write(str(s))
return s
except ValueError:
raise ValueError(result.stderr.rstrip("\n"))
def video_stream_length(videofile_path):
if videofile_path.endswith(".266"):
videofile = videofile_path[:-4] + ".mkv"
else:
videofile = videofile_path
log = videofile + ".stream_length"
if os.path.exists(log):
with open(log, "r") as f:
s = f.readline()
print("stream length hit!")
return float(s)
result = vi.video_length_seconds(videofile)
with open(log, "w") as f:
f.write(str(result))
return result
def video_stream_frames(videofile_path):
if videofile_path.endswith(".266"):
videofile = videofile_path[:-4] + ".mkv"
else:
videofile = videofile_path
log = videofile + ".stream_frames"
if os.path.exists(log):
with open(log, "r") as f:
s = f.readline()
print("stream framenum hit!")
return int(s)
result = vi.video_frames(videofile)
with open(log, "w") as f:
f.write(str(result))
return result
def series_label(key, sequence=None):
if sequence is None or sequence in key:
k = series_labels.keys()
for s in (s for s in k if s in key):
return series_labels[s]
raise KeyError
'''
def simple_plot(x, y, xlabel, ylabel, savefile, minxlim=True):
i1, ax1 = plt.subplots()
plt.plot(x, y)
ax1.set(xlabel=xlabel, ylabel=ylabel)
if minxlim:
ax1.set_xlim(left=min(x), right=max(x))
ax1.grid()
plt.savefig(f"{savefile}.svg")
plt.savefig(f"{savefile}.pgf")
tikzplotlib.save(f"{savefile}.tex")
plt.close(i1)
def composite_plot(mxy, mlegend, xlabel, ylabel, savefile, xlim=None, ylim=None):
i1, ax1 = plt.subplots()
i = enc.count()
for m in mxy:
t = zip(*m)
x, y = [list(t) for t in t]
plt.plot(x, y, label=mlegend[next(i)], marker="+")
ax1.set(xlabel=xlabel, ylabel=ylabel)
plt.legend()
if xlim is True:
ax1.set_xlim(left=min(x), right=max(x))
elif xlim is not None:
ax1.set_xlim(left=xlim[0], right=xlim[1])
if ylim is True:
ax1.set_ylim(bottom=min(y), top=max(y))
elif ylim is not None:
ax1.set_ylim(bottom=ylim[0], top=ylim[1])
ax1.grid()
p = os.path.split(savefile)
enc.create_dir(p[0] + '/svg/')
enc.create_dir(p[0] + '/png/')
enc.create_dir(p[0] + '/tex/')
plt.savefig(f"{p[0] + '/svg/' + p[1]}.svg")
plt.savefig(f"{p[0] + '/png/' + p[1]}.png")
tikzplotlib.save(f"{p[0] + '/tex/' + p[1]}.tex")
plt.close(i1)
def composite_plot_smooth(mxy, mlegend, xlabel, ylabel, savefile, xlim=None, ylim=None):
i1, ax1 = plt.subplots()
i = enc.count()
for m in mxy:
t = zip(*m)
x, y = [list(t) for t in t]
c = plt.scatter(x, y, label=mlegend[next(i)], marker="+")
colr = c.get_facecolor()[0]
lx = np.log(x)
p = sc.interpolate.Akima1DInterpolator(lx, y)
x_smooth = np.linspace(min(x), max(x), 1000)
y_smooth = p(np.log(x_smooth))
plt.plot(x_smooth, y_smooth, color=colr)
ax1.set(xlabel=xlabel, ylabel=ylabel)
plt.legend()
if xlim is True:
ax1.set_xlim(left=x.min(), right=x.max())
elif xlim is not None:
ax1.set_xlim(left=xlim[0], right=xlim[1])
if ylim is True:
ax1.set_ylim(bottom=y.min(), top=y.max())
elif ylim is not None:
ax1.set_ylim(bottom=ylim[0], top=ylim[1])
ax1.grid()
p = os.path.split(savefile)
enc.create_dir(p[0] + '/svg/')
enc.create_dir(p[0] + '/png/')
enc.create_dir(p[0] + '/tex/')
plt.savefig(f"{p[0] + '/svg/' + p[1]}.svg")
plt.savefig(f"{p[0] + '/png/' + p[1]}.png")
tikzplotlib.save(f"{p[0] + '/tex/' + p[1]}.tex")
plt.close(i1)
'''
def plot_graphs(data, sequence=None, codec=None):
if sequence is None and codec is None:
out = graphics_dir
elif sequence is None:
out = graphics_dir + codec + "/"
elif codec is None:
out = graphics_dir + sequences_short[sequence] + "/"
else:
out = graphics_dir + sequences_short[sequence] + "/" + codec + "/"
lower_right = 4
d = df_to_plot(data, "avg_bitrate_mb", "psnr_avg")
composite_plot(d, "Bitrate [Mbit/s]", "PSNR (YUV) [dB]", out + "psnr", xlim=bitrate_lim[sequence], ylim=psnr_lim[sequence], legend_loc=lower_right)
composite_plot(d, "Bitrate [Mbit/s]", "PSNR (YUV) [dB]", out + "psnr_log", ylim=psnr_lim[sequence], xlog=True, legend_loc=lower_right)
d = df_to_plot(data, "avg_bitrate_mb", "ssim_avg")
composite_plot(d, "Bitrate [Mbit/s]", "SSIM", out + "ssim", xlim=bitrate_lim[sequence], ylim=ssim_lim[sequence], legend_loc=lower_right)
# composite_plot(d, "Bitrate [Mbit/s]", "SSIM", out + "ssim_log", ylim=ssim_lim[sequence], xlog=True, legend_loc=lower_right)
d = df_to_plot(data, "avg_bitrate_mb", "msssim_avg")
composite_plot(d, "Bitrate [Mbit/s]", "MS-SSIM", out + "msssim", xlim=bitrate_lim[sequence], ylim=msssim_lim[sequence], legend_loc=lower_right)
# composite_plot(d, "Bitrate [Mbit/s]", "MS-SSIM", out + "msssim_log", ylim=msssim_lim[sequence], xlog=True, legend_loc=lower_right)
d = df_to_plot(data, "avg_bitrate_mb", "vmaf_avg")
composite_plot(d, "Bitrate [Mbit/s]", "VMAF", out + "vmaf", xlim=bitrate_lim[sequence], ylim=vmaf_lim[sequence], legend_loc=lower_right)
# composite_plot(d, "Bitrate [Mbit/s]", "VMAF", out + "vmaf_log", ylim=vmaf_lim[sequence], xlog=True, legend_loc=lower_right)
d = df_to_plot(data, "avg_bitrate_mb", "decode_time_fps")
composite_plot(d, "Bitrate [Mbit/s]", "Rychlost dekódování [frame/s]", out + "decode", ylim=(0, None), xlim=bitrate_lim_log[sequence], xlog=True)
d = df_to_plot(data, "avg_bitrate_mb", "total_time_fps")
composite_plot(d, "Bitrate [Mbit/s]", "Procesorový čas [s/frame]", out + "encode", ylim=(0.1, None), xlim=bitrate_lim_log[sequence], xlog=True, ylog=True)
def df_to_plot(data, x_name, y_name):
tables = [t[[x_name, y_name]].rename(columns={x_name: "x", y_name: "y"}).sort_values(by="x") for t in list(data["table"])]
l = list(data["label"])
s = list(data["speed"])
lt = zip(l, tables, s)
for m in lt:
setattr(m[1], "label", m[0])
setattr(m[1], "speed", m[2])
return tables
def df_to_plot2(data, x_name, y_name):
tables = [data[[x_name, y_name]].rename(columns={x_name: "x", y_name: "y"}).loc[data["codec"] == s].sort_values(by="x") for s in codecs]
lt = zip(codecs, tables)
for m in lt:
setattr(m[1], "label", codecs_short[m[0]])
return tables
#def composite_plot(data, xlabel, ylabel, savefile, xlim=None, ylim=None, log_inter=True, xlog=False, ylog=False, smooth=True, xlogscalar=False, ylogscalar=False, legend_loc=None, tikz_before=True):
#i1, ax1 = plt.subplots()
#if not (xlog or ylog):
#tikz_before = False
#if xlog:
#ax1.set_xscale('log')
#ax1.grid(True, which="both")
#if xlogscalar:
#ax1.xaxis.set_major_formatter(matplotlib.ticker.ScalarFormatter())
#else:
#ax1.set_xscale('linear')
#ax1.grid(True)
#if ylog:
#ax1.set_yscale('log')
#ax1.grid(True, which="both")
#if ylogscalar:
#ax1.yaxis.set_major_formatter(matplotlib.ticker.ScalarFormatter())
#else:
#ax1.set_yscale('linear')
#ax1.grid(True)
#for table in data:
#if smooth:
#c = plt.scatter(table.x, table.y, label=table.label, marker="+")
#colr = c.get_facecolor()[0]
#if log_inter:
#lx = np.log(table.x)
#p = sc.interpolate.Akima1DInterpolator(lx, table.y)
#x_smooth = np.logspace(np.log10(min(table.x)), np.log10(max(table.x)), 200)
#else:
#lx = table.x
#p = sc.interpolate.Akima1DInterpolator(lx, table.y)
#x_smooth = np.linspace(min(table.x), max(table.x), 200)
#y_smooth = p(np.log(x_smooth))
#plt.plot(x_smooth, y_smooth, color=colr)
#else:
#plt.plot(table.x, table.y, label=table.label, marker="+")
#ax1.set(xlabel=xlabel, ylabel=ylabel)
#if legend_loc is None:
#ax1.legend()
#else:
#ax1.legend(loc=legend_loc)
#if xlim is True:
#ax1.set_xlim(left=table.x.min(), right=table.x.max())
#elif xlim is not None:
#ax1.set_xlim(left=xlim[0], right=xlim[1])
#if ylim is True:
#ax1.set_ylim(bottom=table.y.min(), top=table.y.max())
#elif ylim is not None:
#ax1.set_ylim(bottom=ylim[0], top=ylim[1])
#p = os.path.split(savefile)
#enc.create_dir(p[0] + '/svg/')
#enc.create_dir(p[0] + '/png/')
#enc.create_dir(p[0] + '/tex/')
#if tikz_before:
#tikzplotlib.save(f"{p[0] + '/tex/' + p[1]}.tex")
#plt.savefig(f"{p[0] + '/svg/' + p[1]}.svg")
#plt.savefig(f"{p[0] + '/png/' + p[1]}.png")
#if not tikz_before:
#tikzplotlib.save(f"{p[0] + '/tex/' + p[1]}.tex")
#plt.close(i1)
def composite_plot(data, xlabel, ylabel, savefile, xlim=None, ylim=None, log_inter=True, xlog=False, ylog=False, smooth=True, xlogscalar=False, ylogscalar=False, legend_loc=None, tikz_before=True):
plt.figure()
plt.axis()
if not (xlog or ylog):
tikz_before = False
if xlog:
plt.xscale('log')
plt.grid(True, which="both")
# if xlogscalar:
# plt.xaxis.set_major_formatter(matplotlib.ticker.ScalarFormatter())
else:
plt.xscale('linear')
plt.grid(True)
if ylog:
plt.yscale('log')
plt.grid(True, which="both")
# if ylogscalar:
# plt.yaxis.set_major_formatter(matplotlib.ticker.ScalarFormatter())
else:
plt.yscale('linear')
plt.grid(True)
for table in data:
if smooth:
c = plt.scatter(table.x, table.y, label=table.label, marker="+")
colr = c.get_facecolor()[0]
if log_inter:
lx = np.log(table.x)
p = sc.interpolate.Akima1DInterpolator(lx, table.y)
x_smooth = np.logspace(np.log10(min(table.x)), np.log10(max(table.x)), 200)
else:
lx = table.x
p = sc.interpolate.Akima1DInterpolator(lx, table.y)
x_smooth = np.linspace(min(table.x), max(table.x), 200)
y_smooth = p(np.log(x_smooth))
plt.plot(x_smooth, y_smooth, color=colr)
else:
plt.plot(table.x, table.y, label=table.label, marker="+")
plt.xlabel(xlabel)
plt.ylabel(ylabel)
plt.legend(loc=legend_loc)
if xlim is True:
plt.xlim(left=table.x.min(), right=table.x.max())
elif xlim is not None:
plt.xlim(left=xlim[0], right=xlim[1])
if ylim is True:
plt.ylim(bottom=table.y.min(), top=table.y.max())
elif ylim is not None:
plt.ylim(bottom=ylim[0], top=ylim[1])
p = os.path.split(savefile)
enc.create_dir(p[0] + '/svg/')
enc.create_dir(p[0] + '/png/')
enc.create_dir(p[0] + '/tex/')
if tikz_before:
tikzplotlib.save(f"{p[0] + '/tex/' + p[1]}.tex")
plt.savefig(f"{p[0] + '/svg/' + p[1]}.svg")
plt.savefig(f"{p[0] + '/png/' + p[1]}.png")
if not tikz_before:
tikzplotlib.save(f"{p[0] + '/tex/' + p[1]}.tex")
plt.close()
def df_to_latex_table(values, save_path):
pass
def calc_bj(mxy_o, mlegend_o, bd_metric_legend, bd_rate_legend):
mxy = mxy_o.copy()
mlegend = mlegend_o.copy()
xy1 = mxy[mlegend.index(BJ1_serie)]
t1 = zip(*xy1)
x1, y1 = [list(t1) for t1 in t1]
mxy.remove(xy1)
mlegend.remove(BJ1_serie)
i = enc.count()
for m in mxy:
t = zip(*m)
x, y = [list(t) for t in t]
bd_metric = bj_delta(x1, y1, x, y, mode=0)
bd_rate = bj_delta(x1, y1, x, y, mode=1)
l = mlegend[next(i)]
print(f"{l}: BD-{bd_metric_legend}: {bd_metric}%")
print(f"{l}: BD-{bd_rate_legend}: {bd_rate}%")
def formatter1(x):
s = ('%1.2f' % x).replace(".",",") + "\,\%"
return s
def formatter2(x):
s = ('%1.2f' % x).replace(".",",") + "\%"
if x > 0:
s = "\cellcolor{red!25}" + s
elif x < 0:
s = "\cellcolor{green!25}" + s
return s
def calc_bj_cross_to_table(mxy_o, mlegend_o, bd_metric_legend, bd_rate_legend):
table_metric = pd.DataFrame(np.zeros((len(mlegend_o), len(mlegend_o))), columns=mlegend_o, index=mlegend_o)
table_rate = pd.DataFrame(np.zeros((len(mlegend_o), len(mlegend_o))), columns=mlegend_o, index=mlegend_o)
for mleg in mlegend_o:
mxy = mxy_o.copy()
mlegend = mlegend_o.copy()
xy1 = mxy[mlegend.index(mleg)]
t1 = zip(*xy1)
x1, y1 = [list(t1) for t1 in t1]
mxy.remove(xy1)
mlegend.remove(mleg)
i = enc.count()
for m in mxy:
t = zip(*m)
x, y = [list(t) for t in t]
bd_metric = bj_delta(x1, y1, x, y, mode=0)
bd_rate = bj_delta(x1, y1, x, y, mode=1)
l = mlegend[next(i)]
table_metric.loc[l, mleg] = bd_metric
table_rate.loc[l, mleg] = bd_rate
# print(table_metric.to_latex(float_format="%.2f", decimal=","))
# print(table_rate.to_latex(float_format="%.2f"))
return table_metric, table_rate
'''
def calc_bj_akima(dftable, x_name, y_name, bd_metric_legend, bd_rate_legend):
xy1 = mxy[mlegend.index(BJ1_serie)]
t1 = zip(*xy1)
x1, y1 = [list(t1) for t1 in t1]
mxy.remove(xy1)
mlegend.remove(BJ1_serie)
i = enc.count()
for m in mxy:
t = zip(*m)
x, y = [list(t) for t in t]
bd_metric = bj_delta_akima(x1, y1, x, y, mode=0)
bd_rate = bj_delta_akima(x1, y1, x, y, mode=1)
l = mlegend[next(i)]
print(f"{l}: BD-{bd_metric_legend}: {bd_metric}%")
print(f"{l}: BD-{bd_rate_legend}: {bd_rate}%")
'''
def calc_bj_akima(data, x_name, y_name, bd_metric_legend, bd_rate_legend):
df = data.copy()
for t in df.itertuples():
t.table.rename(columns={x_name: "x", y_name: "y"}).sort_values(by="x")
df
bd_metric = bj_delta_akima(x1, y1, x, y, mode=0)
bd_rate = bj_delta_akima(x1, y1, x, y, mode=1)
def read_table_kcolv(logpath):
with open(logpath, "r") as f:
firstline = next(f).rstrip(" \n")
columns = []
for x in firstline.rsplit(" "):
columns.append(x.rsplit(":")[0])
r = range(len(columns))
table = pd.read_table(logpath, names=columns, usecols=list(r), sep=" ",
converters={k: lambda x: (x.rsplit(":")[1]) for k in r})
return table.apply(pd.to_numeric)
class PSNR_values:
def __init__(self, logpath):
self.logpath = logpath
table = read_table_kcolv(self.logpath)
self.n = table.n
self.mse_avg = table.mse_avg
self.mse_y = table.mse_y
self.mse_u = table.mse_u
self.mse_v = table.mse_v
self.psnr_avg = table.psnr_avg
self.psnr_y = table.psnr_y
self.psnr_u = table.psnr_u
self.psnr_v = table.psnr_v
self.mse_avg_avg = np.average(self.mse_avg)
self.mse_y_avg = np.average(self.mse_y)
self.mse_u_avg = np.average(self.mse_u)
self.mse_v_avg = np.average(self.mse_v)
self.psnr_avg_avg = np.average(self.psnr_avg)
self.psnr_y_avg = np.average(self.psnr_y)
self.psnr_u_avg = np.average(self.psnr_u)
self.psnr_v_avg = np.average(self.psnr_v)
class SSIM_values:
def __init__(self, logpath):
self.logpath = logpath
names = ("n", "Y", "U", "V", "All", "unnorm")
table = pd.read_table(self.logpath, names=names, sep=" ",
converters={k: lambda x: (x.rsplit(":")[1]) for k in range(5)})
table.unnorm = table.unnorm.str.slice(start=1, stop=-1)
table = table.apply(pd.to_numeric)
self.n = table.n
self.Y = table.Y
self.U = table.U
self.V = table.V
self.All = table.All
self.unnorm = table.unnorm # unnorm = 10*log10(1-All)
self.Y_avg = np.average(self.Y)
self.U_avg = np.average(self.U)
self.V_avg = np.average(self.V)
self.All_avg = np.average(self.All)
self.unnorm_avg = np.average(self.unnorm)
class VMAF_values:
def __init__(self, logpath):
self.logpath = logpath
table = pd.read_table(logpath, sep=",")
table = table.loc[:, ~table.columns.str.contains('^Unnamed')]
self.table = table
self.vmaf_avg = table.vmaf.mean()
class Useage_values:
def __init__(self, logpath):
self.logpath = logpath
with open(logpath, "r") as log:
firstline = next(log)
self.row_names = firstline.rsplit(",")[0:-1]
table = pd.read_csv(self.logpath)
self.table = table
self.state_names = list(table.state.unique())
total_time = 0
total_cpu_time = 0
for state in [x for x in self.state_names if x not in encode_excluded_states]:
for row in self.row_names:
if row == "state":
pass
else:
arr = | np.array(table[row][table.index[table['state'] == state]]) | numpy.array |
#
# CanvasRenderQt.py -- for rendering into a ImageViewQt widget
#
# This is open-source software licensed under a BSD license.
# Please see the file LICENSE.txt for details.
#
import numpy as np
from ginga.qtw.QtHelp import (QtCore, QPen, QPolygon, QColor, QFontMetrics,
QPainterPath, QImage, QPixmap, get_font,
get_painter)
from ginga import colors
from ginga.vec import CanvasRenderVec as vec
from ginga.canvas import render
# force registration of all canvas types
import ginga.canvas.types.all # noqa
class RenderContext(render.RenderContextBase):
def __init__(self, renderer, viewer, surface):
render.RenderContextBase.__init__(self, renderer, viewer)
self.cr = get_painter(surface)
def __get_color(self, color, alpha):
clr = QColor()
if isinstance(color, tuple):
clr.setRgbF(color[0], color[1], color[2], alpha)
else:
r, g, b = colors.lookup_color(color)
clr.setRgbF(r, g, b, alpha)
return clr
def set_line_from_shape(self, shape):
pen = QPen()
pen.setWidthF(getattr(shape, 'linewidth', 1.0))
if hasattr(shape, 'linestyle'):
if shape.linestyle == 'dash':
pen.setDashPattern([3.0, 4.0, 6.0, 4.0])
pen.setDashOffset(5.0)
alpha = getattr(shape, 'alpha', 1.0)
color = self.__get_color(shape.color, alpha)
pen.setColor(color)
self.cr.setPen(pen)
def set_fill_from_shape(self, shape):
fill = getattr(shape, 'fill', False)
if fill:
if hasattr(shape, 'fillcolor') and shape.fillcolor:
color = shape.fillcolor
else:
color = shape.color
if color is None:
self.cr.setBrush(QtCore.Qt.NoBrush)
else:
alpha = getattr(shape, 'alpha', None)
fillalpha = getattr(shape, 'fillalpha', alpha)
color = self.__get_color(color, fillalpha)
self.cr.setBrush(color)
else:
self.cr.setBrush(QtCore.Qt.NoBrush)
def set_font_from_shape(self, shape):
if hasattr(shape, 'font'):
if (hasattr(shape, 'fontsize') and shape.fontsize is not None and
not getattr(shape, 'fontscale', False)):
fontsize = shape.fontsize
else:
fontsize = shape.scale_font(self.viewer)
fontsize = self.scale_fontsize(fontsize)
font = get_font(shape.font, fontsize)
self.cr.setFont(font)
def initialize_from_shape(self, shape, line=True, fill=True, font=True):
if line:
self.set_line_from_shape(shape)
if fill:
self.set_fill_from_shape(shape)
if font:
self.set_font_from_shape(shape)
def set_line(self, color, alpha=1.0, linewidth=1, style='solid'):
clr = self.__get_color(color, alpha)
pen = self.cr.pen()
pen.setColor(clr)
pen.setWidthF(float(linewidth))
if style == 'dash':
pen.setDashPattern([3.0, 4.0, 6.0, 4.0])
pen.setDashOffset(5.0)
self.cr.setPen(pen)
def set_fill(self, color, alpha=1.0):
if color is None:
self.cr.setBrush(QtCore.Qt.NoBrush)
else:
color = self.__get_color(color, alpha)
self.cr.setBrush(color)
def set_font(self, fontname, fontsize, color='black', alpha=1.0):
self.set_line(color, alpha=alpha)
fontsize = self.scale_fontsize(fontsize)
font = get_font(fontname, fontsize)
self.cr.setFont(font)
def text_extents(self, text):
fm = self.cr.fontMetrics()
if hasattr(fm, 'horizontalAdvance'):
width = fm.horizontalAdvance(text)
else:
width = fm.width(text)
height = fm.height()
return width, height
def setup_pen_brush(self, pen, brush):
if pen is not None:
self.set_line(pen.color, alpha=pen.alpha, linewidth=pen.linewidth,
style=pen.linestyle)
self.cr.setBrush(QtCore.Qt.NoBrush)
if brush is not None:
self.set_fill(brush.color, alpha=brush.alpha)
##### DRAWING OPERATIONS #####
## def draw_image(self, cvs_img, cpoints, cache, whence, order='RGBA'):
## # no-op for this renderer
## pass
def draw_text(self, cx, cy, text, rot_deg=0.0):
self.cr.save()
self.cr.translate(cx, cy)
self.cr.rotate(-rot_deg)
self.cr.drawText(0, 0, text)
self.cr.restore()
def draw_polygon(self, cpoints):
## cpoints = trcalc.strip_z(cpoints)
qpoints = [QtCore.QPoint(p[0], p[1]) for p in cpoints]
p = cpoints[0]
qpoints.append(QtCore.QPoint(p[0], p[1]))
qpoly = QPolygon(qpoints)
self.cr.drawPolygon(qpoly)
def draw_circle(self, cx, cy, cradius):
# this is necessary to work around a bug in Qt--radius of 0
# causes a crash
cradius = max(cradius, 0.000001)
pt = QtCore.QPointF(cx, cy)
self.cr.drawEllipse(pt, float(cradius), float(cradius))
def draw_bezier_curve(self, cp):
path = QPainterPath()
path.moveTo(cp[0][0], cp[0][1])
path.cubicTo(cp[1][0], cp[1][1], cp[2][0], cp[2][1], cp[3][0], cp[3][1])
self.cr.drawPath(path)
def draw_ellipse_bezier(self, cp):
# draw 4 bezier curves to make the ellipse
path = QPainterPath()
path.moveTo(cp[0][0], cp[0][1])
path.cubicTo(cp[1][0], cp[1][1], cp[2][0], cp[2][1], cp[3][0], cp[3][1])
path.cubicTo(cp[4][0], cp[4][1], cp[5][0], cp[5][1], cp[6][0], cp[6][1])
path.cubicTo(cp[7][0], cp[7][1], cp[8][0], cp[8][1], cp[9][0], cp[9][1])
path.cubicTo(cp[10][0], cp[10][1], cp[11][0], cp[11][1], cp[12][0], cp[12][1])
self.cr.drawPath(path)
def draw_line(self, cx1, cy1, cx2, cy2):
self.cr.pen().setCapStyle(QtCore.Qt.RoundCap)
self.cr.drawLine(cx1, cy1, cx2, cy2)
def draw_path(self, cp):
## cp = trcalc.strip_z(cp)
self.cr.pen().setCapStyle(QtCore.Qt.RoundCap)
pts = [QtCore.QLineF(QtCore.QPointF(cp[i][0], cp[i][1]),
QtCore.QPointF(cp[i + 1][0], cp[i + 1][1]))
for i in range(len(cp) - 1)]
self.cr.drawLines(pts)
class CanvasRenderer(render.StandardPipelineRenderer):
def __init__(self, viewer, surface_type='qimage'):
render.StandardPipelineRenderer.__init__(self, viewer)
self.kind = 'qt'
# Qt needs this to be in BGRA
self.rgb_order = 'BGRA'
self.qimg_fmt = QImage.Format_RGB32
self.surface_type = surface_type
# the offscreen drawing surface
self.surface = None
def resize(self, dims):
"""Resize our drawing area to encompass a space defined by the
given dimensions.
"""
width, height = dims[:2]
self.logger.debug("renderer reconfigured to %dx%d" % (
width, height))
new_wd, new_ht = width * 2, height * 2
if self.surface_type == 'qpixmap':
if ((self.surface is None) or (self.surface.width() < width) or
(self.surface.height() < height)):
self.surface = QPixmap(new_wd, new_ht)
else:
self.surface = QImage(width, height, self.qimg_fmt)
super(CanvasRenderer, self).resize(dims)
def _get_qimage(self, rgb_data):
ht, wd, channels = rgb_data.shape
result = QImage(rgb_data.data, wd, ht, self.qimg_fmt)
# Need to hang on to a reference to the array
result.ndarray = rgb_data
return result
def _get_color(self, r, g, b):
# TODO: combine with the method from the RenderContext?
n = 255.0
clr = QColor(int(r * n), int(g * n), int(b * n))
return clr
def get_surface_as_array(self, order=None):
if self.surface_type == 'qpixmap':
qimg = self.surface.toImage()
else:
qimg = self.surface
#qimg = qimg.convertToFormat(QImage.Format_RGBA32)
width, height = qimg.width(), qimg.height()
if hasattr(qimg, 'bits'):
# PyQt
ptr = qimg.bits()
ptr.setsize(qimg.byteCount())
else:
# PySide
ptr = qimg.constBits()
arr = np.array(ptr).reshape(height, width, 4)
# rendering surface is usually larger than window, so cutout
# just enough to show what has been drawn
win_wd, win_ht = self.dims[:2]
arr = | np.ascontiguousarray(arr[:win_ht, :win_wd, :]) | numpy.ascontiguousarray |
# Lint as: python3
# Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for pwlfit/transform."""
import unittest
import numpy as np
from pwlfit import test_util
from pwlfit import transform
import scipy.stats
identity_transform = transform.identity
log_transform = np.log
log1p_transform = np.log1p
symlog1p_transform = transform.symlog1p
class FindBestTransformTest(test_util.PWLFitTest):
def test_weighted_pearson_correlation_is_independent_of_weight_scale(self):
np.random.seed(4)
x = np.random.normal(size=100)
y = x + np.random.normal(size=100)
w = np.random.uniform(size=100)
corr_w = transform.weighted_pearson_correlation(x, y, w)
corr_5w = transform.weighted_pearson_correlation(x, y, 5 * w)
self.assertAlmostEqual(corr_w, corr_5w)
def test_weighted_pearson_correlation_matches_scipy_for_equal_weights(self):
# Verify that our weighted pearson correlation matches scipy's unweighted
# pearson correlation when the weights are equal.
np.random.seed(4)
x = np.random.normal(size=100)
w = np.ones_like(x)
# Non-correlated.
y = np.random.normal(size=100)
weightless_corr, _ = scipy.stats.pearsonr(x, y)
weighted_corr = transform.weighted_pearson_correlation(x, y, w)
self.assertAlmostEqual(weightless_corr, weighted_corr)
# Correlated.
y = x + np.random.normal(size=100)
weightless_corr, _ = scipy.stats.pearsonr(x, y)
weighted_corr = transform.weighted_pearson_correlation(x, y, w)
self.assertAlmostEqual(weightless_corr, weighted_corr)
# Perfect correlation.
y = x
weightless_corr, _ = scipy.stats.pearsonr(x, y)
weighted_corr = transform.weighted_pearson_correlation(x, y, w)
self.assertAlmostEqual(weightless_corr, weighted_corr)
def test_weighted_pearson_correlation_nan_when_x_is_constant(self):
np.random.seed(6)
x = np.repeat(np.random.normal(), 10)
y = np.random.normal(size=10)
w = np.random.uniform(size=10)
correlation = transform.weighted_pearson_correlation(x, y, w)
self.assertTrue(np.isnan(correlation))
def test_weighted_pearson_correlation_nan_when_y_is_constant(self):
np.random.seed(7)
x = np.random.normal(size=10)
y = np.repeat(np.random.normal(), 10)
w = np.random.uniform(size=10)
correlation = transform.weighted_pearson_correlation(x, y, w)
self.assertTrue(np.isnan(correlation))
def test_weighted_pearson_correlation_raises_on_bad_input(self):
no_pts = np.array([], dtype=float)
two_pts = np.array([1., 2.])
three_pts = np.array([1., 2., 3.])
with self.assertRaises(ValueError):
transform.weighted_pearson_correlation(no_pts, no_pts, no_pts)
with self.assertRaises(ValueError):
transform.weighted_pearson_correlation(three_pts, two_pts, two_pts)
with self.assertRaises(ValueError):
transform.weighted_pearson_correlation(three_pts, two_pts, three_pts)
with self.assertRaises(ValueError):
transform.weighted_pearson_correlation(three_pts, three_pts, two_pts)
with self.assertRaises(ValueError):
transform.weighted_pearson_correlation(no_pts, two_pts, three_pts)
# Doesn't raise.
transform.weighted_pearson_correlation(two_pts, two_pts, two_pts)
transform.weighted_pearson_correlation(three_pts, three_pts, three_pts)
def test_identity_function(self):
np.random.seed(4)
xs = np.random.normal(size=100)
self.assert_allclose(xs, transform.identity(xs))
def test_symlog1p_matches_log1p(self):
np.random.seed(4)
xs = np.abs(np.random.normal(size=100))
self.assert_allclose(np.log1p(xs), transform.symlog1p(xs))
self.assert_allclose(-np.log1p(xs), transform.symlog1p(-xs))
def test_find_best_transform_is_identity_for_constant_xs(self):
np.random.seed(5)
x = np.ones(10)
y = np.arange(10)
w = np.random.uniform(size=len(x))
found_transform = transform.find_best_transform(x, y, w)
self.assertEqual(identity_transform, found_transform)
def test_find_best_transform_is_identity_for_constant_ys(self):
np.random.seed(5)
x = np.arange(10)
y = np.ones(10)
w = np.random.uniform(size=len(x))
found_transform = transform.find_best_transform(x, y, w, pct_to_clip=0)
self.assertEqual(identity_transform, found_transform)
def test_find_best_transform_is_identity_for_xs_constant_after_clipping(self):
np.random.seed(5)
x = np.array([1.] + [2] * 100 + [3])
y = | np.log(x) | numpy.log |
#!/usr/bin/env python
import pandas as pd
import numpy as np
import os
from datetime import datetime, timedelta
import math
import logging
from pathlib import Path
import seaborn as sns
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import jinja2
import pdfkit
import sys
sys.path.append('../../')
from src.features import build_features
from src.visualization import visualize
class beiwe_participation_report():
'''
'''
def __init__(self,report_date):
'''
'''
self.report_date = report_date
self.firstDate = datetime(2020,5,13)
self.maxDailySurveys = np.busday_count(self.firstDate.date(), self.report_date.date(), weekmask='Sun Mon Wed Fri')
self.maxWeeklySurveys = np.busday_count(self.firstDate.date(), self.report_date.date(), weekmask='Sat')
def import_survey_summary(self,surveyType='morning'):
'''
Imports survey summary csv files, cuts it down to the specified date, and returns a cleaned dataframe
'''
# importing datafile
temp = pd.read_csv(f"../../data/interim/survey_mood_{surveyType}_summary.csv",index_col=0)
# getting dataframe in date range
df = pd.DataFrame()
for column in temp.columns:
if datetime.strptime(column,'%m/%d/%Y') <= self.report_date:
df = pd.concat([df,temp[column]],axis=1)
# converting elements to numbers and creating sum/percent column
for column in df.columns:
df[column] = pd.to_numeric(df[column],errors='coerce')
df['Sum'] = df.sum(axis=1)
if surveyType in ['morning','evening']:
df['Percent'] = df['Sum'] / self.maxDailySurveys
else:
df['Percent'] = df['Sum'] / self.maxWeeklySurveys
return df
def load_survey_data(self):
'''
'''
# importing
self.morn = self.import_survey_summary('morning')
self.night = self.import_survey_summary('evening')
self.week = self.import_survey_summary('week')
def load_sensor_data(self,dateThru='06082020'):
'''
'''
self.acc = pd.read_csv(f'../../data/interim/acc_summary.csv',
index_col=0)
def create_plots(self):
'''
'''
# morning and evening histograms
fig, axes = plt.subplots(1,2,figsize=(12,6),sharey=True)
i = 0
colors = ('firebrick','cornflowerblue')
for df,name in zip([self.morn,self.night],['morning','evening']):
ax = axes[i]
sns.distplot(df['Sum'],bins=np.arange(0,self.maxDailySurveys+5,1),color=colors[i],kde=False,label=name,ax=ax)
ax.set_xticks(np.arange(0,self.maxDailySurveys+5,1))
ax.set_xlim([0,self.maxDailySurveys+5])
ax.set_ylim([0,10])
ax.set_xlabel('Total Surveys Completed')
ax.legend(title='Survey Timing')
i += 1
axes[0].set_ylabel('Number of Participants')
axes[0].text(self.maxDailySurveys+1,-1.5,f'Max Possible Surveys: {self.maxDailySurveys}')
axes[1].set_xticks(np.arange(1,self.maxDailySurveys+5,1))
plt.subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=0, hspace=None)
plt.savefig('../../reports/beiwe_check/daily_survey_summary_histogram.png')
# weekly histograms
fig,ax = plt.subplots(figsize=(12,6))
sns.distplot(self.week['Sum'],bins=np.arange(0,6,1),kde=False,color='cornflowerblue')
ax.set_xticks(np.arange(0,6,1))
ax.set_xlabel(f'Total Surveys Completed - Max Possible: {self.maxWeeklySurveys}')
ax.set_xlim([0,5])
ax.set_ylabel('Number of Participants')
plt.savefig('../../reports/beiwe_check/weekly_survey_summary_histrogram.png')
# participation tier
for survey,timing in zip([self.morn,self.night],['morning','evening']):
fig, ax = plt.subplots(figsize=(12,8))
colors = ['red','orange','yellow','green','blue','violet']
shapes = ['o', 'v', '^', '<', '>', '8', 's', 'd']
df = survey.sort_values('Sum')
per = | np.zeros(4) | numpy.zeros |
import configparser
import os
import sys
import time
import glob
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from astropy.io import fits
import marg_mcmc as wl
import batman
# Set path to read in get_limb.py from bin_analysis
sys.path.insert(0, '../bin_analysis')
import get_limb as gl
def event_time(date, properties):
"""Program to determine the expected event time
Inputs
date: 1D array of the date of each exposure (MJD)
properties: 1D array containing the last observed eclipse
and the period. (MJD, days)"""
time = properties[1, 0]
time_error = properties[1, 1]
period = properties[4, 0]
period_error = properties[4, 1]
i = 0
while time < date[0]:
i += 1
time += period
epoch_error = np.sqrt(time_error**2 + (i*period_error)**2)
return float(time), float(epoch_error)
def get_orbits(date):
"""Procedure to organize light curve data by HST orbit"""
orbit=np.zeros(1).astype(int)
for i in range(len(date)-1):
t=date[i+1]-date[i]
if t*86400 > 1200.:
orbit=np.append(orbit, i+1) # 1800s is about half an HST orbit
return np.append(orbit, len(date))
def inputs(data, transit=True):
""" Function to read in priors for a system.
INPUTS:
data: Data table of priors for a particular planet
OUTPUTS:
Returns array of system properties with corresponding uncertainties:
[rprs, central event time, inclination, orbit distance/stellar radius (a/Rs),
period, transit/eclipse depth]
"""
inp_values = pd.read_table(data, sep=' ', index_col=None)
data_arr = inp_values.iloc[:,2].values
labels = inp_values.iloc[:,0].values
param_errs = inp_values.iloc[:,3].values
# Conversions are R_Jup to meters, R_solar to meters, AU to meters,
# and JD to MJD.
conversions = np.array([6.9911e7, 6.957e8, 1.49598e11, -2400000.5])
period = data_arr[4]
inc = data_arr[5]
rprs = data_arr[8]
rprs_err = param_errs[8]
a_R = data_arr[9]
if transit==True:
epoch = data_arr[6] + conversions[3]
depth = rprs * rprs
depth_err = 2 * rprs * rprs_err
else:
epoch = data_arr[6] + conversions[3] + period/2.
depth = rprs*rprs*(data_arr[2]/data_arr[3])/3
# Save important inputs to properties (props) array.
props = np.zeros(6)
props[0] = rprs
props[1] = epoch
props[2] = inc
props[3] = a_R
props[4] = period
props[5] = depth
# Save corresponding errors, mostly for priors for MCMC fitting.
errors = np.zeros(6)
errors[0] = rprs_err
errors[1] = param_errs[6]
errors[2] = param_errs[5]
errors[3] = param_errs[9]
errors[4] = param_errs[4]
errors[5] = depth_err
return [props,errors]
# def correction(inputs, date, flux, transit=False):
# params=batman.TransitParams()
# params.w=90.
# params.ecc=0
# params.rp=np.sqrt(inputs[0])
# t0=inputs[1]
# params.inc=inputs[2]
# params.a=inputs[3]
# params.per=inputs[4]
# depth=inputs[5]
# phase = (date-t0)/params.per
# phase = phase - np.floor(phase)
# phase[phase > 0.5] = phase[phase > 0.5] - 1.0
# if transit==True:
# params.t0=t0
# params.u=inputs[6:]
# params.limb_dark="quadratic"
# m=batman.TransitModel(params, date)
# model=m.light_curve(params)
# else:
# params.fp=inputs[5]
# params.t_secondary=t0
# params.u=[]
# params.limb_dark="uniform"
# m=batman.TransitModel(params, date, transittype="secondary")
# model=m.light_curve(params)
# corrected=flux/model
# return corrected
# def remove_bad_data(light_curve, spectra, light_corrected, date1, light_err, spec_err
# , user_inputs, check=False):
# """Procedure to remove "bad" data from light curve"""
# med= np.ma.median(light_corrected)
# sigma = np.sqrt(np.sum((light_corrected-med)**2)/(2*len(light_corrected)))
# medi=np.zeros_like(date1)+med
# sig3=medi+3*sigma
# sig4=medi+4*sigma
# sig5=medi+5*sigma
# sig3m=medi-3*sigma
# sig4m=medi-4*sigma
# sig5m=medi-5*sigma
# if check==False:
# nPasses=int(user_inputs[3])
# sigma_cut_factor=user_inputs[2]
# else:
# data=plt.plot(date1, light_corrected,'bo',ls='dotted')
# plt.xlabel('MJD')
# plt.ylabel('Total Flux')
# s5=plt.plot(date1, sig5,'pink',date1, sig5m, 'pink')
# s5[0].set_label('5-sigma')
# s4=plt.plot(date1, sig4,'g', date1, sig4m, 'g')
# s4[0].set_label('4-sigma')
# s3=plt.plot(date1, sig3,'r', date1, sig3m, 'r')
# s3[0].set_label('3-sigma')
# plt.plot(date1, medi, label='Median',ls='solid')
# plt.legend(scatterpoints=1)
# plt.show(block=False)
# cut = raw_input("Enter the sigma-cut factor (3-5 recommended): ")
# sigma_cut_factor = float(cut)
# user_inputs[2]=sigma_cut_factor
# passes=raw_input("Enter the number of passes for the sigma-cut: ")
# nPasses=int(passes)
# user_inputs[3]=nPasses
# plt.close()
# # Cut out the "bad" data
# for j in range(nPasses):
# med= np.ma.median(light_corrected)
# sigma = np.sqrt(np.sum((light_corrected-med)**2)/(2*len(light_corrected)))
# dif= np.abs(light_corrected-med)
# index=np.where(dif < sigma_cut_factor*sigma)[0]
# light_curve=light_curve[index]
# date1=date1[index]
# light_corrected=light_corrected[index]
# light_err=light_err[index]
# spectra=spectra[index,:]
# spec_err=spec_err[index,:]
# return [light_curve, spectra, light_corrected, date1, light_err, spec_err]
def preprocess_whitelight(visit
, direction
, x=0, y=0
, check=True
, ignore_first_exposures=False
, inp_file=False
, ld_source='claret2012.csv'
, save_processed_data=False
, transit=False
, data_plots=True
, mcmc=False
, include_error_inflation=True
, openinc=False
, openar=True
, fixtime=False
, ld_type="nonlinear"
, linear_slope=True
, quad_slope=False
, exp_slope=False
, log_slope=False
, one_slope=True
, norandomt=True
, fit_plots=False
, plot_best=True
, save_mcmc=False
, save_model_info=False):
"""
Function to allow user to extract relevant orbital data from reduced time
series of a visit. Also allow user to exclude first orbit or first exposure
of each orbit. The selected data is then fed into "marg_mcmc" for model light
curve fitting.
INPUTS
See config.py file
[DATA]
x, y: Allow the user to reduce aperture by (x,y) pixels
checks: set to "on" to manually reduce data
inp_file: Allow user to load in preprocess information instead of manually
finding. Cannot have checks and inp_file both off or both on.
If checks is set to on, "user_inputs" will return the inputs
that the user used: [first orbit, last orbit, sigma cut factor,
number of passes, center eclipse time]. If checks is set to off, then
the user_inputs array will be used as inputs (easier to automate)
[MODEL]
mcmc: Use MCMC sampler, extracting corner plot and other diagnostics
openinc: Fit for inclination (default is fixed)
openar: Fit for a/Rstar (default is fixed)
fixtime: Fix center of event time (default is open)
norandomt: Do now allow center of event time starting point to be vary randomly
fit_plots: Show model light curve fit in real time
[SAVE]
save_processed_data: Save the data with the systematics removed for the best fit model
save_model_info: Save best fit parameters for every systematic model
save_mcmc: Save MCMC products, such as corner plot, autocorrelation, etc.
The save files will all be saved with key or name "planet/visitXX/direction"
"""
if direction != 'both':
folder = '../data_reduction/reduced/%s/%s/final/*.fits' % (visit, direction)
data=np.sort(np.asarray(glob.glob(folder)))
nexposure = len(data)
print('There are %d exposures in this visit' % nexposure)
alldate=np.zeros(len(data))
time=np.zeros_like(alldate)
test=fits.open(data[0])
xlen, ylen = test[0].data.shape
test.close()
xlen-=2*x
ylen-=2*y
allspec=np.ma.zeros((len(data),xlen, ylen))
allerr=np.zeros((len(data),xlen,ylen))
xmin=x
xmax=xlen-x
ymin=y
ymax=ylen-y
for i, img in enumerate(data):
expfile=fits.open(img)
hdr=expfile[0].header
exp=expfile[0].data
mask=expfile[1].data
errs=expfile[2].data
expfile.close()
alldate[i]=(hdr['EXPSTART']+hdr['EXPEND'])/2.
time[i]=hdr['EXPTIME']
expo=exp[xmin:xmax, ymin:ymax]
mask=mask[xmin:xmax, ymin:ymax]
errs=errs[xmin:xmax, ymin:ymax]
allspec[i,:,:]=np.ma.array(expo, mask=mask)
allerr[i,:,:]=np.ma.array(errs, mask=mask)
allspec1d=np.ma.sum(allspec,axis=1)
allerr1d=np.sqrt(np.ma.sum(allerr*allerr, axis=1))
median_flux = np.ma.median(np.ma.sum(allspec1d, axis=1))
# Regardless of direction, if all exposures share the same one we make
# dir_array all zeros for easy parameter use in model fitting.
dir_array = np.zeros_like(alldate)
else:
direction = 'forward'
folder = '../data_reduction/reduced/%s/%s/final/*.fits' % (visit, direction)
data=np.sort(np.asarray(glob.glob(folder)))
nexposure = len(data)
print('There are %d exposures in this visit' % nexposure)
alldate=np.zeros(len(data))
time=np.zeros_like(alldate)
test=fits.open(data[0])
xlen, ylen = test[0].data.shape
test.close()
xlen-=2*x
ylen-=2*y
allspec=np.ma.zeros((len(data),xlen, ylen))
allerr=np.zeros((len(data),xlen,ylen))
xmin=x
xmax=xlen-x
ymin=y
ymax=ylen-y
for i, img in enumerate(data):
expfile=fits.open(img)
hdr=expfile[0].header
exp=expfile[0].data
mask=expfile[1].data
errs=expfile[2].data
expfile.close()
alldate[i]=(hdr['EXPSTART']+hdr['EXPEND'])/2.
time[i]=hdr['EXPTIME']
expo=exp[xmin:xmax, ymin:ymax]
mask=mask[xmin:xmax, ymin:ymax]
errs=errs[xmin:xmax, ymin:ymax]
allspec[i,:,:]=np.ma.array(expo, mask=mask)
allerr[i,:,:]=np.ma.array(errs, mask=mask)
allspec1d=np.ma.sum(allspec,axis=1)
allerr1d=np.sqrt(np.ma.sum(allerr*allerr, axis=1))
median_flux = np.ma.median(np.ma.sum(allspec1d, axis=1))
# Now do for other direction
direction = 'reverse'
folder = '../data_reduction/reduced/%s/%s/final/*.fits' % (visit, direction)
rdata=np.sort(np.asarray(glob.glob(folder)))
nexposure = len(rdata)
print('There are %d exposures in this visit' % nexposure)
rdate=np.zeros(len(rdata))
rtime= | np.zeros_like(rdate) | numpy.zeros_like |
""""
Title : Input fpwb
Written by: <NAME>
Date : 18/11/19
Language : Python
Aeronautical Institute of Technology
Inputs:
MTOW
Outputs:
Cap_Sal
FO_Sal
"""
########################################################################################
"""Importing Modules"""
########################################################################################
import numpy as np
import sys, os
from atmosphere import atmosphere
########################################################################################
"""Constants declaration"""
########################################################################################
def frange(x, y, jump=1.0):
i = 0.0
x = float(x) # Prevent yielding integers.
y = float(y) # Comparison converts y to float every time otherwise.
x0 = x
epsilon = jump / 2.0
yield x # yield always first value
while x + epsilon < y:
i += 1.0
x = x0 + i * jump
yield x
def input_fpwb(M,AirportElevation,
lf,lco,lcab,xle,wS,enf,wingb,diedro,wMAC,
c0,cr,cq,ct,etabreak,FusDiam,xuroot,xlroot,ylroot,yuroot,
xukink,xlkink,ylkink,yukink,xutip,xltip,yutip,yltip,ir,iq,it):
## Constantes
rad = np.pi/180
ft2m = 0.3048
m2ft = 1./ft2m
##
nuroot = len(xuroot)
nlroot = len(xlroot)
nukink = len(xukink)
nlkink = len(xlkink)
nutip = len(xutip)
nltip = len(xltip)
##
ise = 1. # ise - Control parameter for the nonisentropic correction. # ISE=1. - the nonisentropic correction is used # ISE=0. - no correction
order = 2. # order - order of the artificial dissipation in the supersonic zones
# rchord=chord at wing-fuselage intersection#
filename = sys.argv[0]
file_path = os.path.abspath(filename+"/..")
# file_path = 'c:\\Users\\aarc8\\Documents\\Github\\GIT_IAANDOCAC\\IAANDOCAC-aircraft-framework\\aircraft famework\\framework Bento\\'
extensions = ('.ps', '.out','.pl4','.blp','.sav','.inp')
filelist = [ f for f in os.listdir(file_path) if f.endswith(extensions) ]
for f in filelist:
os.remove(os.path.join(file_path, f))
largfus = 1.03*FusDiam/2
wingb2 = wingb/2
dist_quebra = (wingb2)*etabreak
raio = FusDiam/2
YE0 = raio*0.005 # distancia verticla da asa na linha de centro da fuselagem
#
if dist_quebra < largfus:
dist_quebra = 1.15*largfus
# Geracao de secao circular da fuselagem
Nupp = 20
#Secao circular
yc=[]
zc=[]
dteta = np.pi/(2*Nupp-1)
for j in range(0,2*Nupp):
teta= (j)*dteta
yc1=raio*np.cos(teta)
yc.append(yc1)
zc1=raio*np.sin(teta)
zc.append(zc1)
yc = np.flip(yc)
#
minespintra=min(ylroot)
distv=(FusDiam/2)*np.sin(rad*diedro)
d1=-1.1*FusDiam/2-minespintra*c0+distv
if (d1+minespintra*c0) < -0.95*FusDiam/2:
ylew = -0.94*FusDiam/2 + distv - minespintra*c0
else:
ylew=-1.1*FusDiam/2-minespintra*c0
# Secao comprida entre o inicio e o fim da asa
#
zw = []
yw = []
zw.append(0.0)
yw.append(-1.1*raio)
zw.append(raio/4)
yw.append(-1.1*raio)
zw.append(raio/2)
yw.append(-1.1*raio)
zw.append(0.95*raio)
yw.append(-raio)
zw.append(+raio)
yw.append(-0.95*raio)
zw.append(+raio)
yw.append(-0.90*raio)
zw.append(+raio)
yw.append(-0.50*raio)
zw.append(+raio)
yw.append(0.)
dteta=np.pi/2/Nupp
for j in range(Nupp):
teta = (j+1)*dteta
yw1 = raio*np.sin(teta)
yw.append(yw1)
zw1 = raio*np.cos(teta)
zw.append(zw1)
# Secao 1 da fuselagem com carenagem antes da asa
teta1=20*rad
y1 =-raio*np.sin(teta1)
z1 = raio*np.cos(teta1)
zwf1 = []
ywf1 = []
zwf1.append(0.0)
ywf1.append(-raio)
zwf1.append(z1/4)
ywf1.append(-raio)
zwf1.append(z1/2)
ywf1.append(-raio)
zwf1.append(0.90*z1)
ywf1.append(-0.95*raio)
zwf1.append(+z1)
ywf1.append(-0.85*raio)
ywf1.append(0.50*(+y1-0.95*raio))
zwf1.append(z1)
zwf1.append(+z1)
ywf1.append(1.1*y1)
zwf1.append(+z1)
ywf1.append(y1)
jcount = 8
dteta = (np.pi/2+teta1)/Nupp
for j in frange((-teta1+dteta),np.pi/2,dteta):
jcount = jcount + 1
ywf11= raio*np.sin(j)
ywf1.append(ywf11)
zwf11 = raio*np.cos(j)
zwf1.append(zwf11)
#plot(zwf1,ywf1,'-bo')
#hold on
#
# Secao 2 da fuselagem com carenagem antes da asa
#
teta1=30*rad
teta2=60*rad
npontos=10
dteta = teta1/(npontos-1)
ywf = []
zwf = []
for j in frange(1,npontos,1):
ang=(j-1)*dteta
ywf_aux= -raio*np.cos(ang)
ywf.append(ywf_aux)
zwf_aux= +raio*np.sin(ang)
zwf.append(zwf_aux)
y1 = -raio*np.cos(teta1)
y2 = -raio*np.cos(teta2)
#z1 = raio*sin(teta1)
z2 = raio*np.sin(teta2)
ymed = 0.50*(y1+y2)
#zmed = 0.50*(z1+z2)
ywf.append(y1-0.05*ymed)
zwf.append(0.90*z2)
ywf.append(y1-0.150*ymed)
zwf.append(0.97*z2)
npi=2*npontos -(npontos+3)+1
dteta = teta1/(npi-1)
for j in frange((npontos+3),2*npontos,1):
ang=teta2+(j-(npontos+3))*dteta
#angg=ang/rad
ywf_aux=-raio*np.cos(ang)
ywf.append(ywf_aux)
zwf_aux=+raio*np.sin(ang)
zwf.append(zwf_aux)
teta3 =np.pi/2
dteta=teta3/npontos
for j in frange(1,npontos,1):
ang=j*dteta
ywf_aux=raio*np.sin(ang)
ywf.append(ywf_aux)
zwf_aux=raio*np.cos(ang)
zwf.append(zwf_aux)
#plot(zwf,ywf,'--r+')
#
# Secao 2 da fuselagem com carenagem antes da asa
#
teta1=40*rad
teta2=55*rad
npontos=12
dteta = teta1/(npontos-1)
ywf2 = []
zwf2 = []
for j in frange(1,npontos,1):
ang=(j-1)*dteta
ywf2_aux= -raio*np.cos(ang)
ywf2.append(ywf2_aux)
zwf2_aux= +raio*np.sin(ang)
zwf2.append(zwf2_aux)
y1 = -raio*np.cos(teta1)
y2 = -raio*np.cos(teta2)
#z1 = raio*sin(teta1)
z2 = raio*np.sin(teta2)
ymed = 0.50*(y1+y2)
#zmed = 0.50*(z1+z2)
ywf2.append(y1-0.05*ymed)
zwf2.append(0.90*z2)
ywf2.append(y1-0.150*ymed)
zwf2.append(0.97*z2)
npi=2*npontos -(npontos+3)+1
dteta = teta1/(npi-1)
for j in frange((npontos+3),2*npontos,1):
ang=teta2+(j-(npontos+3))*dteta
#angg=ang/rad
ywf2_aux=-raio*np.cos(ang)
ywf2.append(ywf2_aux)
zwf2_aux=+raio*np.sin(ang)
zwf2.append(zwf2_aux)
teta3 =np.pi/2
dteta=teta3/npontos
for j in frange(1,npontos,1):
ang=j*dteta
ywf2_aux=raio*np.sin(ang)
ywf2.append(ywf2_aux)
zwf2_aux=raio*np.cos(ang)
zwf2.append(zwf2_aux)
# ****** Preparacao da geracao dos dois arquivos com angulo de ataque
# diferentes cada um *********************************************
for jj in range(1,3):
#
if jj == 1:
# gera arquivo # 1 para calculo do clmax
CL = 0.5
Ataque = 3
FCONT = 0. # start from scratch
atm = atmosphere(AirportElevation*m2ft,0)
TAE = atm.TAE # temperatura [K]
T8 = TAE
ro = atm.ro # densidade [Kg/m�]
va = atm.va # velocidade do som [m/s]
# ***** air viscosity (begin)******
mi0 = 18.27E-06
Tzero = 291.15 # Reference temperature (15 graus celsius)
Ceh = 120 # C = Sutherland's constant for the gaseous material in question
mi = mi0*((TAE+Ceh)/(Tzero+Ceh))*((TAE/Tzero)**1.5)
vel = va*M
rey = ro*vel*wMAC/mi
fid = open('fpwbclm1.inp','w+')
elif jj == 2:
# gera arquivo # 2 para calculo do CLmax
CL=0.75
Ataque = 5
FCONT =0. # =1 ==>start from previous calculation
atm=atmosphere(AirportElevation*m2ft,0)
TAE=atm.TAE # temperatura [K]
T8 = TAE
ro=atm.ro # densidade [Kg/m�]
va=atm.va # velocidade do som [m/s]
# ***** air viscosity (begin)******
mi0=18.27E-06
Tzero=291.15 # Reference temperature
Ceh= 120 # C = Sutherland's constant for the gaseous material in question
mi=mi0*((TAE+Ceh)/(Tzero+Ceh))*((TAE/Tzero)**1.5)
vel=va*M
rey=ro*vel*wMAC/mi
fid = open('fpwbclm2.inp',"w")
# Stations for viscous calculation
nvisc_i=4
nvisc_e=5
stavi=largfus/wingb2 + 0.0125
stabreak=dist_quebra/wingb2
zvisc_internal=np.linspace(stavi,stabreak,nvisc_i)
zvisc_external=np.linspace(stabreak+0.1,1.,nvisc_e)
zvisc = np.concatenate([zvisc_internal,zvisc_external])
nvisc=nvisc_i+nvisc_e
#nvisc=double(nvisc)
fid.write(' AVAER FULL POTENTIAL ANALYSIS \n')
fid.write(' NX >< NY >< NZ >< NT >< FCONT > \n')
fid.write(' 48. 12. 10. 5. %2.0f \n' % FCONT)
fid.write(' FPICT1 >< FPICT2 >< FPICT3 >< FPICT4 >< FPICT5 >< >< >< tecplot> \n')
fid.write(' 0. 0. 0. 0. 0.0 0. \n')
fid.write(' XMIN >< XMAX >< YMIN >< YMAX >< ZMIN >< ZMAX > \n')
fid.write(' -.1 1.7 -.9 .9 .0 2.7 \n')
fid.write(' EX >< EY >< EZ > \n')
fid.write(' -5. 5. 10. \n')
fid.write(' NP >< ETAE >< T8 >< PR >< PRT >< RRR >< VGL >< VGT > \n')
fid.write(' 21. 4. %4.0f .753 .90 1. 1.26 1.26 \n' % T8)
fid.write(' NTR >< AL_CL >< CL >< DCL/DA > \n')
fid.write(' %6.1f 0. %4.2f 0.40 \n' % (nvisc, CL))
fid.write('< Z >< XTRU >< XTRL > \n')
for jvisc in range(nvisc):
fid.write(' %9.4f 0.05 0.05 \n' % zvisc[jvisc])
fid.write(' NDF >< NVB >< CFXMIN >< F_LK > \n')
fid.write(' 5. 1.0 -5. 0.0 \n')
fid.write(' FPRIN0 >< FPRIN1 >< FPRIN2 >< FPRINB > \n')
fid.write(' 1. -9. -9. -2. \n')
fid.write(' FPLOT1 >< FPLOT2 >< FPLOT3 >< FPLOT4 >< FPLOT5 >< FPLOT6 >< FPLOT7 >< FPLOT8 > \n')
fid.write(' 1. 1. 1. 1. 1. 1. 2. 2. \n')
fid.write(' CPMINW >< CPMINF > \n')
fid.write(' -2. -1.6 \n')
fid.write('< NZOUT > \n')
fid.write(' 6. \n')
fid.write('< ZCPOUT > \n')
fid.write(' 0.150 \n')
fid.write(' 0.250 \n')
fid.write(' 0.415 \n')
fid.write(' 0.500 \n')
fid.write(' 0.700 \n')
fid.write(' 0.950 \n')
fid.write(' NCPOUT > \n')
fid.write(' 20. \n')
fid.write(' CPOUT > \n')
fid.write(' -1.4 \n')
fid.write(' -1.3 \n')
fid.write(' -1.2 \n')
fid.write(' -1.1 \n')
fid.write(' -1.0 \n')
fid.write(' -.9 \n')
fid.write(' -.8 \n')
fid.write(' -.7 \n')
fid.write(' -.6 \n')
fid.write(' -.5 \n')
fid.write(' -.4 \n')
fid.write(' -.3 \n')
fid.write(' -.2 \n')
fid.write(' -.1 \n')
fid.write(' .0 \n')
fid.write(' .1 \n')
fid.write(' .2 \n')
fid.write(' .3 \n')
fid.write(' .4 \n')
fid.write(' .5 \n')
fid.write(' NIT >< MIT >< P1 >< P2 >< PL >< PH >< NLH >< FHALF > \n')
fid.write(' 30. 30. 1.3 1.00 .7 1.5 3. 1. \n')
fid.write(' NBL > \n')
fid.write(' 4. \n')
fid.write(' NITBL >< PB >< PBIV > \n')
fid.write(' 6. .8 \n')
fid.write(' 12. .8 \n')
fid.write(' 18. .8 \n')
fid.write(' 24. .8 \n')
fid.write(' NIT >< MIT >< P1 >< P2 >< PL >< PH >< NLH >< FHALF >\n')
fid.write(' 40. 30. 1.2 1.00 .7 1.5 4. 1. \n')
fid.write(' NBL > \n')
fid.write(' 6. \n')
fid.write(' NITBL >< PB >< PBIV > \n')
fid.write(' 6. .7 \n')
fid.write(' 12. .7 \n')
fid.write(' 18. .7 \n')
fid.write(' 24. .7 \n')
fid.write(' 30. .7 \n')
fid.write(' 36. .7 \n')
fid.write(' NIT >< MIT >< P1 >< P2 >< PL >< PH >< NLH >< FHALF >\n')
fid.write(' 36. 30. 1.0 1.001 .7 1.5 5. 0. \n')
fid.write(' NBL > \n')
fid.write(' 5. \n')
fid.write(' NITBL >< PB >< PBIV > \n')
fid.write(' 6. .55 \n')
fid.write(' 12. .55 \n')
fid.write(' 18. .55 \n')
fid.write(' 24. .55 \n')
fid.write(' 30. .55 \n')
fid.write('< MACH >< ALFA >< RE >< CAX >< SWING >< SE >< ORDER > \n')
fid.write('%8.3f%10.3f%10.0f.%10.3f%10.4f%10.4f%10.4f\n'% (M ,Ataque, rey, wMAC, wS/2, ise, order))
fid.write('< NSEC >< PZROOT >< PZTIP >< PXLE >< PXTE >< PYTE >< PZA >< PZB >\n')
fid.write(' 4.00000 0.15000 0.25000 0.65000 0.65000 0.80000 0.00000 0.00000 \n')
# ROOT SIMMETRY %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
fid.write('< Z >< XLE >< YLE >< CHORD >< THICK >< ALPHA >< FSEC > \n')
fid.write('%9.4f %10.5f%10.5f%10.5f%10.5f%10.5f%10.5f\n' % (0,0,YE0+largfus*np.tan(rad*diedro),c0,1,ir,1))
fid.write('< YSYM >< NU >< NL > \n')
fid.write('%10.5f%10.5f%10.5f\n' % (0,nuroot,nlroot))
fid.write(' < XSING >< YSING >< TRAIL >< SLOPT >\n')
fid.write('%10.5f%10.5f%10.5f%10.5f\n' % (0.00921,0,7.16234,-0.05857))
fid.write(' < XU >< YU >\n')
for j in range(len(xuroot)):
fid.write('%10.5f%10.5f\n' % (xuroot[j], yuroot[j]))
fid.write(' < XL >< YL >\n')
for j in range(len(xlroot)):
fid.write('%10.5f%10.5f\n' % (xlroot[j], ylroot[j]))
# ROOT %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
fid.write('< Z >< XLE >< YLE >< CHORD >< THICK >< ALPHA >< FSEC > \n')
fid.write('%9.4f %10.5f%10.5f%10.5f%10.5f%10.5f%10.5f\n' % (largfus,largfus* | np.tan(rad*enf) | numpy.tan |
import torch
import numpy as np
import torch_utils
from Models import base_model
import torch_utils as my_utils
import time
import interactions
from handlers.output_handler import FileHandler
from handlers.tensorboard_writer import TensorboardWrapper
from setting_keywords import KeyWordSettings
from Fitting.FittingFC.declare_fitter import DeclareFitter
from typing import List
class MultiLevelAttentionCompositeFitter(DeclareFitter):
"""
I implement this class for testing if the padding all zeros sequences are the root cause of performance reduction.
"""
def __init__(self, net: base_model.BaseModel,
loss = "bpr",
n_iter = 100,
testing_epochs = 5,
batch_size = 16,
reg_l2 = 1e-3,
learning_rate = 1e-4,
early_stopping = 0, # means no early stopping
decay_step = None,
decay_weight = None,
optimizer_func = None,
use_cuda = False,
num_negative_samples = 4,
logfolder = None,
curr_date = None,
seed = None,
**kargs):
super(DeclareFitter, self).__init__(net, loss, n_iter, testing_epochs, batch_size, reg_l2, learning_rate,
early_stopping, decay_step, decay_weight, optimizer_func,
use_cuda, num_negative_samples, logfolder, curr_date, seed, **kargs)
self.fixed_num_evidences = kargs[KeyWordSettings.FIXED_NUM_EVIDENCES]
self.output_handler = kargs[KeyWordSettings.OutputHandlerFactChecking]
def fit(self, train_iteractions: interactions.ClassificationInteractions,
verbose = True, # for printing out evaluation during training
topN = 10,
val_interactions: interactions.ClassificationInteractions = None,
test_interactions: interactions.ClassificationInteractions = None):
"""
Fit the model.
Parameters
----------
train_iteractions: :class:`interactions.ClassificationInteractions` The input sequence dataset.
val_interactions: :class:`interactions.ClassificationInteractions`
test_interactions: :class:`interactions.ClassificationInteractions`
"""
self._initialize(train_iteractions)
best_val_auc, best_val_f1_macro, best_epoch, test_auc = 0, 0, 0, 0
test_results_dict = None
iteration_counter = 0
count_patience_epochs = 0
for epoch_num in range(self._n_iter):
# ------ Move to here ----------------------------------- #
self._net.train(True)
query_ids, left_contents, left_lengths, query_sources, \
evd_docs_ids, evd_docs_contents, evd_docs_lens, evd_sources, evd_cnt_each_query, \
pair_labels = self._sampler.get_train_instances_hanfc(train_iteractions, self.fixed_num_evidences)
queries, query_content, query_lengths, query_sources, \
evd_docs, evd_docs_contents, evd_docs_lens, evd_sources, evd_cnt_each_query, \
pair_labels = my_utils.shuffle(query_ids, left_contents, left_lengths, query_sources,
evd_docs_ids, evd_docs_contents, evd_docs_lens, evd_sources,
evd_cnt_each_query, pair_labels)
epoch_loss, total_pairs = 0.0, 0
t1 = time.time()
for (minibatch_num,
(batch_query, batch_query_content, batch_query_len, batch_query_sources, # i.e. claim source
batch_evd_docs, batch_evd_contents, batch_evd_lens, batch_evd_sources,
batch_evd_cnt_each_query, batch_labels)) \
in enumerate(my_utils.minibatch(queries, query_content, query_lengths, query_sources,
evd_docs, evd_docs_contents, evd_docs_lens, evd_sources,
evd_cnt_each_query, pair_labels, batch_size = self._batch_size)):
batch_query = my_utils.gpu(torch.from_numpy(batch_query), self._use_cuda)
batch_query_content = my_utils.gpu(torch.from_numpy(batch_query_content), self._use_cuda)
# batch_query_len = my_utils.gpu(torch.from_numpy(batch_query_len), self._use_cuda)
batch_query_sources = my_utils.gpu(torch.from_numpy(batch_query_sources), self._use_cuda)
batch_evd_docs = my_utils.gpu(torch.from_numpy(batch_evd_docs), self._use_cuda)
batch_evd_contents = my_utils.gpu(torch.from_numpy(batch_evd_contents), self._use_cuda)
# batch_evd_lens = my_utils.gpu(torch.from_numpy(batch_evd_lens), self._use_cuda)
batch_evd_sources = my_utils.gpu(torch.from_numpy(batch_evd_sources), self._use_cuda)
batch_evd_cnt_each_query = my_utils.gpu(torch.from_numpy(batch_evd_cnt_each_query), self._use_cuda)
batch_labels = my_utils.gpu(torch.from_numpy(batch_labels), self._use_cuda)
# total_pairs += self._batch_size * self.
additional_data = {KeyWordSettings.EvidenceCountPerQuery: batch_evd_cnt_each_query}
self._optimizer.zero_grad()
if self._loss in ["bpr", "hinge", "pce", "bce", "cross_entropy",
"vanilla_cross_entropy", "regression_loss", "masked_cross_entropy"]:
loss = self._get_multiple_evidences_predictions_normal(
batch_query, batch_query_content, batch_query_len, batch_query_sources,
batch_evd_docs, batch_evd_contents, batch_evd_lens, batch_evd_sources,
batch_labels, self.fixed_num_evidences, **additional_data)
# print("Loss: ", loss)
epoch_loss += loss.item()
iteration_counter += 1
# if iteration_counter % 2 == 0: break
TensorboardWrapper.mywriter().add_scalar("loss/minibatch_loss", loss.item(), iteration_counter)
loss.backward()
self._optimizer.step()
# for name, param in self._net.named_parameters():
# self.tensorboard_writer.add_histogram(name + "/grad", param.grad, iteration_counter)
# self.tensorboard_writer.add_histogram(name + "/value", param, iteration_counter)
# epoch_loss /= float(total_pairs)
TensorboardWrapper.mywriter().add_scalar("loss/epoch_loss_avg", epoch_loss, epoch_num)
# print("Number of Minibatches: ", minibatch_num, "Avg. loss of epoch: ", epoch_loss)
t2 = time.time()
epoch_train_time = t2 - t1
if verbose: # validation after each epoch
f1_macro_val, auc_val = self._output_results_every_epoch(topN, val_interactions, test_interactions,
epoch_num, epoch_train_time, epoch_loss)
if (f1_macro_val > best_val_f1_macro) or \
(f1_macro_val == best_val_f1_macro and auc_val > best_val_auc): # prioritize f1_macro
# if (hits + ndcg) > (best_hit + best_ndcg):
count_patience_epochs = 0
with open(self.saved_model, "wb") as f:
torch.save(self._net.state_dict(), f)
# test_results_dict = result_test
best_val_auc, best_val_f1_macro, best_epoch = auc_val, f1_macro_val, epoch_num
# test_hit, test_ndcg = hits_test, ndcg_test
else: count_patience_epochs += 1
if self._early_stopping_patience and count_patience_epochs > self._early_stopping_patience:
self.output_handler.myprint("Early Stopped due to no better performance in %s epochs" % count_patience_epochs)
break
if np.isnan(epoch_loss) or epoch_loss == 0.0:
raise ValueError('Degenerate epoch loss: {}'.format(epoch_loss))
self._flush_training_results(best_val_auc, best_epoch)
def _get_multiple_evidences_predictions_normal(self, query_ids: torch.Tensor,
query_contents: torch.Tensor,
query_lens: np.ndarray,
query_sources: torch.Tensor,
evd_doc_ids: torch.Tensor,
evd_doc_contents: torch.Tensor,
evd_docs_lens: np.ndarray,
evd_sources: torch.Tensor,
labels: np.ndarray,
n: int, **kargs) -> torch.Tensor:
"""
compute cross entropy loss
Parameters
----------
query_ids: (B, )
query_contents: (B, L)
query_lens: (B, )
evd_doc_ids: (B, n)
evd_doc_contents: (B, n, R)
evd_docs_lens: (B, n)
evd_sources: (B, n)
labels: (B, ) labels of pair
n: `int` is the number of evidences for each claim/query
kargs: `dict`
Returns
-------
loss value based on a loss function
"""
evd_count_per_query = kargs[KeyWordSettings.EvidenceCountPerQuery] # (B, )
assert evd_doc_ids.size() == evd_docs_lens.shape
assert query_ids.size(0) == evd_doc_ids.size(0)
assert query_lens.shape == labels.size()
assert query_contents.size(0) == evd_doc_contents.size(0) # = batch_size
_, L = query_contents.size()
batch_size = query_ids.size(0)
# prunning at this step to remove padding\
e_lens, e_conts, q_conts, q_lens = [], [], [], []
expaned_labels = []
for evd_cnt, q_cont, q_len, evd_lens, evd_doc_cont, label in \
zip(evd_count_per_query, query_contents, query_lens, evd_docs_lens, evd_doc_contents, labels):
evd_cnt = int(torch_utils.cpu(evd_cnt).detach().numpy())
e_lens.extend(list(evd_lens[:evd_cnt]))
e_conts.append(evd_doc_cont[:evd_cnt, :]) # stacking later
q_lens.extend([q_len] * evd_cnt)
q_conts.append(q_cont.unsqueeze(0).expand(evd_cnt, L))
expaned_labels.extend([int(torch_utils.cpu(label).detach().numpy())] * evd_cnt)
# concat
e_conts = torch.cat(e_conts, dim = 0) # (n1 + n2 + ..., R)
e_lens = np.array(e_lens) # (n1 + n2 + ..., )
q_conts = torch.cat(q_conts, dim = 0) # (n1 + n2 + ..., R)
q_lens = np.array(q_lens)
assert q_conts.size(0) == q_lens.shape[0] == e_conts.size(0) == e_lens.shape[0]
d_new_indices, d_old_indices = torch_utils.get_sorted_index_and_reverse_index(e_lens)
e_lens = my_utils.gpu(torch.from_numpy(e_lens), self._use_cuda)
q_new_indices, q_restoring_indices = torch_utils.get_sorted_index_and_reverse_index(query_lens)
query_lens = my_utils.gpu(torch.from_numpy(query_lens), self._use_cuda)
# query_lens = my_utils.gpu(torch.from_numpy(query_lens), self._use_cuda)
additional_paramters = {
KeyWordSettings.Query_lens: query_lens,
KeyWordSettings.Doc_lens: evd_docs_lens,
KeyWordSettings.DocLensIndices: (d_new_indices, d_old_indices, e_lens),
KeyWordSettings.QueryLensIndices: (q_new_indices, q_restoring_indices, query_lens),
KeyWordSettings.QuerySources: query_sources,
KeyWordSettings.DocSources: evd_sources,
KeyWordSettings.TempLabel: labels,
KeyWordSettings.DocContentNoPaddingEvidence: e_conts,
KeyWordSettings.QueryContentNoPaddingEvidence: q_conts,
KeyWordSettings.EvidenceCountPerQuery: evd_count_per_query,
KeyWordSettings.FIXED_NUM_EVIDENCES: n
}
predictions = self._net(query_contents, evd_doc_contents, **additional_paramters) # (B, )
# labels.unsqueeze(-1).expand(batch_size, n).reshape(batch_size * n)
# labels = torch_utils.gpu(torch.from_numpy(np.array(expaned_labels)), self._use_cuda)
# print("Labels: ", labels)
# mask = (evd_doc_ids >= 0).view(batch_size * n).float()
return self._loss_func(predictions, labels.float())
def evaluate(self, testRatings: interactions.ClassificationInteractions, K: int, output_ranking = False, **kargs):
"""
Compute evaluation metrics. No swearing in code please!!!
Parameters
----------
testRatings
K
output_ranking: whether we should output predictions
kargs
Returns
-------
"""
all_labels = []
all_final_probs = []
list_error_analysis = []
for query, evidences_info in testRatings.dict_claims_and_evidences_test.items():
evd_ids, labels, evd_contents, evd_lengths = evidences_info
assert len(set(labels)) == 1, "Must have only one label due to same claim"
all_labels.append(labels[0])
claim_content = testRatings.dict_claim_contents[query]
claim_source = | np.array([testRatings.dict_claim_source[query]]) | numpy.array |
import random
import numpy as np
import ot
import tqdm
def transform_mOT(src, target, src_label, origin, k, m, iter=100):
np.random.seed(1)
random.seed(1)
ot_transf = np.zeros_like(src)
n = src.shape[0]
for _ in tqdm.tqdm(range(iter)):
s = np.copy(src).reshape(-1, 3).astype("long")
t = | np.array(target) | numpy.array |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
from __future__ import (absolute_import, division, print_function,
unicode_literals)
from six import string_types
# Standard library
import sys
import datetime
import warnings
# Third-party
from astropy.coordinates import (EarthLocation, SkyCoord, AltAz, get_sun,
get_moon, Angle, Longitude)
import astropy.units as u
from astropy.time import Time
from astropy.utils.exceptions import AstropyDeprecationWarning
import numpy as np
import pytz
# Package
from .exceptions import TargetNeverUpWarning, TargetAlwaysUpWarning
from .moon import moon_illumination, moon_phase_angle
from .target import get_skycoord, SunFlag, MoonFlag
__all__ = ["Observer"]
MAGIC_TIME = Time(-999, format='jd')
# Handle deprecated MAGIC_TIME variable
def deprecation_wrap_module(mod, deprecated):
"""Return a wrapped object that warns about deprecated accesses"""
deprecated = set(deprecated)
class DeprecateWrapper(object):
def __getattr__(self, attr):
if attr in deprecated:
warnmsg = ("`MAGIC_TIME` will be deprecated in future versions "
"of astroplan. Use masked Time objects instead.")
warnings.warn(warnmsg, AstropyDeprecationWarning)
return getattr(mod, attr)
return DeprecateWrapper()
sys.modules[__name__] = deprecation_wrap_module(sys.modules[__name__],
deprecated=['MAGIC_TIME'])
def _generate_24hr_grid(t0, start, end, n_grid_points, for_deriv=False):
"""
Generate a nearly linearly spaced grid of time durations.
The midpoints of these grid points will span times from ``t0``+``start``
to ``t0``+``end``, including the end points, which is useful when taking
numerical derivatives.
Parameters
----------
t0 : `~astropy.time.Time`
Time queried for, grid will be built from or up to this time.
start : float
Number of days before/after ``t0`` to start the grid.
end : float
Number of days before/after ``t0`` to end the grid.
n_grid_points : int (optional)
Number of grid points to generate
for_deriv : bool
Generate time series for taking numerical derivative (modify
bounds)?
Returns
-------
`~astropy.time.Time`
"""
if for_deriv:
time_grid = np.concatenate([[start - 1 / (n_grid_points - 1)],
np.linspace(start, end,
n_grid_points)[1:-1],
[end + 1 / (n_grid_points - 1)]]) * u.day
else:
time_grid = np.linspace(start, end, n_grid_points) * u.day
# broadcast so grid is first index, and remaining shape of t0
# falls in later indices. e.g. if t0 is shape (10), time_grid
# will be shape (N, 10). If t0 is shape (5, 2), time_grid is (N, 5, 2)
while time_grid.ndim <= t0.ndim:
time_grid = time_grid[:, np.newaxis]
# we want to avoid 1D grids since we always want to broadcast against targets
if time_grid.ndim == 1:
time_grid = time_grid[:, np.newaxis]
return t0 + time_grid
class Observer(object):
"""
A container class for information about an observer's location and
environment.
Examples
--------
We can create an observer at Subaru Observatory in Hawaii two ways. First,
locations for some observatories are stored in astroplan, and these can be
accessed by name, like so:
>>> from astroplan import Observer
>>> subaru = Observer.at_site("Subaru", timezone="US/Hawaii")
To find out which observatories can be accessed by name, check out
`~astropy.coordinates.EarthLocation.get_site_names`.
Next, you can initialize an observer by specifying the location with
`~astropy.coordinates.EarthLocation`:
>>> from astropy.coordinates import EarthLocation
>>> import astropy.units as u
>>> location = EarthLocation.from_geodetic(-155.4761*u.deg, 19.825*u.deg,
... 4139*u.m)
>>> subaru = Observer(location=location, name="Subaru", timezone="US/Hawaii")
You can also create an observer without an
`~astropy.coordinates.EarthLocation`:
>>> from astroplan import Observer
>>> import astropy.units as u
>>> subaru = Observer(longitude=-155.4761*u.deg, latitude=19.825*u.deg,
... elevation=0*u.m, name="Subaru", timezone="US/Hawaii")
"""
@u.quantity_input(elevation=u.m)
def __init__(self, location=None, timezone='UTC', name=None, latitude=None,
longitude=None, elevation=0*u.m, pressure=None,
relative_humidity=None, temperature=None, description=None):
"""
Parameters
----------
location : `~astropy.coordinates.EarthLocation`
The location (latitude, longitude, elevation) of the observatory.
timezone : str or `datetime.tzinfo` (optional)
The local timezone to assume. If a string, it will be passed
through ``pytz.timezone()`` to produce the timezone object.
name : str
A short name for the telescope, observatory or location.
latitude : float, str, `~astropy.units.Quantity` (optional)
The latitude of the observing location. Should be valid input for
initializing a `~astropy.coordinates.Latitude` object.
longitude : float, str, `~astropy.units.Quantity` (optional)
The longitude of the observing location. Should be valid input for
initializing a `~astropy.coordinates.Longitude` object.
elevation : `~astropy.units.Quantity` (optional), default = 0 meters
The elevation of the observing location, with respect to sea
level. Defaults to sea level.
pressure : `~astropy.units.Quantity` (optional)
The ambient pressure. Defaults to zero (i.e. no atmosphere).
relative_humidity : float (optional)
The ambient relative humidity.
temperature : `~astropy.units.Quantity` (optional)
The ambient temperature.
description : str (optional)
A short description of the telescope, observatory or observing
location.
"""
self.name = name
self.pressure = pressure
self.temperature = temperature
self.relative_humidity = relative_humidity
# If lat/long given instead of EarthLocation, convert them
# to EarthLocation
if location is None and (latitude is not None and
longitude is not None):
self.location = EarthLocation.from_geodetic(longitude, latitude,
elevation)
elif isinstance(location, EarthLocation):
self.location = location
else:
raise TypeError('Observatory location must be specified with '
'either (1) an instance of '
'astropy.coordinates.EarthLocation or (2) '
'latitude and longitude in degrees as '
'accepted by astropy.coordinates.Latitude and '
'astropy.coordinates.Latitude.')
# Accept various timezone inputs, default to UTC
if isinstance(timezone, datetime.tzinfo):
self.timezone = timezone
elif isinstance(timezone, string_types):
self.timezone = pytz.timezone(timezone)
else:
raise TypeError('timezone keyword should be a string, or an '
'instance of datetime.tzinfo')
def __repr__(self):
"""
String representation of the `~astroplan.Observer` object.
Examples
--------
>>> from astroplan import Observer
>>> keck = Observer.at_site("Keck", timezone="US/Hawaii")
>>> print(keck) # doctest: +FLOAT_CMP
<Observer: name='Keck',
location (lon, lat, el)=(-155.478333333 deg, 19.8283333333 deg, 4160.0 m),
timezone=<DstTzInfo 'US/Hawaii' LMT-1 day, 13:29:00 STD>>
"""
class_name = self.__class__.__name__
attr_names = ['name', 'location', 'timezone', 'pressure', 'temperature',
'relative_humidity']
attr_values = [getattr(self, attr) for attr in attr_names]
attributes_strings = []
for name, value in zip(attr_names, attr_values):
if value is not None:
# Format location for easy readability
if name == 'location':
formatted_loc = ["{} {}".format(i.value, i.unit)
for i in value.to_geodetic()]
attributes_strings.append(
"{} (lon, lat, el)=({})".format(
name, ", ".join(formatted_loc)))
else:
if name != 'name':
value = repr(value)
else:
value = "'{}'".format(value)
attributes_strings.append("{}={}".format(name, value))
return "<{}: {}>".format(class_name, ",\n ".join(attributes_strings))
@classmethod
def at_site(cls, site_name, **kwargs):
"""
Initialize an `~astroplan.observer.Observer` object with a site name.
Extra keyword arguments are passed to the `~astroplan.Observer`
constructor (see `~astroplan.Observer` for available keyword
arguments).
Parameters
----------
site_name : str
Observatory name, must be resolvable with
`~astropy.coordinates.EarthLocation.get_site_names`.
Returns
-------
`~astroplan.observer.Observer`
Observer object.
Examples
--------
Initialize an observer at Kitt Peak National Observatory:
>>> from astroplan import Observer
>>> import astropy.units as u
>>> kpno_generic = Observer.at_site('kpno')
>>> kpno_today = Observer.at_site('kpno', pressure=1*u.bar, temperature=0*u.deg_C)
"""
name = kwargs.pop('name', site_name)
if 'location' in kwargs:
raise ValueError("Location kwarg should not be used if "
"initializing an Observer with Observer.at_site()")
return cls(location=EarthLocation.of_site(site_name), name=name, **kwargs)
def astropy_time_to_datetime(self, astropy_time):
"""
Convert the `~astropy.time.Time` object ``astropy_time`` to a
localized `~datetime.datetime` object.
Timezones localized with `pytz`_.
.. _pytz: https://pypi.python.org/pypi/pytz/
Parameters
----------
astropy_time : `~astropy.time.Time`
Scalar or list-like.
Returns
-------
`~datetime.datetime`
Localized datetime, where the timezone of the datetime is
set by the ``timezone`` keyword argument of the
`~astroplan.Observer` constructor.
Examples
--------
Convert an astropy time to a localized `~datetime.datetime`:
>>> from astroplan import Observer
>>> from astropy.time import Time
>>> subaru = Observer.at_site("Subaru", timezone="US/Hawaii")
>>> astropy_time = Time('1999-12-31 06:00:00')
>>> print(subaru.astropy_time_to_datetime(astropy_time))
1999-12-30 20:00:00-10:00
"""
if not astropy_time.isscalar:
return [self.astropy_time_to_datetime(t) for t in astropy_time]
# Convert astropy.time.Time to a UTC localized datetime (aware)
utc_datetime = pytz.utc.localize(astropy_time.utc.datetime)
# Convert UTC to local timezone
return self.timezone.normalize(utc_datetime)
def datetime_to_astropy_time(self, date_time):
"""
Convert the `~datetime.datetime` object ``date_time`` to a
`~astropy.time.Time` object.
Timezones localized with `pytz`_. If the ``date_time`` is naive, the
implied timezone is the ``timezone`` structure of ``self``.
Parameters
----------
date_time : `~datetime.datetime` or list-like
Returns
-------
`~astropy.time.Time`
Astropy time object (no timezone information preserved).
Examples
--------
Convert a localized `~datetime.datetime` to a `~astropy.time.Time`
object. Non-localized datetimes are assumed to be UTC.
<Time object: scale='utc' format='datetime' value=1999-12-31 06:00:00>
>>> from astroplan import Observer
>>> import datetime
>>> import pytz
>>> subaru = Observer.at_site("Subaru", timezone="US/Hawaii")
>>> hi_date_time = datetime.datetime(2005, 6, 21, 20, 0, 0, 0)
>>> subaru.datetime_to_astropy_time(hi_date_time)
<Time object: scale='utc' format='datetime' value=2005-06-22 06:00:00>
>>> utc_date_time = datetime.datetime(2005, 6, 22, 6, 0, 0, 0,
... tzinfo=pytz.timezone("UTC"))
>>> subaru.datetime_to_astropy_time(utc_date_time)
<Time object: scale='utc' format='datetime' value=2005-06-22 06:00:00>
"""
if hasattr(date_time, '__iter__'):
return Time([self.datetime_to_astropy_time(t) for t in date_time])
# For timezone-naive datetimes, assign local timezone
if date_time.tzinfo is None:
date_time = self.timezone.localize(date_time)
return Time(date_time, location=self.location)
def _is_broadcastable(self, shp1, shp2):
"""Test if two shape tuples are broadcastable"""
if shp1 == shp2:
return True
for a, b in zip(shp1[::-1], shp2[::-1]):
if a == 1 or b == 1 or a == b:
pass
else:
return False
return True
def _preprocess_inputs(self, time, target=None, grid_times_targets=False):
"""
Preprocess time and target inputs
This routine takes the inputs for time and target and attempts to
return a single `~astropy.time.Time` and `~astropy.coordinates.SkyCoord`
for each argument, which may be non-scalar if necessary.
time : `~astropy.time.Time` or other (see below)
The time(s) to use in the calculation. It can be anything that
`~astropy.time.Time` will accept (including a `~astropy.time.Time`
object)
target : `~astroplan.FixedTarget`, `~astropy.coordinates.SkyCoord`, or list
The target(s) to use in the calculation.
grid_times_targets: bool
If True, the target object will have extra dimensions packed onto
the end, so that calculations with M targets and N times will
return an (M, N) shaped result. Otherwise, we rely on broadcasting
the shapes together using standard numpy rules. Useful for grid
searches for rise/set times etc.
"""
# make sure we have a non-scalar time
if not isinstance(time, Time):
time = Time(time)
if target is None:
return time, None
# convert any kind of target argument to non-scalar SkyCoord
target = get_skycoord(target)
if grid_times_targets:
if target.isscalar:
# ensure we have a (1, 1) shape coord
target = SkyCoord(np.tile(target, 1))[:, np.newaxis]
else:
while target.ndim <= time.ndim:
target = target[:, np.newaxis]
elif not self._is_broadcastable(target.shape, time.shape):
raise ValueError('Time and Target arguments cannot be broadcast '
'against each other with shapes {} and {}'
.format(time.shape, target.shape))
return time, target
def altaz(self, time, target=None, obswl=None, grid_times_targets=False):
"""
Get an `~astropy.coordinates.AltAz` frame or coordinate.
If ``target`` is None, generates an altitude/azimuth frame. Otherwise,
calculates the transformation to that frame for the requested ``target``.
Parameters
----------
time : `~astropy.time.Time` or other (see below)
The time at which the observation is taking place. Will be used as
the ``obstime`` attribute in the resulting frame or coordinate. This
will be passed in as the first argument to the `~astropy.time.Time`
initializer, so it can be anything that `~astropy.time.Time` will
accept (including a `~astropy.time.Time` object)
target : `~astroplan.FixedTarget`, `~astropy.coordinates.SkyCoord`, or list (optional)
Celestial object(s) of interest. If ``target`` is `None`, returns
the `~astropy.coordinates.AltAz` frame without coordinates.
obswl : `~astropy.units.Quantity` (optional)
Wavelength of the observation used in the calculation.
grid_times_targets: bool (optional)
If True, the target object will have extra dimensions packed
onto the end, so that calculations with M targets and N times
will return an (M, N) shaped result. Otherwise, we rely on
broadcasting the shapes together using standard numpy
rules. Useful for grid searches for rise/set times etc.
Returns
-------
`~astropy.coordinates.AltAz`
If ``target`` is `None`, returns `~astropy.coordinates.AltAz`
frame. If ``target`` is not `None`, returns the ``target``
transformed to the `~astropy.coordinates.AltAz` frame.
Examples
--------
Create an instance of the `~astropy.coordinates.AltAz` frame for an
observer at Apache Point Observatory at a particular time:
>>> from astroplan import Observer
>>> from astropy.time import Time
>>> from astropy.coordinates import SkyCoord
>>> apo = Observer.at_site("APO")
>>> time = Time('2001-02-03 04:05:06')
>>> target = SkyCoord(0*u.deg, 0*u.deg)
>>> altaz_frame = apo.altaz(time)
Now transform the target's coordinates to the alt/az frame:
>>> target_altaz = target.transform_to(altaz_frame) # doctest: +SKIP
Alternatively, construct an alt/az frame and transform the target to
that frame all in one step:
>>> target_altaz = apo.altaz(time, target) # doctest: +SKIP
"""
if target is not None:
time, target = self._preprocess_inputs(time, target, grid_times_targets)
altaz_frame = AltAz(location=self.location, obstime=time,
pressure=self.pressure, obswl=obswl,
temperature=self.temperature,
relative_humidity=self.relative_humidity)
if target is None:
# Return just the frame
return altaz_frame
else:
return target.transform_to(altaz_frame)
def parallactic_angle(self, time, target, grid_times_targets=False):
"""
Calculate the parallactic angle.
Parameters
----------
time : `~astropy.time.Time`
Observation time.
target : `~astroplan.FixedTarget` or `~astropy.coordinates.SkyCoord` or list
Target celestial object(s).
grid_times_targets: bool
If True, the target object will have extra dimensions packed onto
the end, so that calculations with M targets and N times will
return an (M, N) shaped result. Otherwise, we rely on broadcasting
the shapes together using standard numpy rules.
Returns
-------
`~astropy.coordinates.Angle`
Parallactic angle.
Notes
-----
The parallactic angle is the angle between the great circle that
intersects a celestial object and the zenith, and the object's hour
circle [1]_.
.. [1] https://en.wikipedia.org/wiki/Parallactic_angle
"""
time, coordinate = self._preprocess_inputs(time, target, grid_times_targets)
# Eqn (14.1) of Meeus' Astronomical Algorithms
LST = time.sidereal_time('mean', longitude=self.location.lon)
H = (LST - coordinate.ra).radian
q = np.arctan2(np.sin(H),
(np.tan(self.location.lat.radian) *
np.cos(coordinate.dec.radian) -
np.sin(coordinate.dec.radian)*np.cos(H)))*u.rad
return Angle(q)
# Sun-related methods.
@u.quantity_input(horizon=u.deg)
def _horiz_cross(self, t, alt, rise_set, horizon=0*u.degree):
"""
Find time ``t`` when values in array ``a`` go from
negative to positive or positive to negative (exclude endpoints)
``return_limits`` will return nearest times to zero-crossing.
Parameters
----------
t : `~astropy.time.Time`
Grid of N times, any shape. Search grid along first axis, e.g (N, ...)
alt : `~astropy.units.Quantity`
Grid of altitudes
Depending on broadcasting we either have ndim >=3 and
M targets along first axis, e.g (M, N, ...), or
ndim = 2 and targets/times in last axis
rise_set : {"rising", "setting"}
Calculate either rising or setting across the horizon
horizon : float
Number of degrees above/below actual horizon to use
for calculating rise/set times (i.e.,
-6 deg horizon = civil twilight, etc.)
Returns
-------
Returns the lower and upper limits on the time and altitudes
of the horizon crossing. The altitude limits have shape (M, ...) and the
time limits have shape (...). These arrays aresuitable for interpolation
to find the horizon crossing time.
"""
# handle different cases by enforcing standard shapes on
# the altitude grid
finesse_time_indexes = False
if alt.ndim == 1:
raise ValueError('Must supply more at least a 2D grid of altitudes')
elif alt.ndim == 2:
# TODO: this test for ndim=2 doesn't work. if times is e.g (2,5)
# then alt will have ndim=3, but shape (100, 2, 5) so grid
# is in first index...
ntargets = alt.shape[1]
ngrid = alt.shape[0]
unit = alt.unit
alt = np.broadcast_to(alt, (ntargets, ngrid, ntargets)).T
alt = alt*unit
extra_dimension_added = True
if t.shape[1] == 1:
finesse_time_indexes = True
else:
extra_dimension_added = False
output_shape = (alt.shape[0],) + alt.shape[2:]
if rise_set == 'rising':
# Find index where altitude goes from below to above horizon
condition = ((alt[:, :-1, ...] < horizon) *
(alt[:, 1:, ...] > horizon))
elif rise_set == 'setting':
# Find index where altitude goes from above to below horizon
condition = ((alt[:, :-1, ...] > horizon) *
(alt[:, 1:, ...] < horizon))
noncrossing_indices = np.sum(condition, axis=1, dtype=np.intp) < 1
alt_lims1 = u.Quantity(np.zeros(output_shape), unit=u.deg)
alt_lims2 = u.Quantity(np.zeros(output_shape), unit=u.deg)
jd_lims1 = np.zeros(output_shape)
jd_lims2 = np.zeros(output_shape)
if np.any(noncrossing_indices):
for target_index in set(np.where(noncrossing_indices)[0]):
warnmsg = ('Target with index {} does not cross horizon={} '
'within 24 hours'.format(target_index, horizon))
if (alt[target_index, ...] > horizon).all():
warnings.warn(warnmsg, TargetAlwaysUpWarning)
else:
warnings.warn(warnmsg, TargetNeverUpWarning)
alt_lims1[np.nonzero(noncrossing_indices)] = np.nan
alt_lims2[np.nonzero(noncrossing_indices)] = np.nan
jd_lims1[np.nonzero(noncrossing_indices)] = np.nan
jd_lims2[np.nonzero(noncrossing_indices)] = np.nan
before_indices = np.array(np.nonzero(condition))
# we want to add an vector like (0, 1, ...) to get after indices
after_indices = before_indices.copy()
after_indices[1, :] += 1
al1 = alt[tuple(before_indices)]
al2 = alt[tuple(after_indices)]
# slice the time in the same way, but delete the object index
before_time_index_tuple = np.delete(before_indices, 0, 0)
after_time_index_tuple = np.delete(after_indices, 0, 0)
if finesse_time_indexes:
before_time_index_tuple[1:] = 0
after_time_index_tuple[1:] = 0
tl1 = t[tuple(before_time_index_tuple)]
tl2 = t[tuple(after_time_index_tuple)]
alt_lims1[tuple(np.delete(before_indices, 1, 0))] = al1
alt_lims2[tuple(np.delete(before_indices, 1, 0))] = al2
jd_lims1[tuple(np.delete(before_indices, 1, 0))] = tl1.utc.jd
jd_lims2[tuple(np.delete(before_indices, 1, 0))] = tl2.utc.jd
if extra_dimension_added:
return (alt_lims1.diagonal(), alt_lims2.diagonal(),
jd_lims1.diagonal(), jd_lims2.diagonal())
else:
return alt_lims1, alt_lims2, jd_lims1, jd_lims2
@u.quantity_input(horizon=u.deg)
def _two_point_interp(self, jd_before, jd_after,
alt_before, alt_after, horizon=0*u.deg):
"""
Do linear interpolation between two ``altitudes`` at
two ``times`` to determine the time where the altitude
goes through zero.
Parameters
----------
jd_before : `float`
JD(UTC) before crossing event
jd_after : `float`
JD(UTC) after crossing event
alt_before : `~astropy.units.Quantity`
altitude before crossing event
alt_after : `~astropy.units.Quantity`
altitude after crossing event
horizon : `~astropy.units.Quantity`
Solve for the time when the altitude is equal to
reference_alt.
Returns
-------
t : `~astropy.time.Time`
Time when target crosses the horizon
"""
# Approximate the horizon-crossing time:
slope = (alt_after-alt_before) / ((jd_after - jd_before) * u.d)
crossing_jd = (jd_after * u.d - ((alt_after - horizon) / slope))
# TODO: edit after https://github.com/astropy/astropy/issues/9612 has
# been addressed.
# Determine whether or not there are NaNs in the crossing_jd array which
# represent computations where no horizon crossing was found:
nans = np.isnan(crossing_jd)
# If there are, set them equal to zero, rather than np.nan
crossing_jd[nans] = 0
times = Time(crossing_jd, format='jd')
# Create a Time object with masked out times where there were NaNs
times[nans] = np.ma.masked
return np.squeeze(times)
def _altitude_trig(self, LST, target, grid_times_targets=False):
"""
Calculate the altitude of ``target`` at local sidereal times ``LST``.
This method provides a factor of ~3 speed up over calling `altaz`, and
inherently does *not* take the atmosphere into account.
Parameters
----------
LST : `~astropy.time.Time`
Local sidereal times (array)
target : {`~astropy.coordinates.SkyCoord`, `FixedTarget`} or similar
Target celestial object's coordinates.
grid_times_targets: bool
If True, the target object will have extra dimensions packed onto
the end, so that calculations with M targets and N times will
return an (M, N) shaped result. Otherwise, we rely on broadcasting
the shapes together using standard numpy rules.
Returns
-------
alt : `~astropy.unit.Quantity`
Array of altitudes
"""
LST, target = self._preprocess_inputs(LST, target, grid_times_targets)
alt = np.arcsin(np.sin(self.location.lat.radian) *
np.sin(target.dec) +
| np.cos(self.location.lat.radian) | numpy.cos |
# -*- coding: utf-8 -*-
import numpy as np
import pandas as pd
import quantipy as qp
# from matplotlib import pyplot as plt
# import matplotlib.image as mpimg
import string
import pickle
import warnings
try:
import seaborn as sns
from PIL import Image
except:
pass
from quantipy.core.cache import Cache
from quantipy.core.view import View
from quantipy.core.view_generators.view_mapper import ViewMapper
from quantipy.core.view_generators.view_maps import QuantipyViews
from quantipy.core.helpers.functions import emulate_meta
from quantipy.core.tools.view.logic import (has_any, has_all, has_count,
not_any, not_all, not_count,
is_lt, is_ne, is_gt,
is_le, is_eq, is_ge,
union, intersection, get_logic_index)
from quantipy.core.helpers.functions import (paint_dataframe,
emulate_meta,
get_text,
finish_text_key)
from quantipy.core.tools.dp.prep import recode
from quantipy.core.tools.qp_decorators import lazy_property
from operator import add, sub, mul
from operator import truediv as div
#from scipy.stats.stats import _ttest_finish as get_pval
from scipy.stats._stats_py import _ttest_finish as get_pval
from scipy.stats import chi2 as chi2dist
from scipy.stats import f as fdist
from itertools import combinations, chain, product
from collections import defaultdict, OrderedDict, Counter
import gzip
try:
import dill
except:
pass
import json
import copy
import time
import sys
import re
from quantipy.core.rules import Rules
_TOTAL = '@'
_AXES = ['x', 'y']
class ChainManager(object):
def __init__(self, stack):
self.stack = stack
self.__chains = []
self.source = 'native'
self.build_info = {}
self._hidden = []
def __str__(self):
return '\n'.join([chain.__str__() for chain in self])
def __repr__(self):
return self.__str__()
def __getitem__(self, value):
if isinstance(value, str):
element = self.__chains[self._idx_from_name(value)]
is_folder = isinstance(element, dict)
if is_folder:
return list(element.values())[0]
else:
return element
else:
return self.__chains[value]
def __len__(self):
"""returns the number of cached Chains"""
return len(self.__chains)
def __iter__(self):
self.n = 0
return self
def __next__(self):
if self.n < self.__len__():
obj = self[self.n]
self.n += 1
return obj
else:
raise StopIteration
next = __next__
def add_chain(self, chain):
self.__chains.append(chain)
@property
def folders(self):
"""
Folder indices, names and number of stored ``qp.Chain`` items (as tuples).
"""
return [(self.__chains.index(f), list(f.keys())[0], len(list(f.values())[0]))
for f in self if isinstance(f, dict)]
@property
def singles(self):
"""
The list of all non-folder ``qp.Chain`` indices and names (as tuples).
"""
return list(zip(self.single_idxs, self.single_names))
@property
def chains(self):
"""
The flattened list of all ``qp.Chain`` items of self.
"""
all_chains = []
for c in self:
if isinstance(c, dict):
all_chains.extend(list(c.values())[0])
else:
all_chains.append(c)
return all_chains
@property
def folder_idxs(self):
"""
The folders' index positions in self.
"""
return [f[0] for f in self.folders]
@property
def folder_names(self):
"""
The folders' names from self.
"""
return [f[1] for f in self.folders]
@property
def single_idxs(self):
"""
The ``qp.Chain`` instances' index positions in self.
"""
return [self.__chains.index(c) for c in self if isinstance(c, Chain)]
@property
def single_names(self):
"""
The ``qp.Chain`` instances' names.
"""
return [s.name for s in self if isinstance(s, Chain)]
@property
def hidden(self):
"""
All ``qp.Chain`` elements that are hidden.
"""
return [c.name for c in self.chains if c.hidden]
@property
def hidden_folders(self):
"""
All hidden folders.
"""
return [n for n in self._hidden if n in self.folder_names]
def _content_structure(self):
return ['folder' if isinstance(k, dict) else 'single' for k in self]
def _singles_to_idx(self):
return {name: i for i, name in list(self._idx_to_singles().items())}
def _idx_to_singles(self):
return dict(self.singles)
def _idx_fold(self):
return dict([(f[0], f[1]) for f in self.folders])
def _folders_to_idx(self):
return {name: i for i, name in list(self._idx_fold().items())}
def _names(self, unroll=False):
if not unroll:
return self.folder_names + self.single_names
else:
return [c.name for c in self.chains]
def _idxs_to_names(self):
singles = self.singles
folders = [(f[0], f[1]) for f in self.folders]
return dict(singles + folders)
def _names_to_idxs(self):
return {n: i for i, n in list(self._idxs_to_names().items())}
def _name_from_idx(self, name):
return self._idxs_to_names()[name]
def _idx_from_name(self, idx):
return self._names_to_idxs()[idx]
def _is_folder_ref(self, ref):
return ref in self._folders_to_idx() or ref in self._idx_fold()
def _is_single_ref(self, ref):
return ref in self._singles_to_idx or ref in self._idx_to_singles()
def _uniquify_names(self):
all_names = Counter(self.single_names + self.folder_names)
single_name_occ = Counter(self.single_names)
folder_name_occ = {folder: Counter([c.name for c in self[folder]])
for folder in self.folder_names}
for struct_name in all_names:
if struct_name in folder_name_occ:
iter_over = folder_name_occ[struct_name]
is_folder = struct_name
else:
iter_over = single_name_occ
is_folder = False
for name, occ in list(iter_over.items()):
if occ > 1:
new_names = ['{}_{}'.format(name, i) for i in range(1, occ + 1)]
idx = [s[0] for s in self.singles if s[1] == name]
pairs = list(zip(idx, new_names))
if is_folder:
for idx, c in enumerate(self[is_folder]):
c.name = pairs[idx][1]
else:
for p in pairs:
self.__chains[p[0]].name = p[1]
return None
def _set_to_folderitems(self, folder):
"""
Will keep only the ``values()`` ``qp.Chain`` item list from the named
folder. Use this for within-folder-operations...
"""
if not folder in self.folder_names:
err = "A folder named '{}' does not exist!".format(folder)
raise KeyError(err)
else:
org_chains = self.__chains[:]
org_index = self._idx_from_name(folder)
self.__chains = self[folder]
return org_chains, org_index
def _rebuild_org_folder(self, folder, items, index):
"""
After a within-folder-operation this method is using the returns
of ``_set_to_folderitems`` to rebuild the originating folder.
"""
self.fold(folder)
new_folder = self.__chains[:]
self.__chains = items
self.__chains[index] = new_folder[0]
return None
@staticmethod
def _dupes_in_chainref(chain_refs):
return len(set(chain_refs)) != len(chain_refs)
def _check_equality(self, other, return_diffs=True):
"""
"""
chains1 = self.chains
chains2 = other.chains
diffs = {}
if not len(chains1) == len(chains2):
return False
else:
paired = list(zip(chains1, chains2))
for c1, c2 in paired:
atts1 = c1.__dict__
atts2 = c2.__dict__
for att in list(atts1.keys()):
if isinstance(atts1[att], (pd.DataFrame, pd.Index)):
if not atts1[att].equals(atts2[att]):
diffs[att] = [atts1[att], atts2[att]]
else:
if atts1[att] != atts2[att]:
diffs[att] = [atts1[att], atts2[att]]
return diffs if return_diffs else not diffs
def _test_same_structure(self, other):
"""
"""
folders1 = self.folders
singles1 = self.singles
folders2 = other.folders
singles2 = other.singles
if (folders1 != folders2 or singles1 != singles2):
return False
else:
return True
def equals(self, other):
"""
Test equality of self to another ``ChainManager`` object instance.
.. note::
Only the flattened list of ``Chain`` objects stored are tested, i.e.
any folder structure differences are ignored. Use ``compare()`` for
a more detailed comparison.
Parameters
----------
other : ``qp.ChainManager``
Another ``ChainManager`` object to compare.
Returns
-------
equality : bool
"""
return self._check_equality(other, False)
def compare(self, other, strict=True, full_summary=True):
"""
Compare structure and content of self to another ``ChainManager`` instance.
Parameters
----------
other : ``qp.ChainManager``
Another ``ChainManager`` object to compare.
strict : bool, default True
Test if the structure of folders vs. single Chain objects is the
same in both ChainManager instances.
full_summary : bool, default True
``False`` will disable the detailed comparison ``pd.DataFrame``
that informs about differences between the objects.
Returns
-------
result : str
A brief feedback message about the comparison results.
"""
diffs = []
if strict:
same_structure = self._test_same_structure(other)
if not same_structure:
diffs.append('s')
check = self._check_equality(other)
if isinstance(check, bool):
diffs.append('l')
else:
if check: diffs.append('c')
report_full = ['_frame', '_x_keys', '_y_keys', 'index', '_columns',
'base_descriptions', 'annotations']
diffs_in = ''
if diffs:
if 'l' in diffs:
diffs_in += '\n -Length (number of stored Chain objects)'
if 's' in diffs:
diffs_in += '\n -Structure (folders and/or single Chain order)'
if 'c' in diffs:
diffs_in += '\n -Chain elements (properties and content of Chain objects)'
if diffs_in:
result = 'ChainManagers are not identical:\n'
result += '--------------------------------' + diffs_in
else:
result = 'ChainManagers are identical.'
print(result)
return None
def save(self, path, keep_stack=False):
"""
"""
if not keep_stack:
del self.stack
self.stack = None
f = open(path, 'wb')
pickle.dump(self, f, pickle.HIGHEST_PROTOCOL)
f.close()
return None
@staticmethod
def load(path):
"""
"""
f = open(path, 'rb')
obj = pickle.load(f)
f.close()
return obj
def _toggle_vis(self, chains, mode='hide'):
if not isinstance(chains, list): chains = [chains]
for chain in chains:
if isinstance(chain, dict):
fname = list(chain.keys())[0]
elements = list(chain.values())[0]
fidx = self._idx_from_name(fname)
folder = self[fidx][fname]
for c in folder:
if c.name in elements:
c.hidden = True if mode == 'hide' else False
if mode == 'hide' and not c.name in self._hidden:
self._hidden.append(c.name)
if mode == 'unhide' and c.name in self._hidden:
self._hidden.remove(c.name)
else:
if chain in self.folder_names:
for c in self[chain]:
c.hidden = True if mode == 'hide' else False
else:
self[chain].hidden = True if mode == 'hide' else False
if mode == 'hide':
if not chain in self._hidden:
self._hidden.append(chain)
else:
if chain in self._hidden:
self._hidden.remove(chain)
return None
def hide(self, chains):
"""
Flag elements as being hidden.
Parameters
----------
chains : (list) of int and/or str or dict
The ``qp.Chain`` item and/or folder names to hide. To hide *within*
a folder use a dict to map the desired Chain names to the belonging
folder name.
Returns
-------
None
"""
self._toggle_vis(chains, 'hide')
return None
def unhide(self, chains=None):
"""
Unhide elements that have been set as ``hidden``.
Parameters
----------
chains : (list) of int and/or str or dict, default None
The ``qp.Chain`` item and/or folder names to unhide. To unhide *within*
a folder use a dict to map the desired Chain names to the belonging
folder name. If not provided, all hidden elements will be unhidden.
Returns
-------
None
"""
if not chains: chains = self.folder_names + self.single_names
self._toggle_vis(chains, 'unhide')
return None
def clone(self):
"""
Return a full (deep) copy of self.
"""
return copy.deepcopy(self)
def insert(self, other_cm, index=-1, safe_names=False):
"""
Add elements from another ``ChainManager`` instance to self.
Parameters
----------
other_cm : ``quantipy.ChainManager``
A ChainManager instance to draw the elements from.
index : int, default -1
The positional index after which new elements will be added.
Defaults to -1, i.e. elements are appended at the end.
safe_names : bool, default False
If True and any duplicated element names are found after the
operation, names will be made unique (by appending '_1', '_2', '_3',
etc.).
Returns
------
None
"""
if not isinstance(other_cm, ChainManager):
raise ValueError("other_cm must be a quantipy.ChainManager instance.")
if not index == -1:
before_c = self.__chains[:index+1]
after_c = self.__chains[index+1:]
new_chains = before_c + other_cm.__chains + after_c
self.__chains = new_chains
else:
self.__chains.extend(other_cm.__chains)
if safe_names: self._uniquify_names()
return None
def merge(self, folders, new_name=None, drop=True):
"""
Unite the items of two or more folders, optionally providing a new name.
If duplicated ``qp.Chain`` items are found, the first instance will be
kept. The merged folder will take the place of the first folder named
in ``folders``.
Parameters
----------
folders : list of int and/or str
The folders to merge refernced by their positional index or by name.
new_name : str, default None
Use this as the merged folder's name. If not provided, the name
of the first folder in ``folders`` will be used instead.
drop : bool, default True
If ``False``, the original folders will be kept alongside the
new merged one.
Returns
-------
None
"""
if not isinstance(folders, list):
err = "'folders' must be a list of folder references!"
raise TypeError(err)
if len(folders) == 1:
err = "'folders' must contain at least two folder names!"
raise ValueError(err)
if not all(self._is_folder_ref(f) for f in folders):
err = "One or more folder names from 'folders' do not exist!"
ValueError(err)
folders = [f if isinstance(f, str) else self._name_from_idx(f)
for f in folders]
folder_idx = self._idx_from_name(folders[0])
if not new_name: new_name = folders[0]
merged_items = []
seen_names = []
for folder in folders:
for chain in self[folder]:
if not chain.name in seen_names:
merged_items.append(chain)
seen_names.append(chain.name)
if drop:
self.__chains[folder_idx] = {new_name: merged_items}
remove_folders = folders[1:] if new_name != folders[0] else folders
for r in remove_folders:
self.remove(r)
else:
start = self.__chains[:folder_idx]
end = self.__chains[folder_idx:]
self.__chains = start + [{new_name: merged_items}] + end
return None
def fold(self, folder_name=None, chains=None):
"""
Arrange non-``dict`` structured ``qp.Chain`` items in folders.
All separate ``qp.Chain`` items will be mapped to their ``name``
property being the ``key`` in the transformed ``dict`` structure.
Parameters
----------
folder_name : str, default None
Collect all items in a folder keyed by the provided name. If the
key already exists, the items will be appended to the ``dict``
values.
chains : (list) of int and/or str, default None
Select specific ``qp.Chain`` items by providing their positional
indices or ``name`` property value for moving only a subset to the
folder.
Returns
-------
None
"""
if chains:
if not isinstance(chains, list): chains = [chains]
if any(self._is_folder_ref(c) for c in chains):
err = 'Cannot build folder from other folders!'
raise ValueError(err)
all_chain_names = []
singles = []
for c in chains:
if isinstance(c, str):
all_chain_names.append(c)
elif isinstance(c, int) and c in self._idx_to_singles():
all_chain_names.append(self._idx_to_singles()[c])
for c in all_chain_names:
singles.append(self[self._singles_to_idx()[c]])
else:
singles = [s for s in self if isinstance(s, Chain)]
if self._dupes_in_chainref(singles):
err = "Cannot build folder from duplicate qp.Chain references: {}"
raise ValueError(err.format(singles))
for s in singles:
if folder_name:
if folder_name in self.folder_names:
self[folder_name].append(s)
else:
self.__chains.append({folder_name: [s]})
del self.__chains[self._singles_to_idx()[s.name]]
else:
self.__chains[self._singles_to_idx()[s.name]] = {s.name: [s]}
return None
def unfold(self, folder=None):
"""
Remove folder but keep the collected items.
The items will be added starting at the old index position of the
original folder.
Parameters
----------
folder : (list of) str, default None
The name of the folder to drop and extract items from. If not
provided all folders will be unfolded.
Returns
-------
None
"""
if not folder:
folder = self.folder_names
else:
if not isinstance(folder, list): folder = [folder]
invalid = [f for f in folder if f not in self.folder_names]
if invalid:
err = "Folder(s) named '{}' not found.".format(invalid)
raise KeyError(err)
for f in folder:
old_pos = self._idx_from_name(f)
items = self[f]
start = self.__chains[: old_pos]
end = self.__chains[old_pos + 1: ]
self.__chains = start + items + end
return None
def remove(self, chains, folder=None, inplace=True):
"""
Remove (folders of) ``qp.Chain`` items by providing a list of indices
or names.
Parameters
----------
chains : (list) of int and/or str
``qp.Chain`` items or folders by provided by their positional
indices or ``name`` property.
folder : str, default None
If a folder name is provided, items will be dropped within that
folder only instead of removing all found instances.
inplace : bool, default True
By default the new order is applied inplace, set to ``False`` to
return a new object instead.
Returns
-------
None
"""
if inplace:
cm = self
else:
cm = self.clone()
if folder:
org_chains, org_index = cm._set_to_folderitems(folder)
if not isinstance(chains, list): chains = [chains]
remove_idxs= [c if isinstance(c, int) else cm._idx_from_name(c)
for c in chains]
if cm._dupes_in_chainref(remove_idxs):
err = "Cannot remove with duplicate chain references: {}"
raise ValueError(err.format(remove_idxs))
new_items = []
for pos, c in enumerate(cm):
if not pos in remove_idxs: new_items.append(c)
cm.__chains = new_items
if folder: cm._rebuild_org_folder(folder, org_chains, org_index)
if inplace:
return None
else:
return cm
def cut(self, values, ci=None, base=False, tests=False):
"""
Isolate selected axis values in the ``Chain.dataframe``.
Parameters
----------
values : (list of) str
The string must indicate the raw (i.e. the unpainted) second level
axis value, e.g. ``'mean'``, ``'net_1'``, etc.
ci : {'counts', 'c%', None}, default None
The cell item version to target if multiple frequency representations
are present.
base : bool, default False
Controls keeping any existing base view aggregations.
tests : bool, default False
Controls keeping any existing significance test view aggregations.
Returns
-------
None
"""
if not isinstance(values, list): values = [values]
if 'cbase' in values:
values[values.index('cbase')] = 'All'
if base and not 'All' in values:
values = ['All'] + values
for c in self.chains:
# force ci parameter for proper targeting on array summaries...
if c.array_style == 0 and ci is None:
_ci = c.cell_items.split('_')[0]
if not _ci.startswith('counts'):
ci = '%'
else:
ci = 'counts'
if c.sig_test_letters: c._remove_letter_header()
idxs, names, order = c._view_idxs(
values, keep_tests=tests, keep_bases=base, names=True, ci=ci)
idxs = [i for _, i in sorted(zip(order, idxs))]
names = [n for _, n in sorted(zip(order, names))]
if c.ci_count > 1: c._non_grouped_axis()
if c.array_style == 0:
c._fill_cells()
start, repeat = c._row_pattern(ci)
c._frame = c._frame.iloc[start::repeat, idxs]
else:
c._frame = c._frame.iloc[idxs, :]
c.index = c._slice_edited_index(c.index, idxs)
new_views = OrderedDict()
for v in c.views.copy():
if not v in names:
del c._views[v]
else:
c._views[v] = names.count(v)
if not c._array_style == 0:
if not tests:
c.sig_test_letters = None
else:
c._frame = c._apply_letter_header(c._frame)
c.edited = True
return None
def join(self, title='Summary'):
"""
Join **all** ``qp.Chain```elements, concatenating along the matching axis.
Parameters
----------
title : {str, 'auto'}, default 'Summary'
The new title for the joined axis' index representation.
Returns
-------
None
"""
custom_views = []
self.unfold()
chains = self.chains
totalmul = len(chains[0]._frame.columns.get_level_values(0).tolist())
concat_dfs = []
new_labels = []
for c in chains:
new_label = []
if c.sig_test_letters:
c._remove_letter_header()
c._frame = c._apply_letter_header(c._frame)
df = c.dataframe
if not c.array_style == 0:
new_label.append(df.index.get_level_values(0).values.tolist()[0])
new_label.extend((len(c.describe()) - 1) * [''])
else:
new_label.extend(df.index.get_level_values(1).values.tolist())
names = ['Question', 'Values']
join_idx = pd.MultiIndex.from_product([[title], new_label], names=names)
df.index = join_idx
df.rename(columns={c._x_keys[0]: 'Total'}, inplace=True)
if not c.array_style == 0:
custom_views.extend(c._views_per_rows())
else:
df.columns.set_levels(levels=[title]*totalmul, level=0, inplace=True)
concat_dfs.append(df)
new_df = pd.concat(concat_dfs, axis=0, join='inner')
self.chains[0]._frame = new_df
self.reorder([0])
self.rename({self.single_names[0]: title})
self.fold()
self.chains[0]._custom_views = custom_views
return None
def reorder(self, order, folder=None, inplace=True):
"""
Reorder (folders of) ``qp.Chain`` items by providing a list of new
indices or names.
Parameters
----------
order : list of int and/or str
The folder or ``qp.Chain`` references to determine the new order
of items. Any items not referenced will be removed from the new
order.
folder : str, default None
If a folder name is provided, items will be sorted within that
folder instead of applying the sorting to the general items
collection.
inplace : bool, default True
By default the new order is applied inplace, set to ``False`` to
return a new object instead.
Returns
-------
None
"""
if inplace:
cm = self
else:
cm = self.clone()
if folder:
org_chains, org_index = self._set_to_folderitems(folder)
if not isinstance(order, list):
err = "'order' must be a list!"
raise ValueError(err)
new_idx_order = []
for o in order:
if isinstance(o, int):
new_idx_order.append(o)
else:
new_idx_order.append(self._idx_from_name(o))
if cm._dupes_in_chainref(new_idx_order):
err = "Cannot reorder from duplicate qp.Chain references: {}"
raise ValueError(err.format(new_idx_order))
items = [self.__chains[idx] for idx in new_idx_order]
cm.__chains = items
if folder: cm._rebuild_org_folder(folder, org_chains, org_index)
if inplace:
return None
else:
return cm
def rename(self, names, folder=None):
"""
Rename (folders of) ``qp.Chain`` items by providing a mapping of old
to new keys.
Parameters
----------
names : dict
Maps existing names to the desired new ones, i.e.
{'old name': 'new names'} pairs need to be provided.
folder : str, default None
If a folder name is provided, new names will only be applied
within that folder. This is without effect if all ``qp.Chain.name``
properties across the items are unique.
Returns
-------
None
"""
if not isinstance(names, dict):
err = "''names' must be a dict of old_name: new_name pairs."
raise ValueError(err)
if folder and not folder in self.folder_names:
err = "A folder named '{}' does not exist!".format(folder)
raise KeyError(err)
for old, new in list(names.items()):
no_folder_name = folder and not old in self._names(False)
no_name_across = not folder and not old in self._names(True)
if no_folder_name and no_name_across:
err = "'{}' is not an existing folder or ``qp.Chain`` name!"
raise KeyError(err.format(old))
else:
within_folder = old not in self._names(False)
if not within_folder:
idx = self._idx_from_name(old)
if not isinstance(self.__chains[idx], dict):
self.__chains[idx].name = new
else:
self.__chains[idx] = {new: self[old][:]}
else:
iter_over = self[folder] if folder else self.chains
for c in iter_over:
if c.name == old: c.name = new
return None
def _native_stat_names(self, idxvals_list, text_key=None):
"""
"""
if not text_key: text_key = 'en-GB'
replacements = {
'en-GB': {
'Weighted N': 'Base', # Crunch
'N': 'Base', # Crunch
'Mean': 'Mean', # Dims
'StdDev': 'Std. dev', # Dims
'StdErr': 'Std. err. of mean', # Dims
'SampleVar': 'Sample variance' # Dims
},
}
native_stat_names = []
for val in idxvals_list:
if val in replacements[text_key]:
native_stat_names.append(replacements[text_key][val])
else:
native_stat_names.append(val)
return native_stat_names
def _get_ykey_mapping(self):
ys = []
letters = string.ascii_uppercase + string.ascii_lowercase
for c in self.chains:
if c._y_keys not in ys:
ys.append(c._y_keys)
return list(zip(ys, letters))
def describe(self, by_folder=False, show_hidden=False):
"""
Get a structual summary of all ``qp.Chain`` instances found in self.
Parameters
----------
by_folder : bool, default False
If True, only information on ``dict``-structured (folder-like)
``qp.Chain`` items is shown, multiindexed by folder names and item
enumerations.
show_hidden : bool, default False
If True, the summary will also include elements that have been set
hidden using ``self.hide()``.
Returns
-------
None
"""
folders = []
folder_items = []
variables = []
names = []
array_sum = []
sources = []
banner_ids = []
item_pos = []
hidden = []
bannermap = self._get_ykey_mapping()
for pos, chains in enumerate(self):
is_folder = isinstance(chains, dict)
if is_folder:
folder_name = list(chains.keys())
chains = list(chains.values())[0]
folder_items.extend(list(range(0, len(chains))))
item_pos.extend([pos] * len(chains))
else:
chains = [chains]
folder_name = [None]
folder_items.append(None)
item_pos.append(pos)
if chains[0].structure is None:
variables.extend([c._x_keys[0] for c in chains])
names.extend([c.name for c in chains])
folders.extend(folder_name * len(chains))
array_sum.extend([True if c.array_style > -1 else False
for c in chains])
sources.extend(c.source if not c.edited else 'edited'
for c in chains)
for c in chains:
for m in bannermap:
if m[0] == c._y_keys: banner_ids.append(m[1])
else:
variables.extend([chains[0].name])
names.extend([chains[0].name])
folders.extend(folder_name)
array_sum.extend([False])
sources.extend(c.source for c in chains)
banner_ids.append(None)
for c in chains:
if c.hidden:
hidden.append(True)
else:
hidden.append(False)
df_data = [item_pos,
names,
folders,
folder_items,
variables,
sources,
banner_ids,
array_sum,
hidden]
df_cols = ['Position',
'Name',
'Folder',
'Item',
'Variable',
'Source',
'Banner id',
'Array',
'Hidden']
df = pd.DataFrame(df_data).T
df.columns = df_cols
if by_folder:
df = df.set_index(['Position', 'Folder', 'Item'])
if not show_hidden:
df = df[df['Hidden'] == False][df.columns[:-1]]
return df
def from_mtd(self, mtd_doc, ignore=None, paint=True, flatten=False):
"""
Convert a Dimensions table document (.mtd) into a collection of
quantipy.Chain representations.
Parameters
----------
mtd_doc : (pandified) .mtd
A Dimensions .mtd file or the returned result of ``pandify_mtd()``.
A "pandified" .mtd consists of ``dict`` of ``pandas.DataFrame``
and metadata ``dict``. Additional text here...
ignore : bool, default False
Text
labels : bool, default True
Text
flatten : bool, default False
Text
Returns
-------
self : quantipy.ChainManager
Will consist of Quantipy representations of the pandas-converted
.mtd file.
"""
def relabel_axes(df, meta, sigtested, labels=True):
"""
"""
for axis in ['x', 'y']:
if axis == 'x':
transf_axis = df.index
else:
transf_axis = df.columns
levels = transf_axis.nlevels
axis_meta = 'index-emetas' if axis == 'x' else 'columns-emetas'
for l in range(0, levels):
if not (sigtested and axis == 'y' and l == levels -1):
org_vals = transf_axis.get_level_values(l).tolist()
org_names = [ov.split('|')[0] for ov in org_vals]
org_labs = [ov.split('|')[1] for ov in org_vals]
new_vals = org_labs if labels else org_names
if l > 0:
for no, axmeta in enumerate(meta[axis_meta]):
if axmeta['Type'] != 'Category':
new_vals[no] = axmeta['Type']
new_vals = self._native_stat_names(new_vals)
rename_dict = {old: new for old, new in zip(org_vals, new_vals)}
if axis == 'x':
df.rename(index=rename_dict, inplace=True)
df.index.names = ['Question', 'Values'] * (levels / 2)
else:
df.rename(columns=rename_dict, inplace=True)
if sigtested:
df.columns.names = (['Question', 'Values'] * (levels / 2) +
['Test-IDs'])
else:
df.columns.names = ['Question', 'Values'] * (levels / 2)
return None
def split_tab(tab):
"""
"""
df, meta = tab['df'], tab['tmeta']
mtd_slicer = df.index.get_level_values(0)
meta_limits = list(OrderedDict(
(i, mtd_slicer.tolist().count(i)) for i in mtd_slicer).values())
meta_slices = []
for start, end in enumerate(meta_limits):
if start == 0:
i_0 = 0
else:
i_0 = meta_limits[start-1]
meta_slices.append((i_0, end))
df_slicers = []
for e in mtd_slicer:
if not e in df_slicers:
df_slicers.append(e)
dfs = [df.loc[[s], :].copy() for s in df_slicers]
sub_metas = []
for ms in meta_slices:
all_meta = copy.deepcopy(meta)
idx_meta = all_meta['index-emetas'][ms[0]: ms[1]]
all_meta['index-emetas'] = idx_meta
sub_metas.append(all_meta)
return list(zip(dfs, sub_metas))
def _get_axis_vars(df):
axis_vars = []
for axis in [df.index, df.columns]:
ax_var = [v.split('|')[0] for v in axis.unique().levels[0]]
axis_vars.append(ax_var)
return axis_vars[0][0], axis_vars[1]
def to_chain(basic_chain_defintion, add_chain_meta):
new_chain = Chain(None, basic_chain_defintion[1])
new_chain.source = 'Dimensions MTD'
new_chain.stack = None
new_chain.painted = True
new_chain._meta = add_chain_meta
new_chain._frame = basic_chain_defintion[0]
new_chain._x_keys = [basic_chain_defintion[1]]
new_chain._y_keys = basic_chain_defintion[2]
new_chain._given_views = None
new_chain._grp_text_map = []
new_chain._text_map = None
# new_chain._pad_id = None
# new_chain._array_style = None
new_chain._has_rules = False
# new_chain.double_base = False
# new_chain.sig_test_letters = None
# new_chain.totalize = True
# new_chain._meta['var_meta'] = basic_chain_defintion[-1]
# new_chain._extract_base_descriptions()
new_chain._views = OrderedDict()
new_chain._views_per_rows()
for vk in new_chain._views_per_rows():
if not vk in new_chain._views:
new_chain._views[vk] = new_chain._views_per_rows().count(vk)
return new_chain
def mine_mtd(tab_collection, paint, chain_coll, folder=None):
failed = []
unsupported = []
for name, sub_tab in list(tab_collection.items()):
try:
if isinstance(list(sub_tab.values())[0], dict):
mine_mtd(sub_tab, paint, chain_coll, name)
else:
tabs = split_tab(sub_tab)
chain_dfs = []
for tab in tabs:
df, meta = tab[0], tab[1]
nestex_x = None
nested_y = (df.columns.nlevels % 2 == 0
and df.columns.nlevels > 2)
sigtested = (df.columns.nlevels % 2 != 0
and df.columns.nlevels > 2)
if sigtested:
df = df.swaplevel(0, axis=1).swaplevel(0, 1, 1)
else:
invalid = ['-', '*', '**']
df = df.applymap(
lambda x: float(x.replace(',', '.').replace('%', ''))
if isinstance(x, str) and not x in invalid
else x
)
x, y = _get_axis_vars(df)
df.replace('-', np.NaN, inplace=True)
relabel_axes(df, meta, sigtested, labels=paint)
colbase_l = -2 if sigtested else -1
for base in ['Base', 'UnweightedBase']:
df = df.drop(base, axis=1, level=colbase_l)
chain = to_chain((df, x, y), meta)
chain.name = name
chain_dfs.append(chain)
if not folder:
chain_coll.extend(chain_dfs)
else:
folders = [(i, list(c.keys())[0]) for i, c in
enumerate(chain_coll, 0) if
isinstance(c, dict)]
if folder in [f[1] for f in folders]:
pos = [f[0] for f in folders
if f[1] == folder][0]
chain_coll[pos][folder].extend(chain_dfs)
else:
chain_coll.append({folder: chain_dfs})
except:
failed.append(name)
return chain_coll
chain_coll = []
chains = mine_mtd(mtd_doc, paint, chain_coll)
self.__chains = chains
return self
def from_cmt(self, crunch_tabbook, ignore=None, cell_items='c',
array_summaries=True):
"""
Convert a Crunch multitable document (tabbook) into a collection of
quantipy.Chain representations.
Parameters
----------
crunch_tabbook : ``Tabbook`` object instance
Text
ignore : bool, default False
Text
cell_items : {'c', 'p', 'cp'}, default 'c'
Text
array_summaries : bool, default True
Text
Returns
-------
self : quantipy.ChainManager
Will consist of Quantipy representations of the Crunch table
document.
"""
def cubegroups_to_chain_defs(cubegroups, ci, arr_sum):
"""
Convert CubeGroup DataFrame to a Chain.dataframe.
"""
chain_dfs = []
# DataFrame edits to get basic Chain.dataframe rep.
for idx, cubegroup in enumerate(cubegroups):
cubegroup_df = cubegroup.dataframe
array = cubegroup.is_array
# split arrays into separate dfs / convert to summary df...
if array:
ai_aliases = cubegroup.subref_aliases
array_elements = []
dfs = []
if array_summaries:
arr_sum_df = cubegroup_df.copy().unstack()['All']
arr_sum_df.is_summary = True
x_label = arr_sum_df.index.get_level_values(0).tolist()[0]
x_name = cubegroup.rowdim.alias
dfs.append((arr_sum_df, x_label, x_name))
array_elements = cubegroup_df.index.levels[1].values.tolist()
ai_df = cubegroup_df.copy()
idx = cubegroup_df.index.droplevel(0)
ai_df.index = idx
for array_element, alias in zip(array_elements, ai_aliases):
dfs.append((ai_df.loc[[array_element], :].copy(),
array_element, alias))
else:
x_label = cubegroup_df.index.get_level_values(0).tolist()[0]
x_name = cubegroup.rowdim.alias
dfs = [(cubegroup_df, x_label, x_name)]
# Apply QP-style DataFrame conventions (indexing, names, etc.)
for cgdf, x_var_label, x_var_name in dfs:
is_summary = hasattr(cgdf, 'is_summary')
if is_summary:
cgdf = cgdf.T
y_var_names = ['@']
x_names = ['Question', 'Values']
y_names = ['Array', 'Questions']
else:
y_var_names = cubegroup.colvars
x_names = ['Question', 'Values']
y_names = ['Question', 'Values']
cgdf.index = cgdf.index.droplevel(0)
# Compute percentages?
if cell_items == 'p': _calc_pct(cgdf)
# Build x-axis multiindex / rearrange "Base" row
idx_vals = cgdf.index.values.tolist()
cgdf = cgdf.reindex([idx_vals[-1]] + idx_vals[:-1])
idx_vals = cgdf.index.values.tolist()
mi_vals = [[x_var_label], self._native_stat_names(idx_vals)]
row_mi = pd.MultiIndex.from_product(mi_vals, names=x_names)
cgdf.index = row_mi
# Build y-axis multiindex
y_vals = [('Total', 'Total') if y[0] == 'All'
else y for y in cgdf.columns.tolist()]
col_mi = pd.MultiIndex.from_tuples(y_vals, names=y_names)
cgdf.columns = col_mi
if is_summary:
cgdf = cgdf.T
chain_dfs.append((cgdf, x_var_name, y_var_names, cubegroup._meta))
return chain_dfs
def _calc_pct(df):
df.iloc[:-1, :] = df.iloc[:-1, :].div(df.iloc[-1, :]) * 100
return None
def to_chain(basic_chain_defintion, add_chain_meta):
"""
"""
new_chain = Chain(None, basic_chain_defintion[1])
new_chain.source = 'Crunch multitable'
new_chain.stack = None
new_chain.painted = True
new_chain._meta = add_chain_meta
new_chain._frame = basic_chain_defintion[0]
new_chain._x_keys = [basic_chain_defintion[1]]
new_chain._y_keys = basic_chain_defintion[2]
new_chain._given_views = None
new_chain._grp_text_map = []
new_chain._text_map = None
new_chain._pad_id = None
new_chain._array_style = None
new_chain._has_rules = False
new_chain.double_base = False
new_chain.sig_test_letters = None
new_chain.totalize = True
new_chain._meta['var_meta'] = basic_chain_defintion[-1]
new_chain._extract_base_descriptions()
new_chain._views = OrderedDict()
for vk in new_chain._views_per_rows():
if not vk in new_chain._views:
new_chain._views[vk] = new_chain._views_per_rows().count(vk)
return new_chain
# self.name = name OK!
# self._meta = Crunch meta OK!
# self._x_keys = None OK!
# self._y_keys = None OK!
# self._frame = None OK!
# self.totalize = False OK! -> But is True!
# self.stack = stack OK! -> N/A
# self._has_rules = None OK! -> N/A
# self.double_base = False OK! -> N/A
# self.sig_test_letters = None OK! -> N/A
# self._pad_id = None OK! -> N/A
# self._given_views = None OK! -> N/A
# self._grp_text_map = [] OK! -> N/A
# self._text_map = None OK! -> N/A
# self.grouping = None ?
# self._group_style = None ?
# self._transl = qp.core.view.View._metric_name_map() * with CMT/MTD
self.source = 'Crunch multitable'
cubegroups = crunch_tabbook.cube_groups
meta = {'display_settings': crunch_tabbook.display_settings,
'weight': crunch_tabbook.weight}
if cell_items == 'c':
meta['display_settings']['countsOrPercents'] = 'counts'
elif cell_items == 'p':
meta['display_settings']['countsOrPercents'] = 'percent'
chain_defs = cubegroups_to_chain_defs(cubegroups, cell_items,
array_summaries)
self.__chains = [to_chain(c_def, meta) for c_def in chain_defs]
return self
# ------------------------------------------------------------------------
def from_cluster(self, clusters):
"""
Create an OrderedDict of ``Cluster`` names storing new ``Chain``\s.
Parameters
----------
clusters : cluster-like ([dict of] quantipy.Cluster)
Text ...
Returns
-------
new_chain_dict : OrderedDict
Text ...
"""
self.source = 'native (old qp.Cluster of qp.Chain)'
qp.set_option('new_chains', True)
def check_cell_items(views):
c = any('counts' in view.split('|')[-1] for view in views)
p = any('c%' in view.split('|')[-1] for view in views)
cp = c and p
if cp:
cell_items = 'counts_colpct'
else:
cell_items = 'counts' if c else 'colpct'
return cell_items
def check_sigtest(views):
"""
"""
levels = []
sigs = [v.split('|')[1] for v in views if v.split('|')[1].startswith('t.')]
for sig in sigs:
l = '0.{}'.format(sig.split('.')[-1])
if not l in levels: levels.append(l)
return levels
def mine_chain_structure(clusters):
cluster_defs = []
for cluster_def_name, cluster in list(clusters.items()):
for name in cluster:
if isinstance(list(cluster[name].items())[0][1], pd.DataFrame):
cluster_def = {'name': name,
'oe': True,
'df': list(cluster[name].items())[0][1],
'filter': chain.filter,
'data_key': chain.data_key}
else:
xs, views, weight = [], [], []
for chain_name, chain in list(cluster[name].items()):
for v in chain.views:
w = v.split('|')[-2]
if w not in weight: weight.append(w)
if v not in views: views.append(v)
xs.append(chain.source_name)
ys = chain.content_of_axis
cluster_def = {'name': '{}-{}'.format(cluster_def_name, name),
'filter': chain.filter,
'data_key': chain.data_key,
'xs': xs,
'ys': ys,
'views': views,
'weight': weight[-1],
'bases': 'both' if len(weight) == 2 else 'auto',
'cell_items': check_cell_items(views),
'tests': check_sigtest(views)}
cluster_defs.append(cluster_def)
return cluster_defs
from quantipy.core.view_generators.view_specs import ViewManager
cluster_specs = mine_chain_structure(clusters)
for cluster_spec in cluster_specs:
oe = cluster_spec.get('oe', False)
if not oe:
vm = ViewManager(self.stack)
vm.get_views(cell_items=cluster_spec['cell_items'],
weight=cluster_spec['weight'],
bases=cluster_spec['bases'],
stats= ['mean', 'stddev', 'median', 'min', 'max'],
tests=cluster_spec['tests'])
self.get(data_key=cluster_spec['data_key'],
filter_key=cluster_spec['filter'],
x_keys = cluster_spec['xs'],
y_keys = cluster_spec['ys'],
views=vm.views,
orient='x',
prioritize=True)
else:
meta = [cluster_spec['data_key'], cluster_spec['filter']]
df, name = cluster_spec['df'], cluster_spec['name']
self.add(df, meta_from=meta, name=name)
return None
@staticmethod
def _force_list(obj):
if isinstance(obj, (list, tuple)):
return obj
return [obj]
def _check_keys(self, data_key, keys):
""" Checks given keys exist in meta['columns']
"""
keys = self._force_list(keys)
meta = self.stack[data_key].meta
valid = list(meta['columns'].keys()) + list(meta['masks'].keys())
invalid = ['"%s"' % _ for _ in keys if _ not in valid and _ != _TOTAL]
if invalid:
raise ValueError("Keys %s do not exist in meta['columns'] or "
"meta['masks']." % ", ".join(invalid))
return keys
def add(self, structure, meta_from=None, meta=None, name=None):
""" Add a pandas.DataFrame as a Chain.
Parameters
----------
structure : ``pandas.Dataframe``
The dataframe to add to the ChainManger
meta_from : list, list-like, str, default None
The location of the meta in the stack. Either a list-like object with data key and
filter key or a str as the data key
meta : quantipy meta (dict)
External meta used to paint the frame
name : ``str``, default None
The name to give the resulting chain. If not passed, the name will become
the concatenated column names, delimited by a period
Returns
-------
appended : ``quantipy.ChainManager``
"""
name = name or '.'.join(structure.columns.tolist())
chain = Chain(self.stack, name, structure=structure)
chain._frame = chain.structure
chain._index = chain._frame.index
chain._columns = chain._frame.columns
chain._frame_values = chain._frame.values
if meta_from:
if isinstance(meta_from, str):
chain._meta = self.stack[meta_from].meta
else:
data_key, filter_key = meta_from
chain._meta = self.stack[data_key][filter_key].meta
elif meta:
chain._meta = meta
self.__chains.append(chain)
return self
def get(self, data_key, filter_key, x_keys, y_keys, views, orient='x',
rules=True, rules_weight=None, prioritize=True, folder=None):
"""
TODO: Full doc string
Get a (list of) Chain instance(s) in either 'x' or 'y' orientation.
Chain.dfs will be concatenated along the provided 'orient'-axis.
"""
# TODO: VERIFY data_key
# TODO: VERIFY filter_key
# TODO: Add verbose arg to get()
x_keys = self._check_keys(data_key, x_keys)
y_keys = self._check_keys(data_key, y_keys)
if folder and not isinstance(folder, str):
err = "'folder' must be a name provided as string!"
raise ValueError(err)
if orient == 'x':
it, keys = x_keys, y_keys
else:
it, keys = y_keys, x_keys
for key in it:
x_key, y_key = (key, keys) if orient == 'x' else (keys, key)
chain = Chain(self.stack, key)
chain = chain.get(data_key, filter_key, self._force_list(x_key),
self._force_list(y_key), views, rules=rules,
rules_weight=rules_weight, prioritize=prioritize,
orient=orient)
folders = self.folder_names
if folder in folders:
idx = self._idx_from_name(folder)
self.__chains[idx][folder].append(chain)
else:
if folder:
self.__chains.append({folder: [chain]})
else:
self.__chains.append(chain)
return None
def paint_all(self, *args, **kwargs):
"""
Apply labels, sig. testing conversion and other post-processing to the
``Chain.dataframe`` property.
Use this to prepare a ``Chain`` for further usage in an Excel or Power-
point Build.
Parameters
----------
text_key : str, default meta['lib']['default text']
The language version of any variable metadata applied.
text_loc_x : str, default None
The key in the 'text' to locate the text_key for the
``pandas.DataFrame.index`` labels
text_loc_y : str, default None
The key in the 'text' to locate the text_key for the
``pandas.DataFrame.columns`` labels
display : {'x', 'y', ['x', 'y']}, default None
Text
axes : {'x', 'y', ['x', 'y']}, default None
Text
view_level : bool, default False
Text
transform_tests : {False, 'full', 'cells'}, default cells
Text
totalize : bool, default False
Text
Returns
-------
None
The ``.dataframe`` is modified inplace.
"""
for chain in self:
if isinstance(chain, dict):
for c in list(chain.values())[0]:
c.paint(*args, **kwargs)
else:
chain.paint(*args, **kwargs)
return None
HEADERS = ['header-title',
'header-left',
'header-center',
'header-right']
FOOTERS = ['footer-title',
'footer-left',
'footer-center',
'footer-right']
VALID_ANNOT_TYPES = HEADERS + FOOTERS + ['notes']
VALID_ANNOT_CATS = ['header', 'footer', 'notes']
VALID_ANNOT_POS = ['title',
'left',
'center',
'right']
class ChainAnnotations(dict):
def __init__(self):
super(ChainAnnotations, self).__init__()
self.header_title = []
self.header_left = []
self.header_center = []
self.header_right = []
self.footer_title = []
self.footer_left = []
self.footer_center = []
self.footer_right = []
self.notes = []
for v in VALID_ANNOT_TYPES:
self[v] = []
def __setitem__(self, key, value):
self._test_valid_key(key)
return super(ChainAnnotations, self).__setitem__(key, value)
def __getitem__(self, key):
self._test_valid_key(key)
return super(ChainAnnotations, self).__getitem__(key)
def __repr__(self):
headers = [(h.split('-')[1], self[h]) for h in self.populated if
h.split('-')[0] == 'header']
footers = [(f.split('-')[1], self[f]) for f in self.populated if
f.split('-')[0] == 'footer']
notes = self['notes'] if self['notes'] else []
if notes:
ar = 'Notes\n'
ar += '-{:>16}\n'.format(str(notes))
else:
ar = 'Notes: None\n'
if headers:
ar += 'Headers\n'
for pos, text in list(dict(headers).items()):
ar += ' {:>5}: {:>5}\n'.format(str(pos), str(text))
else:
ar += 'Headers: None\n'
if footers:
ar += 'Footers\n'
for pos, text in list(dict(footers).items()):
ar += ' {:>5}: {:>5}\n'.format(str(pos), str(text))
else:
ar += 'Footers: None'
return ar
def _test_valid_key(self, key):
"""
"""
if key not in VALID_ANNOT_TYPES:
splitted = key.split('-')
if len(splitted) > 1:
acat, apos = splitted[0], splitted[1]
else:
acat, apos = key, None
if apos:
if acat == 'notes':
msg = "'{}' annotation type does not support positions!"
msg = msg.format(acat)
elif not acat in VALID_ANNOT_CATS and not apos in VALID_ANNOT_POS:
msg = "'{}' is not a valid annotation type!".format(key)
elif acat not in VALID_ANNOT_CATS:
msg = "'{}' is not a valid annotation category!".format(acat)
elif apos not in VALID_ANNOT_POS:
msg = "'{}' is not a valid annotation position!".format(apos)
else:
msg = "'{}' is not a valid annotation type!".format(key)
raise KeyError(msg)
@property
def header(self):
h_dict = {}
for h in HEADERS:
if self[h]: h_dict[h.split('-')[1]] = self[h]
return h_dict
@property
def footer(self):
f_dict = {}
for f in FOOTERS:
if self[f]: f_dict[f.split('-')[1]] = self[f]
return f_dict
@property
def populated(self):
"""
The annotation fields that are defined.
"""
return sorted([k for k, v in list(self.items()) if v])
@staticmethod
def _annot_key(a_type, a_pos):
if a_pos:
return '{}-{}'.format(a_type, a_pos)
else:
return a_type
def set(self, text, category='header', position='title'):
"""
Add annotation texts defined by their category and position.
Parameters
----------
category : {'header', 'footer', 'notes'}, default 'header'
Defines if the annotation is treated as a *header*, *footer* or
*note*.
position : {'title', 'left', 'center', 'right'}, default 'title'
Sets the placement of the annotation within its category.
Returns
-------
None
"""
if not category: category = 'header'
if not position and category != 'notes': position = 'title'
if category == 'notes': position = None
akey = self._annot_key(category, position)
self[akey].append(text)
self.__dict__[akey.replace('-', '_')].append(text)
return None
CELL_DETAILS = {'en-GB': {'cc': 'Cell Contents',
'N': 'Counts',
'c%': 'Column Percentages',
'r%': 'Row Percentages',
'str': 'Statistical Test Results',
'cp': 'Column Proportions',
'cm': 'Means',
'stats': 'Statistics',
'mb': 'Minimum Base',
'sb': 'Small Base',
'up': ' indicates result is significantly higher than the result in the Total column',
'down': ' indicates result is significantly lower than the result in the Total column'
},
'fr-FR': {'cc': 'Contenu cellule',
'N': 'Total',
'c%': 'Pourcentage de colonne',
'r%': 'Pourcentage de ligne',
'str': 'Résultats test statistique',
'cp': 'Proportions de colonne',
'cm': 'Moyennes de colonne',
'stats': 'Statistiques',
'mb': 'Base minimum',
'sb': 'Petite base',
'up': ' indique que le résultat est significativement supérieur au résultat de la colonne Total',
'down': ' indique que le résultat est significativement inférieur au résultat de la colonne Total'
}}
class Chain(object):
def __init__(self, stack, name, structure=None):
self.stack = stack
self.name = name
self.structure = structure
self.source = 'native'
self.edited = False
self._custom_views = None
self.double_base = False
self.grouping = None
self.sig_test_letters = None
self.totalize = False
self.base_descriptions = None
self.painted = False
self.hidden = False
self.annotations = ChainAnnotations()
self._array_style = None
self._group_style = None
self._meta = None
self._x_keys = None
self._y_keys = None
self._given_views = None
self._grp_text_map = []
self._text_map = None
self._custom_texts = {}
self._transl = qp.core.view.View._metric_name_map()
self._pad_id = None
self._frame = None
self._has_rules = None
self._flag_bases = None
self._is_mask_item = False
self._shapes = None
class _TransformedChainDF(object):
"""
"""
def __init__(self, chain):
c = chain.clone()
self.org_views = c.views
self.df = c._frame
self._org_idx = self.df.index
self._edit_idx = list(range(0, len(self._org_idx)))
self._idx_valmap = {n: o for n, o in
zip(self._edit_idx,
self._org_idx.get_level_values(1))}
self.df.index = self._edit_idx
self._org_col = self.df.columns
self._edit_col = list(range(0, len(self._org_col)))
self._col_valmap = {n: o for n, o in
zip(self._edit_col,
self._org_col.get_level_values(1))}
self.df.columns = self._edit_col
self.array_mi = c._array_style == 0
self.nested_y = c._nested_y
self._nest_mul = self._nesting_multiplier()
return None
def _nesting_multiplier(self):
"""
"""
levels = self._org_col.nlevels
if levels == 2:
return 1
else:
return (levels / 2) + 1
def _insert_viewlikes(self, new_index_flat, org_index_mapped):
inserts = [new_index_flat.index(val) for val in new_index_flat
if not val in list(org_index_mapped.values())]
flatviews = []
for name, no in list(self.org_views.items()):
e = [name] * no
flatviews.extend(e)
for vno, i in enumerate(inserts):
flatviews.insert(i, '__viewlike__{}'.format(vno))
new_views = OrderedDict()
no_of_views = Counter(flatviews)
for fv in flatviews:
if not fv in new_views: new_views[fv] = no_of_views[fv]
return new_views
def _updated_index_tuples(self, axis):
"""
"""
if axis == 1:
current = self.df.columns.values.tolist()
mapped = self._col_valmap
org_tuples = self._org_col.tolist()
else:
current = self.df.index.values.tolist()
mapped = self._idx_valmap
org_tuples = self._org_idx.tolist()
merged = [mapped[val] if val in mapped else val for val in current]
# ================================================================
if (self.array_mi and axis == 1) or axis == 0:
self._transf_views = self._insert_viewlikes(merged, mapped)
else:
self._transf_views = self.org_views
# ================================================================
i = d = 0
new_tuples = []
for merged_val in merged:
idx = i-d if i-d != len(org_tuples) else i-d-1
if org_tuples[idx][1] == merged_val:
new_tuples.append(org_tuples[idx])
else:
empties = ['*'] * self._nest_mul
new_tuple = tuple(empties + [merged_val])
new_tuples.append(new_tuple)
d += 1
i += 1
return new_tuples
def _reindex(self):
"""
"""
y_names = ['Question', 'Values']
if not self.array_mi:
x_names = y_names
else:
x_names = ['Array', 'Questions']
if self.nested_y: y_names = y_names * (self._nest_mul - 1)
tuples = self._updated_index_tuples(axis=1)
self.df.columns = pd.MultiIndex.from_tuples(tuples, names=y_names)
tuples = self._updated_index_tuples(axis=0)
self.df.index = pd.MultiIndex.from_tuples(tuples, names=x_names)
return None
def export(self):
"""
"""
return self._TransformedChainDF(self)
def assign(self, transformed_chain_df):
"""
"""
if not isinstance(transformed_chain_df, self._TransformedChainDF):
raise ValueError("Must pass an exported ``Chain`` instance!")
transformed_chain_df._reindex()
self._frame = transformed_chain_df.df
self.views = transformed_chain_df._transf_views
return None
def __str__(self):
if self.structure is not None:
return '%s...\n%s' % (self.__class__.__name__, str(self.structure.head()))
str_format = ('%s...'
'\nSource: %s'
'\nName: %s'
'\nOrientation: %s'
'\nX: %s'
'\nY: %s'
'\nNumber of views: %s')
return str_format % (self.__class__.__name__,
getattr(self, 'source', 'native'),
getattr(self, 'name', 'None'),
getattr(self, 'orientation', 'None'),
getattr(self, '_x_keys', 'None'),
getattr(self, '_y_keys', 'None'),
getattr(self, 'views', 'None'))
def __repr__(self):
return self.__str__()
def __len__(self):
"""Returns the total number of cells in the Chain.dataframe"""
return (len(getattr(self, 'index', [])) * len(getattr(self, 'columns', [])))
def clone(self):
"""
"""
return copy.deepcopy(self)
@lazy_property
def _default_text(self):
tk = self._meta['lib']['default text']
if tk not in self._transl:
self._transl[tk] = self._transl['en-GB']
return tk
@lazy_property
def orientation(self):
""" TODO: doc string
"""
if len(self._x_keys) == 1 and len(self._y_keys) == 1:
return 'x'
elif len(self._x_keys) == 1:
return 'x'
elif len(self._y_keys) == 1:
return 'y'
if len(self._x_keys) > 1 and len(self._y_keys) > 1:
return None
@lazy_property
def axis(self):
# TODO: name appropriate?
return int(self.orientation=='x')
@lazy_property
def axes(self):
# TODO: name appropriate?
if self.axis == 1:
return self._x_keys, self._y_keys
return self._y_keys, self._x_keys
@property
def dataframe(self):
return self._frame
@property
def index(self):
return self._index
@index.setter
def index(self, index):
self._index = index
@property
def columns(self):
return self._columns
@columns.setter
def columns(self, columns):
self._columns = columns
@property
def frame_values(self):
return self._frame_values
@frame_values.setter
def frame_values(self, frame_values):
self._frame_values = frame_values
@property
def views(self):
return self._views
@views.setter
def views(self, views):
self._views = views
@property
def array_style(self):
return self._array_style
@property
def shapes(self):
if self._shapes is None:
self._shapes = []
return self._shapes
@array_style.setter
def array_style(self, link):
array_style = -1
for view in list(link.keys()):
if link[view].meta()['x']['is_array']:
array_style = 0
if link[view].meta()['y']['is_array']:
array_style = 1
self._array_style = array_style
@property
def pad_id(self):
if self._pad_id is None:
self._pad_id = 0
else:
self._pad_id += 1
return self._pad_id
@property
def sig_levels(self):
sigs = set([v for v in self._valid_views(True)
if v.split('|')[1].startswith('t.')])
tests = [t.split('|')[1].split('.')[1] for t in sigs]
levels = [t.split('|')[1].split('.')[3] for t in sigs]
sig_levels = {}
for m in zip(tests, levels):
l = '.{}'.format(m[1])
t = m[0]
if t in sig_levels:
sig_levels[t].append(l)
else:
sig_levels[t] = [l]
return sig_levels
@property
def cell_items(self):
if self.views:
compl_views = [v for v in self.views if ']*:' in v]
check_views = compl_views[:] or self.views.copy()
for v in check_views:
if v.startswith('__viewlike__'):
if compl_views:
check_views.remove(v)
else:
del check_views[v]
non_freqs = ('d.', 't.')
c = any(v.split('|')[3] == '' and
not v.split('|')[1].startswith(non_freqs) and
not v.split('|')[-1].startswith('cbase')
for v in check_views)
col_pct = any(v.split('|')[3] == 'y' and
not v.split('|')[1].startswith(non_freqs) and
not v.split('|')[-1].startswith('cbase')
for v in check_views)
row_pct = any(v.split('|')[3] == 'x' and
not v.split('|')[1].startswith(non_freqs) and
not v.split('|')[-1].startswith('cbase')
for v in check_views)
c_colpct = c and col_pct
c_rowpct = c and row_pct
c_colrow_pct = c_colpct and c_rowpct
single_ci = not (c_colrow_pct or c_colpct or c_rowpct)
if single_ci:
if c:
return 'counts'
elif col_pct:
return 'colpct'
else:
return 'rowpct'
else:
if c_colrow_pct:
return 'counts_colpct_rowpct'
elif c_colpct:
if self._counts_first():
return 'counts_colpct'
else:
return 'colpct_counts'
else:
return 'counts_rowpct'
@property
def _ci_simple(self):
ci = []
if self.views:
for v in self.views:
if 'significance' in v:
continue
if ']*:' in v:
if v.split('|')[3] == '':
if 'N' not in ci:
ci.append('N')
if v.split('|')[3] == 'y':
if 'c%' not in ci:
ci.append('c%')
if v.split('|')[3] == 'x':
if 'r%' not in ci:
ci.append('r%')
else:
if v.split('|')[-1] == 'counts':
if 'N' not in ci:
ci.append('N')
elif v.split('|')[-1] == 'c%':
if 'c%' not in ci:
ci.append('c%')
elif v.split('|')[-1] == 'r%':
if 'r%' not in ci:
ci.append('r%')
return ci
@property
def ci_count(self):
return len(self.cell_items.split('_'))
@property
def contents(self):
if self.structure:
return
nested = self._array_style == 0
if nested:
dims = self._frame.shape
contents = {row: {col: {} for col in range(0, dims[1])}
for row in range(0, dims[0])}
else:
contents = dict()
for row, idx in enumerate(self._views_per_rows()):
if nested:
for i, v in list(idx.items()):
contents[row][i] = self._add_contents(v)
else:
contents[row] = self._add_contents(idx)
return contents
@property
def cell_details(self):
lang = self._default_text if self._default_text == 'fr-FR' else 'en-GB'
cd = CELL_DETAILS[lang]
ci = self.cell_items
cd_str = '%s (%s)' % (cd['cc'], ', '.join([cd[_] for _ in self._ci_simple]))
against_total = False
if self.sig_test_letters:
mapped = ''
group = None
i = 0 if (self._frame.columns.nlevels in [2, 3]) else 4
for letter, lab in zip(self.sig_test_letters, self._frame.columns.codes[-i]):
if letter == '@':
continue
if group is not None:
if lab == group:
mapped += '/' + letter
else:
group = lab
mapped += ', ' + letter
else:
group = lab
mapped += letter
test_types = cd['cp']
if self.sig_levels.get('means'):
test_types += ', ' + cd['cm']
levels = []
for key in ('props', 'means'):
for level in self.sig_levels.get(key, iter(())):
l = '%s%%' % int(100. - float(level.split('+@')[0].split('.')[1]))
if l not in levels:
levels.append(l)
if '+@' in level:
against_total = True
cd_str = cd_str[:-1] + ', ' + cd['str'] +'), '
cd_str += '%s (%s, (%s): %s' % (cd['stats'], test_types, ', '.join(levels), mapped)
if self._flag_bases:
flags = ([], [])
[(flags[0].append(min), flags[1].append(small)) for min, small in self._flag_bases]
cd_str += ', %s: %s (**), %s: %s (*)' % (cd['mb'], ', '.join(map(str, flags[0])),
cd['sb'], ', '.join(map(str, flags[1])))
cd_str += ')'
cd_str = [cd_str]
if against_total:
cd_str.extend([cd['up'], cd['down']])
return cd_str
def describe(self):
def _describe(cell_defs, row_id):
descr = []
for r, m in list(cell_defs.items()):
descr.append(
[k if isinstance(v, bool) else v for k, v in list(m.items()) if v])
if any('is_block' in d for d in descr):
blocks = self._describe_block(descr, row_id)
calc = 'calc' in blocks
for d, b in zip(descr, blocks):
if b:
d.append(b) if not calc else d.extend([b, 'has_calc'])
return descr
if self._array_style == 0:
description = {k: _describe(v, k) for k, v in list(self.contents.items())}
else:
description = _describe(self.contents, None)
return description
def _fill_cells(self):
"""
"""
self._frame = self._frame.fillna(method='ffill')
return None
# @lazy_property
def _counts_first(self):
for v in self.views:
sname = v.split('|')[-1]
if sname in ['counts', 'c%']:
if sname == 'counts':
return True
else:
return False
#@property
def _views_per_rows(self):
"""
"""
base_vk = 'x|f|x:||{}|cbase'
counts_vk = 'x|f|:||{}|counts'
pct_vk = 'x|f|:|y|{}|c%'
mean_vk = 'x|d.mean|:|y|{}|mean'
stddev_vk = 'x|d.stddev|:|y|{}|stddev'
variance_vk = 'x|d.var|:|y|{}|var'
sem_vk = 'x|d.sem|:|y|{}|sem'
if self.source == 'Crunch multitable':
ci = self._meta['display_settings']['countsOrPercents']
w = self._meta['weight']
if ci == 'counts':
main_vk = counts_vk.format(w if w else '')
else:
main_vk = pct_vk.format(w if w else '')
base_vk = base_vk.format(w if w else '')
metrics = [base_vk] + (len(self.dataframe.index)-1) * [main_vk]
elif self.source == 'Dimensions MTD':
ci = self._meta['cell_items']
w = None
axis_vals = [axv['Type'] for axv in self._meta['index-emetas']]
metrics = []
for axis_val in axis_vals:
if axis_val == 'Base':
metrics.append(base_vk.format(w if w else ''))
if axis_val == 'UnweightedBase':
metrics.append(base_vk.format(w if w else ''))
elif axis_val == 'Category':
metrics.append(counts_vk.format(w if w else ''))
elif axis_val == 'Mean':
metrics.append(mean_vk.format(w if w else ''))
elif axis_val == 'StdDev':
metrics.append(stddev_vk.format(w if w else ''))
elif axis_val == 'StdErr':
metrics.append(sem_vk.format(w if w else ''))
elif axis_val == 'SampleVar':
metrics.append(variance_vk.format(w if w else ''))
return metrics
else:
# Native Chain views
# ----------------------------------------------------------------
if self.edited and (self._custom_views and not self.array_style == 0):
return self._custom_views
else:
if self._array_style != 0:
metrics = []
if self.orientation == 'x':
for view in self._valid_views():
view = self._force_list(view)
initial = view[0]
size = self.views[initial]
metrics.extend(view * size)
else:
for view_part in self.views:
for view in self._valid_views():
view = self._force_list(view)
initial = view[0]
size = view_part[initial]
metrics.extend(view * size)
else:
counts = []
colpcts = []
rowpcts = []
metrics = []
ci = self.cell_items
for v in list(self.views.keys()):
if not v.startswith('__viewlike__'):
parts = v.split('|')
is_completed = ']*:' in v
if not self._is_c_pct(parts):
counts.extend([v]*self.views[v])
if self._is_r_pct(parts):
rowpcts.extend([v]*self.views[v])
if (self._is_c_pct(parts) or self._is_base(parts) or
self._is_stat(parts)):
colpcts.extend([v]*self.views[v])
else:
counts = counts + ['__viewlike__']
colpcts = colpcts + ['__viewlike__']
rowpcts = rowpcts + ['__viewlike__']
dims = self._frame.shape
for row in range(0, dims[0]):
if ci in ['counts_colpct', 'colpct_counts'] and self.grouping:
if row % 2 == 0:
if self._counts_first():
vc = counts
else:
vc = colpcts
else:
if not self._counts_first():
vc = counts
else:
vc = colpcts
else:
vc = counts if ci == 'counts' else colpcts
metrics.append({col: vc[col] for col in range(0, dims[1])})
return metrics
def _valid_views(self, flat=False):
clean_view_list = []
valid = list(self.views.keys())
org_vc = self._given_views
v_likes = [v for v in valid if v.startswith('__viewlike__')]
if isinstance(org_vc, tuple):
v_likes = tuple(v_likes)
view_coll = org_vc + v_likes
for v in view_coll:
if isinstance(v, str):
if v in valid:
clean_view_list.append(v)
else:
new_v = []
for sub_v in v:
if sub_v in valid:
new_v.append(sub_v)
if isinstance(v, tuple):
new_v = list(new_v)
if new_v:
if len(new_v) == 1: new_v = new_v[0]
if not flat:
clean_view_list.append(new_v)
else:
if isinstance(new_v, list):
clean_view_list.extend(new_v)
else:
clean_view_list.append(new_v)
return clean_view_list
def _add_contents(self, viewelement):
"""
"""
if viewelement.startswith('__viewlike__'):
parts = '|||||'
viewlike = True
else:
parts = viewelement.split('|')
viewlike = False
return dict(is_default=self._is_default(parts),
is_c_base=self._is_c_base(parts),
is_r_base=self._is_r_base(parts),
is_e_base=self._is_e_base(parts),
is_c_base_gross=self._is_c_base_gross(parts),
is_counts=self._is_counts(parts),
is_c_pct=self._is_c_pct(parts),
is_r_pct=self._is_r_pct(parts),
is_res_c_pct=self._is_res_c_pct(parts),
is_counts_sum=self._is_counts_sum(parts),
is_c_pct_sum=self._is_c_pct_sum(parts),
is_counts_cumsum=self._is_counts_cumsum(parts),
is_c_pct_cumsum=self._is_c_pct_cumsum(parts),
is_net=self._is_net(parts),
is_block=self._is_block(parts),
is_calc_only = self._is_calc_only(parts),
is_mean=self._is_mean(parts),
is_stddev=self._is_stddev(parts),
is_min=self._is_min(parts),
is_max=self._is_max(parts),
is_median=self._is_median(parts),
is_variance=self._is_variance(parts),
is_sem=self._is_sem(parts),
is_varcoeff=self._is_varcoeff(parts),
is_percentile=self._is_percentile(parts),
is_propstest=self._is_propstest(parts),
is_meanstest=self._is_meanstest(parts),
is_weighted=self._is_weighted(parts),
weight=self._weight(parts),
is_stat=self._is_stat(parts),
stat=self._stat(parts),
siglevel=self._siglevel(parts),
is_viewlike=viewlike)
def _row_pattern(self, target_ci):
"""
"""
cisplit = self.cell_items.split('_')
if target_ci == 'c%':
start = cisplit.index('colpct')
elif target_ci == 'counts':
start = cisplit.index('counts')
repeat = self.ci_count
return (start, repeat)
def _view_idxs(self, view_tags, keep_tests=True, keep_bases=True, names=False, ci=None):
"""
"""
if not isinstance(view_tags, list): view_tags = [view_tags]
rowmeta = self.named_rowmeta
nested = self.array_style == 0
if nested:
if self.ci_count > 1:
rp_idx = self._row_pattern(ci)[0]
rowmeta = rowmeta[rp_idx]
else:
rp_idx = 0
rowmeta = rowmeta[0]
rows = []
for r in rowmeta:
is_code = str(r[0]).isdigit()
if 'is_counts' in r[1] and is_code:
rows.append(('counts', r[1]))
elif 'is_c_pct' in r[1] and is_code:
rows.append(('c%', r[1]))
elif 'is_propstest' in r[1]:
rows.append((r[0], r[1]))
elif 'is_meanstest' in r[1]:
rows.append((r[0], r[1]))
else:
rows.append(r)
invalids = []
if not keep_tests:
invalids.extend(['is_propstest', 'is_meanstest'])
if ci == 'counts':
invalids.append('is_c_pct')
elif ci == 'c%':
invalids.append('is_counts')
idxs = []
names = []
order = []
for i, row in enumerate(rows):
if any([invalid in row[1] for invalid in invalids]):
if not (row[0] == 'All' and keep_bases): continue
if row[0] in view_tags:
order.append(view_tags.index(row[0]))
idxs.append(i)
if nested:
names.append(self._views_per_rows()[rp_idx][i])
else:
names.append(self._views_per_rows()[i])
return (idxs, order) if not names else (idxs, names, order)
@staticmethod
def _remove_grouped_blanks(viewindex_labs):
"""
"""
full = []
for v in viewindex_labs:
if v == '':
full.append(last)
else:
last = v
full.append(last)
return full
def _slice_edited_index(self, axis, positions):
"""
"""
l_zero = axis.get_level_values(0).values.tolist()[0]
l_one = axis.get_level_values(1).values.tolist()
l_one = [l_one[p] for p in positions]
axis_tuples = [(l_zero, lab) for lab in l_one]
if self.array_style == 0:
names = ['Array', 'Questions']
else:
names = ['Question', 'Values']
return pd.MultiIndex.from_tuples(axis_tuples, names=names)
def _non_grouped_axis(self):
"""
"""
axis = self._frame.index
l_zero = axis.get_level_values(0).values.tolist()[0]
l_one = axis.get_level_values(1).values.tolist()
l_one = self._remove_grouped_blanks(l_one)
axis_tuples = [(l_zero, lab) for lab in l_one]
if self.array_style == 0:
names = ['Array', 'Questions']
else:
names = ['Question', 'Values']
self._frame.index = pd.MultiIndex.from_tuples(axis_tuples, names=names)
return None
@property
def named_rowmeta(self):
if self.painted:
self.toggle_labels()
d = self.describe()
if self.array_style == 0:
n = self._frame.columns.get_level_values(1).values.tolist()
n = self._remove_grouped_blanks(n)
mapped = {rowid: list(zip(n, rowmeta)) for rowid, rowmeta in list(d.items())}
else:
n = self._frame.index.get_level_values(1).values.tolist()
n = self._remove_grouped_blanks(n)
mapped = list(zip(n, d))
if not self.painted: self.toggle_labels()
return mapped
@lazy_property
def _nested_y(self):
return any('>' in v for v in self._y_keys)
def _is_default(self, parts):
return parts[-1] == 'default'
def _is_c_base(self, parts):
return parts[-1] == 'cbase'
def _is_r_base(self, parts):
return parts[-1] == 'rbase'
def _is_e_base(self, parts):
return parts[-1] == 'ebase'
def _is_c_base_gross(self, parts):
return parts[-1] == 'cbase_gross'
def _is_base(self, parts):
return (self._is_c_base(parts) or
self._is_c_base_gross(parts) or
self._is_e_base(parts) or
self._is_r_base(parts))
def _is_counts(self, parts):
return parts[1].startswith('f') and parts[3] == ''
def _is_c_pct(self, parts):
return parts[1].startswith('f') and parts[3] == 'y'
def _is_r_pct(self, parts):
return parts[1].startswith('f') and parts[3] == 'x'
def _is_res_c_pct(self, parts):
return parts[-1] == 'res_c%'
def _is_net(self, parts):
return parts[1].startswith(('f', 'f.c:f', 't.props')) and \
len(parts[2]) > 3 and not parts[2] == 'x++'
def _is_calc_only(self, parts):
if self._is_net(parts) and not self._is_block(parts):
return ((self.__has_freq_calc(parts) or
self.__is_calc_only_propstest(parts)) and not
(self._is_counts_sum(parts) or self._is_c_pct_sum(parts)))
else:
return False
def _is_block(self, parts):
if self._is_net(parts):
conditions = parts[2].split('[')
multiple_conditions = len(conditions) > 2
expand = '+{' in parts[2] or '}+' in parts[2]
complete = '*:' in parts[2]
if expand or complete:
return True
if multiple_conditions:
if self.__has_operator_expr(parts):
return True
return False
return False
return False
def _stat(self, parts):
if parts[1].startswith('d.'):
return parts[1].split('.')[-1]
else:
return None
# non-meta relevant helpers
def __has_operator_expr(self, parts):
e = parts[2]
for syntax in [']*:', '[+{', '}+']:
if syntax in e: e = e.replace(syntax, '')
ops = ['+', '-', '*', '/']
return any(len(e.split(op)) > 1 for op in ops)
def __has_freq_calc(self, parts):
return parts[1].startswith('f.c:f')
def __is_calc_only_propstest(self, parts):
return self._is_propstest(parts) and self.__has_operator_expr(parts)
@staticmethod
def _statname(parts):
split = parts[1].split('.')
if len(split) > 1:
return split[1]
return split[-1]
def _is_mean(self, parts):
return self._statname(parts) == 'mean'
def _is_stddev(self, parts):
return self._statname(parts) == 'stddev'
def _is_min(self, parts):
return self._statname(parts) == 'min'
def _is_max(self, parts):
return self._statname(parts) == 'max'
def _is_median(self, parts):
return self._statname(parts) == 'median'
def _is_variance(self, parts):
return self._statname(parts) == 'var'
def _is_sem(self, parts):
return self._statname(parts) == 'sem'
def _is_varcoeff(self, parts):
return self._statname(parts) == 'varcoeff'
def _is_percentile(self, parts):
return self._statname(parts) in ['upper_q', 'lower_q', 'median']
def _is_counts_sum(self, parts):
return parts[-1].endswith('counts_sum')
def _is_c_pct_sum(self, parts):
return parts[-1].endswith('c%_sum')
def _is_counts_cumsum(self, parts):
return parts[-1].endswith('counts_cumsum')
def _is_c_pct_cumsum(self, parts):
return parts[-1].endswith('c%_cumsum')
def _is_weighted(self, parts):
return parts[4] != ''
def _weight(self, parts):
if parts[4] != '':
return parts[4]
else:
return None
def _is_stat(self, parts):
return parts[1].startswith('d.')
def _is_propstest(self, parts):
return parts[1].startswith('t.props')
def _is_meanstest(self, parts):
return parts[1].startswith('t.means')
def _siglevel(self, parts):
if self._is_meanstest(parts) or self._is_propstest(parts):
return parts[1].split('.')[-1]
else:
return None
def _describe_block(self, description, row_id):
if self.painted:
repaint = True
self.toggle_labels()
else:
repaint = False
vpr = self._views_per_rows()
if row_id is not None:
vpr = [v[1] for v in list(vpr[row_id].items())]
idx = self.dataframe.columns.get_level_values(1).tolist()
else:
idx = self.dataframe.index.get_level_values(1).tolist()
idx_view_map = list(zip(idx, vpr))
block_net_vk = [v for v in vpr if len(v.split('|')[2].split('['))>2 or
'[+{' in v.split('|')[2] or '}+]' in v.split('|')[2]]
has_calc = any([v.split('|')[1].startswith('f.c') for v in block_net_vk])
is_tested = any(v.split('|')[1].startswith('t.props') for v in vpr)
if block_net_vk:
expr = block_net_vk[0].split('|')[2]
expanded_codes = set(map(int, re.findall(r'\d+', expr)))
else:
expanded_codes = []
for idx, m in enumerate(idx_view_map):
if idx_view_map[idx][0] == '':
idx_view_map[idx] = (idx_view_map[idx-1][0], idx_view_map[idx][1])
for idx, row in enumerate(description):
if not 'is_block' in row:
idx_view_map[idx] = None
blocks_len = len(expr.split('],')) * (self.ci_count + is_tested)
if has_calc: blocks_len -= (self.ci_count + is_tested)
block_net_def = []
described_nets = 0
for e in idx_view_map:
if e:
if isinstance(e[0], str):
if has_calc and described_nets == blocks_len:
block_net_def.append('calc')
else:
block_net_def.append('net')
described_nets += 1
else:
code = int(e[0])
if code in expanded_codes:
block_net_def.append('expanded')
else:
block_net_def.append('normal')
else:
block_net_def.append(e)
if repaint: self.toggle_labels()
return block_net_def
def get(self, data_key, filter_key, x_keys, y_keys, views, rules=False,
rules_weight=None, orient='x', prioritize=True):
""" Get the concatenated Chain.DataFrame
"""
self._meta = self.stack[data_key].meta
self._given_views = views
self._x_keys = x_keys
self._y_keys = y_keys
concat_axis = 0
if rules:
if not isinstance(rules, list):
self._has_rules = ['x', 'y']
else:
self._has_rules = rules
# use_views = views[:]
# for first in self.axes[0]:
# for second in self.axes[1]:
# link = self._get_link(data_key, filter_key, first, second)
# for v in use_views:
# if v not in link:
# use_views.remove(v)
for first in self.axes[0]:
found = []
x_frames = []
for second in self.axes[1]:
if self.axis == 1:
link = self._get_link(data_key, filter_key, first, second)
else:
link = self._get_link(data_key, filter_key, second, first)
if link is None:
continue
if prioritize: link = self._drop_substituted_views(link)
found_views, y_frames = self._concat_views(
link, views, rules_weight)
found.append(found_views)
try:
if self._meta['columns'][link.x].get('parent'):
self._is_mask_item = True
except KeyError:
pass
# TODO: contains arrary summ. attr.
# TODO: make this work y_frames = self._pad_frames(y_frames)
self.array_style = link
if self.array_style > -1:
concat_axis = 1 if self.array_style == 0 else 0
y_frames = self._pad_frames(y_frames)
x_frames.append(pd.concat(y_frames, axis=concat_axis))
self.shapes.append(x_frames[-1].shape)
self._frame = pd.concat(self._pad(x_frames), axis=self.axis)
if self._group_style == 'reduced' and self.array_style >- 1:
scan_views = [v if isinstance(v, (tuple, list)) else [v]
for v in self._given_views]
scan_views = [v for v in scan_views if len(v) > 1]
no_tests = []
for scan_view in scan_views:
new_views = []
for view in scan_view:
if not view.split('|')[1].startswith('t.'):
new_views.append(view)
no_tests.append(new_views)
cond = any(len(v) >= 2 for v in no_tests)
if cond:
self._frame = self._reduce_grouped_index(self._frame, 2, self._array_style)
if self.axis == 1:
self.views = found[-1]
else:
self.views = found
self.double_base = len([v for v in self.views
if v.split('|')[-1] == 'cbase']) > 1
self._index = self._frame.index
self._columns = self._frame.columns
self._extract_base_descriptions()
del self.stack
return self
def _toggle_bases(self, keep_weighted=True):
df = self._frame
is_array = self._array_style == 0
contents = self.contents[0] if is_array else self.contents
has_wgt_b = [k for k, v in list(contents.items())
if v['is_c_base'] and v['is_weighted']]
has_unwgt_b = [k for k, v in list(contents.items())
if v['is_c_base'] and not v['is_weighted']]
if not (has_wgt_b and has_unwgt_b):
return None
if keep_weighted:
drop_rows = has_unwgt_b
names = ['x|f|x:|||cbase']
else:
drop_rows = has_wgt_b
names = ['x|f|x:||{}|cbase'.format(list(contents.values())[0]['weight'])]
for v in self.views.copy():
if v in names:
del self._views[v]
df = self._frame
if is_array:
cols = [col for x, col in enumerate(df.columns.tolist())
if not x in drop_rows]
df = df.loc[:, cols]
else:
rows = [row for x, row in enumerate(df.index.tolist())
if not x in drop_rows]
df = df.loc[rows, :]
self._frame = df
self._index = df.index
self._columns = df.columns
return None
def _slice_edited_index(self, axis, positions):
"""
"""
l_zero = axis.get_level_values(0).values.tolist()[0]
l_one = axis.get_level_values(1).values.tolist()
l_one = [l_one[p] for p in positions]
axis_tuples = [(l_zero, lab) for lab in l_one]
if self.array_style == 0:
names = ['Array', 'Questions']
else:
names = ['Question', 'Values']
return pd.MultiIndex.from_tuples(axis_tuples, names=names)
def _drop_substituted_views(self, link):
if any(isinstance(sect, (list, tuple)) for sect in self._given_views):
chain_views = list(chain.from_iterable(self._given_views))
else:
chain_views = self._given_views
has_compl = any(']*:' in vk for vk in link)
req_compl = any(']*:' in vk for vk in chain_views)
has_cumsum = any('++' in vk for vk in link)
req_cumsum = any('++' in vk for vk in chain_views)
if (has_compl and req_compl) or (has_cumsum and req_cumsum):
new_link = copy.copy(link)
views = []
for vk in link:
vksplit = vk.split('|')
method, cond, name = vksplit[1], vksplit[2], vksplit[-1]
full_frame = name in ['counts', 'c%']
basic_sigtest = method.startswith('t.') and cond == ':'
if not full_frame and not basic_sigtest: views.append(vk)
for vk in link:
if vk not in views: del new_link[vk]
return new_link
else:
return link
def _pad_frames(self, frames):
""" TODO: doc string
"""
empty_frame = lambda f: pd.DataFrame(index=f.index, columns=f.columns)
max_lab = max(f.axes[self.array_style].size for f in frames)
for e, f in enumerate(frames):
size = f.axes[self.array_style].size
if size < max_lab:
f = pd.concat([f, empty_frame(f)], axis=self.array_style)
order = [None] * (size * 2)
order[::2] = list(range(size))
order[1::2] = list(range(size, size * 2))
if self.array_style == 0:
frames[e] = f.iloc[order, :]
else:
frames[e] = f.iloc[:, order]
return frames
def _get_link(self, data_key, filter_key, x_key, y_key):
"""
"""
base = self.stack[data_key][filter_key]
if x_key in base:
base = base[x_key]
if y_key in base:
return base[y_key]
else:
if self._array_style == -1:
self._y_keys.remove(y_key)
else:
self._x_keys.remove(x_key)
return None
def _index_switch(self, axis):
""" Returns self.dataframe/frame index/ columns based on given x/ y
"""
return dict(x=self._frame.index, y=self._frame.columns).get(axis)
def _pad(self, frames):
""" Pad index/ columns when nlevels is less than the max nlevels
in list of dataframes.
"""
indexes = []
max_nlevels = [max(f.axes[i].nlevels for f in frames) for i in (0, 1)]
for e, f in enumerate(frames):
indexes = []
for i in (0, 1):
if f.axes[i].nlevels < max_nlevels[i]:
indexes.append(self._pad_index(f.axes[i], max_nlevels[i]))
else:
indexes.append(f.axes[i])
frames[e].index, frames[e].columns = indexes
return frames
def _pad_index(self, index, size):
""" Add levels to columns MultiIndex so the nlevels matches
the biggest columns MultiIndex in DataFrames to be concatenated.
"""
pid = self.pad_id
pad = ((size - index.nlevels) // 2)
fill = int((pad % 2) == 1)
names = list(index.names)
names[0:0] = names[:2] * pad
arrays = self._lzip(index.values)
arrays[0:0] = [tuple('#pad-%s' % pid for _ in arrays[i])
for i in range(pad + fill)] * pad
return pd.MultiIndex.from_arrays(arrays, names=names)
@staticmethod
def _reindx_source(df, varname, total):
"""
"""
df.index = df.index.set_levels([varname], level=0, inplace=False)
if df.columns.get_level_values(0).tolist()[0] != varname and total:
df.columns = df.columns.set_levels([varname], level=0, inplace=False)
return df
def _concat_views(self, link, views, rules_weight, found=None):
""" Concatenates the Views of a Chain.
"""
frames = []
totals = [[_TOTAL]] * 2
if found is None:
found = OrderedDict()
if self._text_map is None:
self._text_map = dict()
for view in views:
try:
self.array_style = link
if isinstance(view, (list, tuple)):
if not self.grouping:
self.grouping = True
if isinstance(view, tuple):
self._group_style = 'reduced'
else:
self._group_style = 'normal'
if self.array_style > -1:
use_grp_type = 'normal'
else:
use_grp_type = self._group_style
found, grouped = self._concat_views(link, view, rules_weight, found=found)
if grouped:
frames.append(self._group_views(grouped, use_grp_type))
else:
agg = link[view].meta()['agg']
is_descriptive = agg['method'] == 'descriptives'
is_base = agg['name'] in ['cbase', 'rbase', 'ebase', 'cbase_gross']
is_sum = agg['name'] in ['counts_sum', 'c%_sum']
is_net = link[view].is_net()
oth_src = link[view].has_other_source()
no_total_sign = is_descriptive or is_base or is_sum or is_net
if link[view]._custom_txt and is_descriptive:
statname = agg['fullname'].split('|')[1].split('.')[1]
if not statname in self._custom_texts:
self._custom_texts[statname] = []
self._custom_texts[statname].append(link[view]._custom_txt)
if is_descriptive:
text = agg['name']
try:
self._text_map.update({agg['name']: text})
except AttributeError:
self._text_map = {agg['name']: text}
if agg['text']:
name = dict(cbase='All').get(agg['name'], agg['name'])
try:
self._text_map.update({name: agg['text']})
except AttributeError:
self._text_map = {name: agg['text'],
_TOTAL: 'Total'}
if agg['grp_text_map']:
# try:
if not agg['grp_text_map'] in self._grp_text_map:
self._grp_text_map.append(agg['grp_text_map'])
# except AttributeError:
# self._grp_text_map = [agg['grp_text_map']]
frame = link[view].dataframe
if oth_src:
frame = self._reindx_source(frame, link.x, link.y == _TOTAL)
# RULES SECTION
# ========================================================
# TODO: DYNAMIC RULES:
# - all_rules_axes, rules_weight must be provided not hardcoded
# - Review copy/pickle in original version!!!
rules_weight = None
if self._has_rules:
rules = Rules(link, view, self._has_rules, rules_weight)
# print rules.show_rules()
# rules.get_slicer()
# print rules.show_slicers()
rules.apply()
frame = rules.rules_df()
# ========================================================
if not no_total_sign and (link.x == _TOTAL or link.y == _TOTAL):
if link.x == _TOTAL:
level_names = [[link.y], ['@']]
elif link.y == _TOTAL:
level_names = [[link.x], ['@']]
try:
frame.columns.set_levels(level_names, level=[0, 1],
inplace=True)
except ValueError:
pass
frames.append(frame)
if view not in found:
if self._array_style != 0:
found[view] = len(frame.index)
else:
found[view] = len(frame.columns)
if link[view]._kwargs.get('flag_bases'):
flag_bases = link[view]._kwargs['flag_bases']
try:
if flag_bases not in self._flag_bases:
self._flag_bases.append(flag_bases)
except TypeError:
self._flag_bases = [flag_bases]
except KeyError:
pass
return found, frames
@staticmethod
def _temp_nest_index(df):
"""
Flatten the nested MultiIndex for easier handling.
"""
# Build flat column labels
flat_cols = []
order_idx = []
i = -1
for col in df.columns.values:
flat_col_lab = ''.join(str(col[:-1])).strip()
if not flat_col_lab in flat_cols:
i += 1
order_idx.append(i)
flat_cols.append(flat_col_lab)
else:
order_idx.append(i)
# Drop unwanted levels (keep last Values Index-level in that process)
levels = list(range(0, df.columns.nlevels-1))
drop_levels = levels[:-2]+ [levels[-1]]
df.columns = df.columns.droplevel(drop_levels)
# Apply the new flat labels and resort the columns
df.columns.set_levels(levels=flat_cols, level=0, inplace=True)
df.columns.set_codes(order_idx, level=0, inplace=True)
return df, flat_cols
@staticmethod
def _replace_test_results(df, replacement_map, char_repr):
"""
Swap all digit-based results with letters referencing the column header.
.. note:: The modified df will be stripped of all indexing on both rows
and columns.
"""
all_dfs = []
ignore = False
for col in list(replacement_map.keys()):
target_col = df.columns[0] if col == '@' else col
value_df = df[[target_col]].copy()
if not col == '@':
value_df.drop('@', axis=1, level=1, inplace=True)
values = value_df.replace(np.NaN, '-').values.tolist()
r = replacement_map[col]
new_values = []
case = None
for v in values:
if isinstance(v[0], str):
if char_repr == 'upper':
case = 'up'
elif char_repr == 'lower':
case = 'low'
elif char_repr == 'alternate':
if case == 'up':
case = 'low'
else:
case = 'up'
for no, l in sorted(list(r.items()), reverse=True):
v = [char.replace(str(no), l if case == 'up' else l.lower())
if isinstance(char, str)
else char for char in v]
new_values.append(v)
else:
new_values.append(v)
part_df = pd.DataFrame(new_values)
all_dfs.append(part_df)
letter_df = pd.concat(all_dfs, axis=1)
# Clean it up
letter_df.replace('-', np.NaN, inplace=True)
for signs in [('[', ''), (']', ''), (', ', '.')]:
letter_df = letter_df.applymap(lambda x: x.replace(signs[0], signs[1])
if isinstance(x, str) else x)
return letter_df
@staticmethod
def _get_abc_letters(no_of_cols, incl_total):
"""
Get the list of letter replacements depending on the y-axis length.
"""
repeat_alphabet = int(no_of_cols / 26)
abc = list(string.ascii_uppercase)
letters = list(string.ascii_uppercase)
if repeat_alphabet:
for r in range(0, repeat_alphabet):
letter = abc[r]
extend_abc = ['{}{}'.format(letter, l) for l in abc]
letters.extend(extend_abc)
if incl_total:
letters = ['@'] + letters[:no_of_cols-1]
else:
letters = letters[:no_of_cols]
return letters
def _any_tests(self):
vms = [v.split('|')[1] for v in list(self._views.keys())]
return any('t.' in v for v in vms)
def _no_of_tests(self):
tests = [v for v in list(self._views.keys())
if v.split('|')[1].startswith('t.')]
levels = [v.split('|')[1].split('.')[-1] for v in tests]
return len(set(levels))
def _siglevel_on_row(self):
"""
"""
vpr = self._views_per_rows()
tests = [(no, v) for no, v in enumerate(vpr)
if v.split('|')[1].startswith('t.')]
s = [(t[0],
float(int(t[1].split('|')[1].split('.')[3].split('+')[0]))/100.0)
for t in tests]
return s
def transform_tests(self, char_repr='upper', display_level=True):
"""
Transform column-wise digit-based test representation to letters.
Adds a new row that is applying uppercase letters to all columns (A,
B, C, ...) and maps any significance test's result cells to these column
indicators.
"""
if not self._any_tests(): return None
# Preparation of input dataframe and dimensions of y-axis header
df = self.dataframe.copy()
number_codes = df.columns.get_level_values(-1).tolist()
number_header_row = copy.copy(df.columns)
if self._no_of_tests() != 2 and char_repr == 'alternate':
char_repr = 'upper'
has_total = '@' in self._y_keys
if self._nested_y:
df, questions = self._temp_nest_index(df)
else:
questions = self._y_keys
all_num = number_codes if not has_total else [0] + number_codes[1:]
# Set the new column header (ABC, ...)
column_letters = self._get_abc_letters(len(number_codes), has_total)
vals = df.columns.get_level_values(0).tolist()
mi = pd.MultiIndex.from_arrays(
(vals,
column_letters))
df.columns = mi
self.sig_test_letters = df.columns.get_level_values(1).tolist()
# Build the replacements dict and build list of unique column indices
test_dict = OrderedDict()
for num_idx, col in enumerate(df.columns):
if col[1] == '@':
question = col[1]
else:
question = col[0]
if not question in test_dict: test_dict[question] = {}
number = all_num[num_idx]
letter = col[1]
test_dict[question][number] = letter
letter_df = self._replace_test_results(df, test_dict, char_repr)
# Re-apply indexing & finalize the new crossbreak column header
if display_level:
levels = self._siglevel_on_row()
index = df.index.get_level_values(1).tolist()
for i, l in levels:
index[i] = '#Level: {}'.format(l)
l0 = df.index.get_level_values(0).tolist()[0]
tuples = [(l0, i) for i in index]
index = pd.MultiIndex.from_tuples(
tuples, names=['Question', 'Values'])
letter_df.index = index
else:
letter_df.index = df.index
letter_df.columns = number_header_row
letter_df = self._apply_letter_header(letter_df)
self._frame = letter_df
return self
def _remove_letter_header(self):
self._frame.columns = self._frame.columns.droplevel(level=-1)
return None
def _apply_letter_header(self, df):
"""
"""
new_tuples = []
org_names = [n for n in df.columns.names]
idx = df.columns
for i, l in zip(idx, self.sig_test_letters):
new_tuples.append(i + (l, ))
if not 'Test-IDs' in org_names:
org_names.append('Test-IDs')
mi = pd.MultiIndex.from_tuples(new_tuples, names=org_names)
df.columns = mi
return df
def _extract_base_descriptions(self):
"""
"""
if self.source == 'Crunch multitable':
self.base_descriptions = self._meta['var_meta'].get('notes', None)
else:
base_texts = OrderedDict()
arr_style = self.array_style
if arr_style != -1:
var = self._x_keys[0] if arr_style == 0 else self._y_keys[0]
masks = self._meta['masks']
columns = self._meta['columns']
item = masks[var]['items'][0]['source'].split('@')[-1]
test_item = columns[item]
test_mask = masks[var]
if 'properties' in test_mask:
base_text = test_mask['properties'].get('base_text', None)
elif 'properties' in test_item:
base_text = test_item['properties'].get('base_text', None)
else:
base_text = None
self.base_descriptions = base_text
else:
for x in self._x_keys:
if 'properties' in self._meta['columns'][x]:
bt = self._meta['columns'][x]['properties'].get('base_text', None)
if bt:
base_texts[x] = bt
if base_texts:
if self.orientation == 'x':
self.base_descriptions = list(base_texts.values())[0]
else:
self.base_descriptions = list(base_texts.values())
return None
def _ensure_indexes(self):
if self.painted:
self._frame.index, self._frame.columns = self.index, self.columns
if self.structure is not None:
self._frame.loc[:, :] = self.frame_values
else:
self.index, self.columns = self._frame.index, self._frame.columns
if self.structure is not None:
self.frame_values = self._frame.values
def _finish_text_key(self, text_key, text_loc_x, text_loc_y):
text_keys = dict()
text_key = text_key or self._default_text
if text_loc_x:
text_keys['x'] = (text_loc_x, text_key)
else:
text_keys['x'] = text_key
if text_loc_y:
text_keys['y'] = (text_loc_y, text_key)
else:
text_keys['y'] = text_key
return text_keys
def paint(self, text_key=None, text_loc_x=None, text_loc_y=None, display=None,
axes=None, view_level=False, transform_tests='upper', display_level=True,
add_test_ids=True, add_base_texts='simple', totalize=False,
sep=None, na_rep=None, transform_column_names=None,
exclude_mask_text=False):
"""
Apply labels, sig. testing conversion and other post-processing to the
``Chain.dataframe`` property.
Use this to prepare a ``Chain`` for further usage in an Excel or Power-
point Build.
Parameters
----------
text_keys : str, default None
Text
text_loc_x : str, default None
The key in the 'text' to locate the text_key for the x-axis
text_loc_y : str, default None
The key in the 'text' to locate the text_key for the y-axis
display : {'x', 'y', ['x', 'y']}, default None
Text
axes : {'x', 'y', ['x', 'y']}, default None
Text
view_level : bool, default False
Text
transform_tests : {False, 'upper', 'lower', 'alternate'}, default 'upper'
Text
add_test_ids : bool, default True
Text
add_base_texts : {False, 'all', 'simple', 'simple-no-items'}, default 'simple'
Whether or not to include existing ``.base_descriptions`` str
to the label of the appropriate base view. Selecting ``'simple'``
will inject the base texts to non-array type Chains only.
totalize : bool, default True
Text
sep : str, default None
The seperator used for painting ``pandas.DataFrame`` columns
na_rep : str, default None
numpy.NaN will be replaced with na_rep if passed
transform_column_names : dict, default None
Transformed column_names are added to the labeltexts.
exclude_mask_text : bool, default False
Exclude mask text from mask-item texts.
Returns
-------
None
The ``.dataframe`` is modified inplace.
"""
self._ensure_indexes()
text_keys = self._finish_text_key(text_key, text_loc_x, text_loc_y)
if self.structure is not None:
self._paint_structure(text_key, sep=sep, na_rep=na_rep)
else:
self.totalize = totalize
if transform_tests: self.transform_tests(transform_tests, display_level)
# Remove any letter header row from transformed tests...
if self.sig_test_letters:
self._remove_letter_header()
if display is None:
display = _AXES
if axes is None:
axes = _AXES
self._paint(text_keys, display, axes, add_base_texts,
transform_column_names, exclude_mask_text)
# Re-build the full column index (labels + letter row)
if self.sig_test_letters and add_test_ids:
self._frame = self._apply_letter_header(self._frame)
if view_level:
self._add_view_level()
self.painted = True
return None
def _paint_structure(self, text_key=None, sep=None, na_rep=None):
""" Paint the dataframe-type Chain.
"""
if not text_key:
text_key = self._meta['lib']['default text']
str_format = '%%s%s%%s' % sep
column_mapper = dict()
na_rep = na_rep or ''
pattern = r'\, (?=\W|$)'
for column in self.structure.columns:
if not column in self._meta['columns']: continue
meta = self._meta['columns'][column]
if sep:
column_mapper[column] = str_format % (column, meta['text'][text_key])
else:
column_mapper[column] = meta['text'][text_key]
if meta.get('values'):
values = meta['values']
if isinstance(values, str):
pointers = values.split('@')
values = self._meta[pointers.pop(0)]
while pointers:
values = values[pointers.pop(0)]
if meta['type'] == 'delimited set':
value_mapper = {
str(item['value']): item['text'][text_key]
for item in values
}
series = self.structure[column]
try:
series = (series.str.split(';')
.apply(pd.Series, 1)
.stack(dropna=False)
.map(value_mapper.get) #, na_action='ignore')
.unstack())
first = series[series.columns[0]]
rest = [series[c] for c in series.columns[1:]]
self.structure[column] = (
first
.str.cat(rest, sep=', ', na_rep='')
.str.slice(0, -2)
.replace(to_replace=pattern, value='', regex=True)
.replace(to_replace='', value=na_rep)
)
except AttributeError:
continue
else:
value_mapper = {
item['value']: item['text'][text_key]
for item in values
}
self.structure[column] = (self.structure[column]
.map(value_mapper.get,
na_action='ignore')
)
self.structure[column].fillna(na_rep, inplace=True)
self.structure.rename(columns=column_mapper, inplace=True)
def _paint(self, text_keys, display, axes, bases, transform_column_names,
exclude_mask_text):
""" Paint the Chain.dataframe
"""
indexes = []
for axis in _AXES:
index = self._index_switch(axis)
if axis in axes:
index = self._paint_index(index, text_keys, display, axis,
bases, transform_column_names,
exclude_mask_text)
indexes.append(index)
self._frame.index, self._frame.columns = indexes
def _paint_index(self, index, text_keys, display, axis, bases,
transform_column_names, exclude_mask_text):
""" Paint the Chain.dataframe.index1 """
error = "No text keys from {} found in {}"
level_0_text, level_1_text = [], []
nlevels = index.nlevels
if nlevels > 2:
arrays = []
for i in range(0, nlevels, 2):
index_0 = index.get_level_values(i)
index_1 = index.get_level_values(i+1)
tuples = list(zip(index_0.values, index_1.values))
names = (index_0.name, index_1.name)
sub = pd.MultiIndex.from_tuples(tuples, names=names)
sub = self._paint_index(sub, text_keys, display, axis, bases,
transform_column_names, exclude_mask_text)
arrays.extend(self._lzip(sub.ravel()))
tuples = self._lzip(arrays)
return pd.MultiIndex.from_tuples(tuples, names=index.names)
levels = self._lzip(index.values)
arrays = (self._get_level_0(levels[0], text_keys, display, axis,
transform_column_names, exclude_mask_text),
self._get_level_1(levels, text_keys, display, axis, bases))
new_index = pd.MultiIndex.from_arrays(arrays, names=index.names)
return new_index
def _get_level_0(self, level, text_keys, display, axis,
transform_column_names, exclude_mask_text):
"""
"""
level_0_text = []
for value in level:
if str(value).startswith('#pad'):
pass
elif pd.notnull(value):
if value in list(self._text_map.keys()):
value = self._text_map[value]
else:
text = self._get_text(value, text_keys[axis], exclude_mask_text)
if axis in display:
if transform_column_names:
value = transform_column_names.get(value, value)
value = '{}. {}'.format(value, text)
else:
value = text
level_0_text.append(value)
if '@' in self._y_keys and self.totalize and axis == 'y':
level_0_text = ['Total'] + level_0_text[1:]
return list(map(str, level_0_text))
def _get_level_1(self, levels, text_keys, display, axis, bases):
"""
"""
level_1_text = []
if text_keys[axis] in self._transl:
tk_transl = text_keys[axis]
else:
tk_transl = self._default_text
c_text = copy.deepcopy(self._custom_texts) if self._custom_texts else {}
for i, value in enumerate(levels[1]):
if str(value).startswith('#pad'):
level_1_text.append(value)
elif pd.isnull(value):
level_1_text.append(value)
elif str(value) == '':
level_1_text.append(value)
elif str(value).startswith('#Level: '):
level_1_text.append(value.replace('#Level: ', ''))
else:
translate = list(self._transl[list(self._transl.keys())[0]].keys())
if value in list(self._text_map.keys()) and value not in translate:
level_1_text.append(self._text_map[value])
elif value in translate:
if value == 'All':
text = self._specify_base(i, text_keys[axis], bases)
else:
text = self._transl[tk_transl][value]
if value in c_text:
add_text = c_text[value].pop(0)
text = '{} {}'.format(text, add_text)
level_1_text.append(text)
elif value == 'All (eff.)':
text = self._specify_base(i, text_keys[axis], bases)
level_1_text.append(text)
else:
if any(self.array_style == a and axis == x for a, x in ((0, 'x'), (1, 'y'))):
text = self._get_text(value, text_keys[axis], True)
level_1_text.append(text)
else:
try:
values = self._get_values(levels[0][i])
if not values:
level_1_text.append(value)
else:
for item in self._get_values(levels[0][i]):
if int(value) == item['value']:
text = self._get_text(item, text_keys[axis])
level_1_text.append(text)
except (ValueError, UnboundLocalError):
if self._grp_text_map:
for gtm in self._grp_text_map:
if value in list(gtm.keys()):
text = self._get_text(gtm[value], text_keys[axis])
level_1_text.append(text)
return list(map(str, level_1_text))
@staticmethod
def _unwgt_label(views, base_vk):
valid = ['cbase', 'cbase_gross', 'rbase', 'ebase']
basetype = base_vk.split('|')[-1]
views_split = [v.split('|') for v in views]
multibase = len([v for v in views_split if v[-1] == basetype]) > 1
weighted = base_vk.split('|')[-2]
w_diff = len([v for v in views_split
if not v[-1] in valid and not v[-2] == weighted]) > 0
if weighted:
return False
elif multibase or w_diff:
return True
else:
return False
def _add_base_text(self, base_val, tk, bases):
if self._array_style == 0 and bases != 'all':
return base_val
else:
bt = self.base_descriptions
if isinstance(bt, dict):
bt_by_key = bt[tk]
else:
bt_by_key = bt
if bt_by_key:
if bt_by_key.startswith('%s:' % base_val):
bt_by_key = bt_by_key.replace('%s:' % base_val, '')
return '{}: {}'.format(base_val, bt_by_key)
else:
return base_val
def _specify_base(self, view_idx, tk, bases):
tk_transl = tk if tk in self._transl else self._default_text
base_vk = self._valid_views()[view_idx]
basetype = base_vk.split('|')[-1]
unwgt_label = self._unwgt_label(list(self._views.keys()), base_vk)
if unwgt_label:
if basetype == 'cbase_gross':
base_value = self._transl[tk_transl]['no_w_gross_All']
elif basetype == 'ebase':
base_value = 'Unweighted effective base'
else:
base_value = self._transl[tk_transl]['no_w_All']
else:
if basetype == 'cbase_gross':
base_value = self._transl[tk_transl]['gross All']
elif basetype == 'ebase':
base_value = 'Effective base'
elif not bases or (bases == 'simple-no-items' and self._is_mask_item):
base_value = self._transl[tk_transl]['All']
else:
key = tk
if isinstance(tk, tuple):
_, key = tk
base_value = self._add_base_text(self._transl[tk_transl]['All'],
key, bases)
return base_value
def _get_text(self, value, text_key, item_text=False):
"""
"""
if value in list(self._meta['columns'].keys()):
col = self._meta['columns'][value]
if item_text and col.get('parent'):
parent = list(col['parent'].keys())[0].split('@')[-1]
items = self._meta['masks'][parent]['items']
for i in items:
if i['source'].split('@')[-1] == value:
obj = i['text']
break
else:
obj = col['text']
elif value in list(self._meta['masks'].keys()):
obj = self._meta['masks'][value]['text']
elif 'text' in value:
obj = value['text']
else:
obj = value
return self._get_text_from_key(obj, text_key)
def _get_text_from_key(self, text, text_key):
""" Find the first value in a meta object's "text" key that matches a
text_key for it's axis.
"""
if isinstance(text_key, tuple):
loc, key = text_key
if loc in text:
if key in text[loc]:
return text[loc][key]
elif self._default_text in text[loc]:
return text[loc][self._default_text]
if key in text:
return text[key]
for key in (text_key, self._default_text):
if key in text:
return text[key]
return '<label>'
def _get_values(self, column):
""" Returns values from self._meta["columns"] or
self._meta["lib"]["values"][<mask name>] if parent is "array"
"""
if column in self._meta['columns']:
values = self._meta['columns'][column].get('values', [])
elif column in self._meta['masks']:
values = self._meta['lib']['values'].get(column, [])
if isinstance(values, str):
keys = values.split('@')
values = self._meta[keys.pop(0)]
while keys:
values = values[keys.pop(0)]
return values
def _add_view_level(self, shorten=False):
""" Insert a third Index level containing View keys into the DataFrame.
"""
vnames = self._views_per_rows()
if shorten:
vnames = [v.split('|')[-1] for v in vnames]
self._frame['View'] = pd.Series(vnames, index=self._frame.index)
self._frame.set_index('View', append=True, inplace=True)
def toggle_labels(self):
""" Restore the unpainted/ painted Index, Columns appearance.
"""
if self.painted:
self.painted = False
else:
self.painted = True
attrs = ['index', 'columns']
if self.structure is not None:
attrs.append('_frame_values')
for attr in attrs:
vals = attr[6:] if attr.startswith('_frame') else attr
frame_val = getattr(self._frame, vals)
setattr(self._frame, attr, getattr(self, attr))
setattr(self, attr, frame_val)
if self.structure is not None:
values = self._frame.values
self._frame.loc[:, :] = self.frame_values
self.frame_values = values
return self
@staticmethod
def _single_column(*levels):
""" Returns True if multiindex level 0 has one unique value
"""
return all(len(level) == 1 for level in levels)
def _group_views(self, frame, group_type):
""" Re-sort rows so that they appear as being grouped inside the
Chain.dataframe.
"""
grouped_frame = []
len_of_frame = len(frame)
frame = pd.concat(frame, axis=0)
index_order = frame.index.get_level_values(1).tolist()
index_order = index_order[:int(len(index_order) / len_of_frame)]
gb_df = frame.groupby(level=1, sort=False)
for i in index_order:
grouped_df = gb_df.get_group(i)
if group_type == 'reduced':
grouped_df = self._reduce_grouped_index(grouped_df, len_of_frame-1)
grouped_frame.append(grouped_df)
grouped_frame = pd.concat(grouped_frame, verify_integrity=False)
return grouped_frame
@staticmethod
def _reduce_grouped_index(grouped_df, view_padding, array_summary=-1):
idx = grouped_df.index
q = idx.get_level_values(0).tolist()[0]
if array_summary == 0:
val = idx.get_level_values(1).tolist()
for index in range(1, len(val), 2):
val[index] = ''
grp_vals = val
elif array_summary == 1:
grp_vals = []
indexed = []
val = idx.get_level_values(1).tolist()
for v in val:
if not v in indexed or v == 'All':
grp_vals.append(v)
indexed.append(v)
else:
grp_vals.append('')
else:
val = idx.get_level_values(1).tolist()[0]
grp_vals = [val] + [''] * view_padding
mi = pd.MultiIndex.from_product([[q], grp_vals], names=idx.names)
grouped_df.index = mi
return grouped_df
@staticmethod
def _lzip(arr):
"""
"""
return list(zip(*arr))
@staticmethod
def _force_list(obj):
if isinstance(obj, (list, tuple)):
return obj
return [obj]
@classmethod
def __pad_id(cls):
cls._pad_id += 1
return cls._pad_id
# class MTDChain(Chain):
# def __init__(self, mtd_doc, name=None):
# super(MTDChain, self).__init__(stack=None, name=name, structure=None)
# self.mtd_doc = mtd_doc
# self.source = 'Dimensions MTD'
self.get = self._get
# def _get(self, ignore=None, labels=True):
# per_folder = OrderedDict()
# failed = []
# unsupported = []
# for name, tab_def in self.mtd_doc.items():
# try:
# if isinstance(tab_def.values()[0], dict):
# unsupported.append(name)
# else:
# tabs = split_tab(tab_def)
# chain_dfs = []
# for tab in tabs:
# df, meta = tab[0], tab[1]
# # SOME DFs HAVE TOO MANY / UNUSED LEVELS...
# if len(df.columns.levels) > 2:
# df.columns = df.columns.droplevel(0)
# x, y = _get_axis_vars(df)
# df.replace('-', np.NaN, inplace=True)
# relabel_axes(df, meta, labels=labels)
# df = df.drop('Base', axis=1, level=1)
# try:
# df = df.applymap(lambda x: float(x.replace(',', '.')
# if isinstance(x, (str, unicode)) else x))
# except:
# msg = "Could not convert df values to float for table '{}'!"
# # warnings.warn(msg.format(name))
# chain_dfs.append(to_chain((df, x, y), meta))
# per_folder[name] = chain_dfs
# except:
# failed.append(name)
# print 'Conversion failed for:\n{}\n'.format(failed)
# print 'Subfolder conversion unsupported for:\n{}'.format(unsupported)
# return per_folder
##############################################################################
class Quantity(object):
"""
The Quantity object is the main Quantipy aggregation engine.
Consists of a link's data matrix representation and sectional defintion
of weight vector (wv), x-codes section (xsect) and y-codes section
(ysect). The instance methods handle creation, retrieval and manipulation
of the data input matrices and section definitions as well as the majority
of statistical calculations.
"""
# -------------------------------------------------
# Instance initialization
# -------------------------------------------------
def __init__(self, link, weight=None, use_meta=False, base_all=False):
# Collect information on wv, x- and y-section
self._uses_meta = use_meta
self.ds = self._convert_to_dataset(link)
self.d = self._data
self.base_all = base_all
self._dataidx = link.get_data().index
if self._uses_meta:
self.meta = self._meta
if list(self.meta().values()) == [None] * len(list(self.meta().values())):
self._uses_meta = False
self.meta = None
else:
self.meta = None
self._cache = link.get_cache()
self.f = link.filter
self.x = link.x
self.y = link.y
self.w = weight if weight is not None else '@1'
self.is_weighted = False
self.type = self._get_type()
if self.type == 'nested':
self.nest_def = Nest(self.y, self.d(), self.meta()).nest()
self._squeezed = False
self.idx_map = None
self.xdef = self.ydef = None
self.matrix = self._get_matrix()
self.is_empty = self.matrix.sum() == 0
self.switched = False
self.factorized = None
self.result = None
self.logical_conditions = []
self.cbase = self.rbase = None
self.comb_x = self.comb_y = None
self.miss_x = self.miss_y = None
self.calc_x = self.calc_y = None
self._has_x_margin = self._has_y_margin = False
def __repr__(self):
if self.result is not None:
return '%s' % (self.result)
else:
return 'Quantity - x: {}, xdef: {} y: {}, ydef: {}, w: {}'.format(
self.x, self.xdef, self.y, self.ydef, self.w)
# -------------------------------------------------
# Matrix creation and retrievel
# -------------------------------------------------
def _convert_to_dataset(self, link):
ds = qp.DataSet('')
ds._data = link.stack[link.data_key].data
ds._meta = link.get_meta()
return ds
def _data(self):
return self.ds._data
def _meta(self):
return self.ds._meta
def _get_type(self):
"""
Test variable type that can be "simple", "nested" or "array".
"""
if self._uses_meta:
masks = [self.x, self.y]
if any(mask in list(self.meta()['masks'].keys()) for mask in masks):
mask = {
True: self.x,
False: self.y}.get(self.x in list(self.meta()['masks'].keys()))
if self.meta()['masks'][mask]['type'] == 'array':
if self.x == '@':
self.x, self.y = self.y, self.x
return 'array'
elif '>' in self.y:
return 'nested'
else:
return 'simple'
else:
return 'simple'
def _is_multicode_array(self, mask_element):
return (
self.d()[mask_element].dtype == 'str'
)
def _get_wv(self):
"""
Returns the weight vector of the matrix.
"""
return self.d()[[self.w]].values
def weight(self):
"""
Weight by multiplying the indicator entries with the weight vector.
"""
self.matrix *= np.atleast_3d(self.wv)
# if self.is_weighted:
# self.matrix[:, 1:, 1:] *= np.atleast_3d(self.wv)
# else:
# self.matrix *= np.atleast_3d(self.wv)
# self.is_weighted = True
return None
def unweight(self):
"""
Remove any weighting by dividing the matrix by itself.
"""
self.matrix /= self.matrix
# self.matrix[:, 1:, 1:] /= self.matrix[:, 1:, 1:]
# self.is_weighted = False
return None
def _get_total(self):
"""
Return a vector of 1s for the matrix.
"""
return self.d()[['@1']].values
def _copy(self):
"""
Copy the Quantity instance, i.e. its data matrix, into a new object.
"""
m_copy = np.empty_like(self.matrix)
m_copy[:] = self.matrix
c = copy.copy(self)
c.matrix = m_copy
return c
def _get_response_codes(self, var):
"""
Query the meta specified codes values for a meta-using Quantity.
"""
if self.type == 'array':
rescodes = [v['value'] for v in self.meta()['lib']['values'][var]]
else:
values = emulate_meta(
self.meta(), self.meta()['columns'][var].get('values', None))
rescodes = [v['value'] for v in values]
return rescodes
def _get_response_texts(self, var, text_key=None):
"""
Query the meta specified text values for a meta-using Quantity.
"""
if text_key is None: text_key = 'main'
if self.type == 'array':
restexts = [v[text_key] for v in self.meta()['lib']['values'][var]]
else:
values = emulate_meta(
self.meta(), self.meta()['columns'][var].get('values', None))
restexts = [v['text'][text_key] for v in values]
return restexts
def _switch_axes(self):
"""
"""
if self.switched:
self.switched = False
self.matrix = self.matrix.swapaxes(1, 2)
else:
self.switched = True
self.matrix = self.matrix.swapaxes(2, 1)
self.xdef, self.ydef = self.ydef, self.xdef
self._x_indexers, self._y_indexers = self._y_indexers, self._x_indexers
self.comb_x, self.comb_y = self.comb_y, self.comb_x
self.miss_x, self.miss_y = self.miss_y, self.miss_x
return self
def _reset(self):
for prop in list(self.__dict__.keys()):
if prop in ['_uses_meta', 'base_all', '_dataidx', 'meta', '_cache',
'd', 'idx_map']:
pass
elif prop in ['_squeezed', 'switched']:
self.__dict__[prop] = False
else:
self.__dict__[prop] = None
self.result = None
return None
def swap(self, var, axis='x', inplace=True):
"""
Change the Quantity's x- or y-axis keeping filter and weight setup.
All edits and aggregation results will be removed during the swap.
Parameters
----------
var : str
New variable's name used in axis swap.
axis : {'x', 'y'}, default ``'x'``
The axis to swap.
inplace : bool, default ``True``
Whether to modify the Quantity inplace or return a new instance.
Returns
-------
swapped : New Quantity instance with exchanged x- or y-axis.
"""
if axis == 'x':
x = var
y = self.y
else:
x = self.x
y = var
f, w = self.f, self.w
if inplace:
swapped = self
else:
swapped = self._copy()
swapped._reset()
swapped.x, swapped.y = x, y
swapped.f, swapped.w = f, w
swapped.type = swapped._get_type()
swapped._get_matrix()
if not inplace:
return swapped
def rescale(self, scaling, drop=False):
"""
Modify the object's ``xdef`` property reflecting new value defintions.
Parameters
----------
scaling : dict
Mapping of old_code: new_code, given as of type int or float.
drop : bool, default False
If True, codes not included in the scaling dict will be excluded.
Returns
-------
self
"""
proper_scaling = {old_code: new_code for old_code, new_code
in list(scaling.items()) if old_code in self.xdef}
xdef_ref = [proper_scaling[code] if code in list(proper_scaling.keys())
else code for code in self.xdef]
if drop:
to_drop = [code for code in self.xdef if code not in
list(proper_scaling.keys())]
self.exclude(to_drop, axis='x')
self.xdef = xdef_ref
return self
def exclude(self, codes, axis='x'):
"""
Wrapper for _missingfy(...keep_codes=False, ..., keep_base=False, ...)
Excludes specified codes from aggregation.
"""
self._missingfy(codes, axis=axis, keep_base=False, inplace=True)
return self
def limit(self, codes, axis='x'):
"""
Wrapper for _missingfy(...keep_codes=True, ..., keep_base=True, ...)
Restrict the data matrix entires to contain the specified codes only.
"""
self._missingfy(codes, axis=axis, keep_codes=True, keep_base=True,
inplace=True)
return self
def filter(self, condition, keep_base=True, inplace=False):
"""
Use a Quantipy conditional expression to filter the data matrix entires.
"""
if inplace:
filtered = self
else:
filtered = self._copy()
qualified_rows = self._get_logic_qualifiers(condition)
valid_rows = self.idx_map[self.idx_map[:, 0] == 1][:, 1]
filter_idx = np.in1d(valid_rows, qualified_rows)
if keep_base:
filtered.matrix[~filter_idx, 1:, :] = np.NaN
else:
filtered.matrix[~filter_idx, :, :] = np.NaN
if not inplace:
return filtered
def _get_logic_qualifiers(self, condition):
if not isinstance(condition, dict):
column = self.x
logic = condition
else:
column = list(condition.keys())[0]
logic = list(condition.values())[0]
idx, logical_expression = get_logic_index(self.d()[column], logic, self.d())
logical_expression = logical_expression.split(':')[0]
if not column == self.x:
logical_expression = logical_expression.replace('x[', column+'[')
self.logical_conditions.append(logical_expression)
return idx
def _missingfy(self, codes, axis='x', keep_codes=False, keep_base=True,
indices=False, inplace=True):
"""
Clean matrix from entries preserving or modifying the weight vector.
Parameters
----------
codes : list
A list of codes to be considered in cleaning.
axis : {'x', 'y'}, default 'x'
The axis to clean codes on. Refers to the Link object's x- and y-
axes.
keep_codes : bool, default False
Controls whether the passed codes are kept or erased from the
Quantity matrix data entries.
keep_base: bool, default True
Controls whether the weight vector is set to np.NaN alongside
the x-section rows or remains unmodified.
indices: bool, default False
If ``True``, the data matrix indicies of the corresponding codes
will be returned as well.
inplace : bool, default True
Will overwrite self.matrix with the missingfied matrix by default.
If ``False``, the method will return a new np.array with the
modified entries.
Returns
-------
self or numpy.array (and optionally a list of int when ``indices=True``)
Either a new matrix is returned as numpy.array or the ``matrix``
property is modified inplace.
"""
if inplace:
missingfied = self
else:
missingfied = self._copy()
if axis == 'y' and self.y == '@' and not self.type == 'array':
return self
elif axis == 'y' and self.type == 'array':
ni_err = 'Cannot missingfy array mask element sections!'
raise NotImplementedError(ni_err)
else:
if axis == 'y':
missingfied._switch_axes()
mis_ix = missingfied._get_drop_idx(codes, keep_codes)
mis_ix = [code + 1 for code in mis_ix]
if mis_ix is not None:
for ix in mis_ix:
np.place(missingfied.matrix[:, ix],
missingfied.matrix[:, ix] > 0, np.NaN)
if not keep_base:
if axis == 'x':
self.miss_x = codes
else:
self.miss_y = codes
if self.type == 'array':
mask = np.nansum(missingfied.matrix[:, missingfied._x_indexers],
axis=1, keepdims=True)
mask /= mask
mask = mask > 0
else:
mask = np.nansum(np.sum(missingfied.matrix,
axis=1, keepdims=False),
axis=1, keepdims=True) > 0
missingfied.matrix[~mask] = np.NaN
if axis == 'y':
missingfied._switch_axes()
if inplace:
self.matrix = missingfied.matrix
if indices:
return mis_ix
else:
if indices:
return missingfied, mis_ix
else:
return missingfied
def _organize_global_missings(self, missings):
hidden = [c for c in list(missings.keys()) if missings[c] == 'hidden']
excluded = [c for c in list(missings.keys()) if missings[c] == 'excluded']
shown = [c for c in list(missings.keys()) if missings[c] == 'shown']
return hidden, excluded, shown
def _organize_stats_missings(self, missings):
excluded = [c for c in list(missings.keys())
if missings[c] in ['d.excluded', 'excluded']]
return excluded
def _autodrop_stats_missings(self):
if self.x == '@':
pass
elif self.ds._has_missings(self.x):
missings = self.ds._get_missings(self.x)
to_drop = self._organize_stats_missings(missings)
self.exclude(to_drop)
else:
pass
return None
def _clean_from_global_missings(self):
if self.x == '@':
pass
elif self.ds._has_missings(self.x):
missings = self.ds._get_missings(self.x)
hidden, excluded, shown = self._organize_global_missings(missings)
if excluded:
excluded_codes = excluded
excluded_idxer = self._missingfy(excluded, keep_base=False,
indices=True)
else:
excluded_codes, excluded_idxer = [], []
if hidden:
hidden_codes = hidden
hidden_idxer = self._get_drop_idx(hidden, keep=False)
hidden_idxer = [code + 1 for code in hidden_idxer]
else:
hidden_codes, hidden_idxer = [], []
dropped_codes = excluded_codes + hidden_codes
dropped_codes_idxer = excluded_idxer + hidden_idxer
self._x_indexers = [x_idx for x_idx in self._x_indexers
if x_idx not in dropped_codes_idxer]
self.matrix = self.matrix[:, [0] + self._x_indexers]
self.xdef = [x_c for x_c in self.xdef if x_c not in dropped_codes]
else:
pass
return None
def _get_drop_idx(self, codes, keep):
"""
Produces a list of indices referring to the given input matrix's axes
sections in order to erase data entries.
Parameters
----------
codes : list
Data codes that should be dropped from or kept in the matrix.
keep : boolean
Controls if the the passed code defintion is interpreted as
"codes to keep" or "codes to drop".
Returns
-------
drop_idx : list
List of x section matrix indices.
"""
if codes is None:
return None
else:
if keep:
return [self.xdef.index(code) for code in self.xdef
if code not in codes]
else:
return [self.xdef.index(code) for code in codes
if code in self.xdef]
def group(self, groups, axis='x', expand=None, complete=False):
"""
Build simple or logical net vectors, optionally keeping orginating codes.
Parameters
----------
groups : list, dict of lists or logic expression
The group/net code defintion(s) in form of...
* a simple list: ``[1, 2, 3]``
* a dict of list: ``{'grp A': [1, 2, 3], 'grp B': [4, 5, 6]}``
* a logical expression: ``not_any([1, 2])``
axis : {``'x'``, ``'y'``}, default ``'x'``
The axis to group codes on.
expand : {None, ``'before'``, ``'after'``}, default ``None``
If ``'before'``, the codes that are grouped will be kept and placed
before the grouped aggregation; vice versa for ``'after'``. Ignored
on logical expressions found in ``groups``.
complete : bool, default False
If True, codes that define the Link on the given ``axis`` but are
not present in the ``groups`` defintion(s) will be placed in their
natural position within the aggregation, respecting the value of
``expand``.
Returns
-------
None
"""
# check validity and clean combine instructions
if axis == 'y' and self.type == 'array':
ni_err_array = 'Array mask element sections cannot be combined.'
raise NotImplementedError(ni_err_array)
elif axis == 'y' and self.y == '@':
val_err = 'Total link has no y-axis codes to combine.'
raise ValueError(val_err)
grp_def = self._organize_grp_def(groups, expand, complete, axis)
combines = []
names = []
# generate the net vectors (+ possible expanded originating codes)
for grp in grp_def:
name, group, exp, logical = grp[0], grp[1], grp[2], grp[3]
one_code = len(group) == 1
if one_code and not logical:
vec = self._slice_vec(group[0], axis=axis)
elif not logical and not one_code:
vec, idx = self._grp_vec(group, axis=axis)
else:
vec = self._logic_vec(group)
if axis == 'y':
self._switch_axes()
if exp is not None:
m_idx = [ix for ix in self._x_indexers if ix not in idx]
m_idx = self._sort_indexer_as_codes(m_idx, group)
if exp == 'after':
names.extend(name)
names.extend([c for c in group])
combines.append(
np.concatenate([vec, self.matrix[:, m_idx]], axis=1))
else:
names.extend([c for c in group])
names.extend(name)
combines.append(
np.concatenate([self.matrix[:, m_idx], vec], axis=1))
else:
names.extend(name)
combines.append(vec)
if axis == 'y':
self._switch_axes()
# re-construct the combined data matrix
combines = np.concatenate(combines, axis=1)
if axis == 'y':
self._switch_axes()
combined_matrix = np.concatenate([self.matrix[:, [0]],
combines], axis=1)
if axis == 'y':
combined_matrix = combined_matrix.swapaxes(1, 2)
self._switch_axes()
# update the sectional information
new_sect_def = list(range(0, combined_matrix.shape[1] - 1))
if axis == 'x':
self.xdef = new_sect_def
self._x_indexers = self._get_x_indexers()
self.comb_x = names
else:
self.ydef = new_sect_def
self._y_indexers = self._get_y_indexers()
self.comb_y = names
self.matrix = combined_matrix
def _slice_vec(self, code, axis='x'):
'''
'''
if axis == 'x':
code_idx = self.xdef.index(code) + 1
else:
code_idx = self.ydef.index(code) + 1
if axis == 'x':
m_slice = self.matrix[:, [code_idx]]
else:
self._switch_axes()
m_slice = self.matrix[:, [code_idx]]
self._switch_axes()
return m_slice
def _grp_vec(self, codes, axis='x'):
netted, idx = self._missingfy(codes=codes, axis=axis,
keep_codes=True, keep_base=True,
indices=True, inplace=False)
if axis == 'y':
netted._switch_axes()
net_vec = np.nansum(netted.matrix[:, netted._x_indexers],
axis=1, keepdims=True)
net_vec /= net_vec
return net_vec, idx
def _logic_vec(self, condition):
"""
Create net vector of qualified rows based on passed condition.
"""
filtered = self.filter(condition=condition, inplace=False)
net_vec = np.nansum(filtered.matrix[:, self._x_indexers], axis=1,
keepdims=True)
net_vec /= net_vec
return net_vec
def _grp_type(self, grp_def):
if isinstance(grp_def, list):
if not isinstance(grp_def[0], (int, float)):
return 'block'
else:
return 'list'
elif isinstance(grp_def, tuple):
return 'logical'
elif isinstance(grp_def, dict):
return 'wildcard'
def _add_unused_codes(self, grp_def_list, axis):
'''
'''
query_codes = self.xdef if axis == 'x' else self.ydef
frame_lookup = {c: [[c], [c], None, False] for c in query_codes}
frame = [[code] for code in query_codes]
for grpdef_idx, grpdef in enumerate(grp_def_list):
for code in grpdef[1]:
if [code] in frame:
if grpdef not in frame:
frame[frame.index([code])] = grpdef
else:
frame[frame.index([code])] = '-'
frame = [code for code in frame if not code == '-']
for code in frame:
if code[0] in list(frame_lookup.keys()):
frame[frame.index([code[0]])] = frame_lookup[code[0]]
return frame
def _organize_grp_def(self, grp_def, method_expand, complete, axis):
"""
Sanitize a combine instruction list (of dicts): names, codes, expands.
"""
organized_def = []
codes_used = []
any_extensions = complete
any_logical = False
if method_expand is None and complete:
method_expand = 'before'
if not self._grp_type(grp_def) == 'block':
grp_def = [{'net': grp_def, 'expand': method_expand}]
for grp in grp_def:
if any(isinstance(val, (tuple, dict)) for val in list(grp.values())):
if complete:
ni_err = ('Logical expr. unsupported when complete=True. '
'Only list-type nets/groups can be completed.')
raise NotImplementedError(ni_err)
if 'expand' in list(grp.keys()):
del grp['expand']
expand = None
logical = True
else:
if 'expand' in list(grp.keys()):
grp = copy.deepcopy(grp)
expand = grp['expand']
if expand is None and complete:
expand = 'before'
del grp['expand']
else:
expand = method_expand
logical = False
organized_def.append([list(grp.keys()), list(grp.values())[0], expand, logical])
if expand:
any_extensions = True
if logical:
any_logical = True
codes_used.extend(list(grp.values())[0])
if not any_logical:
if len(set(codes_used)) != len(codes_used) and any_extensions:
ni_err_extensions = ('Same codes in multiple groups unsupported '
'with expand and/or complete =True.')
raise NotImplementedError(ni_err_extensions)
if complete:
return self._add_unused_codes(organized_def, axis)
else:
return organized_def
def _force_to_nparray(self):
"""
Convert the aggregation result into its numpy array equivalent.
"""
if isinstance(self.result, pd.DataFrame):
self.result = self.result.values
return True
else:
return False
def _attach_margins(self):
"""
Force margins back into the current Quantity.result if none are found.
"""
if not self._res_is_stat():
values = self.result
if not self._has_y_margin and not self.y == '@':
margins = False
values = np.concatenate([self.rbase[1:, :], values], 1)
else:
margins = True
if not self._has_x_margin:
margins = False
values = np.concatenate([self.cbase, values], 0)
else:
margins = True
self.result = values
return margins
else:
return False
def _organize_expr_def(self, expression, axis):
"""
"""
# Prepare expression parts and lookups for indexing the agg. result
val1, op, val2 = expression[0], expression[1], expression[2]
if self._res_is_stat():
idx_c = [self.current_agg]
offset = 0
else:
if axis == 'x':
idx_c = self.xdef if not self.comb_x else self.comb_x
else:
idx_c = self.ydef if not self.comb_y else self.comb_y
offset = 1
# Test expression validity and find np.array indices / prepare scalar
# values of the expression
idx_err = '"{}" not found in {}-axis.'
# [1] input is 1. scalar, 2. vector from the agg. result
if isinstance(val1, list):
if not val2 in idx_c:
raise IndexError(idx_err.format(val2, axis))
val1 = val1[0]
val2 = idx_c.index(val2) + offset
expr_type = 'scalar_1'
# [2] input is 1. vector from the agg. result, 2. scalar
elif isinstance(val2, list):
if not val1 in idx_c:
raise IndexError(idx_err.format(val1, axis))
val1 = idx_c.index(val1) + offset
val2 = val2[0]
expr_type = 'scalar_2'
# [3] input is two vectors from the agg. result
elif not any(isinstance(val, list) for val in [val1, val2]):
if not val1 in idx_c:
raise IndexError(idx_err.format(val1, axis))
if not val2 in idx_c:
raise IndexError(idx_err.format(val2, axis))
val1 = idx_c.index(val1) + offset
val2 = idx_c.index(val2) + offset
expr_type = 'vectors'
return val1, op, val2, expr_type, idx_c
@staticmethod
def constant(num):
return [num]
def calc(self, expression, axis='x', result_only=False):
"""
Compute (simple) aggregation level arithmetics.
"""
unsupported = ['cbase', 'rbase', 'summary', 'x_sum', 'y_sum']
if self.result is None:
raise ValueError('No aggregation to base calculation on.')
elif self.current_agg in unsupported:
ni_err = 'Aggregation type "{}" not supported.'
raise NotImplementedError(ni_err.format(self.current_agg))
elif axis not in ['x', 'y']:
raise ValueError('Invalid axis parameter: {}'.format(axis))
is_df = self._force_to_nparray()
has_margin = self._attach_margins()
values = self.result
expr_name = list(expression.keys())[0]
if axis == 'x':
self.calc_x = expr_name
else:
self.calc_y = expr_name
values = values.T
expr = list(expression.values())[0]
v1, op, v2, exp_type, index_codes = self._organize_expr_def(expr, axis)
# ====================================================================
# TODO: generalize this calculation part so that it can "parse"
# arbitrary calculation rules given as nested or concatenated
# operators/codes sequences.
if exp_type == 'scalar_1':
val1, val2 = v1, values[[v2], :]
elif exp_type == 'scalar_2':
val1, val2 = values[[v1], :], v2
elif exp_type == 'vectors':
val1, val2 = values[[v1], :], values[[v2], :]
calc_res = op(val1, val2)
# ====================================================================
if axis == 'y':
calc_res = calc_res.T
ap_axis = 0 if axis == 'x' else 1
if result_only:
if not self._res_is_stat():
self.result = np.concatenate([self.result[[0], :], calc_res],
ap_axis)
else:
self.result = calc_res
else:
self.result = np.concatenate([self.result, calc_res], ap_axis)
if axis == 'x':
self.calc_x = index_codes + [self.calc_x]
else:
self.calc_y = index_codes + [self.calc_y]
self.cbase = self.result[[0], :]
if self.type in ['simple', 'nested']:
self.rbase = self.result[:, [0]]
else:
self.rbase = None
if not self._res_is_stat():
self.current_agg = 'calc'
self._organize_margins(has_margin)
else:
self.current_agg = 'calc'
if is_df:
self.to_df()
return self
def count(self, axis=None, raw_sum=False, margin=True, as_df=True):
"""
Count entries over all cells or per axis margin.
Parameters
----------
axis : {None, 'x', 'y'}, deafult None
When axis is None, the frequency of all cells from the uni- or
multivariate distribution is presented. If the axis is specified
to be either 'x' or 'y' the margin per axis becomes the resulting
aggregation.
raw_sum : bool, default False
If True will perform a simple summation over the cells given the
axis parameter. This ignores net counting of qualifying answers in
favour of summing over all answers given when considering margins.
margin : bool, deafult True
Controls whether the margins of the aggregation result are shown.
This also applies to margin aggregations themselves, since they
contain a margin in (form of the total number of cases) as well.
as_df : bool, default True
Controls whether the aggregation is transformed into a Quantipy-
multiindexed (following the Question/Values convention)
pandas.DataFrame or will be left in its numpy.array format.
Returns
-------
self
Passes a pandas.DataFrame or numpy.array of cell or margin counts
to the ``result`` property.
"""
if axis is None and raw_sum:
raise ValueError('Cannot calculate raw sum without axis.')
if axis is None:
self.current_agg = 'freq'
elif axis == 'x':
self.current_agg = 'cbase' if not raw_sum else 'x_sum'
elif axis == 'y':
self.current_agg = 'rbase' if not raw_sum else 'y_sum'
if not self.w == '@1':
self.weight()
if not self.is_empty or self._uses_meta:
counts = np.nansum(self.matrix, axis=0)
else:
counts = self._empty_result()
self.cbase = counts[[0], :]
if self.type in ['simple', 'nested']:
self.rbase = counts[:, [0]]
else:
self.rbase = None
if axis is None:
self.result = counts
elif axis == 'x':
if not raw_sum:
self.result = counts[[0], :]
else:
self.result = np.nansum(counts[1:, :], axis=0, keepdims=True)
elif axis == 'y':
if not raw_sum:
self.result = counts[:, [0]]
else:
if self.x == '@' or self.y == '@':
self.result = counts[:, [0]]
else:
self.result = np.nansum(counts[:, 1:], axis=1, keepdims=True)
self._organize_margins(margin)
if as_df:
self.to_df()
self.unweight()
return self
def _empty_result(self):
if self._res_is_stat() or self.current_agg == 'summary':
self.factorized = 'x'
xdim = 1 if self._res_is_stat() else 8
if self.ydef is None:
ydim = 1
elif self.ydef is not None and len(self.ydef) == 0:
ydim = 2
else:
ydim = len(self.ydef) + 1
else:
if self.xdef is not None:
if len(self.xdef) == 0:
xdim = 2
else:
xdim = len(self.xdef) + 1
if self.ydef is None:
ydim = 1
elif self.ydef is not None and len(self.ydef) == 0:
ydim = 2
else:
ydim = len(self.ydef) + 1
elif self.xdef is None:
xdim = 2
if self.ydef is None:
ydim = 1
elif self.ydef is not None and len(self.ydef) == 0:
ydim = 2
else:
ydim = len(self.ydef) + 1
return np.zeros((xdim, ydim))
def _effective_n(self, axis=None, margin=True):
self.weight()
effective = (np.nansum(self.matrix, axis=0)**2 /
np.nansum(self.matrix**2, axis=0))
self.unweight()
start_on = 0 if margin else 1
if axis is None:
return effective[start_on:, start_on:]
elif axis == 'x':
return effective[[0], start_on:]
else:
return effective[start_on:, [0]]
def summarize(self, stat='summary', axis='x', margin=True, as_df=True):
"""
Calculate distribution statistics across the given axis.
Parameters
----------
stat : {'summary', 'mean', 'median', 'var', 'stddev', 'sem', varcoeff',
'min', 'lower_q', 'upper_q', 'max'}, default 'summary'
The measure to calculate. Defaults to a summary output of the most
important sample statistics.
axis : {'x', 'y'}, default 'x'
The axis which is reduced in the aggregation, e.g. column vs. row
means.
margin : bool, default True
Controls whether statistic(s) of the marginal distribution are
shown.
as_df : bool, default True
Controls whether the aggregation is transformed into a Quantipy-
multiindexed (following the Question/Values convention)
pandas.DataFrame or will be left in its numpy.array format.
Returns
-------
self
Passes a pandas.DataFrame or numpy.array of the descriptive (summary)
statistic(s) to the ``result`` property.
"""
self.current_agg = stat
if self.is_empty:
self.result = self._empty_result()
else:
self._autodrop_stats_missings()
if stat == 'summary':
stddev, mean, base = self._dispersion(axis, measure='sd',
_return_mean=True,
_return_base=True)
self.result = np.concatenate([
base, mean, stddev,
self._min(axis),
self._percentile(perc=0.25),
self._percentile(perc=0.50),
self._percentile(perc=0.75),
self._max(axis)
], axis=0)
elif stat == 'mean':
self.result = self._means(axis)
elif stat == 'var':
self.result = self._dispersion(axis, measure='var')
elif stat == 'stddev':
self.result = self._dispersion(axis, measure='sd')
elif stat == 'sem':
self.result = self._dispersion(axis, measure='sem')
elif stat == 'varcoeff':
self.result = self._dispersion(axis, measure='varcoeff')
elif stat == 'min':
self.result = self._min(axis)
elif stat == 'lower_q':
self.result = self._percentile(perc=0.25)
elif stat == 'median':
self.result = self._percentile(perc=0.5)
elif stat == 'upper_q':
self.result = self._percentile(perc=0.75)
elif stat == 'max':
self.result = self._max(axis)
self._organize_margins(margin)
if as_df:
self.to_df()
return self
def _factorize(self, axis='x', inplace=True):
self.factorized = axis
if inplace:
factorized = self
else:
factorized = self._copy()
if axis == 'y':
factorized._switch_axes()
np.copyto(factorized.matrix[:, 1:, :],
np.atleast_3d(factorized.xdef),
where=factorized.matrix[:, 1:, :]>0)
if not inplace:
return factorized
def _means(self, axis, _return_base=False):
fact = self._factorize(axis=axis, inplace=False)
if not self.w == '@1':
fact.weight()
fact_prod = np.nansum(fact.matrix, axis=0)
fact_prod_sum = np.nansum(fact_prod[1:, :], axis=0, keepdims=True)
bases = fact_prod[[0], :]
means = fact_prod_sum/bases
if axis == 'y':
self._switch_axes()
means = means.T
bases = bases.T
if _return_base:
return means, bases
else:
return means
def _dispersion(self, axis='x', measure='sd', _return_mean=False,
_return_base=False):
"""
Extracts measures of dispersion from the incoming distribution of
X vs. Y. Can return the arithm. mean by request as well. Dispersion
measure supported are standard deviation, variance, coeffiecient of
variation and standard error of the mean.
"""
means, bases = self._means(axis, _return_base=True)
unbiased_n = bases - 1
self.unweight()
factorized = self._factorize(axis, inplace=False)
factorized.matrix[:, 1:] -= means
factorized.matrix[:, 1:] *= factorized.matrix[:, 1:, :]
if not self.w == '@1':
factorized.weight()
diff_sqrt = np.nansum(factorized.matrix[:, 1:], axis=1)
disp = np.nansum(diff_sqrt/unbiased_n, axis=0, keepdims=True)
disp[disp <= 0] = np.NaN
disp[np.isinf(disp)] = np.NaN
if measure == 'sd':
disp = np.sqrt(disp)
elif measure == 'sem':
disp = np.sqrt(disp) / np.sqrt((unbiased_n + 1))
elif measure == 'varcoeff':
disp = np.sqrt(disp) / means
self.unweight()
if _return_mean and _return_base:
return disp, means, bases
elif _return_mean:
return disp, means
elif _return_base:
return disp, bases
else:
return disp
def _max(self, axis='x'):
factorized = self._factorize(axis, inplace=False)
vals = np.nansum(factorized.matrix[:, 1:, :], axis=1)
return np.nanmax(vals, axis=0, keepdims=True)
def _min(self, axis='x'):
factorized = self._factorize(axis, inplace=False)
vals = np.nansum(factorized.matrix[:, 1:, :], axis=1)
if 0 not in factorized.xdef: np.place(vals, vals == 0, np.inf)
return np.nanmin(vals, axis=0, keepdims=True)
def _percentile(self, axis='x', perc=0.5):
"""
Computes percentiles from the incoming distribution of X vs.Y and the
requested percentile value. The implementation mirrors the algorithm
used in SPSS Dimensions and the EXAMINE procedure in SPSS Statistics.
It based on the percentile defintion #6 (adjusted for survey weights)
in:
Hyndman, <NAME>. and <NAME> (1996) -
"Sample Quantiles in Statistical Packages",
The American Statistician, 50, No. 4, 361-365.
Parameters
----------
axis : {'x', 'y'}, default 'x'
The axis which is reduced in the aggregation, i.e. column vs. row
medians.
perc : float, default 0.5
Defines the percentile to be computed. Defaults to 0.5,
the sample median.
Returns
-------
percs : np.array
Numpy array storing percentile values.
"""
percs = []
factorized = self._factorize(axis, inplace=False)
vals = np.nansum(np.nansum(factorized.matrix[:, 1:, :], axis=1,
keepdims=True), axis=1)
weights = (vals/vals)*self.wv
for shape_i in range(0, vals.shape[1]):
iter_weights = weights[:, shape_i]
iter_vals = vals[:, shape_i]
mask = ~np.isnan(iter_weights)
iter_weights = iter_weights[mask]
iter_vals = iter_vals[mask]
sorter = np.argsort(iter_vals)
iter_vals = np.take(iter_vals, sorter)
iter_weights = np.take(iter_weights, sorter)
iter_wsum = np.nansum(iter_weights, axis=0)
iter_wcsum = np.cumsum(iter_weights, axis=0)
k = (iter_wsum + 1.0) * perc
if iter_vals.shape[0] == 0:
percs.append(0.00)
elif iter_vals.shape[0] == 1:
percs.append(iter_vals[0])
elif iter_wcsum[0] > k:
wcsum_k = iter_wcsum[0]
percs.append(iter_vals[0])
elif iter_wcsum[-1] <= k:
percs.append(iter_vals[-1])
else:
wcsum_k = iter_wcsum[iter_wcsum <= k][-1]
p_k_idx = np.searchsorted(np.ndarray.flatten(iter_wcsum), wcsum_k)
p_k = iter_vals[p_k_idx]
p_k1 = iter_vals[p_k_idx+1]
w_k1 = iter_weights[p_k_idx+1]
excess = k - wcsum_k
if excess >= 1.0:
percs.append(p_k1)
else:
if w_k1 >= 1.0:
percs.append((1.0-excess)*p_k + excess*p_k1)
else:
percs.append((1.0-(excess/w_k1))*p_k +
(excess/w_k1)*p_k1)
return np.array(percs)[None, :]
def _organize_margins(self, margin):
if self._res_is_stat():
if self.type == 'array' or self.y == '@' or self.x == '@':
self._has_y_margin = self._has_x_margin = False
else:
if self.factorized == 'x':
if not margin:
self._has_x_margin = False
self._has_y_margin = False
self.result = self.result[:, 1:]
else:
self._has_x_margin = False
self._has_y_margin = True
else:
if not margin:
self._has_x_margin = False
self._has_y_margin = False
self.result = self.result[1:, :]
else:
self._has_x_margin = True
self._has_y_margin = False
if self._res_is_margin():
if self.y == '@' or self.x == '@':
if self.current_agg in ['cbase', 'x_sum']:
self._has_y_margin = self._has_x_margin = False
if self.current_agg in ['rbase', 'y_sum']:
if not margin:
self._has_y_margin = self._has_x_margin = False
self.result = self.result[1:, :]
else:
self._has_x_margin = True
self._has_y_margin = False
else:
if self.current_agg in ['cbase', 'x_sum']:
if not margin:
self._has_y_margin = self._has_x_margin = False
self.result = self.result[:, 1:]
else:
self._has_x_margin = False
self._has_y_margin = True
if self.current_agg in ['rbase', 'y_sum']:
if not margin:
self._has_y_margin = self._has_x_margin = False
self.result = self.result[1:, :]
else:
self._has_x_margin = True
self._has_y_margin = False
elif self.current_agg in ['freq', 'summary', 'calc']:
if self.type == 'array' or self.y == '@' or self.x == '@':
if not margin:
self.result = self.result[1:, :]
self._has_x_margin = False
self._has_y_margin = False
else:
self._has_x_margin = True
self._has_y_margin = False
else:
if not margin:
self.result = self.result[1:, 1:]
self._has_x_margin = False
self._has_y_margin = False
else:
self._has_x_margin = True
self._has_y_margin = True
else:
pass
def _sort_indexer_as_codes(self, indexer, codes):
mapping = sorted(zip(indexer, codes), key=lambda l: l[1])
return [i[0] for i in mapping]
def _get_y_indexers(self):
if self._squeezed or self.type in ['simple', 'nested']:
if self.ydef is not None:
idxs = list(range(1, len(self.ydef)+1))
return self._sort_indexer_as_codes(idxs, self.ydef)
else:
return [1]
else:
y_indexers = []
xdef_len = len(self.xdef)
zero_based_ys = [idx for idx in range(0, xdef_len)]
for y_no in range(0, len(self.ydef)):
if y_no == 0:
y_indexers.append(zero_based_ys)
else:
y_indexers.append([idx + y_no * xdef_len
for idx in zero_based_ys])
return y_indexers
def _get_x_indexers(self):
if self._squeezed or self.type in ['simple', 'nested']:
idxs = list(range(1, len(self.xdef)+1))
return self._sort_indexer_as_codes(idxs, self.xdef)
else:
x_indexers = []
upper_x_idx = len(self.ydef)
start_x_idx = [len(self.xdef) * offset
for offset in range(0, upper_x_idx)]
for x_no in range(0, len(self.xdef)):
x_indexers.append([idx + x_no for idx in start_x_idx])
return x_indexers
def _squeeze_dummies(self):
"""
Reshape and replace initial 2D dummy matrix into its 3D equivalent.
"""
self.wv = self.matrix[:, [-1]]
sects = []
if self.type == 'array':
x_sections = self._get_x_indexers()
y_sections = self._get_y_indexers()
y_total = np.nansum(self.matrix[:, x_sections], axis=1)
y_total /= y_total
y_total = y_total[:, None, :]
for sect in y_sections:
sect = self.matrix[:, sect]
sects.append(sect)
sects = np.dstack(sects)
self._squeezed = True
sects = np.concatenate([y_total, sects], axis=1)
self.matrix = sects
self._x_indexers = self._get_x_indexers()
self._y_indexers = []
elif self.type in ['simple', 'nested']:
x = self.matrix[:, :len(self.xdef)+1]
y = self.matrix[:, len(self.xdef)+1:-1]
for i in range(0, y.shape[1]):
sects.append(x * y[:, [i]])
sects = np.dstack(sects)
self._squeezed = True
self.matrix = sects
self._x_indexers = self._get_x_indexers()
self._y_indexers = self._get_y_indexers()
#=====================================================================
#THIS CAN SPEED UP PERFOMANCE BY A GOOD AMOUNT BUT STACK-SAVING
#TIME & SIZE WILL SUFFER. WE CAN DEL THE "SQUEEZED" COLLECTION AT
#SAVE STAGE.
#=====================================================================
# self._cache.set_obj(collection='squeezed',
# key=self.f+self.w+self.x+self.y,
# obj=(self.xdef, self.ydef,
# self._x_indexers, self._y_indexers,
# self.wv, self.matrix, self.idx_map))
def _get_matrix(self):
wv = self._cache.get_obj('weight_vectors', self.w)
if wv is None:
wv = self._get_wv()
self._cache.set_obj('weight_vectors', self.w, wv)
total = self._cache.get_obj('weight_vectors', '@1')
if total is None:
total = self._get_total()
self._cache.set_obj('weight_vectors', '@1', total)
if self.type == 'array':
xm, self.xdef, self.ydef = self._dummyfy()
self.matrix = np.concatenate((xm, wv), 1)
else:
if self.y == '@' or self.x == '@':
section = self.x if self.y == '@' else self.y
xm, self.xdef = self._cache.get_obj('matrices', section)
if xm is None:
xm, self.xdef = self._dummyfy(section)
self._cache.set_obj('matrices', section, (xm, self.xdef))
self.ydef = None
self.matrix = np.concatenate((total, xm, total, wv), 1)
else:
xm, self.xdef = self._cache.get_obj('matrices', self.x)
if xm is None:
xm, self.xdef = self._dummyfy(self.x)
self._cache.set_obj('matrices', self.x, (xm, self.xdef))
ym, self.ydef = self._cache.get_obj('matrices', self.y)
if ym is None:
ym, self.ydef = self._dummyfy(self.y)
self._cache.set_obj('matrices', self.y, (ym, self.ydef))
self.matrix = np.concatenate((total, xm, total, ym, wv), 1)
self.matrix = self.matrix[self._dataidx]
self.matrix = self._clean()
self._squeeze_dummies()
self._clean_from_global_missings()
return self.matrix
def _dummyfy(self, section=None):
if section is not None:
# i.e. Quantipy multicode data
if self.d()[section].dtype == 'str' or self.d()[section].dtype == 'object':
section_data = self.d()[section].astype('str').str.get_dummies(';')
if self._uses_meta:
res_codes = self._get_response_codes(section)
section_data.columns = [int(col) for col in section_data.columns]
section_data = section_data.reindex(columns=res_codes)
section_data.replace(np.NaN, 0, inplace=True)
if not self._uses_meta:
section_data.sort_index(axis=1, inplace=True)
# i.e. Quantipy single-coded/numerical data
else:
section_data = pd.get_dummies(self.d()[section])
if self._uses_meta and not self._is_raw_numeric(section):
res_codes = self._get_response_codes(section)
section_data = section_data.reindex(columns=res_codes)
section_data.replace(np.NaN, 0, inplace=True)
section_data.rename(
columns={
col: int(col)
if float(col).is_integer()
else col
for col in section_data.columns
},
inplace=True)
return section_data.values, section_data.columns.tolist()
elif section is None and self.type == 'array':
a_i = [i['source'].split('@')[-1] for i in
self.meta()['masks'][self.x]['items']]
a_res = self._get_response_codes(self.x)
dummies = []
if self._is_multicode_array(a_i[0]):
for i in a_i:
i_dummy = self.d()[i].str.get_dummies(';')
i_dummy.columns = [int(col) for col in i_dummy.columns]
dummies.append(i_dummy.reindex(columns=a_res))
else:
for i in a_i:
dummies.append(pd.get_dummies(self.d()[i]).reindex(columns=a_res))
a_data = pd.concat(dummies, axis=1)
return a_data.values, a_res, a_i
def _clean(self):
"""
Drop empty sectional rows from the matrix.
"""
mat = self.matrix.copy()
mat_indexer = np.expand_dims(self._dataidx, 1)
if not self.type == 'array':
xmask = (np.nansum(mat[:, 1:len(self.xdef)+1], axis=1) > 0)
if self.ydef is not None:
if self.base_all:
ymask = (np.nansum(mat[:, len(self.xdef)+1:-1], axis=1) > 0)
else:
ymask = (np.nansum(mat[:, len(self.xdef)+2:-1], axis=1) > 0)
self.idx_map = np.concatenate(
[np.expand_dims(xmask & ymask, 1), mat_indexer], axis=1)
return mat[xmask & ymask]
else:
self.idx_map = np.concatenate(
[np.expand_dims(xmask, 1), mat_indexer], axis=1)
return mat[xmask]
else:
mask = (np.nansum(mat[:, :-1], axis=1) > 0)
self.idx_map = np.concatenate(
[np.expand_dims(mask, 1), mat_indexer], axis=1)
return mat[mask]
def _is_raw_numeric(self, var):
return self.meta()['columns'][var]['type'] in ['int', 'float']
def _res_from_count(self):
return self._res_is_margin() or self.current_agg == 'freq'
def _res_from_summarize(self):
return self._res_is_stat() or self.current_agg == 'summary'
def _res_is_margin(self):
return self.current_agg in ['tbase', 'cbase', 'rbase', 'x_sum', 'y_sum']
def _res_is_stat(self):
return self.current_agg in ['mean', 'min', 'max', 'varcoeff', 'sem',
'stddev', 'var', 'median', 'upper_q',
'lower_q']
def to_df(self):
if self.current_agg == 'freq':
if not self.comb_x:
self.x_agg_vals = self.xdef
else:
self.x_agg_vals = self.comb_x
if not self.comb_y:
self.y_agg_vals = self.ydef
else:
self.y_agg_vals = self.comb_y
elif self.current_agg == 'calc':
if self.calc_x:
self.x_agg_vals = self.calc_x
self.y_agg_vals = self.ydef if not self.comb_y else self.comb_y
else:
self.x_agg_vals = self.xdef if not self.comb_x else self.comb_x
self.y_agg_vals = self.calc_y
elif self.current_agg == 'summary':
summary_vals = ['mean', 'stddev', 'min', '25%',
'median', '75%', 'max']
self.x_agg_vals = summary_vals
self.y_agg_vals = self.ydef
elif self.current_agg in ['x_sum', 'cbase']:
self.x_agg_vals = 'All' if self.current_agg == 'cbase' else 'sum'
self.y_agg_vals = self.ydef
elif self.current_agg in ['y_sum', 'rbase']:
self.x_agg_vals = self.xdef
self.y_agg_vals = 'All' if self.current_agg == 'rbase' else 'sum'
elif self._res_is_stat():
if self.factorized == 'x':
self.x_agg_vals = self.current_agg
self.y_agg_vals = self.ydef if not self.comb_y else self.comb_y
else:
self.x_agg_vals = self.xdef if not self.comb_x else self.comb_x
self.y_agg_vals = self.current_agg
# can this made smarter WITHOUT 1000000 IF-ELSEs above?:
if ((self.current_agg in ['freq', 'cbase', 'x_sum', 'summary', 'calc'] or
self._res_is_stat()) and not self.type == 'array'):
if self.y == '@' or self.x == '@':
self.y_agg_vals = '@'
df = pd.DataFrame(self.result)
idx, cols = self._make_multiindex()
df.index = idx
df.columns = cols
self.result = df if not self.x == '@' else df.T
if self.type == 'nested':
self._format_nested_axis()
return self
def _make_multiindex(self):
x_grps = self.x_agg_vals
y_grps = self.y_agg_vals
if not isinstance(x_grps, list):
x_grps = [x_grps]
if not isinstance(y_grps, list):
y_grps = [y_grps]
if not x_grps: x_grps = [None]
if not y_grps: y_grps = [None]
if self._has_x_margin:
x_grps = ['All'] + x_grps
if self._has_y_margin:
y_grps = ['All'] + y_grps
if self.type == 'array':
x_unit = y_unit = self.x
x_names = ['Question', 'Values']
y_names = ['Array', 'Questions']
else:
x_unit = self.x if not self.x == '@' else self.y
y_unit = self.y if not self.y == '@' else self.x
x_names = y_names = ['Question', 'Values']
x = [x_unit, x_grps]
y = [y_unit, y_grps]
index = pd.MultiIndex.from_product(x, names=x_names)
columns = pd.MultiIndex.from_product(y, names=y_names)
return index, columns
def _format_nested_axis(self):
nest_mi = self._make_nest_multiindex()
if not len(self.result.columns) > len(nest_mi.values):
self.result.columns = nest_mi
else:
total_mi_values = []
for var in self.nest_def['variables']:
total_mi_values += [var, -1]
total_mi = pd.MultiIndex.from_product(total_mi_values,
names=nest_mi.names)
full_nest_mi = nest_mi.union(total_mi)
for lvl, c in zip(list(range(1, len(full_nest_mi)+1, 2)),
self.nest_def['level_codes']):
full_nest_mi.set_levels(['All'] + c, level=lvl, inplace=True)
self.result.columns = full_nest_mi
return None
def _make_nest_multiindex(self):
values = []
names = ['Question', 'Values'] * (self.nest_def['levels'])
for lvl_var, lvl_c in zip(self.nest_def['variables'],
self.nest_def['level_codes']):
values.append(lvl_var)
values.append(lvl_c)
mi = pd.MultiIndex.from_product(values, names=names)
return mi
def normalize(self, on='y'):
"""
Convert a raw cell count result to its percentage representation.
Parameters
----------
on : {'y', 'x'}, default 'y'
Defines the base to normalize the result on. ``'y'`` will
produce column percentages, ``'x'`` will produce row
percentages.
Returns
-------
self
Updates an count-based aggregation in the ``result`` property.
"""
if self.x == '@':
on = 'y' if on == 'x' else 'x'
if on == 'y':
if self._has_y_margin or self.y == '@' or self.x == '@':
base = self.cbase
else:
if self._get_type() == 'array':
base = self.cbase
else:
base = self.cbase[:, 1:]
else:
if self._has_x_margin:
base = self.rbase
else:
base = self.rbase[1:, :]
if isinstance(self.result, pd.DataFrame):
if self.x == '@':
self.result = self.result.T
if on == 'y':
base = np.repeat(base, self.result.shape[0], axis=0)
else:
base = np.repeat(base, self.result.shape[1], axis=1)
self.result = self.result / base * 100
if self.x == '@':
self.result = self.result.T
return self
def rebase(self, reference, on='counts', overwrite_margins=True):
"""
"""
val_err = 'No frequency aggregation to rebase.'
if self.result is None:
raise ValueError(val_err)
elif self.current_agg != 'freq':
raise ValueError(val_err)
is_df = self._force_to_nparray()
has_margin = self._attach_margins()
ref = self.swap(var=reference, inplace=False)
if self._sects_identical(self.xdef, ref.xdef):
pass
elif self._sects_different_order(self.xdef, ref.xdef):
ref.xdef = self.xdef
ref._x_indexers = ref._get_x_indexers()
ref.matrix = ref.matrix[:, ref._x_indexers + [0]]
elif self._sect_is_subset(self.xdef, ref.xdef):
ref.xdef = [code for code in ref.xdef if code in self.xdef]
ref._x_indexers = ref._sort_indexer_as_codes(ref._x_indexers,
self.xdef)
ref.matrix = ref.matrix[:, [0] + ref._x_indexers]
else:
idx_err = 'Axis defintion is not a subset of rebase reference.'
raise IndexError(idx_err)
ref_freq = ref.count(as_df=False)
self.result = (self.result/ref_freq.result) * 100
if overwrite_margins:
self.rbase = ref_freq.rbase
self.cbase = ref_freq.cbase
self._organize_margins(has_margin)
if is_df: self.to_df()
return self
@staticmethod
def _sects_identical(axdef1, axdef2):
return axdef1 == axdef2
@staticmethod
def _sects_different_order(axdef1, axdef2):
if not len(axdef1) == len(axdef2):
return False
else:
if (x for x in axdef1 if x in axdef2):
return True
else:
return False
@staticmethod
def _sect_is_subset(axdef1, axdef2):
return set(axdef1).intersection(set(axdef2)) > 0
class Test(object):
"""
The Quantipy Test object is a defined by a Link and the view name notation
string of a counts or means view. All auxiliary figures needed to arrive
at the test results are computed inside the instance of the object.
"""
def __init__(self, link, view_name_notation, test_total=False):
super(Test, self).__init__()
# Infer whether a mean or proportion test is being performed
view = link[view_name_notation]
if view.meta()['agg']['method'] == 'descriptives':
self.metric = 'means'
else:
self.metric = 'proportions'
self.invalid = None
self.no_pairs = None
self.no_diffs = None
self.parameters = None
self.test_total = test_total
self.mimic = None
self.level = None
# Calculate the required baseline measures for the test using the
# Quantity instance
self.Quantity = qp.Quantity(link, view.weights(), use_meta=True,
base_all=self.test_total)
self._set_baseline_aggregates(view)
# Set information about the incoming aggregation
# to be able to route correctly through the algorithms
# and re-construct a Quantipy-indexed pd.DataFrame
self.is_weighted = view.meta()['agg']['is_weighted']
self.has_calc = view.has_calc()
self.x = view.meta()['x']['name']
self.xdef = view.dataframe.index.get_level_values(1).tolist()
self.y = view.meta()['y']['name']
self.ydef = view.dataframe.columns.get_level_values(1).tolist()
columns_to_pair = ['@'] + self.ydef if self.test_total else self.ydef
self.ypairs = list(combinations(columns_to_pair, 2))
self.y_is_multi = view.meta()['y']['is_multi']
self.multiindex = (view.dataframe.index, view.dataframe.columns)
def __repr__(self):
return ('%s, total included: %s, test metric: %s, parameters: %s, '
'mimicked: %s, level: %s ')\
% (Test, self.test_total, self.metric, self.parameters,
self.mimic, self.level)
def _set_baseline_aggregates(self, view):
"""
Derive or recompute the basic values required by the ``Test`` instance.
"""
grps, exp, compl, calc, exclude, rescale = view.get_edit_params()
if exclude is not None:
self.Quantity.exclude(exclude)
if self.metric == 'proportions' and self.test_total and view._has_code_expr():
self.Quantity.group(grps, expand=exp, complete=compl)
if self.metric == 'means':
aggs = self.Quantity._dispersion(_return_mean=True,
_return_base=True)
self.sd, self.values, self.cbases = aggs[0], aggs[1], aggs[2]
if not self.test_total:
self.sd = self.sd[:, 1:]
self.values = self.values[:, 1:]
self.cbases = self.cbases[:, 1:]
elif self.metric == 'proportions':
if not self.test_total:
self.values = view.dataframe.values.copy()
self.cbases = view.cbases[:, 1:]
self.rbases = view.rbases[1:, :]
self.tbase = view.cbases[0, 0]
else:
agg = self.Quantity.count(margin=True, as_df=False)
if calc is not None:
calc_only = view._kwargs.get('calc_only', False)
self.Quantity.calc(calc, axis='x', result_only=calc_only)
self.values = agg.result[1:, :]
self.cbases = agg.cbase
self.rbases = agg.rbase[1:, :]
self.tbase = agg.cbase[0, 0]
def set_params(self, test_total=False, level='mid', mimic='Dim', testtype='pooled',
use_ebase=True, ovlp_correc=True, cwi_filter=False,
flag_bases=None):
"""
Sets the test algorithm parameters and defines the type of test.
This method sets the test's global parameters and derives the
necessary measures for the computation of the test statistic.
The default values correspond to the SPSS Dimensions Column Tests
algorithms that control for bias introduced by weighting and
overlapping samples in the column pairs of multi-coded questions.
.. note:: The Dimensions implementation uses variance pooling.
Parameters
----------
test_total : bool, default False
If set to True, the test algorithms will also include an existent
total (@-) version of the original link and test against the
unconditial data distribution.
level : str or float, default 'mid'
The level of significance given either as per 'low' = 0.1,
'mid' = 0.05, 'high' = 0.01 or as specific float, e.g. 0.15.
mimic : {'askia', 'Dim'} default='Dim'
Will instruct the mimicking of a software specific test.
testtype : str, default 'pooled'
Global definition of the tests.
use_ebase : bool, default True
If True, will use the effective sample sizes instead of the
the simple weighted ones when testing a weighted aggregation.
ovlp_correc : bool, default True
If True, will consider and correct for respondent overlap when
testing between multi-coded column pairs.
cwi_filter : bool, default False
If True, will check an incoming count aggregation for cells that
fall below a treshhold comparison aggregation that assumes counts
to be independent.
flag_bases : list of two int, default None
If provided, the output dataframe will replace results that have
been calculated on (eff.) bases below the first int with ``'**'``
and mark results in columns with bases below the second int with
``'*'``
Returns
-------
self
"""
# Check if the aggregation is non-empty
# and that there are >1 populated columns
if np.nansum(self.values) == 0 or len(self.ydef) == 1:
self.invalid = True
if np.nansum(self.values) == 0:
self.no_diffs = True
if len(self.ydef) == 1:
self.no_pairs = True
self.mimic = mimic
self.comparevalue, self.level = self._convert_level(level)
else:
# Set global test algorithm parameters
self.invalid = False
self.no_diffs = False
self.no_pairs = False
valid_mimics = ['Dim', 'askia']
if mimic not in valid_mimics:
raise ValueError('Failed to mimic: "%s". Select from: %s\n'
% (mimic, valid_mimics))
else:
self.mimic = mimic
if self.mimic == 'askia':
self.parameters = {'testtype': 'unpooled',
'use_ebase': False,
'ovlp_correc': False,
'cwi_filter': True,
'base_flags': None}
self.test_total = False
elif self.mimic == 'Dim':
self.parameters = {'testtype': 'pooled',
'use_ebase': True,
'ovlp_correc': True,
'cwi_filter': False,
'base_flags': flag_bases}
self.level = level
self.comparevalue, self.level = self._convert_level(level)
# Get value differences between column pairings
if self.metric == 'means':
self.valdiffs = np.array(
[m1 - m2 for m1, m2 in combinations(self.values[0], 2)])
if self.metric == 'proportions':
# special to askia testing: counts-when-independent filtering
if cwi_filter:
self.values = self._cwi()
props = (self.values / self.cbases).T
self.valdiffs = np.array([p1 - p2 for p1, p2
in combinations(props, 2)]).T
# Set test specific measures for Dimensions-like testing:
# [1] effective base usage
if use_ebase and self.is_weighted:
if not self.test_total:
self.ebases = self.Quantity._effective_n(axis='x', margin=False)
else:
self.ebases = self.Quantity._effective_n(axis='x', margin=True)
else:
self.ebases = self.cbases
# [2] overlap correction
if self.y_is_multi and self.parameters['ovlp_correc']:
self.overlap = self._overlap()
else:
self.overlap = np.zeros(self.valdiffs.shape)
# [3] base flags
if flag_bases:
self.flags = {'min': flag_bases[0],
'small': flag_bases[1]}
self.flags['flagged_bases'] = self._get_base_flags()
else:
self.flags = None
return self
# -------------------------------------------------
# Main algorithm methods to compute test statistics
# -------------------------------------------------
def run(self):
"""
Performs the testing algorithm and creates an output pd.DataFrame.
The output is indexed according to Quantipy's Questions->Values
convention. Significant results between columns are presented as
lists of integer y-axis codes where the column with the higher value
is holding the codes of the columns with the lower values. NaN is
indicating that a cell is not holding any sig. higher values
compared to the others.
"""
if not self.invalid:
sigs = self.get_sig()
return self._output(sigs)
else:
return self._empty_output()
def get_sig(self):
"""
TODO: implement returning tstats only.
"""
stat = self.get_statistic()
stat = self._convert_statistic(stat)
if self.metric == 'means':
diffs = pd.DataFrame(self.valdiffs, index=self.ypairs, columns=self.xdef).T
elif self.metric == 'proportions':
stat = pd.DataFrame(stat, index=self.xdef, columns=self.ypairs)
diffs = pd.DataFrame(self.valdiffs, index=self.xdef, columns=self.ypairs)
if self.mimic == 'Dim':
return diffs[(diffs != 0) & (stat < self.comparevalue)]
elif self.mimic == 'askia':
return diffs[(diffs != 0) & (stat > self.comparevalue)]
def get_statistic(self):
"""
Returns the test statistic of the algorithm.
"""
return self.valdiffs / self.get_se()
def get_se(self):
"""
Compute the standard error (se) estimate of the tested metric.
The calculation of the se is defined by the parameters of the setup.
The main difference is the handling of variances. **unpooled**
implicitly assumes variance inhomogenity between the column pairing's
samples. **pooled** treats variances effectively as equal.
"""
if self.metric == 'means':
if self.parameters['testtype'] == 'unpooled':
return self._se_mean_unpooled()
elif self.parameters['testtype'] == 'pooled':
return self._se_mean_pooled()
elif self.metric == 'proportions':
if self.parameters['testtype'] == 'unpooled':
return self._se_prop_unpooled()
if self.parameters['testtype'] == 'pooled':
return self._se_prop_pooled()
# -------------------------------------------------
# Conversion methods for levels and statistics
# -------------------------------------------------
def _convert_statistic(self, teststat):
"""
Convert test statistics to match the decision rule of the test logic.
Either transforms to p-values or returns the absolute value of the
statistic, depending on the decision rule of the test.
This is used to mimic other software packages as some tests'
decision rules check test-statistic against pre-defined treshholds
while others check sig. level against p-value.
"""
if self.mimic == 'Dim':
ebases_pairs = [eb1 + eb2 for eb1, eb2
in combinations(self.ebases[0], 2)]
dof = ebases_pairs - self.overlap - 2
dof[dof <= 1] = np.NaN
return get_pval(dof, teststat)[1]
elif self.mimic == 'askia':
return abs(teststat)
def _convert_level(self, level):
"""
Determines the comparison value for the test's decision rule.
Checks whether the level of test is a string that defines low, medium,
or high significance or an "actual" level of significance and
converts it to a comparison level/significance level tuple.
This is used to mimic other software packages as some test's
decision rules check test-statistic against pre-defined treshholds
while others check sig. level against p-value.
"""
if isinstance(level, str):
if level == 'low':
if self.mimic == 'Dim':
comparevalue = siglevel = 0.10
elif self.mimic == 'askia':
comparevalue = 1.65
siglevel = 0.10
elif level == 'mid':
if self.mimic == 'Dim':
comparevalue = siglevel = 0.05
elif self.mimic == 'askia':
comparevalue = 1.96
siglevel = 0.05
elif level == 'high':
if self.mimic == 'Dim':
comparevalue = siglevel = 0.01
elif self.mimic == 'askia':
comparevalue = 2.576
siglevel = 0.01
else:
if self.mimic == 'Dim':
comparevalue = siglevel = level
elif self.mimic == 'askia':
comparevalue = 1.65
siglevel = 0.10
return comparevalue, siglevel
# -------------------------------------------------
# Standard error estimates calculation methods
# -------------------------------------------------
def _se_prop_unpooled(self):
"""
Estimated standard errors of prop. diff. (unpool. var.) per col. pair.
"""
props = self.values/self.cbases
unp_sd = ((props*(1-props))/self.cbases).T
return np.array([np.sqrt(cat1 + cat2)
for cat1, cat2 in combinations(unp_sd, 2)]).T
def _se_mean_unpooled(self):
"""
Estimated standard errors of mean diff. (unpool. var.) per col. pair.
"""
sd_base_ratio = self.sd / self.cbases
return np.array([np.sqrt(sd_b_r1 + sd_b_r2)
for sd_b_r1, sd_b_r2
in combinations(sd_base_ratio[0], 2)])[None, :]
def _se_prop_pooled(self):
"""
Estimated standard errors of prop. diff. (pooled var.) per col. pair.
Controlling for effective base sizes and overlap responses is
supported and applied as defined by the test's parameters setup.
"""
ebases_correc_pairs = np.array([1 / x + 1 / y
for x, y
in combinations(self.ebases[0], 2)])
if self.y_is_multi and self.parameters['ovlp_correc']:
ovlp_correc_pairs = ((2 * self.overlap) /
[x * y for x, y
in combinations(self.ebases[0], 2)])
else:
ovlp_correc_pairs = self.overlap
counts_sum_pairs = np.array(
[c1 + c2 for c1, c2 in combinations(self.values.T, 2)])
bases_sum_pairs = np.expand_dims(
[b1 + b2 for b1, b2 in combinations(self.cbases[0], 2)], 1)
pooled_props = (counts_sum_pairs/bases_sum_pairs).T
return (np.sqrt(pooled_props * (1 - pooled_props) *
(np.array(ebases_correc_pairs - ovlp_correc_pairs))))
def _se_mean_pooled(self):
"""
Estimated standard errors of mean diff. (pooled var.) per col. pair.
Controlling for effective base sizes and overlap responses is
supported and applied as defined by the test's parameters setup.
"""
ssw_base_ratios = self._sum_sq_w(base_ratio=True)
enum = np.nan_to_num((self.sd ** 2) * (self.cbases-1))
denom = self.cbases-ssw_base_ratios
enum_pairs = np.array([enum1 + enum2
for enum1, enum2
in combinations(enum[0], 2)])
denom_pairs = np.array([denom1 + denom2
for denom1, denom2
in combinations(denom[0], 2)])
ebases_correc_pairs = np.array([1/x + 1/y
for x, y
in combinations(self.ebases[0], 2)])
if self.y_is_multi and self.parameters['ovlp_correc']:
ovlp_correc_pairs = ((2*self.overlap) /
[x * y for x, y
in combinations(self.ebases[0], 2)])
else:
ovlp_correc_pairs = self.overlap[None, :]
return (np.sqrt((enum_pairs/denom_pairs) *
(ebases_correc_pairs - ovlp_correc_pairs)))
# -------------------------------------------------
# Specific algorithm values & test option measures
# -------------------------------------------------
def _sum_sq_w(self, base_ratio=True):
"""
"""
if not self.Quantity.w == '@1':
self.Quantity.weight()
if not self.test_total:
ssw = np.nansum(self.Quantity.matrix ** 2, axis=0)[[0], 1:]
else:
ssw = np.nansum(self.Quantity.matrix ** 2, axis=0)[[0], :]
if base_ratio:
return ssw/self.cbases
else:
return ssw
def _cwi(self, threshold=5, as_df=False):
"""
Derives the count distribution assuming independence between columns.
"""
c_col_n = self.cbases
c_cell_n = self.values
t_col_n = self.tbase
if self.rbases.shape[1] > 1:
t_cell_n = self.rbases[1:, :]
else:
t_cell_n = self.rbases[0]
np.place(t_col_n, t_col_n == 0, np.NaN)
np.place(t_cell_n, t_cell_n == 0, np.NaN)
np.place(c_col_n, c_col_n == 0, np.NaN)
np.place(c_cell_n, c_cell_n == 0, np.NaN)
cwi = (t_cell_n * c_col_n) / t_col_n
cwi[cwi < threshold] = np.NaN
if as_df:
return pd.DataFrame(c_cell_n + cwi - cwi,
index=self.xdef, columns=self.ydef)
else:
return c_cell_n + cwi - cwi
def _overlap(self):
if self.is_weighted:
self.Quantity.weight()
m = self.Quantity.matrix.copy()
m = np.nansum(m, 1) if self.test_total else np.nansum(m[:, 1:, 1:], 1)
if not self.is_weighted:
m /= m
m[m == 0] = np.NaN
col_pairs = list(combinations(list(range(0, m.shape[1])), 2))
if self.parameters['use_ebase'] and self.is_weighted:
# Overlap computation when effective base is being used
w_sum_sq = np.array([np.nansum(m[:, [c1]] + m[:, [c2]], axis=0)**2
for c1, c2 in col_pairs])
w_sq_sum = np.array([np.nansum(m[:, [c1]]**2 + m[:, [c2]]**2, axis=0)
for c1, c2 in col_pairs])
return np.nan_to_num((w_sum_sq/w_sq_sum)/2).T
else:
# Overlap with simple weighted/unweighted base size
ovlp = np.array([np.nansum(m[:, [c1]] + m[:, [c2]], axis=0)
for c1, c2 in col_pairs])
return (np.nan_to_num(ovlp)/2).T
def _get_base_flags(self):
bases = self.ebases[0]
small = self.flags['small']
minimum = self.flags['min']
flags = []
for base in bases:
if base >= small:
flags.append('')
elif base < small and base >= minimum:
flags.append('*')
else:
flags.append('**')
return flags
# -------------------------------------------------
# Output creation
# -------------------------------------------------
def _output(self, sigs):
res = {y: {x: [] for x in self.xdef} for y in self.ydef}
test_columns = ['@'] + self.ydef if self.test_total else self.ydef
for col, val in sigs.items():
if self._flags_exist():
b1ix, b2ix = test_columns.index(col[0]), test_columns.index(col[1])
b1_ok = self.flags['flagged_bases'][b1ix] != '**'
b2_ok = self.flags['flagged_bases'][b2ix] != '**'
else:
b1_ok, b2_ok = True, True
for row, v in val.items():
if v > 0:
if b2_ok:
if col[0] == '@':
res[col[1]][row].append('@H')
else:
res[col[0]][row].append(col[1])
if v < 0:
if b1_ok:
if col[0] == '@':
res[col[1]][row].append('@L')
else:
res[col[1]][row].append(col[0])
test = pd.DataFrame(res).applymap(lambda x: str(x))
test = test.reindex(index=self.xdef, columns=self.ydef)
if self._flags_exist():
test = self._apply_base_flags(test)
test.replace('[]*', '*', inplace=True)
test.replace('[]', np.NaN, inplace=True)
# removing test results on post-aggregation rows [calc()]
if self.has_calc:
if len(test.index) > 1:
test.iloc[-1:, :] = np.NaN
else:
test.iloc[:, :] = np.NaN
test.index, test.columns = self.multiindex[0], self.multiindex[1]
return test
def _empty_output(self):
"""
"""
values = self.values
if self.metric == 'proportions':
if self.no_pairs or self.no_diffs:
values[:] = np.NaN
if values.shape == (1, 1) or values.shape == (1, 0):
values = [np.NaN]
if self.metric == 'means':
if self.no_pairs:
values = [np.NaN]
if self.no_diffs and not self.no_pairs:
values[:] = np.NaN
return pd.DataFrame(values,
index=self.multiindex[0],
columns=self.multiindex[1])
def _flags_exist(self):
return (self.flags is not None and
not all(self.flags['flagged_bases']) == '')
def _apply_base_flags(self, sigres, replace=True):
flags = self.flags['flagged_bases']
if self.test_total: flags = flags[1:]
for res_col, flag in zip(sigres.columns, flags):
if flag == '**':
if replace:
sigres[res_col] = flag
else:
sigres[res_col] = sigres[res_col] + flag
elif flag == '*':
sigres[res_col] = sigres[res_col] + flag
return sigres
class Nest(object):
"""
Description of class...
"""
def __init__(self, nest, data, meta):
self.data = data
self.meta = meta
self.name = nest
self.variables = nest.split('>')
self.levels = len(self.variables)
self.level_codes = []
self.code_maps = None
self._needs_multi = self._any_multicoded()
def nest(self):
self._get_nested_meta()
self._get_code_maps()
interlocked = self._interlock_codes()
if not self.name in self.data.columns:
recode_map = {code: intersection(code_pair) for code, code_pair
in enumerate(interlocked, start=1)}
self.data[self.name] = np.NaN
self.data[self.name] = recode(self.meta, self.data,
target=self.name, mapper=recode_map)
nest_info = {'variables': self.variables,
'level_codes': self.level_codes,
'levels': self.levels}
return nest_info
def _any_multicoded(self):
return any(self.data[self.variables].dtypes == 'str')
def _get_code_maps(self):
code_maps = []
for level, var in enumerate(self.variables):
mapping = [{var: [int(code)]} for code
in self.level_codes[level]]
code_maps.append(mapping)
self.code_maps = code_maps
return None
def _interlock_codes(self):
return list(product(*self.code_maps))
def _get_nested_meta(self):
meta_dict = {}
qtext, valtexts = self._interlock_texts()
meta_dict['type'] = 'delimited set' if self._needs_multi else 'single'
meta_dict['text'] = {'en-GB': '>'.join(qtext[0])}
meta_dict['values'] = [{'text' : {'en-GB': '>'.join(valtext)},
'value': c}
for c, valtext
in enumerate(valtexts, start=1)]
self.meta['columns'][self.name] = meta_dict
return None
def _interlock_texts(self):
all_valtexts = []
all_qtexts = []
for var in self.variables:
var_valtexts = []
values = self.meta['columns'][var]['values']
all_qtexts.append(list(self.meta['columns'][var]['text'].values()))
for value in values:
var_valtexts.append(list(value['text'].values())[0])
all_valtexts.append(var_valtexts)
self.level_codes.append([code['value'] for code in values])
interlocked_valtexts = list(product(*all_valtexts))
interlocked_qtexts = list(product(*all_qtexts))
return interlocked_qtexts, interlocked_valtexts
##############################################################################
class Multivariate(object):
def __init__(self):
pass
def _select_variables(self, x, y=None, w=None, drop_listwise=False):
x_vars, y_vars = [], []
if not isinstance(x, list): x = [x]
if not isinstance(y, list) and not y=='@': y = [y]
if w is None: w = '@1'
wrong_var_sel_1_on_1 = 'Can only analyze 1-to-1 relationships.'
if self.analysis == 'Reduction' and (not (len(x) == 1 and len(y) == 1) or y=='@'):
raise AttributeError(wrong_var_sel_1_on_1)
for var in x:
if self.ds._is_array(var):
if self.analysis == 'Reduction': raise AttributeError(wrong_var_sel_1_on_1)
x_a_items = self.ds._get_itemmap(var, non_mapped='items')
x_vars += x_a_items
else:
x_vars.append(var)
if y and not y == '@':
for var in y:
if self.ds._is_array(var):
if self.analysis == 'Reduction': raise AttributeError(wrong_var_sel_1_on_1)
y_a_items = self.ds._get_itemmap(var, non_mapped='items')
y_vars += y_a_items
else:
y_vars.append(var)
elif y == '@':
y_vars = x_vars
if x_vars == y_vars or y is None:
data_slice = x_vars + [w]
else:
data_slice = x_vars + y_vars + [w]
if self.analysis == 'Relations' and y != '@':
self.x = self.y = x_vars + y_vars
self._org_x, self._org_y = x_vars, y_vars
else:
self.x = self._org_x = x_vars
self.y = self._org_y = y_vars
self.w = w
self._analysisdata = self.ds[data_slice]
self._drop_missings()
if drop_listwise:
self._analysisdata.dropna(inplace=True)
valid = self._analysisdata.index
self.ds._data = self.ds._data.loc[valid, :]
return None
def _drop_missings(self):
data = self._analysisdata.copy()
for var in data.columns:
if self.ds._has_missings(var):
drop = self.ds._get_missing_list(var, globally=False)
data[var].replace(drop, np.NaN, inplace=True)
self._analysisdata = data
return None
def _has_analysis_data(self):
if not hasattr(self, '_analysisdata'):
raise AttributeError('No analysis variables assigned!')
def _has_yvar(self):
if self.y is None:
raise AttributeError('Must select at least one y-variable or '
'"@"-matrix indicator!')
def _get_quantities(self, create='all'):
crossed_quantities = []
single_quantities = []
helper_stack = qp.Stack()
helper_stack.add_data(self.ds.name, self.ds._data, self.ds._meta)
w = self.w if self.w != '@1' else None
for x, y in product(self.x, self.y):
helper_stack.add_link(x=x, y=y)
l = helper_stack[self.ds.name]['no_filter'][x][y]
crossed_quantities.append(qp.Quantity(l, weight=w))
for x in self._org_x+self._org_y:
helper_stack.add_link(x=x, y='@')
l = helper_stack[self.ds.name]['no_filter'][x]['@']
single_quantities.append(qp.Quantity(l, weight=w))
self.single_quantities = single_quantities
self.crossed_quantities = crossed_quantities
return None
class Reductions(Multivariate):
def __init__(self, dataset):
self.ds = dataset
self.single_quantities = None
self.crossed_quantities = None
self.analysis = 'Reduction'
def plot(self, type, point_coords):
plt.set_autoscale_on = False
plt.figure(figsize=(5, 5))
plt.xlim([-1, 1])
plt.ylim([-1, 1])
#plt.axvline(x=0.0, c='grey', ls='solid', linewidth=0.9)
#plt.axhline(y=0.0, c='grey', ls='solid', linewidth=0.9)
x = plt.scatter(point_coords['x'][0], point_coords['x'][1],
edgecolor='w', marker='o', c='red', s=20)
y = plt.scatter(point_coords['y'][0], point_coords['y'][1],
edgecolor='k', marker='^', c='lightgrey', s=20)
fig = x.get_figure()
# print fig.get_axes()[0].grid()
fig.get_axes()[0].tick_params(labelsize=6)
fig.get_axes()[0].patch.set_facecolor('w')
fig.get_axes()[0].grid(which='major', linestyle='solid', color='grey',
linewidth=0.6)
fig.get_axes()[0].xaxis.get_major_ticks()[0].label1.set_visible(False)
x0 = fig.get_axes()[0].get_position().x0
y0 = fig.get_axes()[0].get_position().y0
x1 = fig.get_axes()[0].get_position().x1
y1 = fig.get_axes()[0].get_position().y1
text = 'Correspondence map'
plt.figtext(x0+0.015, 1.09-y0, text, fontsize=12, color='w',
fontweight='bold', verticalalignment='top',
bbox={'facecolor':'red', 'alpha': 0.8, 'edgecolor': 'w',
'pad': 10})
label_map = self._get_point_label_map('CA', point_coords)
for axis in list(label_map.keys()):
for lab, coord in list(label_map[axis].items()):
plt.annotate(lab, coord, ha='left', va='bottom',
fontsize=6)
plt.legend((x, y), (self.x[0], self.y[0]),
loc='best', bbox_to_anchor=(1.325, 1.07),
ncol=2, fontsize=6, title=' ')
x_codes, x_texts = self.ds._get_valuemap(self.x[0], non_mapped='lists')
y_codes, y_texts = self.ds._get_valuemap(self.y[0], non_mapped='lists')
text = ' '*80
for var in zip(x_codes, x_texts):
text += '\n{}: {}\n'.format(var[0], var[1])
fig.text(1.06-x0, 0.85, text, fontsize=5, verticalalignment='top',
bbox={'facecolor':'red',
'edgecolor': 'w', 'pad': 10})
x_len = len(x_codes)
text = ' '*80
for var in zip(y_codes, y_texts):
text += '\n{}: {}\n'.format(var[0], var[1])
test = fig.text(1.06-x0, 0.85-((x_len)*0.0155)-((x_len)*0.0155)-0.05, text, fontsize=5, verticalalignment='top',
bbox={'facecolor': 'lightgrey', 'alpha': 0.65,
'edgecolor': 'w', 'pad': 10})
logo = Image.open('C:/Users/alt/Documents/IPython Notebooks/Designs/Multivariate class/__resources__/YG_logo.png')
newax = fig.add_axes([x0+0.005, y0-0.25, 0.1, 0.1], anchor='NE', zorder=-1)
newax.imshow(logo)
newax.axis('off')
fig.savefig(self.ds.path + 'correspond.png', bbox_inches='tight', dpi=300)
def correspondence(self, x, y, w=None, norm='sym', diags=True, plot=True):
"""
Perform a (multiple) correspondence analysis.
Parameters
----------
norm : {'sym', 'princ'}, default 'sym'
<DESCP>
summary : bool, default True
If True, the output will contain a dataframe that summarizes core
information about the Inertia decomposition.
plot : bool, default False
If set to True, a correspondence map plot will be saved in the
Stack's data path location.
Returns
-------
results: pd.DataFrame
Summary of analysis results.
"""
self._select_variables(x, y, w)
self._get_quantities()
# 1. Chi^2 analysis
obs, exp = self.expected_counts(x=x, y=y, return_observed=True)
chisq, sig = self.chi_sq(x=x, y=y, sig=True)
inertia = chisq / np.nansum(obs)
# 2. svd on standardized residuals
std_residuals = ((obs - exp) / np.sqrt(exp)) / np.sqrt(np.nansum(obs))
sv, row_eigen_mat, col_eigen_mat, ev = self._svd(std_residuals)
# 3. row and column coordinates
a = 0.5 if norm == 'sym' else 1.0
row_mass = self.mass(x=x, y=y, margin='x')
col_mass = self.mass(x=x, y=y, margin='y')
dim = min(row_mass.shape[0]-1, col_mass.shape[0]-1)
row_sc = (row_eigen_mat * sv[:, 0] ** a) / np.sqrt(row_mass)
col_sc = (col_eigen_mat.T * sv[:, 0] ** a) / np.sqrt(col_mass)
if plot:
# prep coordinates for plot
item_sep = len(self.single_quantities[0].xdef)
dim1_c = [r_s[0] for r_s in row_sc] + [c_s[0] for c_s in col_sc]
# dim2_c = [r_s[1]*(-1) for r_s in row_sc] + [c_s[1]*(-1) for c_s in col_sc]
dim2_c = [r_s[1] for r_s in row_sc] + [c_s[1] for c_s in col_sc]
dim1_xitem, dim2_xitem = dim1_c[:item_sep], dim2_c[:item_sep]
dim1_yitem, dim2_yitem = dim1_c[item_sep:], dim2_c[item_sep:]
coords = {'x': [dim1_xitem, dim2_xitem],
'y': [dim1_yitem, dim2_yitem]}
self.plot('CA', coords)
plt.show()
if diags:
_dim = range(1, dim+1)
chisq_stats = [chisq, 'sig: {}'.format(sig),
'dof: {}'.format((obs.shape[0] - 1)*(obs.shape[1] - 1))]
_chisq = ([np.NaN] * (dim-3)) + chisq_stats
_sig = ([np.NaN] * (dim-2)) + [chisq]
_sv, _ev = sv[:dim, 0], ev[:dim, 0]
_expl_inertia = 100 * (ev[:dim, 0] / inertia)
_cumul_expl_inertia = np.cumsum(_expl_inertia)
_perc_chisq = _expl_inertia / 100 * chisq
labels = ['Dimension', 'Singular values', 'Eigen values',
'explained % of Inertia', 'cumulative % explained',
'explained Chi^2', 'Total Chi^2']
results = pd.DataFrame([_dim, _sv, _ev, _expl_inertia,
_cumul_expl_inertia,_perc_chisq, _chisq]).T
results.columns = labels
results.set_index('Dimension', inplace=True)
return results
def _get_point_label_map(self, type, point_coords):
if type == 'CA':
xcoords = list(zip(point_coords['x'][0],point_coords['x'][1]))
xlabels = self.crossed_quantities[0].xdef
x_point_map = {lab: coord for lab, coord in zip(xlabels, xcoords)}
ycoords = list(zip(point_coords['y'][0], point_coords['y'][1]))
ylabels = self.crossed_quantities[0].ydef
y_point_map = {lab: coord for lab, coord in zip(ylabels, ycoords)}
return {'x': x_point_map, 'y': y_point_map}
def mass(self, x, y, w=None, margin=None):
"""
Compute rel. margins or total cell frequencies of a contigency table.
"""
counts = self.crossed_quantities[0].count(margin=False)
total = counts.cbase[0, 0]
if margin is None:
return counts.result.values / total
elif margin == 'x':
return counts.rbase[1:, :] / total
elif margin == 'y':
return (counts.cbase[:, 1:] / total).T
def expected_counts(self, x, y, w=None, return_observed=False):
"""
Compute expected cell distribution given observed absolute frequencies.
"""
#self.single_quantities, self.crossed_quantities = self._get_quantities()
counts = self.crossed_quantities[0].count(margin=False)
total = counts.cbase[0, 0]
row_m = counts.rbase[1:, :]
col_m = counts.cbase[:, 1:]
if not return_observed:
return (row_m * col_m) / total
else:
return counts.result.values, (row_m * col_m) / total
def chi_sq(self, x, y, w=None, sig=False, as_inertia=False):
"""
Compute global Chi^2 statistic, optionally transformed into Inertia.
"""
obs, exp = self.expected_counts(x=x, y=y, return_observed=True)
diff_matrix = ((obs - exp)**2) / exp
total_chi_sq = np.nansum(diff_matrix)
if sig:
dof = (obs.shape[0] - 1) * (obs.shape[1] - 1)
sig_result = np.round(1 - chi2dist.cdf(total_chi_sq, dof), 3)
if as_inertia: total_chi_sq /= np.nansum(obs)
if sig:
return total_chi_sq, sig_result
else:
return total_chi_sq
def _svd(self, matrix, return_eigen_matrices=True, return_eigen=True):
"""
Singular value decomposition wrapping np.linalg.svd().
"""
u, s, v = np.linalg.svd(matrix, full_matrices=False)
s = s[:, None]
if not return_eigen:
if return_eigen_matrices:
return s, u, v
else:
return s
else:
if return_eigen_matrices:
return s, u, v, (s ** 2)
else:
return s, (s ** 2)
class LinearModels(Multivariate):
"""
OLS REGRESSION, ...
"""
def __init__(self, dataset):
self.ds = dataset.copy()
self.single_quantities = None
self.crossed_quantities = None
self.analysis = 'LinearModels'
def set_model(self, y, x, w=None, intercept=True):
"""
"""
self._select_variables(x=x, y=y, w=w, drop_listwise=True)
self._get_quantities()
self._matrix = self.ds[self.y + self.x + [self.w]].dropna().values
ymean = self.single_quantities[-1].summarize('mean', as_df=False)
self._ymean = ymean.result[0, 0]
self._use_intercept = intercept
self.dofs = self._dofs()
predictors = ' + '.join(self.x)
if self._use_intercept: predictors = 'c + ' + predictors
self.formula = '{} ~ {}'.format(y, predictors)
return self
def _dofs(self):
"""
"""
correction = 1 if self._use_intercept else 0
obs = self._matrix[:, -1].sum()
tdof = obs - correction
mdof = len(self.x)
rdof = obs - mdof - correction
return [tdof, mdof, rdof]
def _vectors(self):
"""
"""
w = self._matrix[:, [-1]]
y = self._matrix[:, [0]]
x = self._matrix[:, 1:-1]
x = np.concatenate([np.ones((x.shape[0], 1)), x], axis=1)
return w, y, x
def get_coefs(self, standardize=False):
coefs = self._coefs() if not standardize else self._betas()
coef_df = pd.DataFrame(coefs,
index = ['-c-'] + self.x
if self._use_intercept else self.x,
columns = ['b']
if not standardize else ['beta'])
coef_df.replace(np.NaN, '', inplace=True)
return coef_df
def _betas(self):
"""
"""
corr_mat = Relations(self.ds).corr(self.x, self.y, self.w, n=False, sig=None,
drop_listwise=True, matrixed=True)
corr_mat = corr_mat.values
predictors = corr_mat[:-1, :-1]
y = corr_mat[:-1, [-1]]
inv_predictors = np.linalg.inv(predictors)
betas = inv_predictors.dot(y)
if self._use_intercept:
betas = np.vstack([[np.NaN], betas])
return betas
def _coefs(self):
"""
"""
w, y, x = self._vectors()
coefs = np.dot(np.linalg.inv(np.dot(x.T, x*w)), np.dot(x.T, y*w))
return coefs
def get_modelfit(self, r_sq=True):
anova, fit_stats = self._sum_of_squares()
dofs = np.round(np.array(self.dofs)[:, None], 0)
anova_stats = np.hstack([anova, dofs, fit_stats])
anova_df = pd.DataFrame(anova_stats,
index=['total', 'model', 'residual'],
columns=['sum of squares', 'dof', 'R', 'R^2'])
anova_df.replace(np.NaN, '', inplace=True)
return anova_df
def _sum_of_squares(self):
"""
"""
w, y, x = self._vectors()
x_w = x*w
hat = x_w.dot(np.dot(np.linalg.inv(np.dot(x.T, x_w)), x.T))
tss = (w*(y - self._ymean)**2).sum()[None]
rss = y.T.dot(np.dot(np.eye(hat.shape[0])-hat, y*w))[0]
ess = tss-rss
all_ss = np.vstack([tss, ess, rss])
rsq = np.vstack([[np.NaN], ess/tss, [np.NaN]])
r = np.sqrt(rsq)
all_rs = np.hstack([r, rsq])
return all_ss, all_rs
def estimate(self, estimator='ols', diags=True):
"""
"""
# Wrap up the modularized computation methods
coefs, betas = self.get_coefs(), self.get_coefs(True)
modelfit = self.get_modelfit()
# Compute diagnostics, i.e. standard errors and sig. of estimates/fit
# prerequisites
w, _, x = self._vectors()
rss = modelfit.loc['residual', 'sum of squares']
ess = modelfit.loc['model', 'sum of squares']
# coefficients: std. errors, t-stats, sigs
c_se = np.diagonal(np.sqrt(np.linalg.inv(np.dot(x.T,x*w)) *
(rss/self.dofs[-1])))[None].T
c_sigs = np.hstack(get_pval(self.dofs[-1], coefs/c_se))
c_diags = np.round(np.hstack([c_se, c_sigs]), 6)
c_diags_df = pd.DataFrame(c_diags, index=coefs.index,
columns=['se', 't-stat', 'p'])
# modelfit: se, F-stat, ...
m_se = np.vstack([[np.NaN], np.sqrt(rss/self.dofs[-1]), [np.NaN]])
m_fstat = np.vstack([[np.NaN],
(ess/self.dofs[1]) / (rss/self.dofs[-1]),
[np.NaN]])
m_sigs = 1-fdist.cdf(m_fstat, self.dofs[1], self.dofs[-1])
m_diags = np.round(np.hstack([m_se, m_fstat, m_sigs]), 6)
m_diags_df = pd.DataFrame(m_diags, index=modelfit.index,
columns=['se', 'F-stat', 'p'])
# Put everything together
parameter_results = pd.concat([coefs, betas, c_diags_df], axis=1)
fit_summary = pd.concat([modelfit, m_diags_df], axis=1).replace(np.NaN, '')
return parameter_results, fit_summary
def _lmg_models_per_var(self):
all_models = self._lmg_combs()
models_by_var = {x: [] for x in self.x}
for var in self.x:
qualified_models = []
for model in all_models:
if var in model: qualified_models.append(model)
for qualified_model in qualified_models:
q_m = list(qualified_model)
q_m.remove(var)
models_by_var[var].append([qualified_model, q_m])
return models_by_var
def _lmg_combs(self):
full = self.x
lmg_combs = []
for combine_no in range(1, len(full)):
lmg_combs.extend([list(comb) for comb in
list(combinations(full, combine_no))])
lmg_combs.append(full)
return lmg_combs
def _rsq_lmg_subset(self, subset):
self.set_model(self.y, subset, self.w)
anova = self.get_modelfit()
return anova['R^2'].replace('', np.NaN).dropna().values[0]
def lmg(self, norm=True, plot=False):
known_rsq = {}
x_results = {}
full_len = len(self.x)
cols = self.y + self.x
self._analysisdata = self._analysisdata.copy().dropna(subset=cols)
total_rsq = self._rsq_lmg_subset(self.x)
all_models = self._lmg_models_per_var()
model_max_no = len(list(all_models.keys())) * len(list(all_models.values())[0])
# print 'LMG analysis on {} models started...'.format(model_max_no)
for x, diff_models in list(all_models.items()):
group_results = {size: [] for size in range(1, full_len + 1)}
for diff_model in diff_models:
# sys.stdout.write('|')
# sys.stdout.flush()
if not diff_model[1]:
if tuple(diff_model[0]) in list(known_rsq.keys()):
r1 = known_rsq[tuple(diff_model[0])]
else:
r1 = self._rsq_lmg_subset(diff_model[0])
known_rsq[tuple(diff_model[0])] = r1
group_results[len(diff_model[0])].append((r1))
else:
if tuple(diff_model[0]) in list(known_rsq.keys()):
r1 = known_rsq[tuple(diff_model[0])]
else:
r1 = self._rsq_lmg_subset(diff_model[0])
known_rsq[tuple(diff_model[0])] = r1
if tuple(diff_model[1]) in list(known_rsq.keys()):
r2 = known_rsq[tuple(diff_model[1])]
else:
r2 = self._rsq_lmg_subset(diff_model[1])
known_rsq[tuple(diff_model[1])] = r2
group_results[len(diff_model[0])].append((r1-r2))
x_results[x] = group_results
lmgs = []
for var, results in list(x_results.items()):
res = np.mean([ | np.mean(val) | numpy.mean |
# 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]) | numpy.array |
import numpy as np
from numpy import sin, cos, sqrt, deg2rad, pi
import pandas as pd
import scipy.interpolate
import os
import sys
import subprocess
import json
import argparse
from collections import OrderedDict
# path to OpenTsiolkovsky
path_opentsio = os.getenv('PATH_OPENTSIO', "/usr/local/OpenTsiolkovsky/bin")
# import local modules
path_tools = os.path.join(path_opentsio, "../tools")
sys.path.append(path_tools)
from coordinate_transform import *
# functions
def calc_IIP(acc, ddtheta, t_stop, ang_dir, posLLH, velNED, dcmBODY2NED_, delta=0.0):
# theta = 0.5 * ddtheta * t_stop**2
(ssa, csa) = scipy.special.fresnel(sqrt(ddtheta / pi) * t_stop)
dv_para = acc * sqrt(pi / ddtheta) * csa
dv_vert = acc * sqrt(pi / ddtheta) * ssa
dv_ax = dv_para * cos(delta) + dv_vert * sin(delta)
dv_no = - dv_para * sin(delta) + dv_vert * cos(delta)
vec_dir = np.array([0., -sin(deg2rad(ang_dir)), cos(deg2rad(ang_dir))])
dv = np.array([dv_ax, 0., 0.]) + vec_dir * dv_no
velNED_new = np.matmul(dcmBODY2NED_, dv) + velNED
posLLH_impact = posLLH_IIP(posLLH, velNED_new)
return posLLH_impact[:2]
# global difinitions
directions = [
{"name": "head", "offset[deg]": 0.},
{"name": "left", "offset[deg]": 90.},
{"name": "tail", "offset[deg]": 180.},
{"name":"right", "offset[deg]": 270.},
]
opentsio = os.path.join(path_opentsio, "OpenTsiolkovsky")
if __name__ == "__main__":
# read command-line arguments
parser = argparse.ArgumentParser()
parser.add_argument("filename.json", type=str)
parser.add_argument("max_emst_time", type=float) # max emergency stop time[s]
parser.add_argument("max_gimbal_angle", type=float) # max gimable angle [deg]
parser.add_argument("-ts", "--time_step", type=float, default=1.0) # timestep of output [s]
parser.add_argument("-dts", "--dt_stop", type=float, default=0.05) # calculation timestep of emergency stop time [s]
args = parser.parse_args()
filename_json = vars(args)["filename.json"]
time_emst_max = args.max_emst_time
gimbal_angle_max = args.max_gimbal_angle
time_step = args.time_step
dt_stop = args.dt_stop
# read nominal json file
with open(filename_json) as f:
nominal_json = json.load(f, object_pairs_hook=OrderedDict)
# import body specs
filename_inertia = nominal_json["stage1"]["6DoF"]["moment of inertia file name(str)"]
filename_cgxt = nominal_json["stage1"]["attitude neutrality(3DoF)"]["CG, Controller position file(str)"]
df_inertia = pd.read_csv(filename_inertia, index_col=False)
inertia_yy_at = scipy.interpolate.interp1d(df_inertia["time [s]"], df_inertia["inertia all at CG [kgm^2]"])
df_cgxt = pd.read_csv(filename_cgxt, index_col=False)
length_cg2cont = df_cgxt["Controller_pos_STA[m]"].values - df_cgxt["CG_pos_STA[m]"].values
length_cg2cont_at = scipy.interpolate.interp1d(df_cgxt["time[s]"], length_cg2cont)
# make rocket dynamics CSV output for IIP calculation
tmp_json = nominal_json.copy()
tmp_json["name(str)"] += "_temp"
if time_step is not None:
tmp_json["calculate condition"]["time step for output[s]"] = time_step
tmp_dir = "./_temp_"
while os.path.exists(tmp_dir):
tmp_dir += "_"
os.mkdir(tmp_dir)
exists_output_dir = os.path.exists("./output")
if not exists_output_dir:
os.mkdir("./output")
filename_tmp = os.path.join(tmp_dir, "{}.json".format(tmp_json["name(str)"]))
with open(filename_tmp, "w") as f:
json.dump(tmp_json, f, indent=4)
subprocess.run([opentsio, filename_tmp], stdout=subprocess.PIPE)
filename_result = os.path.join("./output", "{}_dynamics_1.csv".format(tmp_json["name(str)"]))
df_result = pd.read_csv(filename_result, index_col=False)
df_pwd = df_result[df_result["is_powered(1=powered 0=free)"] == 1]
# IIP calculation with additional velocity
array_out = []
for index, se_pwd in df_pwd.iterrows(): # each break time
t_break, mass, thrust = se_pwd[["time(s)", "mass(kg)", "thrust(N)"]].values
posLLH = se_pwd[["lat(deg)", "lon(deg)", "altitude(m)"]].values
velNED = se_pwd[["vel_NED_X(m/s)", "vel_NED_Y(m/s)", "vel_NED_Z(m/s)"]].values
dcmBODY2ECI_ = se_pwd[["dcmBODY2ECI_{0}{1}".format(i, j) for i in range(1, 4) for j in range(1, 4)]].values
dcmBODY2ECI_ = np.reshape(dcmBODY2ECI_, (3, 3))
dcmECI2ECEF_ = dcmECI2ECEF(t_break)
dcmECEF2NED_ = dcmECEF2NEDfromLLH(posLLH)
dcmBODY2NED_ = np.matmul(dcmECEF2NED_, np.matmul(dcmECI2ECEF_, dcmBODY2ECI_))
acc = thrust / mass
ddtheta = thrust * sin( | deg2rad(gimbal_angle_max) | numpy.deg2rad |
import numpy as np
import scipy.sparse
import kmeans
import json
#Make sure we get consistent, reproducible results
| np.random.seed(seed=1) | numpy.random.seed |
"""
inheritance-diagram:: dfo.optimizer.direct
:parts: 1
"""
from misc.debug import DbgMsgOut, DbgMsg
from .base import BoxConstrainedOptimizer
from numpy import max, min, abs, array
import numpy as np
import heapq
__all__ = ['Cube', 'DIRECT']
class Cube(object):
def __init__(self, x, f, depth):
self.x = array(x)
self.f = f
self.ndim = self.x.shape[0]
self.depth = depth
def increase_depth(self, i=None):
if i is not None:
self.depth[i] += 1
else:
for i in range(self.ndim):
self.depth[i] += 1
class DIRECT(BoxConstrainedOptimizer):
def __init__(self, function, xlo=None, xhi=None, debug=0, fstop=None, maxiter=None):
BoxConstrainedOptimizer.__init__(self, function, xlo, xhi, debug, fstop, maxiter, cache=True)
self.pq_cache = None
self.eps = 1e-2
self.K = 0
self.max_depth = 5
self.visited = []
def check(self):
"""
Checks the optimization algorithm's settings and raises an exception if
something is wrong.
"""
BoxConstrainedOptimizer.check(self)
# if self.samplesize is None:
# raise Exception(DbgMsg("DIRECT", "The sample size should not be None."))
def reset(self, x0):
"""
Puts the optimizer in its initial state and sets the initial point to
be the 1-dimensional array *x0*. The length of the array becomes the
dimension of the optimization problem (:attr:`ndim` member). The shape
of *x* must match that of *xlo* and *xhi*.
"""
BoxConstrainedOptimizer.reset(self, x0)
# Debug message
if self.debug:
DbgMsgOut("DIRECT", "Resetting DIRECT")
def run(self):
"""
Run the DIRECT algorithm.
"""
# Debug message
if self.debug:
DbgMsgOut("CSOPT", "Starting a coordinate search run at i=" + str(self.niter))
# Reset stop flag
self.stop = False
# Check
self.check()
self.x = 0.5 * | np.ones(shape=(self.ndim,)) | numpy.ones |
# Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import print_function
import paddle.fluid as fluid
import paddle.fluid.core as core
import unittest
import numpy
import numbers
class TestTensor(unittest.TestCase):
def setUp(self):
self.support_dtypes = [
'bool', 'uint8', 'int8', 'int16', 'int32', 'int64', 'float16',
'float32', 'float64'
]
def test_int_tensor(self):
scope = core.Scope()
var = scope.var("test_tensor")
place = core.CPUPlace()
tensor = var.get_tensor()
tensor._set_dims([1000, 784])
tensor._alloc_int(place)
tensor_array = numpy.array(tensor)
self.assertEqual((1000, 784), tensor_array.shape)
tensor_array[3, 9] = 1
tensor_array[19, 11] = 2
tensor.set(tensor_array, place)
tensor_array_2 = numpy.array(tensor)
self.assertEqual(1, tensor_array_2[3, 9])
self.assertEqual(2, tensor_array_2[19, 11])
def test_float_tensor(self):
scope = core.Scope()
var = scope.var("test_tensor")
place = core.CPUPlace()
tensor = var.get_tensor()
tensor._set_dims([1000, 784])
tensor._alloc_float(place)
tensor_array = numpy.array(tensor)
self.assertEqual((1000, 784), tensor_array.shape)
tensor_array[3, 9] = 1.0
tensor_array[19, 11] = 2.0
tensor.set(tensor_array, place)
tensor_array_2 = numpy.array(tensor)
self.assertAlmostEqual(1.0, tensor_array_2[3, 9])
self.assertAlmostEqual(2.0, tensor_array_2[19, 11])
def test_int8_tensor(self):
scope = core.Scope()
var = scope.var("int8_tensor")
cpu_tensor = var.get_tensor()
tensor_array = numpy.random.randint(
-127, high=128, size=[100, 200], dtype=numpy.int8)
place = core.CPUPlace()
cpu_tensor.set(tensor_array, place)
cpu_tensor_array_2 = numpy.array(cpu_tensor)
self.assertAlmostEqual(cpu_tensor_array_2.all(), tensor_array.all())
if core.is_compiled_with_cuda():
cuda_tensor = var.get_tensor()
tensor_array = numpy.random.randint(
-127, high=128, size=[100, 200], dtype=numpy.int8)
place = core.CUDAPlace(0)
cuda_tensor.set(tensor_array, place)
cuda_tensor_array_2 = numpy.array(cuda_tensor)
self.assertAlmostEqual(cuda_tensor_array_2.all(),
tensor_array.all())
def test_int_lod_tensor(self):
place = core.CPUPlace()
scope = core.Scope()
var_lod = scope.var("test_lod_tensor")
lod_tensor = var_lod.get_tensor()
lod_tensor._set_dims([4, 4, 6])
lod_tensor._alloc_int(place)
array = numpy.array(lod_tensor)
array[0, 0, 0] = 3
array[3, 3, 5] = 10
lod_tensor.set(array, place)
lod_tensor.set_recursive_sequence_lengths([[2, 2]])
lod_v = numpy.array(lod_tensor)
self.assertTrue(numpy.alltrue(array == lod_v))
lod = lod_tensor.recursive_sequence_lengths()
self.assertEqual(2, lod[0][0])
self.assertEqual(2, lod[0][1])
def test_float_lod_tensor(self):
place = core.CPUPlace()
scope = core.Scope()
var_lod = scope.var("test_lod_tensor")
lod_tensor = var_lod.get_tensor()
lod_tensor._set_dims([5, 2, 3, 4])
lod_tensor._alloc_float(place)
tensor_array = numpy.array(lod_tensor)
self.assertEqual((5, 2, 3, 4), tensor_array.shape)
tensor_array[0, 0, 0, 0] = 1.0
tensor_array[0, 0, 0, 1] = 2.0
lod_tensor.set(tensor_array, place)
lod_v = numpy.array(lod_tensor)
self.assertAlmostEqual(1.0, lod_v[0, 0, 0, 0])
self.assertAlmostEqual(2.0, lod_v[0, 0, 0, 1])
self.assertEqual(len(lod_tensor.recursive_sequence_lengths()), 0)
lod_py = [[2, 1], [1, 2, 2]]
lod_tensor.set_recursive_sequence_lengths(lod_py)
lod = lod_tensor.recursive_sequence_lengths()
self.assertListEqual(lod_py, lod)
def test_lod_tensor_init(self):
place = core.CPUPlace()
lod_py = [[2, 1], [1, 2, 2]]
lod_tensor = core.LoDTensor()
lod_tensor._set_dims([5, 2, 3, 4])
lod_tensor.set_recursive_sequence_lengths(lod_py)
lod_tensor._alloc_float(place)
tensor_array = numpy.array(lod_tensor)
tensor_array[0, 0, 0, 0] = 1.0
tensor_array[0, 0, 0, 1] = 2.0
lod_tensor.set(tensor_array, place)
lod_v = numpy.array(lod_tensor)
self.assertAlmostEqual(1.0, lod_v[0, 0, 0, 0])
self.assertAlmostEqual(2.0, lod_v[0, 0, 0, 1])
self.assertListEqual(lod_py, lod_tensor.recursive_sequence_lengths())
def test_lod_tensor_gpu_init(self):
if not core.is_compiled_with_cuda():
return
place = core.CUDAPlace(0)
lod_py = [[2, 1], [1, 2, 2]]
lod_tensor = core.LoDTensor()
lod_tensor._set_dims([5, 2, 3, 4])
lod_tensor.set_recursive_sequence_lengths(lod_py)
lod_tensor._alloc_float(place)
tensor_array = numpy.array(lod_tensor)
tensor_array[0, 0, 0, 0] = 1.0
tensor_array[0, 0, 0, 1] = 2.0
lod_tensor.set(tensor_array, place)
lod_v = numpy.array(lod_tensor)
self.assertAlmostEqual(1.0, lod_v[0, 0, 0, 0])
self.assertAlmostEqual(2.0, lod_v[0, 0, 0, 1])
self.assertListEqual(lod_py, lod_tensor.recursive_sequence_lengths())
def test_empty_tensor(self):
place = core.CPUPlace()
scope = core.Scope()
var = scope.var("test_tensor")
tensor = var.get_tensor()
tensor._set_dims([0, 1])
tensor._alloc_float(place)
tensor_array = numpy.array(tensor)
self.assertEqual((0, 1), tensor_array.shape)
if core.is_compiled_with_cuda():
gpu_place = core.CUDAPlace(0)
tensor._alloc_float(gpu_place)
tensor_array = numpy.array(tensor)
self.assertEqual((0, 1), tensor_array.shape)
def run_slice_tensor(self, place, dtype):
tensor = fluid.Tensor()
shape = [3, 3, 3]
tensor._set_dims(shape)
tensor_array = numpy.array(
[[[1, 2, 3], [4, 5, 6], [7, 8, 9]],
[[10, 11, 12], [13, 14, 15], [16, 17, 18]],
[[19, 20, 21], [22, 23, 24], [25, 26, 27]]]).astype(dtype)
tensor.set(tensor_array, place)
n1 = tensor[1]
t1 = tensor_array[1]
self.assertTrue((numpy.array(n1) == numpy.array(t1)).all())
n2 = tensor[1:]
t2 = tensor_array[1:]
self.assertTrue((numpy.array(n2) == numpy.array(t2)).all())
n3 = tensor[0:2:]
t3 = tensor_array[0:2:]
self.assertTrue((numpy.array(n3) == numpy.array(t3)).all())
n4 = tensor[2::-2]
t4 = tensor_array[2::-2]
self.assertTrue((numpy.array(n4) == numpy.array(t4)).all())
n5 = tensor[2::-2][0]
t5 = tensor_array[2::-2][0]
self.assertTrue((numpy.array(n5) == numpy.array(t5)).all())
n6 = tensor[2:-1:-1]
t6 = tensor_array[2:-1:-1]
self.assertTrue((numpy.array(n6) == numpy.array(t6)).all())
n7 = tensor[0:, 0:]
t7 = tensor_array[0:, 0:]
self.assertTrue((numpy.array(n7) == numpy.array(t7)).all())
n8 = tensor[0::1, 0::-1, 2:]
t8 = tensor_array[0::1, 0::-1, 2:]
self.assertTrue((numpy.array(n8) == numpy.array(t8)).all())
def test_slice_tensor(self):
for dtype in self.support_dtypes:
# run cpu first
place = core.CPUPlace()
self.run_slice_tensor(place, dtype)
if core.is_compiled_with_cuda():
place = core.CUDAPlace(0)
self.run_slice_tensor(place, dtype)
def test_print_tensor(self):
scope = core.Scope()
var = scope.var("test_tensor")
place = core.CPUPlace()
tensor = var.get_tensor()
tensor._set_dims([10, 10])
tensor._alloc_int(place)
tensor_array = numpy.array(tensor)
self.assertEqual((10, 10), tensor_array.shape)
tensor_array[0, 0] = 1
tensor_array[2, 2] = 2
tensor.set(tensor_array, place)
print(tensor)
self.assertTrue(isinstance(str(tensor), str))
if core.is_compiled_with_cuda():
tensor.set(tensor_array, core.CUDAPlace(0))
print(tensor)
self.assertTrue(isinstance(str(tensor), str))
def test_tensor_poiter(self):
place = core.CPUPlace()
scope = core.Scope()
var = scope.var("test_tensor")
place = core.CPUPlace()
tensor = var.get_tensor()
dtype = core.VarDesc.VarType.FP32
self.assertTrue(
isinstance(tensor._mutable_data(place, dtype), numbers.Integral))
if core.is_compiled_with_cuda():
place = core.CUDAPlace(0)
self.assertTrue(
isinstance(
tensor._mutable_data(place, dtype), numbers.Integral))
place = core.CUDAPinnedPlace()
self.assertTrue(
isinstance(
tensor._mutable_data(place, dtype), numbers.Integral))
places = fluid.cuda_pinned_places()
self.assertTrue(
isinstance(
tensor._mutable_data(places[0], dtype), numbers.Integral))
def test_tensor_set_fp16(self):
array = numpy.random.random((300, 500)).astype("float16")
tensor = fluid.Tensor()
place = core.CPUPlace()
tensor.set(array, place)
self.assertEqual(tensor._dtype(), core.VarDesc.VarType.FP16)
self.assertTrue(numpy.array_equal(numpy.array(tensor), array))
if core.is_compiled_with_cuda():
place = core.CUDAPlace(0)
tensor.set(array, place)
self.assertEqual(tensor._dtype(), core.VarDesc.VarType.FP16)
self.assertTrue(numpy.array_equal(numpy.array(tensor), array))
place = core.CUDAPinnedPlace()
tensor.set(array, place)
self.assertEqual(tensor._dtype(), core.VarDesc.VarType.FP16)
self.assertTrue(numpy.array_equal(numpy.array(tensor), array))
def test_tensor_set_int16(self):
array = numpy.random.randint(100, size=(300, 500)).astype("int16")
tensor = fluid.Tensor()
place = core.CPUPlace()
tensor.set(array, place)
self.assertEqual(tensor._dtype(), core.VarDesc.VarType.INT16)
self.assertTrue(numpy.array_equal(numpy.array(tensor), array))
if core.is_compiled_with_cuda():
place = core.CUDAPlace(0)
tensor.set(array, place)
self.assertEqual(tensor._dtype(), core.VarDesc.VarType.INT16)
self.assertTrue(numpy.array_equal( | numpy.array(tensor) | numpy.array |
# This module has been generated automatically from space group information
# obtained from the Computational Crystallography Toolbox
#
"""
Space groups
This module contains a list of all the 230 space groups that can occur in
a crystal. The variable space_groups contains a dictionary that maps
space group numbers and space group names to the corresponding space
group objects.
.. moduleauthor:: <NAME> <<EMAIL>>
"""
#-----------------------------------------------------------------------------
# Copyright (C) 2013 The Mosaic Development Team
#
# Distributed under the terms of the BSD License. The full license is in
# the file LICENSE.txt, distributed as part of this software.
#-----------------------------------------------------------------------------
import numpy as N
class SpaceGroup(object):
"""
Space group
All possible space group objects are created in this module. Other
modules should access these objects through the dictionary
space_groups rather than create their own space group objects.
"""
def __init__(self, number, symbol, transformations):
"""
:param number: the number assigned to the space group by
international convention
:type number: int
:param symbol: the Hermann-Mauguin space-group symbol as used
in PDB and mmCIF files
:type symbol: str
:param transformations: a list of space group transformations,
each consisting of a tuple of three
integer arrays (rot, tn, td), where
rot is the rotation matrix and tn/td
are the numerator and denominator of the
translation vector. The transformations
are defined in fractional coordinates.
:type transformations: list
"""
self.number = number
self.symbol = symbol
self.transformations = transformations
self.transposed_rotations = N.array([N.transpose(t[0])
for t in transformations])
self.phase_factors = N.exp(N.array([(-2j*N.pi*t[1])/t[2]
for t in transformations]))
def __repr__(self):
return "SpaceGroup(%d, %s)" % (self.number, repr(self.symbol))
def __len__(self):
"""
:return: the number of space group transformations
:rtype: int
"""
return len(self.transformations)
def symmetryEquivalentMillerIndices(self, hkl):
"""
:param hkl: a set of Miller indices
:type hkl: Scientific.N.array_type
:return: a tuple (miller_indices, phase_factor) of two arrays
of length equal to the number of space group
transformations. miller_indices contains the Miller
indices of each reflection equivalent by symmetry to the
reflection hkl (including hkl itself as the first element).
phase_factor contains the phase factors that must be applied
to the structure factor of reflection hkl to obtain the
structure factor of the symmetry equivalent reflection.
:rtype: tuple
"""
hkls = N.dot(self.transposed_rotations, hkl)
p = N.multiply.reduce(self.phase_factors**hkl, -1)
return hkls, p
space_groups = {}
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(1, 'P 1', transformations)
space_groups[1] = sg
space_groups['P 1'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(2, 'P -1', transformations)
space_groups[2] = sg
space_groups['P -1'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(3, 'P 1 2 1', transformations)
space_groups[3] = sg
space_groups['P 1 2 1'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(4, 'P 1 21 1', transformations)
space_groups[4] = sg
space_groups['P 1 21 1'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(5, 'C 1 2 1', transformations)
space_groups[5] = sg
space_groups['C 1 2 1'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(6, 'P 1 m 1', transformations)
space_groups[6] = sg
space_groups['P 1 m 1'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(7, 'P 1 c 1', transformations)
space_groups[7] = sg
space_groups['P 1 c 1'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(8, 'C 1 m 1', transformations)
space_groups[8] = sg
space_groups['C 1 m 1'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(9, 'C 1 c 1', transformations)
space_groups[9] = sg
space_groups['C 1 c 1'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(10, 'P 1 2/m 1', transformations)
space_groups[10] = sg
space_groups['P 1 2/m 1'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(11, 'P 1 21/m 1', transformations)
space_groups[11] = sg
space_groups['P 1 21/m 1'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(12, 'C 1 2/m 1', transformations)
space_groups[12] = sg
space_groups['C 1 2/m 1'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(13, 'P 1 2/c 1', transformations)
space_groups[13] = sg
space_groups['P 1 2/c 1'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(14, 'P 1 21/c 1', transformations)
space_groups[14] = sg
space_groups['P 1 21/c 1'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(15, 'C 1 2/c 1', transformations)
space_groups[15] = sg
space_groups['C 1 2/c 1'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(16, 'P 2 2 2', transformations)
space_groups[16] = sg
space_groups['P 2 2 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(17, 'P 2 2 21', transformations)
space_groups[17] = sg
space_groups['P 2 2 21'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(18, 'P 21 21 2', transformations)
space_groups[18] = sg
space_groups['P 21 21 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(19, 'P 21 21 21', transformations)
space_groups[19] = sg
space_groups['P 21 21 21'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(20, 'C 2 2 21', transformations)
space_groups[20] = sg
space_groups['C 2 2 21'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(21, 'C 2 2 2', transformations)
space_groups[21] = sg
space_groups['C 2 2 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(22, 'F 2 2 2', transformations)
space_groups[22] = sg
space_groups['F 2 2 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(23, 'I 2 2 2', transformations)
space_groups[23] = sg
space_groups['I 2 2 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(24, 'I 21 21 21', transformations)
space_groups[24] = sg
space_groups['I 21 21 21'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(25, 'P m m 2', transformations)
space_groups[25] = sg
space_groups['P m m 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(26, 'P m c 21', transformations)
space_groups[26] = sg
space_groups['P m c 21'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(27, 'P c c 2', transformations)
space_groups[27] = sg
space_groups['P c c 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(28, 'P m a 2', transformations)
space_groups[28] = sg
space_groups['P m a 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(29, 'P c a 21', transformations)
space_groups[29] = sg
space_groups['P c a 21'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(30, 'P n c 2', transformations)
space_groups[30] = sg
space_groups['P n c 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(31, 'P m n 21', transformations)
space_groups[31] = sg
space_groups['P m n 21'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(32, 'P b a 2', transformations)
space_groups[32] = sg
space_groups['P b a 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(33, 'P n a 21', transformations)
space_groups[33] = sg
space_groups['P n a 21'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(34, 'P n n 2', transformations)
space_groups[34] = sg
space_groups['P n n 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(35, 'C m m 2', transformations)
space_groups[35] = sg
space_groups['C m m 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(36, 'C m c 21', transformations)
space_groups[36] = sg
space_groups['C m c 21'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(37, 'C c c 2', transformations)
space_groups[37] = sg
space_groups['C c c 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(38, 'A m m 2', transformations)
space_groups[38] = sg
space_groups['A m m 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(39, 'A b m 2', transformations)
space_groups[39] = sg
space_groups['A b m 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(40, 'A m a 2', transformations)
space_groups[40] = sg
space_groups['A m a 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(41, 'A b a 2', transformations)
space_groups[41] = sg
space_groups['A b a 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(42, 'F m m 2', transformations)
space_groups[42] = sg
space_groups['F m m 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([3,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([3,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([3,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([3,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(43, 'F d d 2', transformations)
space_groups[43] = sg
space_groups['F d d 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(44, 'I m m 2', transformations)
space_groups[44] = sg
space_groups['I m m 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(45, 'I b a 2', transformations)
space_groups[45] = sg
space_groups['I b a 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(46, 'I m a 2', transformations)
space_groups[46] = sg
space_groups['I m a 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(47, 'P m m m', transformations)
space_groups[47] = sg
space_groups['P m m m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(48, 'P n n n :2', transformations)
space_groups[48] = sg
space_groups['P n n n :2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(49, 'P c c m', transformations)
space_groups[49] = sg
space_groups['P c c m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(50, 'P b a n :2', transformations)
space_groups[50] = sg
space_groups['P b a n :2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(51, 'P m m a', transformations)
space_groups[51] = sg
space_groups['P m m a'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(52, 'P n n a', transformations)
space_groups[52] = sg
space_groups['P n n a'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(53, 'P m n a', transformations)
space_groups[53] = sg
space_groups['P m n a'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(54, 'P c c a', transformations)
space_groups[54] = sg
space_groups['P c c a'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(55, 'P b a m', transformations)
space_groups[55] = sg
space_groups['P b a m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(56, 'P c c n', transformations)
space_groups[56] = sg
space_groups['P c c n'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(57, 'P b c m', transformations)
space_groups[57] = sg
space_groups['P b c m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(58, 'P n n m', transformations)
space_groups[58] = sg
space_groups['P n n m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(59, 'P m m n :2', transformations)
space_groups[59] = sg
space_groups['P m m n :2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(60, 'P b c n', transformations)
space_groups[60] = sg
space_groups['P b c n'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(61, 'P b c a', transformations)
space_groups[61] = sg
space_groups['P b c a'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(62, 'P n m a', transformations)
space_groups[62] = sg
space_groups['P n m a'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(63, 'C m c m', transformations)
space_groups[63] = sg
space_groups['C m c m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(64, 'C m c a', transformations)
space_groups[64] = sg
space_groups['C m c a'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(65, 'C m m m', transformations)
space_groups[65] = sg
space_groups['C m m m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(66, 'C c c m', transformations)
space_groups[66] = sg
space_groups['C c c m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(67, 'C m m a', transformations)
space_groups[67] = sg
space_groups['C m m a'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(68, 'C c c a :2', transformations)
space_groups[68] = sg
space_groups['C c c a :2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(69, 'F m m m', transformations)
space_groups[69] = sg
space_groups['F m m m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([4,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([4,4,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([4,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([4,4,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,3,3])
trans_den = N.array([1,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([4,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,3,1])
trans_den = N.array([4,4,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,1,1])
trans_den = N.array([4,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,1,1])
trans_den = N.array([4,4,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([2,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([3,0,3])
trans_den = N.array([4,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([3,1,1])
trans_den = N.array([4,4,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,-1,1])
trans_den = N.array([2,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([4,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,-1,1])
trans_den = N.array([4,4,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,3,1])
trans_den = N.array([2,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([3,1,1])
trans_den = N.array([4,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([3,3,0])
trans_den = N.array([4,4,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,-1])
trans_den = N.array([2,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,-1])
trans_den = N.array([4,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([4,4,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(70, 'F d d d :2', transformations)
space_groups[70] = sg
space_groups['F d d d :2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(71, 'I m m m', transformations)
space_groups[71] = sg
space_groups['I m m m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(72, 'I b a m', transformations)
space_groups[72] = sg
space_groups['I b a m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(73, 'I b c a', transformations)
space_groups[73] = sg
space_groups['I b c a'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(74, 'I m m a', transformations)
space_groups[74] = sg
space_groups['I m m a'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(75, 'P 4', transformations)
space_groups[75] = sg
space_groups['P 4'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,3])
trans_den = N.array([1,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(76, 'P 41', transformations)
space_groups[76] = sg
space_groups['P 41'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(77, 'P 42', transformations)
space_groups[77] = sg
space_groups['P 42'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,3])
trans_den = N.array([1,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(78, 'P 43', transformations)
space_groups[78] = sg
space_groups['P 43'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(79, 'I 4', transformations)
space_groups[79] = sg
space_groups['I 4'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,3])
trans_den = N.array([2,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,3])
trans_den = N.array([2,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,5])
trans_den = N.array([1,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,5])
trans_den = N.array([1,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(80, 'I 41', transformations)
space_groups[80] = sg
space_groups['I 41'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(81, 'P -4', transformations)
space_groups[81] = sg
space_groups['P -4'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(82, 'I -4', transformations)
space_groups[82] = sg
space_groups['I -4'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(83, 'P 4/m', transformations)
space_groups[83] = sg
space_groups['P 4/m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(84, 'P 42/m', transformations)
space_groups[84] = sg
space_groups['P 42/m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(85, 'P 4/n :2', transformations)
space_groups[85] = sg
space_groups['P 4/n :2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(86, 'P 42/n :2', transformations)
space_groups[86] = sg
space_groups['P 42/n :2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(87, 'I 4/m', transformations)
space_groups[87] = sg
space_groups['I 4/m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-3,-3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([3,5,5])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([3,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,-1,-1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(88, 'I 41/a :2', transformations)
space_groups[88] = sg
space_groups['I 41/a :2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(89, 'P 4 2 2', transformations)
space_groups[89] = sg
space_groups['P 4 2 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(90, 'P 4 21 2', transformations)
space_groups[90] = sg
space_groups['P 4 21 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,3])
trans_den = N.array([1,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,3])
trans_den = N.array([1,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,4])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(91, 'P 41 2 2', transformations)
space_groups[91] = sg
space_groups['P 41 2 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([2,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([2,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(92, 'P 41 21 2', transformations)
space_groups[92] = sg
space_groups['P 41 21 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(93, 'P 42 2 2', transformations)
space_groups[93] = sg
space_groups['P 42 2 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(94, 'P 42 21 2', transformations)
space_groups[94] = sg
space_groups['P 42 21 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,3])
trans_den = N.array([1,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,3])
trans_den = N.array([1,1,4])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(95, 'P 43 2 2', transformations)
space_groups[95] = sg
space_groups['P 43 2 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([2,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([2,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(96, 'P 43 21 2', transformations)
space_groups[96] = sg
space_groups['P 43 21 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(97, 'I 4 2 2', transformations)
space_groups[97] = sg
space_groups['I 4 2 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,3])
trans_den = N.array([2,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,3])
trans_den = N.array([2,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,3])
trans_den = N.array([2,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,3])
trans_den = N.array([2,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,5])
trans_den = N.array([1,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,5])
trans_den = N.array([1,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,5])
trans_den = N.array([1,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,5])
trans_den = N.array([1,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(98, 'I 41 2 2', transformations)
space_groups[98] = sg
space_groups['I 41 2 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(99, 'P 4 m m', transformations)
space_groups[99] = sg
space_groups['P 4 m m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(100, 'P 4 b m', transformations)
space_groups[100] = sg
space_groups['P 4 b m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(101, 'P 42 c m', transformations)
space_groups[101] = sg
space_groups['P 42 c m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(102, 'P 42 n m', transformations)
space_groups[102] = sg
space_groups['P 42 n m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(103, 'P 4 c c', transformations)
space_groups[103] = sg
space_groups['P 4 c c'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(104, 'P 4 n c', transformations)
space_groups[104] = sg
space_groups['P 4 n c'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(105, 'P 42 m c', transformations)
space_groups[105] = sg
space_groups['P 42 m c'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(106, 'P 42 b c', transformations)
space_groups[106] = sg
space_groups['P 42 b c'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(107, 'I 4 m m', transformations)
space_groups[107] = sg
space_groups['I 4 m m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(108, 'I 4 c m', transformations)
space_groups[108] = sg
space_groups['I 4 c m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,3])
trans_den = N.array([2,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,3])
trans_den = N.array([2,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,3])
trans_den = N.array([2,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,3])
trans_den = N.array([2,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,5])
trans_den = N.array([1,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,5])
trans_den = N.array([1,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,5])
trans_den = N.array([1,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,5])
trans_den = N.array([1,2,4])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(109, 'I 41 m d', transformations)
space_groups[109] = sg
space_groups['I 41 m d'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,3])
trans_den = N.array([2,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,3])
trans_den = N.array([2,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,5])
trans_den = N.array([1,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,5])
trans_den = N.array([1,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([1,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([1,2,4])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(110, 'I 41 c d', transformations)
space_groups[110] = sg
space_groups['I 41 c d'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(111, 'P -4 2 m', transformations)
space_groups[111] = sg
space_groups['P -4 2 m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(112, 'P -4 2 c', transformations)
space_groups[112] = sg
space_groups['P -4 2 c'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(113, 'P -4 21 m', transformations)
space_groups[113] = sg
space_groups['P -4 21 m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(114, 'P -4 21 c', transformations)
space_groups[114] = sg
space_groups['P -4 21 c'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(115, 'P -4 m 2', transformations)
space_groups[115] = sg
space_groups['P -4 m 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(116, 'P -4 c 2', transformations)
space_groups[116] = sg
space_groups['P -4 c 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(117, 'P -4 b 2', transformations)
space_groups[117] = sg
space_groups['P -4 b 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(118, 'P -4 n 2', transformations)
space_groups[118] = sg
space_groups['P -4 n 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(119, 'I -4 m 2', transformations)
space_groups[119] = sg
space_groups['I -4 m 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(120, 'I -4 c 2', transformations)
space_groups[120] = sg
space_groups['I -4 c 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(121, 'I -4 2 m', transformations)
space_groups[121] = sg
space_groups['I -4 2 m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,3])
trans_den = N.array([2,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,3])
trans_den = N.array([2,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,3])
trans_den = N.array([2,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,3])
trans_den = N.array([2,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,5])
trans_den = N.array([1,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,5])
trans_den = N.array([1,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,5])
trans_den = N.array([1,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,5])
trans_den = N.array([1,2,4])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(122, 'I -4 2 d', transformations)
space_groups[122] = sg
space_groups['I -4 2 d'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(123, 'P 4/m m m', transformations)
space_groups[123] = sg
space_groups['P 4/m m m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(124, 'P 4/m c c', transformations)
space_groups[124] = sg
space_groups['P 4/m c c'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(125, 'P 4/n b m :2', transformations)
space_groups[125] = sg
space_groups['P 4/n b m :2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(126, 'P 4/n n c :2', transformations)
space_groups[126] = sg
space_groups['P 4/n n c :2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(127, 'P 4/m b m', transformations)
space_groups[127] = sg
space_groups['P 4/m b m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(128, 'P 4/m n c', transformations)
space_groups[128] = sg
space_groups['P 4/m n c'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(129, 'P 4/n m m :2', transformations)
space_groups[129] = sg
space_groups['P 4/n m m :2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(130, 'P 4/n c c :2', transformations)
space_groups[130] = sg
space_groups['P 4/n c c :2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(131, 'P 42/m m c', transformations)
space_groups[131] = sg
space_groups['P 42/m m c'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(132, 'P 42/m c m', transformations)
space_groups[132] = sg
space_groups['P 42/m c m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(133, 'P 42/n b c :2', transformations)
space_groups[133] = sg
space_groups['P 42/n b c :2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(134, 'P 42/n n m :2', transformations)
space_groups[134] = sg
space_groups['P 42/n n m :2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(135, 'P 42/m b c', transformations)
space_groups[135] = sg
space_groups['P 42/m b c'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(136, 'P 42/m n m', transformations)
space_groups[136] = sg
space_groups['P 42/m n m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(137, 'P 42/n m c :2', transformations)
space_groups[137] = sg
space_groups['P 42/n m c :2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(138, 'P 42/n c m :2', transformations)
space_groups[138] = sg
space_groups['P 42/n c m :2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(139, 'I 4/m m m', transformations)
space_groups[139] = sg
space_groups['I 4/m m m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(140, 'I 4/m c m', transformations)
space_groups[140] = sg
space_groups['I 4/m c m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-3,-1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-3,-1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([3,5,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([3,3,5])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([3,5,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([3,3,5])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,-1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,-1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,-1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,-1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(141, 'I 41/a m d :2', transformations)
space_groups[141] = sg
space_groups['I 41/a m d :2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-3,-1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-3,-3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,-1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([3,5,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([3,3,5])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([3,5,5])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([3,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,-1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,-1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,-1,-1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(142, 'I 41/a c d :2', transformations)
space_groups[142] = sg
space_groups['I 41/a c d :2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(143, 'P 3', transformations)
space_groups[143] = sg
space_groups['P 3'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(144, 'P 31', transformations)
space_groups[144] = sg
space_groups['P 31'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(145, 'P 32', transformations)
space_groups[145] = sg
space_groups['P 32'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(146, 'R 3 :H', transformations)
space_groups[146] = sg
space_groups['R 3 :H'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(147, 'P -3', transformations)
space_groups[147] = sg
space_groups['P -3'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(148, 'R -3 :H', transformations)
space_groups[148] = sg
space_groups['R -3 :H'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(149, 'P 3 1 2', transformations)
space_groups[149] = sg
space_groups['P 3 1 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(150, 'P 3 2 1', transformations)
space_groups[150] = sg
space_groups['P 3 2 1'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(151, 'P 31 1 2', transformations)
space_groups[151] = sg
space_groups['P 31 1 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(152, 'P 31 2 1', transformations)
space_groups[152] = sg
space_groups['P 31 2 1'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(153, 'P 32 1 2', transformations)
space_groups[153] = sg
space_groups['P 32 1 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(154, 'P 32 2 1', transformations)
space_groups[154] = sg
space_groups['P 32 2 1'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(155, 'R 3 2 :H', transformations)
space_groups[155] = sg
space_groups['R 3 2 :H'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(156, 'P 3 m 1', transformations)
space_groups[156] = sg
space_groups['P 3 m 1'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(157, 'P 3 1 m', transformations)
space_groups[157] = sg
space_groups['P 3 1 m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(158, 'P 3 c 1', transformations)
space_groups[158] = sg
space_groups['P 3 c 1'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(159, 'P 3 1 c', transformations)
space_groups[159] = sg
space_groups['P 3 1 c'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(160, 'R 3 m :H', transformations)
space_groups[160] = sg
space_groups['R 3 m :H'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,7])
trans_den = N.array([3,3,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,7])
trans_den = N.array([3,3,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,7])
trans_den = N.array([3,3,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,5])
trans_den = N.array([3,3,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,5])
trans_den = N.array([3,3,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,5])
trans_den = N.array([3,3,6])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(161, 'R 3 c :H', transformations)
space_groups[161] = sg
space_groups['R 3 c :H'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(162, 'P -3 1 m', transformations)
space_groups[162] = sg
space_groups['P -3 1 m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(163, 'P -3 1 c', transformations)
space_groups[163] = sg
space_groups['P -3 1 c'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(164, 'P -3 m 1', transformations)
space_groups[164] = sg
space_groups['P -3 m 1'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(165, 'P -3 c 1', transformations)
space_groups[165] = sg
space_groups['P -3 c 1'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(166, 'R -3 m :H', transformations)
space_groups[166] = sg
space_groups['R -3 m :H'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,2,7])
trans_den = N.array([3,3,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,2,7])
trans_den = N.array([3,3,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,2,7])
trans_den = N.array([3,3,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,2,2])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,1])
trans_den = N.array([3,3,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,1])
trans_den = N.array([3,3,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,2,1])
trans_den = N.array([3,3,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([2,1,5])
trans_den = N.array([3,3,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([2,1,5])
trans_den = N.array([3,3,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([2,1,5])
trans_den = N.array([3,3,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([2,1,1])
trans_den = N.array([3,3,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,-1])
trans_den = N.array([3,3,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,-1])
trans_den = N.array([3,3,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([2,1,-1])
trans_den = N.array([3,3,6])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(167, 'R -3 c :H', transformations)
space_groups[167] = sg
space_groups['R -3 c :H'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(168, 'P 6', transformations)
space_groups[168] = sg
space_groups['P 6'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,5])
trans_den = N.array([1,1,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(169, 'P 61', transformations)
space_groups[169] = sg
space_groups['P 61'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,5])
trans_den = N.array([1,1,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(170, 'P 65', transformations)
space_groups[170] = sg
space_groups['P 65'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(171, 'P 62', transformations)
space_groups[171] = sg
space_groups['P 62'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(172, 'P 64', transformations)
space_groups[172] = sg
space_groups['P 64'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(173, 'P 63', transformations)
space_groups[173] = sg
space_groups['P 63'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(174, 'P -6', transformations)
space_groups[174] = sg
space_groups['P -6'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(175, 'P 6/m', transformations)
space_groups[175] = sg
space_groups['P 6/m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(176, 'P 63/m', transformations)
space_groups[176] = sg
space_groups['P 63/m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(177, 'P 6 2 2', transformations)
space_groups[177] = sg
space_groups['P 6 2 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,5])
trans_den = N.array([1,1,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,5])
trans_den = N.array([1,1,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,6])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(178, 'P 61 2 2', transformations)
space_groups[178] = sg
space_groups['P 61 2 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,5])
trans_den = N.array([1,1,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,6])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,5])
trans_den = N.array([1,1,6])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(179, 'P 65 2 2', transformations)
space_groups[179] = sg
space_groups['P 65 2 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(180, 'P 62 2 2', transformations)
space_groups[180] = sg
space_groups['P 62 2 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,2])
trans_den = N.array([1,1,3])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(181, 'P 64 2 2', transformations)
space_groups[181] = sg
space_groups['P 64 2 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(182, 'P 63 2 2', transformations)
space_groups[182] = sg
space_groups['P 63 2 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(183, 'P 6 m m', transformations)
space_groups[183] = sg
space_groups['P 6 m m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(184, 'P 6 c c', transformations)
space_groups[184] = sg
space_groups['P 6 c c'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(185, 'P 63 c m', transformations)
space_groups[185] = sg
space_groups['P 63 c m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(186, 'P 63 m c', transformations)
space_groups[186] = sg
space_groups['P 63 m c'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(187, 'P -6 m 2', transformations)
space_groups[187] = sg
space_groups['P -6 m 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(188, 'P -6 c 2', transformations)
space_groups[188] = sg
space_groups['P -6 c 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(189, 'P -6 2 m', transformations)
space_groups[189] = sg
space_groups['P -6 2 m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(190, 'P -6 2 c', transformations)
space_groups[190] = sg
space_groups['P -6 2 c'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(191, 'P 6/m m m', transformations)
space_groups[191] = sg
space_groups['P 6/m m m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(192, 'P 6/m c c', transformations)
space_groups[192] = sg
space_groups['P 6/m c c'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(193, 'P 63/m c m', transformations)
space_groups[193] = sg
space_groups['P 63/m c m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,1,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,1,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,-1,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,-1,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(194, 'P 63/m m c', transformations)
space_groups[194] = sg
space_groups['P 63/m m c'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(195, 'P 2 3', transformations)
space_groups[195] = sg
space_groups['P 2 3'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(196, 'F 2 3', transformations)
space_groups[196] = sg
space_groups['F 2 3'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(197, 'I 2 3', transformations)
space_groups[197] = sg
space_groups['I 2 3'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(198, 'P 21 3', transformations)
space_groups[198] = sg
space_groups['P 21 3'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(199, 'I 21 3', transformations)
space_groups[199] = sg
space_groups['I 21 3'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(200, 'P m -3', transformations)
space_groups[200] = sg
space_groups['P m -3'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(201, 'P n -3 :2', transformations)
space_groups[201] = sg
space_groups['P n -3 :2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(202, 'F m -3', transformations)
space_groups[202] = sg
space_groups['F m -3'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([4,4,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([4,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([4,4,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([4,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([4,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([4,4,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([4,4,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([4,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([4,4,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([4,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([4,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([4,4,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,1])
trans_den = N.array([4,4,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,3,3])
trans_den = N.array([1,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([4,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,1])
trans_den = N.array([4,4,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([4,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,3,3])
trans_den = N.array([1,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,3,3])
trans_den = N.array([1,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([4,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,3,1])
trans_den = N.array([4,4,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([-1,1,1])
trans_den = N.array([4,4,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([-1,1,1])
trans_den = N.array([4,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([-1,1,1])
trans_den = N.array([4,4,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([-1,1,1])
trans_den = N.array([4,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,1,1])
trans_den = N.array([4,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,1,1])
trans_den = N.array([4,4,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([3,1,1])
trans_den = N.array([4,4,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([2,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([3,0,3])
trans_den = N.array([4,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([3,1,1])
trans_den = N.array([4,4,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([3,0,3])
trans_den = N.array([4,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([2,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([2,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([3,0,3])
trans_den = N.array([4,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([3,1,1])
trans_den = N.array([4,4,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,-1,1])
trans_den = N.array([4,4,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,-1,1])
trans_den = N.array([2,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([4,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,-1,1])
trans_den = N.array([4,4,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([4,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,-1,1])
trans_den = N.array([2,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,-1,1])
trans_den = N.array([2,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([4,1,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,-1,1])
trans_den = N.array([4,4,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([3,3,0])
trans_den = N.array([4,4,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,1])
trans_den = N.array([2,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([3,1,1])
trans_den = N.array([4,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([3,3,0])
trans_den = N.array([4,4,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([3,1,1])
trans_den = N.array([4,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,1])
trans_den = N.array([2,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,3,1])
trans_den = N.array([2,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([3,1,1])
trans_den = N.array([4,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([3,3,0])
trans_den = N.array([4,4,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([4,4,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,-1])
trans_den = N.array([2,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,-1])
trans_den = N.array([4,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([4,4,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,-1])
trans_den = N.array([4,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,-1])
trans_den = N.array([2,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,-1])
trans_den = N.array([2,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,-1])
trans_den = N.array([4,2,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([4,4,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(203, 'F d -3 :2', transformations)
space_groups[203] = sg
space_groups['F d -3 :2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(204, 'I m -3', transformations)
space_groups[204] = sg
space_groups['I m -3'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,-1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,-1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,-1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(205, 'P a -3', transformations)
space_groups[205] = sg
space_groups['P a -3'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,-1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([-1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,-1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(206, 'I a -3', transformations)
space_groups[206] = sg
space_groups['I a -3'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(207, 'P 4 3 2', transformations)
space_groups[207] = sg
space_groups['P 4 3 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(208, 'P 42 3 2', transformations)
space_groups[208] = sg
space_groups['P 42 3 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(209, 'F 4 3 2', transformations)
space_groups[209] = sg
space_groups['F 4 3 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([3,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([3,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([3,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([3,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([3,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([3,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([3,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([3,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([3,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([3,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([3,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([3,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([3,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([3,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([3,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([3,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([3,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([3,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([3,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([3,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([3,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([3,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([3,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([3,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(210, 'F 41 3 2', transformations)
space_groups[210] = sg
space_groups['F 41 3 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(211, 'I 4 3 2', transformations)
space_groups[211] = sg
space_groups['I 4 3 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([3,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([3,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([3,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([3,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([3,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([3,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(212, 'P 43 3 2', transformations)
space_groups[212] = sg
space_groups['P 43 3 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([3,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([3,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([3,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([3,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([3,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([3,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(213, 'P 41 3 2', transformations)
space_groups[213] = sg
space_groups['P 41 3 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([3,3,5])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([3,5,5])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([3,5,5])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([3,5,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([3,5,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([3,3,5])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([3,5,5])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([3,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([3,3,5])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([3,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([3,5,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([3,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(214, 'I 41 3 2', transformations)
space_groups[214] = sg
space_groups['I 41 3 2'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(215, 'P -4 3 m', transformations)
space_groups[215] = sg
space_groups['P -4 3 m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(216, 'F -4 3 m', transformations)
space_groups[216] = sg
space_groups['F -4 3 m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(217, 'I -4 3 m', transformations)
space_groups[217] = sg
space_groups['I -4 3 m'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(218, 'P -4 3 n', transformations)
space_groups[218] = sg
space_groups['P -4 3 n'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,1])
trans_den = N.array([1,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([2,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([2,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
sg = SpaceGroup(219, 'F -4 3 c', transformations)
space_groups[219] = sg
space_groups['F -4 3 c'] = sg
transformations = []
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,0])
trans_den = N.array([1,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,-1,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,-1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,0,0,1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,-1,0,0,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,1,0,0,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,0,0,-1,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,-1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([0,0,1])
trans_den = N.array([1,1,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,1,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([1,0,0])
trans_den = N.array([2,1,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,-1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([0,1,0])
trans_den = N.array([1,2,1])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,-1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,3,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,1,0,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,-1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([1,3,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,0,1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([1,0,0,0,1,0,0,0,1])
rot.shape = (3, 3)
trans_num = N.array([1,1,1])
trans_den = N.array([2,2,2])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,1,0,-1,0])
rot.shape = (3, 3)
trans_num = N.array([3,3,5])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([-1,0,0,0,0,-1,0,1,0])
rot.shape = (3, 3)
trans_num = N.array([3,5,5])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,-1,0,-1,0,1,0,0])
rot.shape = (3, 3)
trans_num = N.array([3,5,5])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,0,1,0,-1,0,-1,0,0])
rot.shape = (3, 3)
trans_num = N.array([3,5,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,1,0,-1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([3,5,3])
trans_den = N.array([4,4,4])
transformations.append((rot, trans_num, trans_den))
rot = N.array([0,-1,0,1,0,0,0,0,-1])
rot.shape = (3, 3)
trans_num = N.array([3,3,5])
trans_den = | N.array([4,4,4]) | numpy.array |
#!/usr/bin/python
"""
Perform HI survey Fisher forecast based on Pedro's formalism (see notes from
August 2013).
Requires up-to-date NumPy, SciPy (tested with version 0.11.0) and matplotlib.
A number of functions can optionally use MPI (mpi4py).
(<NAME> & <NAME>, 2013--2014)
"""
import numpy as np
import scipy.integrate
import scipy.interpolate
from scipy.misc import derivative
import pylab as P
import matplotlib.patches
import matplotlib.cm
from .units import *
import uuid, os, sys, copy
from hashlib import md5
from . import camb_wrapper as camb
from . import mg_growth
from tempfile import gettempdir
# No. of samples in log space in each dimension. 300 seems stable for (AA).
NSAMP_K = 500 # 1000
NSAMP_U = 1500 # 3000
# Debug settings (set all to False for normal operation)
DBG_PLOT_CUMUL_INTEGRAND = False # Plot k-space integrand of the dP/P integral
INF_NOISE = 1e200 # Very large finite no. used to denote infinite noise
EXP_OVERFLOW_VAL = 250. # Max. value of exponent for np.exp() before assuming overflow
# Decide which RSD function to use (N.B. interpretation of sigma_NL changes
# slightly depending on option)
RSD_FUNCTION = 'kaiser'
#RSD_FUNCTION = 'loeb'
# Location of CAMB fiducial P(k) file
# NOTE: Currently expects CAMB P(k) needs to be at chosen z value (z=0 here).
CAMB_KMAX = 20. / 0.7 # Max. k for CAMB, in h Mpc^-1
CAMB_EXEC = "/home/phil/lynx/oslo/bao21cm/camb" # Directory containing camb executable
################################################################################
# Plotting functions
################################################################################
def figure_of_merit(p1, p2, F, cov=None, twosigma=False):
"""
DETF Figure of Merit, defined as the area inside the 95% contour of w0,wa.
fom = 1 / [ sqrt( |cov(w0, wa)| ) ], where cov = F^-1, and cov(w0, wa)
is the w0,wa 2x2 sub-matrix of the covmat.
If twosigma=True, there is an additional factor of 1/4 that comes from
looking at the 95% (2-sigma) contours.
"""
if cov == None: cov = np.linalg.inv(F)
# Calculate determinant
c11 = cov[p1,p1]
c22 = cov[p2,p2]
c12 = cov[p1,p2]
det = c11*c22 - c12**2.
fom = 1. / np.sqrt(det)
if twosigma: fom *= 0.25
return fom
def ellipse_for_fisher_params(p1, p2, F, Finv=None):
"""
Return covariance ellipse parameters (width, height, angle) from
Fisher matrix F, for parameters in the matrix with indices p1 and p2.
See arXiv:0906.4123 for expressions.
"""
if Finv is not None:
cov = Finv
else:
cov = np.linalg.inv(F)
c11 = cov[p1,p1]
c22 = cov[p2,p2]
c12 = cov[p1,p2]
# Calculate ellipse parameters (Eqs. 2-4 of Coe, arXiv:0906.4123)
y1 = 0.5*(c11 + c22)
y2 = np.sqrt( 0.25*(c11 - c22)**2. + c12**2. )
a = 2. * np.sqrt(y1 + y2) # Factor of 2 because def. is *total* width of ellipse
b = 2. * np.sqrt(y1 - y2)
# Flip major/minor axis depending on which parameter is dominant
if c11 >= c22:
w = a; h = b
else:
w = b; h = a
# Handle c11==c22 case for angle calculation
if c11 != c22:
ang = 0.5*np.arctan( 2.*c12 / (c11 - c22) )
else:
ang = 0.5*np.arctan( 2.*c12 / 1e-20 ) # Sign sensitivity here
# Factors to use if 1,2,3-sigma contours required
alpha = [1.52, 2.48, 3.44]
return w, h, ang * 180./np.pi, alpha
def plot_ellipse(F, p1, p2, fiducial, names, ax=None):
"""
Show error ellipse for 2 parameters from Fisher matrix.
"""
alpha = [1.52, 2.48, 3.44] # 1/2/3-sigma scalings, from Table 1 of arXiv:0906.4123
# Get ellipse parameters
x, y = fiducial
a, b, ang = ellipse_for_fisher_params(p1, p2, F)
# Get 1,2,3-sigma ellipses and plot
ellipses = [matplotlib.patches.Ellipse(xy=(x, y), width=alpha[k]*b,
height=alpha[k]*a, angle=ang, fc='none') for k in range(0, 2)]
if ax is None: ax = P.subplot(111)
for e in ellipses: ax.add_patch(e)
ax.plot(x, y, 'bx')
if ax is None:
ax.set_xlabel(names[0])
ax.set_ylabel(names[1])
P.show()
def triangle_plot(fiducial, F, names, priors=None, skip=None):
"""
Show triangle plot of 2D error ellipses from Fisher matrix.
"""
alpha = [1.52, 2.48, 3.44] # 1/2/3-sigma scalings, from Table 1 of arXiv:0906.4123
# Calculate covmat
N = len(fiducial)
Finv = np.linalg.inv(F)
# Remove unwanted variables (after marginalisation though)
if skip is not None:
Finv = fisher_with_excluded_params(Finv, skip)
# Loop through elements of matrix, plotting 2D contours or 1D marginals
for i in range(N):
for j in range(N):
x = fiducial[i]; y = fiducial[j]
# Plot 2D contours
if j > i:
a, b, ang = ellipse_for_fisher_params(i, j, F=None, Finv=Finv)
# Get 1,2,3-sigma ellipses and plot
ellipses = [matplotlib.patches.Ellipse(xy=(x, y), width=alpha[k]*b,
height=alpha[k]*a, angle=ang, fc='none') for k in range(0, 2)]
ax = P.subplot(N, N, N*j + i + 1)
for e in ellipses: ax.add_patch(e)
P.plot(x, y, 'bx')
ax.tick_params(axis='both', which='major', labelsize=8)
ax.tick_params(axis='both', which='minor', labelsize=8)
# Plot 1D Gaussian
if i==j:
ax = P.subplot(N, N, N*i + j + 1)
P.title(names[i])
u = fiducial[i]
std = np.sqrt(Finv[i,i])
_x = np.linspace(u - 4.*std, u + 4.*std, 500)
_y = np.exp(-0.5*(_x - u)**2. / std**2.) \
/ np.sqrt(2.*np.pi*std**2.)
P.plot(_x, _y, 'r-')
# Add priors to plot
if priors is not None:
if not np.isinf(priors[i]):
std = priors[i]
yp = np.exp(-0.5*(_x - u)**2. / priors[i]**2.) \
/ np.sqrt(2.*np.pi*std**2.)
P.plot(_x, yp, 'b-', alpha=0.5)
ax.tick_params(axis='both', which='major', labelsize=8)
ax.tick_params(axis='both', which='minor', labelsize=8)
if i==0: P.ylabel(names[j])
P.show()
def fix_log_plot(y, yerr):
"""
Corrects errorbars for log plot.
"""
yup = yerr.copy()
ylow = yerr.copy()
ylow[np.where(y - yerr <= 0.)] = y[np.where(y - yerr <= 0.)]*0.99999
# Correct inf's too
ylow[np.isinf(yerr)] = y[np.isinf(yerr)]*0.99999
yup[np.isinf(yerr)] = y[np.isinf(yup)]*1e5
return yup, ylow
def plot_corrmat(F, names):
"""
Plot the correlation matrix for a given Fisher matrix.
Returns matplotlib Figure object.
"""
# Construct correlation matrix
F_corr = np.zeros(F.shape)
for ii in range(F.shape[0]):
for jj in range(F.shape[0]):
F_corr[ii,jj] = F[ii, jj] / np.sqrt(F[ii,ii] * F[jj,jj])
# Plot corrmat
fig = P.figure()
ax = fig.add_subplot(111)
#F_corr = F_corr**3.
matshow = ax.matshow(F_corr, vmin=-1., vmax=1., cmap=matplotlib.cm.get_cmap("RdBu"))
#ax.title("z = %3.3f" % zc[i])
fig.colorbar(matshow)
"""
# Label the ticks correctly
locs, labels = (ax.get_xticks(), ax.get_xticklabels())
print labels, len(labels)
print locs, len(locs)
#labels = ['',]
labels = ['',] + names
new_labels = [x.format(locs[ii]) for ii,x in enumerate(labels)]
ax.set_xticks(locs, new_labels)
locs, labels = (ax.get_yticks(), ax.get_yticklabels())
ax.set_yticks(locs, new_labels)
ax.xlim((-0.5, 5.5))
ax.ylim((5.5, -0.5))
"""
lbls = ["%d:%s" % (i, names[i]) for i in range(len(names))]
#ax.set_xlabel(lbls)
ax.text(1.3, 0.99, "\n".join(lbls), horizontalalignment='left',
verticalalignment='top', transform=ax.transAxes)
for tick in ax.xaxis.get_major_ticks():
tick.tick1line.set_markersize(0)
tick.tick2line.set_markersize(0)
tick.label1.set_horizontalalignment('center')
fig.show()
P.show()
#P.savefig("corrcoeff-%s-%3.3f.png" % (names[k], zc[i]))
################################################################################
# Binning strategies
################################################################################
def zbins_fixed(expt, zbin_min=0., zbin_max=6., dz=0.1):
"""
Construct a sensible binning for a given experiment for bins with fixed dz,
equally spaced from z=zbin_min. If the band does not exactly divide into
the binning, smaller bins will be added at the end of the band.
"""
zs = np.arange(zbin_min, zbin_max, dz)
zc = (zs + 0.5*dz)[:-1]
# Get redshift ranges of actual experiment
zmin = expt['nu_line'] / expt['survey_numax'] - 1.
zmax = expt['nu_line'] / (expt['survey_numax'] - expt['survey_dnutot']) - 1.
# Remove bins with no overlap
idxs = np.where(np.logical_and(zs >= zmin, zs <= zmax))
zs = zs[idxs]
# Add end bins to cover as much of the full band as possible
if (zs[0] - zmin) > 0.1*dz:
zs = np.concatenate(([zmin,], zs))
if (zmax - zs[-1]) > 0.1*dz:
zs = np.concatenate((zs, [zmax,]))
# Return bin edges and centroids
zc = np.array([0.5*(zs[i+1] + zs[i]) for i in range(zs.size - 1)])
return zs, zc
def zbins_equal_spaced(expt, bins=None, dz=None):
"""
Return redshift bin edges and centroids for an equally-spaced redshift
binning.
"""
if (bins is not None) and (dz is not None):
raise ValueError("Specify either bins *or* dz; you can't specify both.")
# Get redshift ranges
zmin = expt['nu_line'] / expt['survey_numax'] - 1.
zmax = expt['nu_line'] / (expt['survey_numax'] - expt['survey_dnutot']) - 1.
# Set number of bins
if dz is not None:
bins = int((zmax - zmin) / dz)
# Return bin edges and centroids
zs = np.linspace(zmin, zmax, bins+1)
zc = [0.5*(zs[i+1] + zs[i]) for i in range(zs.size - 1)]
return zs, np.array(zc)
def zbins_const_dr(expt, cosmo, bins=None, nsamples=500, initial_dz=None):
"""
Return redshift bin edges and centroids for bins that are equally-spaced
in r(z). Will either split the full range into some number of bins, or else
fill the range using bins of const. dr. set from an initial bin delta_z.
"""
# Get redshift range
zmin = expt['nu_line'] / expt['survey_numax'] - 1.
zmax = expt['nu_line'] / (expt['survey_numax'] - expt['survey_dnutot']) - 1.
# Fiducial cosmological values
_z = np.linspace(0., zmax, nsamples)
a = 1. / (1. + _z)
H0 = (100.*cosmo['h']); w0 = cosmo['w0']; wa = cosmo['wa']
om = cosmo['omega_M_0']; ol = cosmo['omega_lambda_0']
ok = 1. - om - ol
# Sample comoving dist. r(z) at discrete points (assumes ok~0 in last step)
omegaDE = ol * np.exp(3.*wa*(a - 1.)) / a**(3.*(1. + w0 + wa))
E = np.sqrt( om * a**(-3.) + ok * a**(-2.) + omegaDE )
_r = (C/H0) * np.concatenate( ([0.], scipy.integrate.cumtrapz(1./E, _z)) )
# Interpolate to get z(r) and r(z)
r_z = scipy.interpolate.interp1d(_z, _r, kind='linear')
z_r = scipy.interpolate.interp1d(_r, _z, kind='linear')
# Return bin edges and centroids
if bins is not None:
# Get certain no. of bins
rbins = np.linspace(r_z(zmin), r_z(zmax), bins+1)
zbins = z_r(rbins)
else:
# Get bins with const. dr from initial delta_z
rmin = r_z(zmin)
rmax = r_z(zmax)
dr = r_z(zmin + initial_dz) - rmin
print("Const. dr =", dr, "Mpc")
# Loop through range, filling with const. dr bins as far as possible
rtot = rmin
zbins = []
while rtot < rmax:
zbins.append(z_r(rtot))
rtot += dr
zbins.append(z_r(rmax))
zbins = np.array(zbins)
zc = [0.5*(zbins[i+1] + zbins[i]) for i in range(zbins.size - 1)]
return zbins, np.array(zc)
def zbins_const_dnu(expt, cosmo, bins=None, dnu=None, initial_dz=None):
"""
Return redshift bin edges and centroids for bins that are equally-spaced
in frequency (nu). Will either split the full range into some number of
bins, or else fill the range using bins of const. dnu set from an initial
bin delta_z.
"""
# Get redshift range
zmin = expt['nu_line'] / expt['survey_numax'] - 1.
zmax = expt['nu_line'] / (expt['survey_numax'] - expt['survey_dnutot']) - 1.
numax = expt['nu_line'] / (1. + zmin)
numin = expt['nu_line'] / (1. + zmax)
# nu as a function of z
nu_z = lambda zz: expt['nu_line'] / (1. + zz)
z_nu = lambda f: expt['nu_line'] / f - 1.
# Return bin edges and centroids
if bins is not None:
# Get certain no. of bins
nubins = np.linspace(numax, numin, bins+1)
zbins = z_nu(nubins)
else:
# Get bins with const. dr from initial delta_z
if dnu is None:
dnu = nu_z(zmin + initial_dz) - nu_z(zmin)
dnu = -1. * np.abs(dnu) # dnu negative, to go from highest to lowest freq.
# Loop through range, filling with const. dr bins as far as possible
nu = numax
zbins = []
while nu > numin:
zbins.append(z_nu(nu))
nu += dnu
zbins.append(z_nu(numin))
# Check we haven't exactly hit the edge (to ensure no zero-width bins)
if np.abs(zbins[-1] - zbins[-2]) < 1e-4:
del zbins[-2] # Remove interstitial bin edge
zbins = np.array(zbins)
zc = [0.5*(zbins[i+1] + zbins[i]) for i in range(zbins.size - 1)]
return zbins, np.array(zc)
def zbins_split_width(expt, dz=(0.1, 0.3), zsplit=2.):
"""
Construct a binning scheme with bin widths that change after a certain
redshift. The first redshift range is filled with equal-sized bins that may
go over the split redshift. The remaining range is filled with bins of the
other width (apart from the last bin, that may be truncated).
Parameters
----------
expt : dict
Dict of experimental settings.
dz : tuple (length 2)
Widths of redshift bins before and after the split redshift.
zsplit : float
Redshift at which to change from the first bin width to the second.
"""
# Get redshift ranges of actual experiment
zmin = expt['nu_line'] / expt['survey_numax'] - 1.
zmax = expt['nu_line'] / (expt['survey_numax'] - expt['survey_dnutot']) - 1.
# Special case if zmin > zsplit or zmax < zsplit
if (zmin > zsplit) or (zmax < zsplit):
_dz = dz[0] if (zmax < zsplit) else dz[1]
nbins = np.floor((zmax - zmin) / _dz)
zs = np.linspace(zmin, zmin + nbins*_dz, nbins+1)
if (zmax - zs[-1]) > 0.2 * _dz:
zs = np.concatenate((zs, [zmax,]))
zc = np.array([0.5*(zs[i+1] + zs[i]) for i in range(zs.size - 1)])
return zs, zc
# Fill first range with equal-sized bins with width dz[0]
nbins = np.ceil((zsplit - zmin) / dz[0])
z1 = np.linspace(zmin, zmin + nbins*dz[0], nbins+1)
# Fill remaining range with equal-sized bins with width dz[1]
nbins = np.floor((zmax - z1[-1]) / dz[1])
z2 = np.linspace(z1[-1] + dz[1], z1[-1] + nbins*dz[1], nbins)
zs = np.concatenate((z1, z2))
# Add final bin to fill range only if >20% of dz[1]
if (zmax - zs[-1]) > 0.2 * dz[1]:
zs = np.concatenate((zs, [zmax,]))
zc = np.array([0.5*(zs[i+1] + zs[i]) for i in range(zs.size - 1)])
return zs, zc
################################################################################
# Experiment specification handler functions
################################################################################
def load_interferom_file(fname):
"""
Load n(u) file for interferometer and return linear interpolation function.
"""
x, _nx = | np.genfromtxt(fname) | numpy.genfromtxt |
"""Tests for the mask.py script."""
import pytest
import sys
import os
import numpy as np
import matplotlib.pyplot as plt
import unittest.mock as mock
from deltametrics import cube
from deltametrics import mask
from deltametrics.plan import OpeningAnglePlanform
from deltametrics.sample_data import _get_rcm8_path, _get_golf_path
rcm8_path = _get_rcm8_path()
with pytest.warns(UserWarning):
rcm8cube = cube.DataCube(rcm8_path)
golf_path = _get_golf_path()
golfcube = cube.DataCube(golf_path)
_OAP_0 = OpeningAnglePlanform.from_elevation_data(
golfcube['eta'][-1, :, :],
elevation_threshold=0)
_OAP_05 = OpeningAnglePlanform.from_elevation_data(
golfcube['eta'][-1, :, :],
elevation_threshold=0.5)
@mock.patch.multiple(mask.BaseMask,
__abstractmethods__=set())
class TestBaseMask:
"""
To test the BaseMask, we patch the base job with a filled abstract method
`.run()`.
.. note:: This patch is handled at the class level above!!
"""
fake_input = np.ones((100, 200))
@mock.patch('deltametrics.mask.BaseMask._set_shape_mask')
def test_name_setter(self, patched):
basemask = mask.BaseMask('somename', self.fake_input)
assert basemask.mask_type == 'somename'
patched.assert_called() # this would change the shape
assert basemask.shape is None # so shape is not set
assert basemask._mask is None # so mask is not set
def test_simple_example(self):
basemask = mask.BaseMask('field', self.fake_input)
# make a bunch of assertions
assert np.all(basemask._mask == False)
assert np.all(basemask.integer_mask == 0)
assert basemask._mask is basemask.mask
assert basemask.shape == self.fake_input.shape
def test_trim_mask_length(self):
basemask = mask.BaseMask('field', self.fake_input)
# mock as though the mask were made
basemask._mask = self.fake_input.astype(bool)
assert np.all(basemask.integer_mask == 1)
_l = 5
basemask.trim_mask(length=_l)
assert basemask._mask.dtype == bool
assert np.all(basemask.integer_mask[:_l, :] == 0)
assert np.all(basemask.integer_mask[_l:, :] == 1)
@pytest.mark.xfail(raises=NotImplementedError, strict=True,
reason='Have not implemented pathway.')
def test_trim_mask_cube(self):
basemask = mask.BaseMask('field', self.fake_input)
# mock as though the mask were made
basemask._mask = self.fake_input.astype(bool)
assert np.all(basemask.integer_mask == 1)
basemask.trim_mask(golfcube)
# assert np.all(basemask.integer_mask[:5, :] == 0)
# assert np.all(basemask.integer_mask[5:, :] == 1)
@pytest.mark.xfail(raises=NotImplementedError, strict=True,
reason='Have not implemented pathway.')
def test_trim_mask_noargs(self):
basemask = mask.BaseMask('field', self.fake_input)
# mock as though the mask were made
basemask._mask = self.fake_input.astype(bool)
assert np.all(basemask.integer_mask == 1)
basemask.trim_mask()
# assert np.all(basemask.integer_mask[:5, :] == 0)
# assert np.all(basemask.integer_mask[5:, :] == 1)
def test_trim_mask_axis1_withlength(self):
basemask = mask.BaseMask('field', self.fake_input)
# mock as though the mask were made
basemask._mask = self.fake_input.astype(bool)
assert np.all(basemask.integer_mask == 1)
_l = 5
basemask.trim_mask(axis=0, length=_l)
assert basemask._mask.dtype == bool
assert np.all(basemask.integer_mask[:, :_l] == 0)
assert np.all(basemask.integer_mask[:, _l:] == 1)
def test_trim_mask_diff_True(self):
basemask = mask.BaseMask('field', self.fake_input)
# everything is False (0)
assert np.all(basemask.integer_mask == 0)
_l = 5
basemask.trim_mask(value=True, length=_l)
assert basemask._mask.dtype == bool
assert np.all(basemask.integer_mask[:_l, :] == 1)
assert np.all(basemask.integer_mask[_l:, :] == 0)
def test_trim_mask_diff_ints(self):
basemask = mask.BaseMask('field', self.fake_input)
# everything is False (0)
assert np.all(basemask.integer_mask == 0)
_l = 5
basemask.trim_mask(value=1, length=_l)
assert basemask._mask.dtype == bool
assert np.all(basemask.integer_mask[:_l, :] == 1)
basemask.trim_mask(value=0, length=_l)
assert basemask._mask.dtype == bool
assert np.all(basemask.integer_mask[:_l, :] == 0)
basemask.trim_mask(value=5, length=_l)
assert basemask._mask.dtype == bool
assert np.all(basemask.integer_mask[:_l, :] == 1)
basemask.trim_mask(value=5.534, length=_l)
assert basemask._mask.dtype == bool
assert np.all(basemask.integer_mask[:_l, :] == 1)
def test_trim_mask_toomanyargs(self):
basemask = mask.BaseMask('field', self.fake_input)
with pytest.raises(ValueError):
basemask.trim_mask('arg1', 'arg2', value=1, length=1)
def test_show(self):
"""
Here, we just test whether it works, and whether it takes a
specific axis.
"""
basemask = mask.BaseMask('field', self.fake_input)
# test show with nothing
basemask.show()
plt.close()
# test show with colorbar
basemask.show(colorbar=True)
plt.close()
# test show with title
basemask.show(title='a title')
plt.close()
# test show with axes, bad values
fig, ax = plt.subplots()
basemask.show(ax=ax)
plt.close()
def test_show_error_nomask(self):
"""
Here, we just test whether it works, and whether it takes a
specific axis.
"""
basemask = mask.BaseMask('field', self.fake_input)
# mock as though something went wrong
basemask._mask = None
with pytest.raises(RuntimeError):
basemask.show()
def test_no_data(self):
"""Test when no data input raises error."""
with pytest.raises(ValueError, match=r'Expected 1 input, got 0.'):
_ = mask.BaseMask('field')
def test_invalid_data(self):
"""Test invalid data input."""
with pytest.raises(TypeError, match=r'Unexpected type was input: .*'):
_ = mask.BaseMask('field', 'a string!!')
def test_invalid_second_data(self):
"""Test invalid data input."""
with pytest.raises(TypeError, match=r'First input to mask .*'):
_ = mask.BaseMask('field', np.zeros((100, 200)), 'a string!!')
def test_return_empty(self):
"""Test when no data input, but allow empty, returns empty."""
empty_basemask = mask.BaseMask('field', allow_empty=True)
assert empty_basemask.mask_type == 'field'
assert empty_basemask.shape is None
assert empty_basemask._mask is None
assert empty_basemask._mask is empty_basemask.mask
def test_is_mask_deprecationwarning(self):
"""Test that TypeError is raised if is_mask is invalid."""
with pytest.warns(DeprecationWarning):
_ = mask.BaseMask('field', self.fake_input,
is_mask='invalid')
with pytest.warns(DeprecationWarning):
_ = mask.BaseMask('field', self.fake_input,
is_mask=True)
def test_3dinput_deprecationerror(self):
"""Test that TypeError is raised if is_mask is invalid."""
with pytest.raises(ValueError, match=r'Creating a `Mask` .*'):
_ = mask.BaseMask('field', np.random.uniform(size=(10, 100, 200)))
class TestShorelineMask:
"""Tests associated with the mask.ShorelineMask class."""
# define an input mask for the mask instantiation pathway
_ElevationMask = mask.ElevationMask(
golfcube['eta'][-1, :, :],
elevation_threshold=0)
def test_default_vals_array(self):
"""Test that instantiation works for an array."""
# define the mask
shoremask = mask.ShorelineMask(
rcm8cube['eta'][-1, :, :],
elevation_threshold=0)
# make assertions
assert shoremask._input_flag == 'array'
assert shoremask.mask_type == 'shoreline'
assert shoremask.angle_threshold > 0
assert shoremask._mask.dtype == bool
assert isinstance(shoremask._mask, np.ndarray)
@pytest.mark.xfail(raises=NotImplementedError, strict=True,
reason='Have not implemented pathway.')
def test_default_vals_cube(self):
"""Test that instantiation works for an array."""
# define the mask
shoremask = mask.ShorelineMask(rcm8cube, t=-1)
# make assertions
assert shoremask._input_flag == 'cube'
assert shoremask.mask_type == 'shoreline'
assert shoremask.angle_threshold > 0
assert shoremask._mask.dtype == bool
@pytest.mark.xfail(raises=NotImplementedError, strict=True,
reason='Have not implemented pathway.')
def test_default_vals_cubewithmeta(self):
"""Test that instantiation works for an array."""
# define the mask
shoremask = mask.ShorelineMask(golfcube, t=-1)
# make assertions
assert shoremask._input_flag == 'cube'
assert shoremask.mask_type == 'shoreline'
assert shoremask.angle_threshold > 0
assert shoremask._mask.dtype == bool
@pytest.mark.xfail(raises=NotImplementedError, strict=True,
reason='Have not implemented pathway.')
def test_default_vals_mask(self):
"""Test that instantiation works for an array."""
# define the mask
shoremask = mask.ShorelineMask(self._ElevationMask)
# make assertions
assert shoremask._input_flag == 'mask'
assert shoremask.mask_type == 'shoreline'
assert shoremask.angle_threshold > 0
assert shoremask._mask.dtype == bool
def test_angle_threshold(self):
"""Test that instantiation works for an array."""
# define the mask
shoremask_default = mask.ShorelineMask(
rcm8cube['eta'][-1, :, :],
elevation_threshold=0)
shoremask = mask.ShorelineMask(
rcm8cube['eta'][-1, :, :],
elevation_threshold=0,
angle_threshold=45)
# make assertions
assert shoremask.angle_threshold == 45
assert not np.all(shoremask_default == shoremask)
def test_submergedLand(self):
"""Check what happens when there is no land above water."""
# define the mask
shoremask = mask.ShorelineMask(
rcm8cube['eta'][0, :, :],
elevation_threshold=0)
# assert - expect all True values should be in one row
_whr_edge = np.where(shoremask._mask[:, 0])
assert _whr_edge[0].size > 0 # if fails, no shoreline found!
_row = int(_whr_edge[0][0])
assert np.all(shoremask._mask[_row, :] == 1)
assert np.all(shoremask._mask[_row+1:, :] == 0)
def test_static_from_OAP(self):
shoremask = mask.ShorelineMask(
golfcube['eta'][-1, :, :],
elevation_threshold=0)
mfOAP = mask.ShorelineMask.from_OAP(_OAP_0)
shoremask_05 = mask.ShorelineMask(
golfcube['eta'][-1, :, :],
elevation_threshold=0.5)
mfOAP_05 = mask.ShorelineMask.from_OAP(_OAP_05)
assert np.all(shoremask._mask == mfOAP._mask)
assert np.all(shoremask_05._mask == mfOAP_05._mask)
def test_static_from_mask_ElevationMask(self):
shoremask = mask.ShorelineMask(
golfcube['eta'][-1, :, :],
elevation_threshold=0)
mfem = mask.ShorelineMask.from_mask(self._ElevationMask)
shoremask_05 = mask.ShorelineMask(
golfcube['eta'][-1, :, :],
elevation_threshold=0.5)
assert np.all(shoremask._mask == mfem._mask)
assert np.sum(shoremask_05.integer_mask) < np.sum(shoremask.integer_mask)
def test_static_from_array(self):
"""Test that instantiation works for an array."""
# define the mask
_arr = np.ones((100, 200))
_arr[50:55, :] = 0
shoremask = mask.ShorelineMask.from_array(_arr)
# make assertions
assert shoremask.mask_type == 'shoreline'
assert shoremask._input_flag is None
assert np.all(shoremask._mask == _arr)
_arr2 = np.random.uniform(size=(100, 200))
_arr2_bool = _arr2.astype(bool)
assert _arr2.dtype == float
shoremask2 = mask.ShorelineMask.from_array(_arr2)
# make assertions
assert shoremask2.mask_type == 'shoreline'
assert shoremask2._input_flag is None
assert np.all(shoremask2._mask == _arr2_bool)
class TestElevationMask:
"""Tests associated with the mask.LandMask class."""
def test_default_vals_array(self):
"""Test that instantiation works for an array."""
# define the mask
elevationmask = mask.ElevationMask(
golfcube['eta'][-1, :, :],
elevation_threshold=0)
# make assertions
assert elevationmask._input_flag == 'array'
assert elevationmask.mask_type == 'elevation'
assert elevationmask.elevation_threshold == 0
assert elevationmask.threshold == 0
assert elevationmask.elevation_threshold is elevationmask.threshold
assert elevationmask._mask.dtype == bool
def test_all_below_threshold(self):
elevationmask = mask.ElevationMask(
golfcube['eta'][-1, :, :],
elevation_threshold=10)
# make assertions
assert elevationmask._input_flag == 'array'
assert elevationmask.mask_type == 'elevation'
assert elevationmask.elevation_threshold == 10
assert elevationmask.threshold == 10
assert elevationmask.elevation_threshold is elevationmask.threshold
assert elevationmask._mask.dtype == bool
assert np.all(elevationmask.mask == 0)
def test_all_above_threshold(self):
elevationmask = mask.ElevationMask(
golfcube['eta'][-1, :, :],
elevation_threshold=-10)
# make assertions
assert elevationmask._input_flag == 'array'
assert elevationmask.mask_type == 'elevation'
assert elevationmask.elevation_threshold == -10
assert elevationmask.threshold == -10
assert elevationmask.elevation_threshold is elevationmask.threshold
assert elevationmask._mask.dtype == bool
assert np.all(elevationmask.mask == 1)
def test_default_vals_array_needs_elevation_threshold(self):
"""Test that instantiation works for an array."""
# define the mask
with pytest.raises(TypeError, match=r'.* missing'):
_ = mask.ElevationMask(rcm8cube['eta'][-1, :, :])
def test_default_vals_cube(self):
"""Test that instantiation works for an array."""
# define the mask
elevationmask = mask.ElevationMask(
rcm8cube, t=-1,
elevation_threshold=0)
# make assertions
assert elevationmask._input_flag == 'cube'
assert elevationmask.mask_type == 'elevation'
assert elevationmask._mask.dtype == bool
def test_default_vals_cubewithmeta(self):
"""Test that instantiation works for an array."""
# define the mask
elevationmask = mask.ElevationMask(
golfcube, t=-1,
elevation_threshold=0)
# make assertions
assert elevationmask._input_flag == 'cube'
assert elevationmask.mask_type == 'elevation'
assert elevationmask._mask.dtype == bool
# compare with another instantiated from array
elevationmask_comp = mask.ElevationMask(
golfcube['eta'][-1, :, :],
elevation_threshold=0)
assert np.all(elevationmask_comp.mask == elevationmask.mask)
# try with a different elevation_threshold (higher)
elevationmask_higher = mask.ElevationMask(
golfcube, t=-1,
elevation_threshold=0.5)
assert (np.sum(elevationmask_higher.integer_mask) <
np.sum(elevationmask.integer_mask))
def test_default_vals_cube_needs_elevation_threshold(self):
"""Test that instantiation works for an array."""
# define the mask
with pytest.raises(TypeError, match=r'.* missing'):
_ = mask.ElevationMask(
rcm8cube, t=-1)
with pytest.raises(TypeError, match=r'.* missing'):
_ = mask.ElevationMask(
golfcube, t=-1)
def test_default_vals_mask_notimplemented(self):
"""Test that instantiation works for an array."""
# define the mask
_ElevationMask = mask.ElevationMask(
golfcube['eta'][-1, :, :],
elevation_threshold=0)
with pytest.raises(NotImplementedError,
match=r'Cannot instantiate .*'):
_ = mask.ElevationMask(
_ElevationMask,
elevation_threshold=0)
def test_submergedLand(self):
"""Check what happens when there is no land above water."""
# define the mask
elevationmask = mask.ElevationMask(
rcm8cube['eta'][0, :, :],
elevation_threshold=0)
# assert - expect all True values should be up to a point
_whr_land = np.where(elevationmask._mask[:, 0])
assert _whr_land[0].size > 0 # if fails, no land found!
_row = int(_whr_land[0][-1]) + 1 # last index
third = elevationmask.shape[1]//3 # limit to left of inlet
assert np.all(elevationmask._mask[:_row, :third] == 1)
assert np.all(elevationmask._mask[_row:, :] == 0)
@pytest.mark.xfail(raises=NotImplementedError, strict=True,
reason='Have not implemented pathway.')
def test_static_from_array(self):
"""Test that instantiation works for an array."""
# define the mask
elevationmask = mask.ElevationMask.from_array(np.ones((100, 200)))
# make assertions
assert elevationmask._input_flag == 'elevation'
class TestFlowMask:
"""Tests associated with the mask.LandMask class."""
def test_default_vals_array(self):
"""Test that instantiation works for an array."""
# define the mask
flowmask = mask.FlowMask(
golfcube['velocity'][-1, :, :],
flow_threshold=0.3)
# make assertions
assert flowmask._input_flag == 'array'
assert flowmask.mask_type == 'flow'
assert flowmask.flow_threshold == 0.3
assert flowmask.threshold == 0.3
assert flowmask.flow_threshold is flowmask.threshold
assert flowmask._mask.dtype == bool
# note that, the mask will take any array though...
# define the mask
flowmask_any = mask.FlowMask(
golfcube['eta'][-1, :, :],
flow_threshold=0)
assert flowmask_any._input_flag == 'array'
assert flowmask_any.mask_type == 'flow'
assert flowmask_any.flow_threshold == 0
assert flowmask_any.threshold == 0
assert flowmask_any.flow_threshold is flowmask_any.threshold
def test_all_below_threshold(self):
flowmask = mask.FlowMask(
golfcube['velocity'][-1, :, :],
flow_threshold=20)
# make assertions
assert flowmask._input_flag == 'array'
assert flowmask.mask_type == 'flow'
assert flowmask.flow_threshold == 20
assert flowmask.threshold == 20
assert flowmask.flow_threshold is flowmask.threshold
assert flowmask._mask.dtype == bool
assert np.all(flowmask.mask == 0)
def test_all_above_threshold(self):
flowmask = mask.FlowMask(
golfcube['velocity'][-1, :, :],
flow_threshold=-5)
# make assertions
assert flowmask._input_flag == 'array'
assert flowmask.mask_type == 'flow'
assert flowmask.flow_threshold == -5
assert flowmask.threshold == -5
assert flowmask.flow_threshold is flowmask.threshold
assert flowmask._mask.dtype == bool
assert np.all(flowmask.mask == 1)
def test_default_vals_array_needs_flow_threshold(self):
"""Test that instantiation works for an array."""
# define the mask
with pytest.raises(TypeError, match=r'.* missing'):
_ = mask.FlowMask(rcm8cube['velocity'][-1, :, :])
def test_default_vals_cube(self):
"""Test that instantiation works for an array."""
# define the mask
flowmask = mask.FlowMask(
rcm8cube, t=-1,
flow_threshold=0.3)
# make assertions
assert flowmask._input_flag == 'cube'
assert flowmask.mask_type == 'flow'
assert flowmask._mask.dtype == bool
def test_vals_cube_different_fields(self):
"""Test that instantiation works for an array."""
# define the mask
velmask = mask.FlowMask(
rcm8cube, t=-1,
cube_key='velocity',
flow_threshold=0.3)
# make assertions
assert velmask._input_flag == 'cube'
assert velmask.mask_type == 'flow'
assert velmask._mask.dtype == bool
dismask = mask.FlowMask(
rcm8cube, t=-1,
cube_key='discharge',
flow_threshold=0.3)
# make assertions
assert dismask._input_flag == 'cube'
assert dismask.mask_type == 'flow'
assert dismask._mask.dtype == bool
assert not np.all(velmask.mask == dismask.mask)
def test_default_vals_cubewithmeta(self):
"""Test that instantiation works
For a cube with metadata.
"""
# define the mask
flowmask = mask.FlowMask(
golfcube, t=-1,
flow_threshold=0.3)
# make assertions
assert flowmask._input_flag == 'cube'
assert flowmask.mask_type == 'flow'
assert flowmask._mask.dtype == bool
# compare with another instantiated from array
flowmask_comp = mask.FlowMask(
golfcube['velocity'][-1, :, :],
flow_threshold=0.3)
assert np.all(flowmask_comp.mask == flowmask.mask)
def test_flowthresh_vals_cubewithmeta(self):
# make default
flowmask = mask.FlowMask(
golfcube, t=-1,
flow_threshold=0.3)
# try with a different flow_threshold (higher)
flowmask_higher = mask.FlowMask(
golfcube, t=-1,
flow_threshold=0.5)
assert (np.sum(flowmask_higher.integer_mask) <
np.sum(flowmask.integer_mask))
def test_default_vals_cube_needs_flow_threshold(self):
"""Test that instantiation works for an array."""
# define the mask
with pytest.raises(TypeError, match=r'.* missing'):
_ = mask.FlowMask(
rcm8cube, t=-1)
with pytest.raises(TypeError, match=r'.* missing'):
_ = mask.FlowMask(
golfcube, t=-1)
def test_default_vals_mask_notimplemented(self):
"""Test that instantiation works for an array."""
# define the mask
_ElevationMask = mask.ElevationMask(
golfcube['eta'][-1, :, :],
elevation_threshold=0)
with pytest.raises(NotImplementedError,
match=r'Cannot instantiate .*'):
_ = mask.FlowMask(
_ElevationMask,
flow_threshold=0.3)
def test_submergedLand(self):
"""Check what happens when there is no land above water."""
# define the mask
flowmask = mask.FlowMask(
rcm8cube['velocity'][0, :, :],
flow_threshold=0.3)
# assert - expect doesnt care about land
assert flowmask.mask_type == 'flow'
@pytest.mark.xfail(raises=NotImplementedError, strict=True,
reason='Have not implemented pathway.')
def test_static_from_array(self):
"""Test that instantiation works for an array."""
# define the mask
flowmask = mask.FlowMask.from_array(np.ones((100, 200)))
# make assertions
assert flowmask._input_flag == 'flow'
class TestLandMask:
"""Tests associated with the mask.LandMask class."""
# define an input mask for the mask instantiation pathway
_ElevationMask = mask.ElevationMask(
golfcube['eta'][-1, :, :],
elevation_threshold=0)
_OAP_0 = OpeningAnglePlanform.from_elevation_data(
golfcube['eta'][-1, :, :],
elevation_threshold=0)
_OAP_05 = OpeningAnglePlanform.from_elevation_data(
golfcube['eta'][-1, :, :],
elevation_threshold=0.5)
def test_default_vals_array(self):
"""Test that instantiation works for an array."""
# define the mask
landmask = mask.LandMask(
rcm8cube['eta'][-1, :, :],
elevation_threshold=0)
# make assertions
assert landmask._input_flag == 'array'
assert landmask.mask_type == 'land'
assert landmask.angle_threshold > 0
assert landmask._mask.dtype == bool
def test_default_vals_array_needs_elevation_threshold(self):
"""Test that instantiation works for an array."""
# define the mask
with pytest.raises(TypeError, match=r'.* missing'):
_ = mask.LandMask(rcm8cube['eta'][-1, :, :])
@pytest.mark.xfail(raises=NotImplementedError, strict=True,
reason='Have not implemented pathway.')
def test_default_vals_cube(self):
"""Test that instantiation works for an array."""
# define the mask
landmask = mask.LandMask(rcm8cube, t=-1)
# make assertions
assert landmask._input_flag == 'cube'
assert landmask.mask_type == 'land'
assert landmask.angle_threshold > 0
assert landmask._mask.dtype == bool
@pytest.mark.xfail(raises=NotImplementedError, strict=True,
reason='Have not implemented pathway.')
def test_default_vals_cubewithmeta(self):
"""Test that instantiation works for an array."""
# define the mask
landmask = mask.LandMask(golfcube, t=-1)
# make assertions
assert landmask._input_flag == 'cube'
assert landmask.mask_type == 'land'
assert landmask.angle_threshold > 0
assert landmask._mask.dtype == bool
@pytest.mark.xfail(raises=NotImplementedError, strict=True,
reason='Have not implemented pathway.')
def test_default_vals_mask(self):
"""Test that instantiation works for an array."""
# define the mask
landmask = mask.LandMask(self._ElevationMask)
# make assertions
assert landmask._input_flag == 'mask'
assert landmask.mask_type == 'land'
assert landmask.angle_threshold > 0
assert landmask._mask.dtype == bool
def test_angle_threshold(self):
"""
Test that the angle threshold argument is used by the LandMask
when instantiated.
"""
# define the mask
landmask_default = mask.LandMask(
rcm8cube['eta'][-1, :, :],
elevation_threshold=0)
landmask = mask.LandMask(
rcm8cube['eta'][-1, :, :],
elevation_threshold=0,
angle_threshold=45)
# make assertions
assert landmask.angle_threshold == 45
assert not np.all(landmask_default == landmask)
def test_submergedLand(self):
"""Check what happens when there is no land above water."""
# define the mask
landmask = mask.LandMask(
rcm8cube['eta'][0, :, :],
elevation_threshold=0)
# assert - expect all True values should be in one row
_whr_land = np.where(landmask._mask[:, 0])
assert _whr_land[0].size > 0 # if fails, no land found!
_row = int(_whr_land[0][-1]) + 1 # last index
assert np.all(landmask._mask[:_row, :] == 1)
assert np.all(landmask._mask[_row:, :] == 0)
def test_static_from_OAP(self):
landmask = mask.LandMask(
golfcube['eta'][-1, :, :],
elevation_threshold=0)
mfOAP = mask.LandMask.from_OAP(_OAP_0)
landmask_05 = mask.LandMask(
golfcube['eta'][-1, :, :],
elevation_threshold=0.5)
mfOAP_05 = mask.LandMask.from_OAP(_OAP_05)
assert np.all(landmask._mask == mfOAP._mask)
assert np.all(landmask_05._mask == mfOAP_05._mask)
def test_static_from_mask_ElevationMask(self):
landmask = mask.LandMask(
golfcube['eta'][-1, :, :],
elevation_threshold=0)
mfem = mask.LandMask.from_mask(self._ElevationMask)
landmask_05 = mask.LandMask(
golfcube['eta'][-1, :, :],
elevation_threshold=0.5)
assert np.all(landmask._mask == mfem._mask)
assert np.sum(landmask_05.integer_mask) < np.sum(landmask.integer_mask)
@pytest.mark.xfail(raises=NotImplementedError, strict=True,
reason='Have not implemented pathway.')
def test_static_from_array(self):
"""Test that instantiation works for an array."""
# define the mask
landmask = mask.LandMask.from_array(np.ones((100, 200)))
# make assertions
assert landmask._input_flag == 'land'
class TestWetMask:
"""Tests associated with the mask.WetMask class."""
# define an input mask for the mask instantiation pathway
_ElevationMask = mask.ElevationMask(
golfcube['eta'][-1, :, :],
elevation_threshold=0)
def test_default_vals_array(self):
"""Test that instantiation works for an array."""
# define the mask
wetmask = mask.WetMask(
rcm8cube['eta'][-1, :, :],
elevation_threshold=0)
# make assertions
assert wetmask._input_flag == 'array'
assert wetmask.mask_type == 'wet'
assert wetmask._mask.dtype == bool
def test_default_vals_array_needs_elevation_threshold(self):
"""Test that instantiation works for an array."""
# define the mask
with pytest.raises(TypeError, match=r'.* missing 1 .*'):
_ = mask.WetMask(rcm8cube['eta'][-1, :, :])
@pytest.mark.xfail(raises=NotImplementedError, strict=True,
reason='Have not implemented pathway.')
def test_default_vals_cube(self):
"""Test that instantiation works for an array."""
# define the mask
wetmask = mask.WetMask(rcm8cube, t=-1)
# make assertions
assert wetmask._input_flag == 'cube'
assert wetmask.mask_type == 'wet'
assert wetmask._mask.dtype == bool
@pytest.mark.xfail(raises=NotImplementedError, strict=True,
reason='Have not implemented pathway.')
def test_default_vals_cubewithmeta(self):
"""Test that instantiation works for an array."""
# define the mask
wetmask = mask.WetMask(golfcube, t=-1)
# make assertions
assert wetmask._input_flag == 'cube'
assert wetmask.mask_type == 'wet'
assert wetmask._mask.dtype == bool
@pytest.mark.xfail(raises=NotImplementedError, strict=True,
reason='Have not implemented pathway.')
def test_default_vals_mask(self):
"""Test that instantiation works for an array."""
# define the mask
wetmask = mask.WetMask(self._ElevationMask)
# make assertions
assert wetmask._input_flag == 'mask'
assert wetmask.mask_type == 'wet'
assert wetmask._mask.dtype == bool
def test_angle_threshold(self):
"""
Test that the angle threshold argument is passed along to the LandMask
when instantiated.
"""
# define the mask
wetmask_default = mask.WetMask(
rcm8cube['eta'][-1, :, :],
elevation_threshold=0)
wetmask = mask.WetMask(
rcm8cube['eta'][-1, :, :],
elevation_threshold=0,
angle_threshold=45)
# make assertions
assert not np.all(wetmask_default == wetmask)
assert np.sum(wetmask.integer_mask) < np.sum(wetmask_default.integer_mask)
def test_submergedLand(self):
"""Check what happens when there is no land above water."""
# define the mask
wetmask = mask.WetMask(
rcm8cube['eta'][0, :, :],
elevation_threshold=0)
# assert - expect all True values should be in one row
_whr_edge = np.where(wetmask._mask[:, 0])
assert _whr_edge[0].size > 0 # if fails, no shoreline found!
_row = int(_whr_edge[0][0])
assert np.all(wetmask._mask[_row, :] == 1)
assert np.all(wetmask._mask[_row+1:, :] == 0)
def test_static_from_OAP(self):
# create two with sea level = 0
landmask = mask.LandMask(
golfcube['eta'][-1, :, :],
elevation_threshold=0)
mfOAP = mask.LandMask.from_OAP(_OAP_0)
# create two with diff elevation threshold
landmask_05 = mask.LandMask(
golfcube['eta'][-1, :, :],
elevation_threshold=0.5)
mfOAP_05 = mask.LandMask.from_OAP(_OAP_05)
assert np.all(landmask._mask == mfOAP._mask)
assert np.all(landmask_05._mask == mfOAP_05._mask)
def test_static_from_mask_ElevationMask(self):
wetmask = mask.WetMask(
golfcube['eta'][-1, :, :],
elevation_threshold=0)
mfem = mask.WetMask.from_mask(self._ElevationMask)
wetmask_05 = mask.WetMask(
golfcube['eta'][-1, :, :],
elevation_threshold=0.5)
assert np.all(wetmask._mask == mfem._mask)
assert np.sum(wetmask_05.integer_mask) < np.sum(wetmask.integer_mask)
@pytest.mark.xfail(raises=NotImplementedError, strict=True,
reason='Have not implemented pathway.')
def test_static_from_array(self):
"""Test that instantiation works for an array."""
# define the mask
wetmask = mask.WetMask.from_array(np.ones((100, 200)))
# make assertions
assert wetmask._input_flag == 'land'
class TestChannelMask:
"""Tests associated with the mask.ChannelMask class."""
# define an input mask for the mask instantiation pathway
_ElevationMask = mask.ElevationMask(
golfcube['eta'][-1, :, :],
elevation_threshold=0)
def test_default_vals_array(self):
"""Test that instantiation works for an array."""
# define the mask
channelmask = mask.ChannelMask(
rcm8cube['eta'][-1, :, :],
rcm8cube['velocity'][-1, :, :],
elevation_threshold=0,
flow_threshold=0.5)
# make assertions
assert channelmask._input_flag == 'array'
assert channelmask.mask_type == 'channel'
assert channelmask._mask.dtype == bool
def test_default_vals_array_needs_elevation_threshold(self):
"""Test that instantiation works for an array."""
# define the mask
with pytest.raises(TypeError, match=r'.* missing 1 .*'):
_ = mask.ChannelMask(
rcm8cube['eta'][-1, :, :],
rcm8cube['velocity'][-1, :, :],
flow_threshold=10)
def test_default_vals_array_needs_flow_threshold(self):
"""Test that instantiation works for an array."""
# define the mask
with pytest.raises(TypeError, match=r'.* missing 1 .*'):
_ = mask.ChannelMask(
rcm8cube['eta'][-1, :, :],
rcm8cube['velocity'][-1, :, :],
elevation_threshold=10)
@pytest.mark.xfail(raises=NotImplementedError, strict=True,
reason='Have not implemented pathway.')
def test_default_vals_cube(self):
"""Test that instantiation works for an array."""
# define the mask
channelmask = mask.ChannelMask(rcm8cube, t=-1)
# make assertions
assert channelmask._input_flag == 'cube'
assert channelmask.mask_type == 'channel'
assert channelmask._mask.dtype == bool
@pytest.mark.xfail(raises=NotImplementedError, strict=True,
reason='Have not implemented pathway.')
def test_default_vals_cubewithmeta(self):
"""Test that instantiation works for an array."""
# define the mask
channelmask = mask.ChannelMask(golfcube, t=-1)
# make assertions
assert channelmask._input_flag == 'cube'
assert channelmask.mask_type == 'channel'
assert channelmask._mask.dtype == bool
@pytest.mark.xfail(raises=NotImplementedError, strict=True,
reason='Have not implemented pathway.')
def test_default_vals_mask(self):
"""Test that instantiation works for an array."""
# define the mask
channelmask = mask.ChannelMask(self._ElevationMask)
# make assertions
assert channelmask._input_flag == 'mask'
assert channelmask.mask_type == 'channel'
assert channelmask._mask.dtype == bool
def test_angle_threshold(self):
"""
Test that the angle threshold argument is passed along to the
when instantiated.
"""
# define the mask
channelmask_default = mask.ChannelMask(
rcm8cube['eta'][-1, :, :],
rcm8cube['velocity'][-1, :, :],
elevation_threshold=0,
flow_threshold=0.5)
channelmask = mask.ChannelMask(
rcm8cube['eta'][-1, :, :],
rcm8cube['velocity'][-1, :, :],
elevation_threshold=0,
flow_threshold=0.5,
angle_threshold=45)
# make assertions
assert not np.all(channelmask_default == channelmask)
assert np.sum(channelmask.integer_mask) < np.sum(channelmask_default.integer_mask)
def test_submergedLand(self):
"""Check what happens when there is no land above water."""
# define the mask
channelmask = mask.ChannelMask(
rcm8cube['eta'][0, :, :],
rcm8cube['velocity'][-1, :, :],
elevation_threshold=0,
flow_threshold=0.5)
# assert - expect all True values should be in center and first rows
_cntr_frst = channelmask.mask[:3, rcm8cube.shape[2]//2]
assert np.all(_cntr_frst == 1)
def test_static_from_OAP_not_implemented(self):
with pytest.raises(NotImplementedError,
match=r'`from_OAP` is not defined .*'):
_ = mask.ChannelMask.from_OAP(_OAP_0)
def test_static_from_OAP_and_FlowMask(self):
"""
Test combinations to ensure that arguments passed to array instant
match the arguments passed to the independ FlowMask and OAP
objects.
"""
channelmask_03 = mask.ChannelMask(
golfcube['eta'][-1, :, :],
golfcube['velocity'][-1, :, :],
elevation_threshold=0,
flow_threshold=0.3)
flowmask_03 = mask.FlowMask(
golfcube['velocity'][-1, :, :],
flow_threshold=0.3)
mfOAP_03 = mask.ChannelMask.from_OAP_and_FlowMask(_OAP_0, flowmask_03)
channelmask_06 = mask.ChannelMask(
golfcube['eta'][-1, :, :],
golfcube['velocity'][-1, :, :],
elevation_threshold=0.5,
flow_threshold=0.6)
flowmask_06 = mask.FlowMask(
golfcube['velocity'][-1, :, :],
flow_threshold=0.6)
mfOAP_06 = mask.ChannelMask.from_OAP_and_FlowMask(_OAP_05, flowmask_06)
assert np.all(channelmask_03._mask == mfOAP_03._mask)
assert np.all(channelmask_06._mask == mfOAP_06._mask)
assert not np.all(channelmask_03._mask == mfOAP_06._mask)
assert not np.all(channelmask_03._mask == channelmask_06._mask)
assert | np.sum(mfOAP_06.integer_mask) | numpy.sum |
# -*- coding: utf-8 -*-
"""
Created on 2017-6-27
@author: cheng.li
"""
import numpy as np
from typing import Union
from typing import Tuple
from typing import Optional
from typing import Dict
import cvxpy
from alphamind.cython.optimizers import QPOptimizer
from alphamind.cython.optimizers import CVOptimizer
from alphamind.exceptions.exceptions import PortfolioBuilderException
def _create_bounds(lbound,
ubound,
bm,
risk_exposure,
risk_target):
lbound = lbound - bm
ubound = ubound - bm
if risk_exposure is not None:
cons_mat = risk_exposure.T
bm_risk = cons_mat @ bm
clbound = risk_target[0] - bm_risk
cubound = risk_target[1] - bm_risk
else:
cons_mat = None
clbound = None
cubound = None
return lbound, ubound, cons_mat, clbound, cubound
def _create_result(optimizer, bm):
if optimizer.status() == 0 or optimizer.status() == 1:
return 'optimal', optimizer.feval(), optimizer.x_value() + bm
else:
raise PortfolioBuilderException(optimizer.status())
def mean_variance_builder(er: np.ndarray,
risk_model: Dict[str, Union[None, np.ndarray]],
bm: np.ndarray,
lbound: Union[np.ndarray, float],
ubound: Union[np.ndarray, float],
risk_exposure: Optional[np.ndarray],
risk_target: Optional[Tuple[np.ndarray, np.ndarray]],
lam: float=1.) -> Tuple[str, float, np.ndarray]:
lbound, ubound, cons_mat, clbound, cubound = _create_bounds(lbound, ubound, bm, risk_exposure, risk_target)
if np.all(lbound == -np.inf) and np.all(ubound == np.inf) and cons_mat is None:
# using fast path cvxpy
n = len(er)
w = cvxpy.Variable(n)
cov = risk_model['cov']
special_risk = risk_model['idsync']
risk_cov = risk_model['factor_cov']
risk_exposure = risk_model['factor_loading']
if cov is None:
risk = cvxpy.sum_squares(cvxpy.multiply(cvxpy.sqrt(special_risk), w)) \
+ cvxpy.quad_form((w.T * risk_exposure).T, risk_cov)
else:
risk = cvxpy.quad_form(w, cov)
objective = cvxpy.Minimize(-w.T * er + 0.5 * lam * risk)
prob = cvxpy.Problem(objective)
prob.solve(solver='ECOS', feastol=1e-9, abstol=1e-9, reltol=1e-9)
if prob.status == 'optimal' or prob.status == 'optimal_inaccurate':
return 'optimal', prob.value, | np.array(w.value) | numpy.array |
import numpy as np
from gips.gistmodel.fitting import MC_fitter
from gips.gistmodel._numerical_ext import gist_functional_6p_ext
from gips.gistmodel._numerical_ext import gist_functional_5p_ext
from gips.gistmodel._numerical_ext import gist_functional_4p_ext
from gips.gistmodel._numerical_ext import gist_restraint_ext
from gips.gistmodel._numerical_ext import merge_casedata_ext
from gips.gistmodel._numerical_ext import pair_difference_ext
from gips.utils.misc import parms_error
from gips import FLOAT
from gips import DOUBLE
MODE=3
class mode3(MC_fitter):
def __init__(self, gdatarec_dict,
gdata_dict,
ref_energy=-11.108,
parms=6,
pairs=False,
radiusadd=[0.,3.],
softness=1.0,
softcut=2.0,
boundsdict=None,
pairlist=None,
exclude=None,
scaling=2.0,
select=None,
decomp_E=False,
decomp_S=False,
verbose=False):
super(mode3, self).__init__(gdatarec_dict=gdatarec_dict,
gdata_dict=gdata_dict,
ref_energy=ref_energy,
mode=MODE,
radiusadd=radiusadd,
softness=softness,
softcut=softcut,
exclude=exclude,
scaling=scaling,
verbose=verbose)
self.pairs = pairs
self.parms = parms
self._parms = parms
self._gist_functional_ext = None
self.boundsdict = boundsdict
self.pairlist = pairlist
if self.pairs:
self.set_pairs()
self.set_selection(select)
self.set_functional()
self.set_bounds()
self.set_step()
self.set_x0()
self.w = self.w.astype(DOUBLE)
self.w_cplx = self.w_cplx.astype(DOUBLE)
self.w_lig = self.w_lig.astype(DOUBLE)
def gist_functional(self, x):
### &PyArray_Type, &E,
### &PyArray_Type, &S,
### &PyArray_Type, &g,
### &PyArray_Type, &vol,
### &PyArray_Type, &ind,
### &PyArray_Type, &x,
### &PyArray_Type, &dx,
### &PyArray_Type, &fun,
### &PyArray_Type, &grad,
### &verbose
### x[0] = E_aff
### x[1] = e_co
### x[2] = S_aff
### x[3] = s_co
### x[4] = g_co
### x[5] = C
_x = np.zeros(self.parms, dtype=DOUBLE)
_x[:-1] = x[:-1]
### Make sure all types are DOUBLE
if not self.pairs:
if not self._gist_functional_ext(self.E, self.S, self.g, self.vol,
self.ind_rec, _x, self._dx, self._calc_data,
self._gradients, 0, int(self.anal_grad)):
raise ValueError("Something went wrong in gist functional calculation.")
if not self._gist_functional_ext(self.E_cplx, self.S_cplx, self.g_cplx, self.vol_cplx,
self.ind_rec_cplx, _x, self._dx, self._calc_data_cplx,
self._gradients_cplx, 0, int(self.anal_grad)):
raise ValueError("Something went wrong in gist functional calculation.")
if not self._gist_functional_ext(self.E_lig, self.S_lig, self.g_lig, self.vol_lig,
self.ind_rec_lig, _x, self._dx, self._calc_data_lig,
self._gradients_lig, 0, int(self.anal_grad)):
raise ValueError("Something went wrong in gist functional calculation.")
### &PyArray_Type, &x,
### &PyArray_Type, &xmin,
### &PyArray_Type, &xmax,
### &k,
### &restraint,
### &PyArray_Type, &restraint_grad
if self.anal_boundary:
self._restraint = gist_restraint_ext(x,
self.xmin,
self.xmax,
self.kforce_f,
self.kforce,
self._restraint_grad)
def _f_process(self, x):
__doc___= """
returns the squared sum of residuals
objective function is the free energy
"""
self.gist_functional(x)
self._f[:] = 0.
if self.anal_grad:
self._g[:] = 0.
### Complex and Ligand contributions
### &PyArray_Type, &source,
### &PyArray_Type, &assign,
### &PyArray_Type, &factor,
### &PyArray_Type, &assign_factor
if self.pairs:
_f = merge_casedata_ext(self._calc_data_cplx, self.ind_case_cplx, self.w_cplx, self.ind_case_cplx)
_f -= merge_casedata_ext(self._calc_data_lig, self.ind_case_lig, self.w_lig, self.ind_case_lig)
self._f[:] += pair_difference_ext(_f, self.pairidx)
for i in range(self.parms-1):
_g = merge_casedata_ext(self._gradients_cplx[:,i], self.ind_case_cplx, self.w_cplx, self.ind_case_cplx)
_g -= merge_casedata_ext(self._gradients_lig[:, i], self.ind_case_lig, self.w_lig, self.ind_case_lig)
self._g[:,i] += pair_difference_ext(_g, self.pairidx)
else:
self._f[:] = merge_casedata_ext(self._calc_data_cplx, self.ind_case_cplx, self.w_cplx, self.ind_case_cplx)
self._f[:] -= merge_casedata_ext(self._calc_data, self.ind_case, self.w, self.ind_rec)
self._f[:] -= merge_casedata_ext(self._calc_data_lig, self.ind_case_lig, self.w_lig, self.ind_case_lig)
for i in range(self.parms):
self._g[:,i] = merge_casedata_ext(self._gradients_cplx[:,i], self.ind_case_cplx, self.w_cplx, self.ind_case_cplx)
self._g[:,i] -= merge_casedata_ext(self._gradients[:,i], self.ind_case, self.w, self.ind_rec)
self._g[:,i] -= merge_casedata_ext(self._gradients_lig[:, i], self.ind_case_lig, self.w_lig, self.ind_case_lig)
self._f[:] += x[-1]
self._g[:,-1] = 1
else:
if self.pairs:
### Complex and Ligand contributions
_f = merge_casedata_ext(self._calc_data_cplx, self.ind_case_cplx, self.w_cplx, self.ind_case_cplx)
_f -= merge_casedata_ext(self._calc_data_lig, self.ind_case_lig, self.w_lig, self.ind_case_lig)
self._f[:] += pair_difference_ext(_f, self.pairidx)
else:
### Receptor contributions
self._f[:] = merge_casedata_ext(self._calc_data_cplx, self.ind_case_cplx, self.w_cplx, self.ind_case_cplx)
self._f[:] -= merge_casedata_ext(self._calc_data, self.ind_case, self.w, self.ind_rec)
self._f[:] -= merge_casedata_ext(self._calc_data_lig, self.ind_case_lig, self.w_lig, self.ind_case_lig)
self._f[:] += x[-1]
def set_bounds(self):
__doc__ = """
Ensures that we don't run out of bounds during MC steps.
"""
self.xmin = np.zeros(self._parms, dtype=DOUBLE)
self.xmax = np.zeros(self._parms, dtype=DOUBLE)
self._restraint_grad = np.zeros(self._parms, dtype=DOUBLE)
self._restraint = 0.
self.kforce_f = np.zeros(self._parms, dtype=DOUBLE)
_E = np.min([np.min(self.E_cplx),np.min(self.E),np.min(self.E_lig)]),\
np.max([np.max(self.E_cplx),np.max(self.E), | np.max(self.E_lig) | numpy.max |
#!/usr/bin/env python
# coding: utf-8
# # Introduction
# ## The Data Set
# In today's workshop, we will revisit the data set you worked with in the Machine Learning workshop. As a refresher: this data set is from the GSE53987 dataset on Bipolar disorder (BD) and major depressive disorder (MDD) and schizophrenia:
#
# <NAME>, <NAME>, <NAME>, <NAME> et al. STEP levels are unchanged in pre-frontal cortex and associative striatum in post-mortem human brain samples from subjects with schizophrenia, bipolar disorder and major depressive disorder. PLoS One 2015;10(3):e0121744. PMID: 25786133
#
# This is a microarray data on platform GPL570 (HG-U133_Plus_2, Affymetrix Human Genome U133 Plus 2.0 Array) consisting of 54675 probes.
#
# The raw CEL files of the GEO series were downloaded, frozen-RMA normalized, and the probes have been converted to HUGO gene symbols using the annotate package averaging on genes. The sample clinical data (meta-data) was parsed from the series matrix file. You can download it **here**.
#
# In total there are 205 rows consisting of 19 individuals diagnosed with BPD, 19 with MDD, 19 schizophrenia and 19 controls. Each sample has gene expression from 3 tissues (post-mortem brain). There are a total of 13768 genes (numeric features) and 10 meta features and 1 ID (GEO sample accession):
#
# - Age
# - Race (W for white and B for black)
# - Gender (F for female and M for male)
# - Ph: pH of the brain tissue
# - Pmi: post mortal interval
# - Rin: RNA integrity number
# - Patient: Unique ID for each patient. Each patient has up to 3 tissue samples. The patient ID is written as disease followed by a number from 1 to 19
# - Tissue: tissue the expression was obtained from.
# - Disease.state: class of disease the patient belongs to: bipolar, schizophrenia, depression or control.
# - source.name: combination of the tissue and disease.state
#
# ## Workshop Goals
# This workshop will walk you through an analysis of the GSE53987 microarray data set. This workshop has the following three tasks:
# 1. Visualize the demographics of the data set
# 2. Cluster gene expression data and appropriately visualize the cluster results
# 3. Compute differential gene expression and visualize the differential expression
#
# Each task has a __required__ section and a __bonus__ section. Focus on completing the three __required__ sections first, then if you have time at the end, revisit the __bonus__ sections.
#
# Finally, as this is your final workshop, we hope that you will this as an opportunity to integrate the different concepts that you have learned in previous workshops.
#
# ## Workshop Logistics
# As mentioned in the pre-workshop documentation, you can do this workshop either in a Jupyter Notebook, or in a python script. Please make sure you have set-up the appropriate environment for youself. This workshop will be completed using "paired-programming" and the "driver" will switch every 15 minutes. Also, we will be using the python plotting libraries matplotlib and seaborn.
# ## TASK 0: Import Libraries and Data
# - Download the data set (above) as a .csv file
# - Initialize your script by loading the following libraries.
# In[2]:
# Import Necessary Libraries
import pandas as pd
import numpy as np
import seaborn as sns
from sklearn import cluster, metrics, decomposition
from matplotlib import pyplot as plt
import itertools
data = pd.read_csv('GSE53987_combined.csv', index_col=0)
genes = data.columns[10:]
# ## TASK 1: Visualize Dataset Demographics
# ### Required Workshop Task:
# ##### Use the skeleton code to write 3 plotting functions:
# 1. plot_distribution()
# - Returns a distribution plot object given a dataframe and one observation
# 2. plot_relational()
# - Returns a distribution plot object given a dataframe and (x,y) observations
# 3. plot_categorical()
# - Returns a categorical plot object given a dataframe and (x,y) observations
# ##### Use these functions to produce the following plots:
# 1. Histogram of patient ages
# 2. Histogram of gene expression for 1 gene
# 3. Scatter plot of gene expression for 1 gene by ages
# 4. Scatter plot of gene expression for 1 gene by disease state
# Your plots should satisfy the following critical components:
# - Axis titles
# - Figure title
# - Legend (if applicable)
# - Be readable
#
# ### Bonus Task:
# 1. Return to these functions and include functionality to customize color palettes, axis legends, etc. You can choose to define your own plotting "style" and keep that consistent for all of your plotting functions.
# 2. Faceting your plots. Modify your functions to take in a "facet" argument that when facet is an observation, the function will create a facet grid and facet on that observation. Read more about faceting here:
# Faceting generates multi-plot grids by __mapping a dataset onto multiple axes arrayed in a grid of rows and columns that correspond to levels of variables in the dataset.__
# - In order to use facteting, your data __must be__ in a Pandas DataFrame and it must take the form of what Hadley Whickam calls “tidy” data.
# - In brief, that means your dataframe should be structured such that each column is a variable and each row is an observation. There are figure-level functions (e.g. relplot() or catplot()) that will create facet grids automatically and can be used in place of things like distplot() or scatterplot().
# In[63]:
# Import the data (.csv file) as a data frame
data = pd.read_csv("/Users/ebriars/Desktop/Bioinformatics/BRITE REU Workshops/Data Visualization/GSE53987_combined.csv", index_col=0)
# Function to Plot a Distribtion
def plot_distribution(df, obs1, obs2=''):
"""
Create a distribution plot for at least one observation
Arguments:
df (pandas data frame): data frame containing at least 1 column of numerical values
obs1 (string): observation to plot distribution on
obs2 (string, optional)
Returns:
axes object
"""
if obs2 == '':
ax = sns.distplot(df[obs1])
else:
ax = sns.FacetGrid(df, hue=obs2)
ax = (g.map(sns.distplot, obs1, hist=False))
return ax
# Function to Plot Relational (x,y) Plots
def plot_relational(df, x, y, hue=None, kind=None):
"""
Create a plot for an x,y relationship (default = scatter plot)
Optional functionality for additional observations.
Arguments:
df (pandas data frame): data frame containing at least 2 columns of numerical values
x (string): observation for the independent variable
y (string): observation for the dependent variable
hue (string, optional): additional observation to color the plot on
kind (string, optional): type of plot to create [scatter, line]
Returns:
axes object
"""
if kind == None or kind == "scatter":
ax = sns.scatterplot(data=df, x=x, y=y, hue=hue)
else:
ax = sns.lineplot(data=df, x=x, y=y, hue=hue)
return ax
def plot_categorical(df, x, y, hue=None, kind=None):
"""
Create a plot for an x,y relationship where x is categorical (not numerical)
Arguments:
df (pandas data frame): data frame containing at least 2 columns of numerical values
x (string): observation for the independent variable (categorical)
y (string): observation for the dependent variable
hue (string, optional): additional observation to color the plot on
kind (string, optional): type of plot to create. Options should include at least:
strip (default), box, and violin
"""
if kind == None or kind == "strip":
ax = sns.stripplot(data=df, x=x, y=y, hue=hue)
elif kind == "violin":
ax = sns.violinplot(data=df, x=x, y=y, hue=hue)
elif kind == "box":
ax = sns.boxplot(data=df, x=x, y=y, hue=hue)
return ax
def main():
"""
Generate the following plots:
1. Histogram of patient ages
2. Histogram of gene expression for 1 gene
3. Scatter plot of gene expression for 1 gene by ages
4. Scatter plot of gene expression for 1 gene by disease state
"""
# ## TASK 2: Differential Expression Analysis
#
# Differential expression analysis is a fancy way of saying, "We want to find which genes exhibit increased or decreased expression compared to a control group". Neat. Because the dataset we're working with is MicroArray data -- which is mostly normally distributed -- we'll be using a simple One-Way ANOVA. If, however, you were working with sequence data -- which follows a Negative Binomial distribution -- you would need more specialized tools. A helper function is provided below.
# In[7]:
def differential_expression(data, group_col, features, reference=None):
"""
Perform a one-way ANOVA across all provided features for a given grouping.
Arguments
---------
data : (pandas.DataFrame)
DataFrame containing group information and feature values.
group_col : (str)
Column in `data` containing sample group labels.
features : (list, numpy.ndarray):
Columns in `data` to test for differential expression. Having them
be gene names would make sense. :thinking:
reference : (str, optional)
Value in `group_col` to use as the reference group. Default is None,
and the value will be chosen.
Returns
-------
pandas.DataFrame
A DataFrame of differential expression results with columns for
fold changes between groups, maximum fold change from reference,
f values, p values, and adjusted p-values by Bonferroni correction.
"""
if group_col not in data.columns:
raise ValueError("`group_col` {} not found in data".format(group_col))
if any([x not in data.columns for x in features]):
raise ValueError("Not all provided features found in data.")
if reference is None:
reference = data[group_col].unique()[0]
print("No reference group provided. Using {}".format(reference))
elif reference not in data[group_col].unique():
raise ValueError("Reference value {} not found in column {}.".format(
reference, group_col))
by_group = data.groupby(group_col)
reference_avg = by_group.get_group(reference).loc[:,features].mean()
values = []
results = {}
for each, index in by_group.groups.items():
values.append(data.loc[index, features])
if each != reference:
key = "{}.FoldChange".format(each)
results[key] = data.loc[index, features].mean() / reference_avg
fold_change_cols = list(results.keys())
fvalues, pvalues = stats.f_oneway(*values)
results['f.value'] = fvalues
results['p.value'] = pvalues
results['p.value.adj'] = pvalues * len(features)
results_df = pd.DataFrame(results)
def largest_deviation(x):
i = np.where(abs(x) == max(abs(x)))[0][0]
return x[i]
results_df['Max.FoldChange'] = results_df[fold_change_cols].apply(
lambda x: largest_deviation(x.values), axis=1)
return results_df
# In[15]:
# Here's some pre-subsetted data
hippocampus = data[data["Tissue"] == "hippocampus"]
pf_cortex = data[data["Tissue"] == "Pre-frontal cortex (BA46)"]
as_striatum = data[data["Tissue"] == "Associative striatum"]
# Here's how we can subset a dataset by two conditions.
# You might find it useful :thinking:
data[(data["Tissue"] == 'hippocampus') & (data['Disease.state'] == 'control')]
# ### Task 2a: Volcano Plots
#
# Volcano plots are ways to showcase the number of differentially expressed genes found during high throughput sequencing analysis. Log fold changes are plotted along the x-axis, while p-values are plotted along the y-axis. Genes are marked significant if they exceed some absolute Log fold change theshold **as well** some p-value level for significance. This can be seen in the plot below.
#
# 
#
# Your first task will be to generate some Volcano plots:
#
# **Requirments**
# 1. Use the provided function to perform an ANOVA (analysis of variance) between control and experimental groups in each tissue.
# - Perform a separate analysis for each tissue.
# 2. Implement the skeleton function to create a volcano plot to visualize both the log fold change in expression values and the adjusted p-values from the ANOVA
# 3. Highlight significant genes with distinct colors
# In[ ]:
def volcano_plot(data, sig_col, fc_col, sig_thresh, fc_thresh):
"""
Generate a volcano plot to showcasing differentially expressed genes.
Parameters
----------
data : (pandas.DataFrame)
A data frame containing differential expression results
sig_col : str
Column in `data` with adjusted p-values.
fc_col : str
Column in `data` with fold changes.
sig_thresh : str
Threshold for statistical significance.
fc_thresh
"""
data['significant'] = False
data[fc_col] = np.log2(data[fc_col])
de_genes = (data[sig_col] < sig_thesh) & (data[fc_col].abs() > fc_thresh)
data.loc[de_genes, 'significant'] = True
ax = sns.scatterplot(x=fc_col, y=sig_col, hue='significant', data=data,
palette=['black', 'red'], alpha=0.75)
linewidth = plt.rcParams['lines.linewidth'] - 1
plt.axvline(x=fc_thresh, linestyle='--', linewidth=linewidth,
color='#4D4E4F')
plt.axvline(x=-fc_thresh, linestyle='--', linewidth=linewidth,
color='#4D4E4F')
plt.axhline(y=sig_thresh, linestyle='--', linewidth=linewidth,
color='#4D4E4F')
ax.legend().set_visible(False)
ylabel = sig_col
if sig_col.lower() == 'fdr':
ylabel = 'False Discovery Rate'
plt.xlabel(r"$log_2$ Fold Change")
plt.ylabel(ylabel)
for spine in ['right', 'top']:
ax.spines[spine].set_visible(False)
plt.tight_layout()
return ax
# ### Task 2b: Plot the Top 1000 Differentially Expressed Genes
#
# Clustered heatmaps are hugely popular for displaying differences in gene expression values. To reference such a plot, look back at the introductory material. Here we will be plotting the 1000 most differentially expressed genes for each of the analysis performed before.
#
# **Requirements**
# - Implement the skeleton function below
# - Z normalize gene values
# - Use a diverging and perceptually uniform colormap
# - Generate plots for each of the DE results above
#
# **Hint**: Look over all the options for [sns.clustermap()](https://seaborn.pydata.org/generated/seaborn.clustermap.html). It might make things easier.
# In[ ]:
def heatmap(data, genes, group_col):
"""[summary]
Parameters
----------
data : pd.DataFrame
A (sample x gene) data matrix containing gene expression values for each sample.
genes : list, str
List of genes to plot
"""
plot_data = anno_df[:, genes]
ax = sns.clustermap(data, cmap='RdBu_r', z_score=1)
return ax
# **Bonus** There's nothing denoting which samples belong to which experimental group. Fix it.
#
# *Bonus hint*: Look real close at the documentation.
# ## TASK 3: Clustering Analysis
#
# You've seen clustering in the previous machine learning workshop. Some basic plots were generated for you, including plotting the clusters on the principle componets. While we can certainly do more of that, we will also be introducing two new plots: elbow plots and silhouette plots.
#
# ### Elbow Plots
#
# Elbow plots are plots that are used to help diagnose the perennial question of K-means clustering: how do I chose K? To create the graph, you plot the number of clusters on the x-axis and some evaluation of "cluster goodness" on the y-axis. Looking at the name of the plot, you might guess that we're looking for an "elbow". This is the point in the graph when we start getting diminished returns in performance, and specifying more clusters may lead to over-clustering the data. An example plot is shown below.
#
# 
#
# You can see the K selected (K = 3), is right before diminishing returns start to kick in. Mathematically, this point is defined as the point in which curvature is maximized. However, the inflection point is also a decent -- though more conservative -- estimate. However, we'll just stick to eye-balling it for this workshop. If you would like to know how to automatically find the elbow point, more information can be found [here](https://raghavan.usc.edu/papers/kneedle-simplex11.pdf)
#
# ### Task 2a: Implement a function that creates an elbow plot
#
# Skeleton code is provided below. The function expects a list of k-values and their associated scores. An optional "ax" parameter is also provided. This parameter should be an axes object and can be created by issueing the following command:
#
# ```ax = plt.subplot()```
#
# While we won't need the parameter right now, we'll likely use it in the future.
#
# **Function Requirements**
# - Generate plot data by clustering the entire dataset on the first 50 principle components. Vary K values from 2 - 10.
# - While you've been supplied a helper function for clustering, you'll need to supply the principle components yourself. Refer to your machine learning workshop along with the scikit-learn [documentation](https://scikit-learn.org/stable/modules/generated/sklearn.decomposition.PCA.html)
# - Plots each k and it's associated value.
# - Plots lines connecting each data point.
# - Produces a plot with correctly labelled axes.
#
# **Hint:** Working with an axis object is similar to base matplotlib, except `plt.scatter()` might become something like `ax.scatter()`.
#
# #### Helper Function
# In[6]:
def cluster_data(X, k):
"""
Cluster data using K-Means.
Parameters
----------
X : (numpy.ndarray)
Data matrix to cluster samples on. Should be (samples x features).
k : int
Number of clusters to find.
Returns
-------
tuple (numpy.ndarray, float)
A tuple where the first value is the assigned cluster labels for
each sample, and the second value is the score associated with
the particular clustering.
"""
model = cluster.KMeans(n_clusters=k).fit(X)
score = model.score(X)
return (model.labels_, score)
# #### Task 2a Implementation
# In[3]:
def elbow_plot(ks, scores, best=None, ax=None):
"""
Create a scatter plot to aid in choosing the number of clusters using K-means.
Arguments
---------
ks : (numpy.ndarray)
Tested values for the number of clusters.
scores: (numpy.ndarray)
Cluster scores associated with each number K.
ax: plt.Axes Object, optional
"""
if ax is None:
fig, ax = plt.subplots()
ax.scatter(ks, scores)
ax.plot(ks, scores)
ax.set_xlabel("Number of Clusters")
ax.set_ylabel("Negative Distance From Mean")
return ax
# Once you've created the base plotting function, you'll probably realize we have no indivation of where the elbow point is. Fix this by adding another optional parameter (`best`) to your function. The parameter `best` should be the K value that produces the elbow point.
#
# **Function Requirements**
#
# - Add an optional parameter `best` that if supplied denotes the elbow point with a vertical, dashed line.
# - If `best` is not supplied, the plot should still be produced but without denoting the elbow point.
#
# **Hint**: `plt.axvline` and `plt.axhline` can be used to produce vertical and horizontal lines, respectively. More information [here](https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.pyplot.axvline.html)
#
# **Note**: You are not required to have the line end at the associated score value.
# In[2]:
def elbow_plot(ks, scores, best=None, ax=None):
"""
Create a scatter plot to aid in choosing the number of clusters using K-means.
Arguments
---------
ks : (numpy.ndarray)
Tested values for the number of clusters.
scores: (numpy.ndarray)
Cluster scores associated with each number K.
best: int, optional
The best value for K. Determined by the K that falls at the elbow. If
passed, a black dashed line will be plotted to indicate the best.
Default is no line.
ax: plt.Axes Object, optional
"""
if ax is None:
fig, ax = plt.subplots()
ax.scatter(ks, scores)
ax.plot(ks, scores)
ax.set_xlabel("Number of Clusters")
ax.set_ylabel("Negative Distance From Mean")
if best is not None:
if best not in ks:
raise ValueError("{} not included in provided number "
"of clusters.")
idx = np.where(np.array(ks) == best)[0][0]
ymin, ymax = ax.get_ylim()
point = (scores[idx] - ymin) / (ymax - ymin)
print(point)
ax.axvline(x=best, ymax=point, linestyle="--", c='black')
ax.scatter([3], scores[idx], edgecolor='black', facecolor="none",
s=200)
ax.set_title("Elbow at K={}".format(best), loc='left')
return ax
# ### Silhouette Plots
#
# Silhouette plots are another way to visually diagnose cluster performance. They are created by finding the [silhouette coefficient](https://en.wikipedia.org/wiki/Silhouette_(clustering)) for each sample in the data, and plotting an area graph for each cluster. The silhouette coefficient measures how well-separated clusters are from each other. The value ranges from $[-1 , 1]$, where 1 indicates good separation, 0 indicates randomness, and -1 indicates mixing of clusters. An example is posted below.
#
# 
#
# As you can see, each sample in each cluster has the area filled from some minimal point (usually 0 or the minimum score in the dataset) and clusters are separated to produce distinct [silhouettes](https://www.youtube.com/watch?v=-TcUvXzgwMY).
#
# ### Task 3b: Implement a function to plot silhouette coefficients
#
# Because the code for create a silhouette plot can be a little bit involved, we've created both a skeleton function with documentation, and provided the following pseudo-code:
#
# ```
# - Calculate scores for each sample.
# - Get a set of unique sample labels.
# - Set a score minimum
# - Initialize variables y_lower, and y_step
# - y_lower is the lower bound on the x-axis for the first cluster's silhouette
# - y_step is the distance between cluster silhouettes
# - Initialize variable, breaks
# - breaks are the middle point of each cluster silhouette and will be used to
# position the axis label
# - Interate through each cluster label, for each cluster:
# - Calcaluate the variable y_upper by adding the number of samples
# - Fill the area between y_lower and y_upper using the silhoutte scores for
# each sample
# - Calculate middle point of y distance. Append the variable break.
# - Calculate new y_lower value
# - Label axes with appropriate names and tick marks
# - Create dashed line at the average silhouette score over all samples
# ```
#
# **Hint**: you might find [ax.fill_betweenx()](https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.axes.Axes.fill_betweenx.html)
# and [ax.set_yticks()](https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.axes.Axes.set_yticks.html?highlight=set_yticks#matplotlib.axes.Axes.set_yticks)/
# [ax.set_yticklabels()](https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.axes.Axes.set_yticklabels.html?highlight=set_yticklabels#matplotlib.axes.Axes.set_yticklabels) useful.
# In[4]:
def silhouette_plot(X, y, ax=None):
"""
Plot silhouette scores for all samples across clusters.
Parameters
----------
X : numpy.ndarray
Numerical data used to cluster the data.
y : numpy.ndarray
Cluster labels assigned to each sample.
ax : matplotlib.Axes
Axis object to plot scores onto. Default is None, and a new axis will
be created.
Returns
-------
matplotlib.Axes
"""
if ax is None:
ax = plt.subplot()
scores = metrics.silhouette_samples(X, y)
clusters = sorted(np.unique(y))
score_min = 0
y_lower, y_step = 5, 5
props = plt.rcParams['axes.prop_cycle']
colors = itertools.cycle(props.by_key()['color'])
breaks = []
for each, color in zip(clusters, colors):
# Aggregate the silhouette scores for samples, sort scores for
# area filling
cluster_scores = scores[y == each]
cluster_scores.sort()
y_upper = y_lower + len(cluster_scores)
ax.fill_betweenx( | np.arange(y_lower, y_upper) | numpy.arange |
""" A set of NumPy functions to apply per chunk """
from __future__ import absolute_import, division, print_function
from collections import Container, Iterable, Sequence
from functools import wraps
from toolz import concat
import numpy as np
from . import numpy_compat as npcompat
from ..compatibility import getargspec
from ..utils import ignoring
def keepdims_wrapper(a_callable):
"""
A wrapper for functions that don't provide keepdims to ensure that they do.
"""
if "keepdims" in getargspec(a_callable).args:
return a_callable
@wraps(a_callable)
def keepdims_wrapped_callable(x, axis=None, keepdims=None, *args, **kwargs):
r = a_callable(x, axis=axis, *args, **kwargs)
if not keepdims:
return r
axes = axis
if axes is None:
axes = range(x.ndim)
if not isinstance(axes, (Container, Iterable, Sequence)):
axes = [axes]
r_slice = tuple()
for each_axis in range(x.ndim):
if each_axis in axes:
r_slice += (None,)
else:
r_slice += (slice(None),)
r = r[r_slice]
return r
return keepdims_wrapped_callable
# Wrap NumPy functions to ensure they provide keepdims.
sum = keepdims_wrapper(np.sum)
prod = keepdims_wrapper(np.prod)
min = keepdims_wrapper(np.min)
max = keepdims_wrapper(np.max)
argmin = keepdims_wrapper(np.argmin)
nanargmin = keepdims_wrapper(np.nanargmin)
argmax = keepdims_wrapper(np.argmax)
nanargmax = keepdims_wrapper(np.nanargmax)
any = keepdims_wrapper(np.any)
all = keepdims_wrapper(np.all)
nansum = keepdims_wrapper(np.nansum)
try:
from numpy import nanprod, nancumprod, nancumsum
except ImportError: # pragma: no cover
nanprod = npcompat.nanprod
nancumprod = npcompat.nancumprod
nancumsum = npcompat.nancumsum
nanprod = keepdims_wrapper(nanprod)
nancumprod = keepdims_wrapper(nancumprod)
nancumsum = keepdims_wrapper(nancumsum)
nanmin = keepdims_wrapper(np.nanmin)
nanmax = keepdims_wrapper(np.nanmax)
mean = keepdims_wrapper(np.mean)
with ignoring(AttributeError):
nanmean = keepdims_wrapper(np.nanmean)
var = keepdims_wrapper(np.var)
with ignoring(AttributeError):
nanvar = keepdims_wrapper(np.nanvar)
std = keepdims_wrapper(np.std)
with ignoring(AttributeError):
nanstd = keepdims_wrapper(np.nanstd)
def coarsen(reduction, x, axes, trim_excess=False):
""" Coarsen array by applying reduction to fixed size neighborhoods
Parameters
----------
reduction: function
Function like np.sum, np.mean, etc...
x: np.ndarray
Array to be coarsened
axes: dict
Mapping of axis to coarsening factor
Examples
--------
>>> x = np.array([1, 2, 3, 4, 5, 6])
>>> coarsen(np.sum, x, {0: 2})
array([ 3, 7, 11])
>>> coarsen(np.max, x, {0: 3})
array([3, 6])
Provide dictionary of scale per dimension
>>> x = np.arange(24).reshape((4, 6))
>>> x
array([[ 0, 1, 2, 3, 4, 5],
[ 6, 7, 8, 9, 10, 11],
[12, 13, 14, 15, 16, 17],
[18, 19, 20, 21, 22, 23]])
>>> coarsen(np.min, x, {0: 2, 1: 3})
array([[ 0, 3],
[12, 15]])
You must avoid excess elements explicitly
>>> x = np.array([1, 2, 3, 4, 5, 6, 7, 8])
>>> coarsen(np.min, x, {0: 3}, trim_excess=True)
array([1, 4])
"""
# Insert singleton dimensions if they don't exist already
for i in range(x.ndim):
if i not in axes:
axes[i] = 1
if trim_excess:
ind = tuple(slice(0, -(d % axes[i]))
if d % axes[i] else
slice(None, None) for i, d in enumerate(x.shape))
x = x[ind]
# (10, 10) -> (5, 2, 5, 2)
newshape = tuple(concat([(x.shape[i] / axes[i], axes[i])
for i in range(x.ndim)]))
return reduction(x.reshape(newshape), axis=tuple(range(1, x.ndim * 2, 2)))
def trim(x, axes=None):
""" Trim boundaries off of array
>>> x = np.arange(24).reshape((4, 6))
>>> trim(x, axes={0: 0, 1: 1})
array([[ 1, 2, 3, 4],
[ 7, 8, 9, 10],
[13, 14, 15, 16],
[19, 20, 21, 22]])
>>> trim(x, axes={0: 1, 1: 1})
array([[ 7, 8, 9, 10],
[13, 14, 15, 16]])
"""
if isinstance(axes, int):
axes = [axes] * x.ndim
if isinstance(axes, dict):
axes = [axes.get(i, 0) for i in range(x.ndim)]
return x[tuple(slice(ax, -ax if ax else None) for ax in axes)]
try:
from numpy import broadcast_to
except ImportError: # pragma: no cover
broadcast_to = npcompat.broadcast_to
def topk(k, x):
""" Top k elements of an array
>>> topk(2, np.array([5, 1, 3, 6]))
array([6, 5])
"""
# http://stackoverflow.com/a/23734295/616616 by larsmans
k = np.minimum(k, len(x))
ind = np.argpartition(x, -k)[-k:]
return | np.sort(x[ind]) | numpy.sort |
# coding: utf-8
# /*##########################################################################
#
# Copyright (c) 2014-2018 European Synchrotron Radiation Facility
#
# 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 modules provides the rendering of plot titles, axes and grid.
"""
__authors__ = ["<NAME>"]
__license__ = "MIT"
__date__ = "03/04/2017"
# TODO
# keep aspect ratio managed here?
# smarter dirty flag handling?
import datetime as dt
import math
import weakref
import logging
from collections import namedtuple
import numpy
from ...._glutils import gl, Program
from ..._utils import FLOAT32_SAFE_MIN, FLOAT32_MINPOS, FLOAT32_SAFE_MAX
from .GLSupport import mat4Ortho
from .GLText import Text2D, CENTER, BOTTOM, TOP, LEFT, RIGHT, ROTATE_270
from ..._utils.ticklayout import niceNumbersAdaptative, niceNumbersForLog10
from ..._utils.dtime_ticklayout import calcTicksAdaptive, bestFormatString
from ..._utils.dtime_ticklayout import timestamp
_logger = logging.getLogger(__name__)
# PlotAxis ####################################################################
class PlotAxis(object):
"""Represents a 1D axis of the plot.
This class is intended to be used with :class:`GLPlotFrame`.
"""
def __init__(self, plot,
tickLength=(0., 0.),
labelAlign=CENTER, labelVAlign=CENTER,
titleAlign=CENTER, titleVAlign=CENTER,
titleRotate=0, titleOffset=(0., 0.)):
self._ticks = None
self._plot = weakref.ref(plot)
self._isDateTime = False
self._timeZone = None
self._isLog = False
self._dataRange = 1., 100.
self._displayCoords = (0., 0.), (1., 0.)
self._title = ''
self._tickLength = tickLength
self._labelAlign = labelAlign
self._labelVAlign = labelVAlign
self._titleAlign = titleAlign
self._titleVAlign = titleVAlign
self._titleRotate = titleRotate
self._titleOffset = titleOffset
@property
def dataRange(self):
"""The range of the data represented on the axis as a tuple
of 2 floats: (min, max)."""
return self._dataRange
@dataRange.setter
def dataRange(self, dataRange):
assert len(dataRange) == 2
assert dataRange[0] <= dataRange[1]
dataRange = float(dataRange[0]), float(dataRange[1])
if dataRange != self._dataRange:
self._dataRange = dataRange
self._dirtyTicks()
@property
def isLog(self):
"""Whether the axis is using a log10 scale or not as a bool."""
return self._isLog
@isLog.setter
def isLog(self, isLog):
isLog = bool(isLog)
if isLog != self._isLog:
self._isLog = isLog
self._dirtyTicks()
@property
def timeZone(self):
"""Returnss datetime.tzinfo that is used if this axis plots date times."""
return self._timeZone
@timeZone.setter
def timeZone(self, tz):
"""Sets dateetime.tzinfo that is used if this axis plots date times."""
self._timeZone = tz
self._dirtyTicks()
@property
def isTimeSeries(self):
"""Whether the axis is showing floats as datetime objects"""
return self._isDateTime
@isTimeSeries.setter
def isTimeSeries(self, isTimeSeries):
isTimeSeries = bool(isTimeSeries)
if isTimeSeries != self._isDateTime:
self._isDateTime = isTimeSeries
self._dirtyTicks()
@property
def displayCoords(self):
"""The coordinates of the start and end points of the axis
in display space (i.e., in pixels) as a tuple of 2 tuples of
2 floats: ((x0, y0), (x1, y1)).
"""
return self._displayCoords
@displayCoords.setter
def displayCoords(self, displayCoords):
assert len(displayCoords) == 2
assert len(displayCoords[0]) == 2
assert len(displayCoords[1]) == 2
displayCoords = tuple(displayCoords[0]), tuple(displayCoords[1])
if displayCoords != self._displayCoords:
self._displayCoords = displayCoords
self._dirtyTicks()
@property
def title(self):
"""The text label associated with this axis as a str in latin-1."""
return self._title
@title.setter
def title(self, title):
if title != self._title:
self._title = title
plot = self._plot()
if plot is not None:
plot._dirty()
@property
def ticks(self):
"""Ticks as tuples: ((x, y) in display, dataPos, textLabel)."""
if self._ticks is None:
self._ticks = tuple(self._ticksGenerator())
return self._ticks
def getVerticesAndLabels(self):
"""Create the list of vertices for axis and associated text labels.
:returns: A tuple: List of 2D line vertices, List of Text2D labels.
"""
vertices = list(self.displayCoords) # Add start and end points
labels = []
tickLabelsSize = [0., 0.]
xTickLength, yTickLength = self._tickLength
for (xPixel, yPixel), dataPos, text in self.ticks:
if text is None:
tickScale = 0.5
else:
tickScale = 1.
label = Text2D(text=text,
x=xPixel - xTickLength,
y=yPixel - yTickLength,
align=self._labelAlign,
valign=self._labelVAlign)
width, height = label.size
if width > tickLabelsSize[0]:
tickLabelsSize[0] = width
if height > tickLabelsSize[1]:
tickLabelsSize[1] = height
labels.append(label)
vertices.append((xPixel, yPixel))
vertices.append((xPixel + tickScale * xTickLength,
yPixel + tickScale * yTickLength))
(x0, y0), (x1, y1) = self.displayCoords
xAxisCenter = 0.5 * (x0 + x1)
yAxisCenter = 0.5 * (y0 + y1)
xOffset, yOffset = self._titleOffset
# Adaptative title positioning:
# tickNorm = math.sqrt(xTickLength ** 2 + yTickLength ** 2)
# xOffset = -tickLabelsSize[0] * xTickLength / tickNorm
# xOffset -= 3 * xTickLength
# yOffset = -tickLabelsSize[1] * yTickLength / tickNorm
# yOffset -= 3 * yTickLength
axisTitle = Text2D(text=self.title,
x=xAxisCenter + xOffset,
y=yAxisCenter + yOffset,
align=self._titleAlign,
valign=self._titleVAlign,
rotate=self._titleRotate)
labels.append(axisTitle)
return vertices, labels
def _dirtyTicks(self):
"""Mark ticks as dirty and notify listener (i.e., background)."""
self._ticks = None
plot = self._plot()
if plot is not None:
plot._dirty()
@staticmethod
def _frange(start, stop, step):
"""range for float (including stop)."""
while start <= stop:
yield start
start += step
def _ticksGenerator(self):
"""Generator of ticks as tuples:
((x, y) in display, dataPos, textLabel).
"""
dataMin, dataMax = self.dataRange
if self.isLog and dataMin <= 0.:
_logger.warning(
'Getting ticks while isLog=True and dataRange[0]<=0.')
dataMin = 1.
if dataMax < dataMin:
dataMax = 1.
if dataMin != dataMax: # data range is not null
(x0, y0), (x1, y1) = self.displayCoords
if self.isLog:
if self.isTimeSeries:
_logger.warning("Time series not implemented for log-scale")
logMin, logMax = math.log10(dataMin), math.log10(dataMax)
tickMin, tickMax, step, _ = niceNumbersForLog10(logMin, logMax)
xScale = (x1 - x0) / (logMax - logMin)
yScale = (y1 - y0) / (logMax - logMin)
for logPos in self._frange(tickMin, tickMax, step):
if logMin <= logPos <= logMax:
dataPos = 10 ** logPos
xPixel = x0 + (logPos - logMin) * xScale
yPixel = y0 + (logPos - logMin) * yScale
text = '1e%+03d' % logPos
yield ((xPixel, yPixel), dataPos, text)
if step == 1:
ticks = list(self._frange(tickMin, tickMax, step))[:-1]
for logPos in ticks:
dataOrigPos = 10 ** logPos
for index in range(2, 10):
dataPos = dataOrigPos * index
if dataMin <= dataPos <= dataMax:
logSubPos = math.log10(dataPos)
xPixel = x0 + (logSubPos - logMin) * xScale
yPixel = y0 + (logSubPos - logMin) * yScale
yield ((xPixel, yPixel), dataPos, None)
else:
xScale = (x1 - x0) / (dataMax - dataMin)
yScale = (y1 - y0) / (dataMax - dataMin)
nbPixels = math.sqrt(pow(x1 - x0, 2) + pow(y1 - y0, 2))
# Density of 1.3 label per 92 pixels
# i.e., 1.3 label per inch on a 92 dpi screen
tickDensity = 1.3 / 92
if not self.isTimeSeries:
tickMin, tickMax, step, nbFrac = niceNumbersAdaptative(
dataMin, dataMax, nbPixels, tickDensity)
for dataPos in self._frange(tickMin, tickMax, step):
if dataMin <= dataPos <= dataMax:
xPixel = x0 + (dataPos - dataMin) * xScale
yPixel = y0 + (dataPos - dataMin) * yScale
if nbFrac == 0:
text = '%g' % dataPos
else:
text = ('%.' + str(nbFrac) + 'f') % dataPos
yield ((xPixel, yPixel), dataPos, text)
else:
# Time series
dtMin = dt.datetime.fromtimestamp(dataMin, tz=self.timeZone)
dtMax = dt.datetime.fromtimestamp(dataMax, tz=self.timeZone)
tickDateTimes, spacing, unit = calcTicksAdaptive(
dtMin, dtMax, nbPixels, tickDensity)
for tickDateTime in tickDateTimes:
if dtMin <= tickDateTime <= dtMax:
dataPos = timestamp(tickDateTime)
xPixel = x0 + (dataPos - dataMin) * xScale
yPixel = y0 + (dataPos - dataMin) * yScale
fmtStr = bestFormatString(spacing, unit)
text = tickDateTime.strftime(fmtStr)
yield ((xPixel, yPixel), dataPos, text)
# GLPlotFrame #################################################################
class GLPlotFrame(object):
"""Base class for rendering a 2D frame surrounded by axes."""
_TICK_LENGTH_IN_PIXELS = 5
_LINE_WIDTH = 1
_SHADERS = {
'vertex': """
attribute vec2 position;
uniform mat4 matrix;
void main(void) {
gl_Position = matrix * vec4(position, 0.0, 1.0);
}
""",
'fragment': """
uniform vec4 color;
uniform float tickFactor; /* = 1./tickLength or 0. for solid line */
void main(void) {
if (mod(tickFactor * (gl_FragCoord.x + gl_FragCoord.y), 2.) < 1.) {
gl_FragColor = color;
} else {
discard;
}
}
"""
}
_Margins = namedtuple('Margins', ('left', 'right', 'top', 'bottom'))
# Margins used when plot frame is not displayed
_NoDisplayMargins = _Margins(0, 0, 0, 0)
def __init__(self, margins):
"""
:param margins: The margins around plot area for axis and labels.
:type margins: dict with 'left', 'right', 'top', 'bottom' keys and
values as ints.
"""
self._renderResources = None
self._margins = self._Margins(**margins)
self.axes = [] # List of PlotAxis to be updated by subclasses
self._grid = False
self._size = 0., 0.
self._title = ''
self._displayed = True
@property
def isDirty(self):
"""True if it need to refresh graphic rendering, False otherwise."""
return self._renderResources is None
GRID_NONE = 0
GRID_MAIN_TICKS = 1
GRID_SUB_TICKS = 2
GRID_ALL_TICKS = (GRID_MAIN_TICKS + GRID_SUB_TICKS)
@property
def displayed(self):
"""Whether axes and their labels are displayed or not (bool)"""
return self._displayed
@displayed.setter
def displayed(self, displayed):
displayed = bool(displayed)
if displayed != self._displayed:
self._displayed = displayed
self._dirty()
@property
def margins(self):
"""Margins in pixels around the plot."""
if not self.displayed:
return self._NoDisplayMargins
else:
return self._margins
@property
def grid(self):
"""Grid display mode:
- 0: No grid.
- 1: Grid on main ticks.
- 2: Grid on sub-ticks for log scale axes.
- 3: Grid on main and sub ticks."""
return self._grid
@grid.setter
def grid(self, grid):
assert grid in (self.GRID_NONE, self.GRID_MAIN_TICKS,
self.GRID_SUB_TICKS, self.GRID_ALL_TICKS)
if grid != self._grid:
self._grid = grid
self._dirty()
@property
def size(self):
"""Size in pixels of the plot area including margins."""
return self._size
@size.setter
def size(self, size):
assert len(size) == 2
size = tuple(size)
if size != self._size:
self._size = size
self._dirty()
@property
def plotOrigin(self):
"""Plot area origin (left, top) in widget coordinates in pixels."""
return self.margins.left, self.margins.top
@property
def plotSize(self):
"""Plot area size (width, height) in pixels."""
w, h = self.size
w -= self.margins.left + self.margins.right
h -= self.margins.top + self.margins.bottom
return w, h
@property
def title(self):
"""Main title as a str in latin-1."""
return self._title
@title.setter
def title(self, title):
if title != self._title:
self._title = title
self._dirty()
# In-place update
# if self._renderResources is not None:
# self._renderResources[-1][-1].text = title
def _dirty(self):
# When Text2D require discard we need to handle it
self._renderResources = None
def _buildGridVertices(self):
if self._grid == self.GRID_NONE:
return []
elif self._grid == self.GRID_MAIN_TICKS:
def test(text):
return text is not None
elif self._grid == self.GRID_SUB_TICKS:
def test(text):
return text is None
elif self._grid == self.GRID_ALL_TICKS:
def test(_):
return True
else:
logging.warning('Wrong grid mode: %d' % self._grid)
return []
return self._buildGridVerticesWithTest(test)
def _buildGridVerticesWithTest(self, test):
"""Override in subclass to generate grid vertices"""
return []
def _buildVerticesAndLabels(self):
# To fill with copy of axes lists
vertices = []
labels = []
for axis in self.axes:
axisVertices, axisLabels = axis.getVerticesAndLabels()
vertices += axisVertices
labels += axisLabels
vertices = numpy.array(vertices, dtype=numpy.float32)
# Add main title
xTitle = (self.size[0] + self.margins.left -
self.margins.right) // 2
yTitle = self.margins.top - self._TICK_LENGTH_IN_PIXELS
labels.append(Text2D(text=self.title,
x=xTitle,
y=yTitle,
align=CENTER,
valign=BOTTOM))
# grid
gridVertices = numpy.array(self._buildGridVertices(),
dtype=numpy.float32)
self._renderResources = (vertices, gridVertices, labels)
_program = Program(
_SHADERS['vertex'], _SHADERS['fragment'], attrib0='position')
def render(self):
if not self.displayed:
return
if self._renderResources is None:
self._buildVerticesAndLabels()
vertices, gridVertices, labels = self._renderResources
width, height = self.size
matProj = mat4Ortho(0, width, height, 0, 1, -1)
gl.glViewport(0, 0, width, height)
prog = self._program
prog.use()
gl.glLineWidth(self._LINE_WIDTH)
gl.glUniformMatrix4fv(prog.uniforms['matrix'], 1, gl.GL_TRUE,
matProj.astype(numpy.float32))
gl.glUniform4f(prog.uniforms['color'], 0., 0., 0., 1.)
gl.glUniform1f(prog.uniforms['tickFactor'], 0.)
gl.glEnableVertexAttribArray(prog.attributes['position'])
gl.glVertexAttribPointer(prog.attributes['position'],
2,
gl.GL_FLOAT,
gl.GL_FALSE,
0, vertices)
gl.glDrawArrays(gl.GL_LINES, 0, len(vertices))
for label in labels:
label.render(matProj)
def renderGrid(self):
if self._grid == self.GRID_NONE:
return
if self._renderResources is None:
self._buildVerticesAndLabels()
vertices, gridVertices, labels = self._renderResources
width, height = self.size
matProj = mat4Ortho(0, width, height, 0, 1, -1)
gl.glViewport(0, 0, width, height)
prog = self._program
prog.use()
gl.glLineWidth(self._LINE_WIDTH)
gl.glUniformMatrix4fv(prog.uniforms['matrix'], 1, gl.GL_TRUE,
matProj.astype(numpy.float32))
gl.glUniform4f(prog.uniforms['color'], 0.7, 0.7, 0.7, 1.)
gl.glUniform1f(prog.uniforms['tickFactor'], 0.) # 1/2.) # 1/tickLen
gl.glEnableVertexAttribArray(prog.attributes['position'])
gl.glVertexAttribPointer(prog.attributes['position'],
2,
gl.GL_FLOAT,
gl.GL_FALSE,
0, gridVertices)
gl.glDrawArrays(gl.GL_LINES, 0, len(gridVertices))
# GLPlotFrame2D ###############################################################
class GLPlotFrame2D(GLPlotFrame):
def __init__(self, margins):
"""
:param margins: The margins around plot area for axis and labels.
:type margins: dict with 'left', 'right', 'top', 'bottom' keys and
values as ints.
"""
super(GLPlotFrame2D, self).__init__(margins)
self.axes.append(PlotAxis(self,
tickLength=(0., -5.),
labelAlign=CENTER, labelVAlign=TOP,
titleAlign=CENTER, titleVAlign=TOP,
titleRotate=0,
titleOffset=(0, self.margins.bottom // 2)))
self._x2AxisCoords = ()
self.axes.append(PlotAxis(self,
tickLength=(5., 0.),
labelAlign=RIGHT, labelVAlign=CENTER,
titleAlign=CENTER, titleVAlign=BOTTOM,
titleRotate=ROTATE_270,
titleOffset=(-3 * self.margins.left // 4,
0)))
self._y2Axis = PlotAxis(self,
tickLength=(-5., 0.),
labelAlign=LEFT, labelVAlign=CENTER,
titleAlign=CENTER, titleVAlign=TOP,
titleRotate=ROTATE_270,
titleOffset=(3 * self.margins.right // 4,
0))
self._isYAxisInverted = False
self._dataRanges = {
'x': (1., 100.), 'y': (1., 100.), 'y2': (1., 100.)}
self._baseVectors = (1., 0.), (0., 1.)
self._transformedDataRanges = None
self._transformedDataProjMat = None
self._transformedDataY2ProjMat = None
def _dirty(self):
super(GLPlotFrame2D, self)._dirty()
self._transformedDataRanges = None
self._transformedDataProjMat = None
self._transformedDataY2ProjMat = None
@property
def isDirty(self):
"""True if it need to refresh graphic rendering, False otherwise."""
return (super(GLPlotFrame2D, self).isDirty or
self._transformedDataRanges is None or
self._transformedDataProjMat is None or
self._transformedDataY2ProjMat is None)
@property
def xAxis(self):
return self.axes[0]
@property
def yAxis(self):
return self.axes[1]
@property
def y2Axis(self):
return self._y2Axis
@property
def isY2Axis(self):
"""Whether to display the left Y axis or not."""
return len(self.axes) == 3
@isY2Axis.setter
def isY2Axis(self, isY2Axis):
if isY2Axis != self.isY2Axis:
if isY2Axis:
self.axes.append(self._y2Axis)
else:
self.axes = self.axes[:2]
self._dirty()
@property
def isYAxisInverted(self):
"""Whether Y axes are inverted or not as a bool."""
return self._isYAxisInverted
@isYAxisInverted.setter
def isYAxisInverted(self, value):
value = bool(value)
if value != self._isYAxisInverted:
self._isYAxisInverted = value
self._dirty()
DEFAULT_BASE_VECTORS = (1., 0.), (0., 1.)
"""Values of baseVectors for orthogonal axes."""
@property
def baseVectors(self):
"""Coordinates of the X and Y axes in the orthogonal plot coords.
Raises ValueError if corresponding matrix is singular.
2 tuples of 2 floats: (xx, xy), (yx, yy)
"""
return self._baseVectors
@baseVectors.setter
def baseVectors(self, baseVectors):
self._dirty()
(xx, xy), (yx, yy) = baseVectors
vectors = (float(xx), float(xy)), (float(yx), float(yy))
det = (vectors[0][0] * vectors[1][1] - vectors[1][0] * vectors[0][1])
if det == 0.:
raise ValueError("Singular matrix for base vectors: " +
str(vectors))
if vectors != self._baseVectors:
self._baseVectors = vectors
self._dirty()
@property
def dataRanges(self):
"""Ranges of data visible in the plot on x, y and y2 axes.
This is different to the axes range when axes are not orthogonal.
Type: ((xMin, xMax), (yMin, yMax), (y2Min, y2Max))
"""
return self._DataRanges(self._dataRanges['x'],
self._dataRanges['y'],
self._dataRanges['y2'])
@staticmethod
def _clipToSafeRange(min_, max_, isLog):
# Clip range if needed
minLimit = FLOAT32_MINPOS if isLog else FLOAT32_SAFE_MIN
min_ = numpy.clip(min_, minLimit, FLOAT32_SAFE_MAX)
max_ = numpy.clip(max_, minLimit, FLOAT32_SAFE_MAX)
assert min_ < max_
return min_, max_
def setDataRanges(self, x=None, y=None, y2=None):
"""Set data range over each axes.
The provided ranges are clipped to possible values
(i.e., 32 float range + positive range for log scale).
:param x: (min, max) data range over X axis
:param y: (min, max) data range over Y axis
:param y2: (min, max) data range over Y2 axis
"""
if x is not None:
self._dataRanges['x'] = \
self._clipToSafeRange(x[0], x[1], self.xAxis.isLog)
if y is not None:
self._dataRanges['y'] = \
self._clipToSafeRange(y[0], y[1], self.yAxis.isLog)
if y2 is not None:
self._dataRanges['y2'] = \
self._clipToSafeRange(y2[0], y2[1], self.y2Axis.isLog)
self.xAxis.dataRange = self._dataRanges['x']
self.yAxis.dataRange = self._dataRanges['y']
self.y2Axis.dataRange = self._dataRanges['y2']
_DataRanges = namedtuple('dataRanges', ('x', 'y', 'y2'))
@property
def transformedDataRanges(self):
"""Bounds of the displayed area in transformed data coordinates
(i.e., log scale applied if any as well as skew)
3-tuple of 2-tuple (min, max) for each axis: x, y, y2.
"""
if self._transformedDataRanges is None:
(xMin, xMax), (yMin, yMax), (y2Min, y2Max) = self.dataRanges
if self.xAxis.isLog:
try:
xMin = math.log10(xMin)
except ValueError:
_logger.info('xMin: warning log10(%f)', xMin)
xMin = 0.
try:
xMax = math.log10(xMax)
except ValueError:
_logger.info('xMax: warning log10(%f)', xMax)
xMax = 0.
if self.yAxis.isLog:
try:
yMin = math.log10(yMin)
except ValueError:
_logger.info('yMin: warning log10(%f)', yMin)
yMin = 0.
try:
yMax = math.log10(yMax)
except ValueError:
_logger.info('yMax: warning log10(%f)', yMax)
yMax = 0.
try:
y2Min = math.log10(y2Min)
except ValueError:
_logger.info('yMin: warning log10(%f)', y2Min)
y2Min = 0.
try:
y2Max = math.log10(y2Max)
except ValueError:
_logger.info('yMax: warning log10(%f)', y2Max)
y2Max = 0.
# Non-orthogonal axes
if self.baseVectors != self.DEFAULT_BASE_VECTORS:
(xx, xy), (yx, yy) = self.baseVectors
skew_mat = | numpy.array(((xx, yx), (xy, yy))) | numpy.array |
'''
Unit tests for CurvRectRegridder
@author: <NAME>
'''
from __future__ import print_function
import unittest
import numpy
import ESMP
from esmpcontrol import ESMPControl
from regrid2d import CurvRectRegridder
class CurvRectRegridderTests(unittest.TestCase):
'''
Unit tests for the CurvRectRegridder class
'''
# flag to indicate when to call ESMPControl().stopESMP()
last_test = False
def setUp(self):
'''
Create some repeatedly used test data.
'''
# Use tuples for the arrays to make sure the NumPy
# arrays created in the class methods are always used;
# not arrays that happened to be passed as input.
# Also verifies passed data is not modified.
# Rectilinear coordinates, data. and flags
crn_lons = numpy.linspace(-110, -90, 11)
crn_lats = numpy.linspace(0, 32, 9)
ctr_lons = 0.5 * (crn_lons[:-1] + crn_lons[1:])
ctr_lats = 0.5 * (crn_lats[:-1] + crn_lats[1:])
ctr_lats_mat, ctr_lons_mat = numpy.meshgrid(ctr_lats, ctr_lons)
data = -2.0 * numpy.sin(numpy.deg2rad(ctr_lons_mat)) \
* numpy.cos(numpy.deg2rad(ctr_lats_mat))
ctr_flags = numpy.zeros(data.shape, dtype=numpy.int32)
ctr_flags[:2, :2] = 1
crn_flags = numpy.zeros((crn_lons.shape[0], crn_lats.shape[0]), dtype=numpy.int32)
crn_flags[:2, :2] = 1
# Turn rectilinear arrays into tuples
self.rect_corner_lons = tuple(crn_lons)
self.rect_corner_lats = tuple(crn_lats)
self.rect_center_lons = tuple(ctr_lons)
self.rect_center_lats = tuple(ctr_lats)
self.rect_center_ignr = tuple([tuple(subarr) for subarr in ctr_flags.tolist()])
self.rect_corner_ignr = tuple([tuple(subarr) for subarr in crn_flags.tolist()])
self.rect_data = tuple([tuple(subarr) for subarr in data.tolist()])
# Curvilinear coordindates - one step further out on all sides of the region
crn_lons = numpy.linspace(-112, -88, 13)
crn_lats = numpy.linspace(-4, 36, 11)
crn_lats_mat, crn_lons_mat = numpy.meshgrid(crn_lats, crn_lons)
ctr_lons = 0.5 * (crn_lons[:-1] + crn_lons[1:])
ctr_lats = 0.5 * (crn_lats[:-1] + crn_lats[1:])
ctr_lats_mat, ctr_lons_mat = numpy.meshgrid(ctr_lats, ctr_lons)
# Pull coordinates in some towards the center
crn_lons = crn_lons_mat * numpy.cos(numpy.deg2rad(crn_lats_mat - 16.0) / 2.0)
crn_lats = crn_lats_mat * numpy.cos(numpy.deg2rad(crn_lons_mat + 100.0) / 2.0)
ctr_lons = ctr_lons_mat * numpy.cos(numpy.deg2rad(ctr_lats_mat - 16.0) / 2.0)
ctr_lats = ctr_lats_mat * numpy.cos(numpy.deg2rad(ctr_lons_mat + 100.0) / 2.0)
# Curvilinear data and flags
data = -2.0 * numpy.sin(numpy.deg2rad(ctr_lons)) \
* numpy.cos(numpy.deg2rad(ctr_lats))
ctr_flags = numpy.zeros(data.shape, dtype=numpy.int32)
ctr_flags[:3, :3] = 1
crn_flags = numpy.zeros(crn_lons.shape, dtype=numpy.int32)
crn_flags[:3, :3] = 1
# Turn curvilinear arrays into tuples
self.curv_corner_lons = tuple([tuple(subarr) for subarr in crn_lons.tolist()])
self.curv_corner_lats = tuple([tuple(subarr) for subarr in crn_lats.tolist()])
self.curv_center_lons = tuple([tuple(subarr) for subarr in ctr_lons.tolist()])
self.curv_center_lats = tuple([tuple(subarr) for subarr in ctr_lats.tolist()])
self.curv_center_ignr = tuple([tuple(subarr) for subarr in ctr_flags.tolist()])
self.curv_corner_ignr = tuple([tuple(subarr) for subarr in crn_flags.tolist()])
self.curv_data = tuple([tuple(subarr) for subarr in data.tolist()])
# undef_val must be a numpy array
self.undef_val = numpy.array([1.0E10], dtype=numpy.float64)
if not ESMPControl().startCheckESMP():
self.fail("startCheckESMP did not succeed - test called after last_test set to True")
def test01CurvRectRegridderInit(self):
'''
Test of the CurvRectRegridder.__init__ method.
'''
regridder = CurvRectRegridder()
self.assertTrue(regridder != None, "CurvRectRegridder() returned None")
regridder.finalize()
def test02CreateCurvGrid(self):
'''
Tests the CurvRectRegridder.createCurvGrid method.
Since nothing is returned from this method, just
checks for unexpected/expected Errors being raised.
'''
regridder = CurvRectRegridder()
# Test with all corner and center data
regridder.createCurvGrid(self.curv_center_lons, self.curv_center_lats,
self.curv_center_ignr, self.curv_corner_lons,
self.curv_corner_lats, self.curv_corner_ignr)
# Test without flags
regridder.createCurvGrid(self.curv_center_lons, self.curv_center_lats,
None, self.curv_corner_lons, self.curv_corner_lats)
# Test without corners
regridder.createCurvGrid(self.curv_center_lons, self.curv_center_lats,
self.curv_center_ignr)
# Test without corners or flags
regridder.createCurvGrid(self.curv_center_lons, self.curv_center_lats)
# TODO: Test invalid cases
# Done with this regridder
regridder.finalize()
def test03AssignCurvField(self):
'''
Tests the CurvRectRegridder.assignCurvGrid method.
Since nothing is returned from this method, just
checks for unexpected/expected Errors being raised.
'''
regridder = CurvRectRegridder()
# Test with all corner and center data
regridder.createCurvGrid(self.curv_center_lons, self.curv_center_lats,
self.curv_center_ignr, self.curv_corner_lons,
self.curv_corner_lats, self.curv_corner_ignr)
regridder.assignCurvField()
regridder.assignCurvField(self.curv_data)
# Test without flags
regridder.createCurvGrid(self.curv_center_lons, self.curv_center_lats,
None, self.curv_corner_lons, self.curv_corner_lats)
regridder.assignCurvField(self.curv_data)
regridder.assignCurvField()
# Test without corners
regridder.createCurvGrid(self.curv_center_lons, self.curv_center_lats,
self.curv_center_ignr)
regridder.assignCurvField(self.curv_data)
regridder.assignCurvField()
# Test without corners or flags
regridder.createCurvGrid(self.curv_center_lons, self.curv_center_lats)
regridder.assignCurvField()
regridder.assignCurvField(self.curv_data)
# TODO: Test invalid cases
# Done with this regridder
regridder.finalize()
def test04CreateRectGrid(self):
'''
Tests the CurvRectRegridder.createRectGrid method.
Since nothing is returned from this method, just
checks for unexpected/expected Errors being raised.
'''
regridder = CurvRectRegridder()
# Test with all corner and center data
regridder.createRectGrid(self.rect_center_lons, self.rect_center_lats,
self.rect_center_ignr, self.rect_corner_lons,
self.rect_corner_lats, self.rect_corner_ignr)
# Test without flags
regridder.createRectGrid(self.rect_center_lons, self.rect_center_lats,
None, self.rect_corner_lons, self.rect_corner_lats)
# Test without corners
regridder.createRectGrid(self.rect_center_lons, self.rect_center_lats,
self.rect_center_ignr)
# Test without corners or flags
regridder.createRectGrid(self.rect_center_lons, self.rect_center_lats)
# TODO: Test invalid cases
# Done with this regridder
regridder.finalize()
def test05AssignRectField(self):
'''
Tests the CurvRectRegridder.assignRectGrid method.
Since nothing is returned from this method, just
checks for unexpected/expected Errors being raised.
'''
regridder = CurvRectRegridder()
# Test with all corner and center data
regridder.createRectGrid(self.rect_center_lons, self.rect_center_lats,
self.rect_center_ignr, self.rect_corner_lons,
self.rect_corner_lats, self.rect_corner_ignr)
regridder.assignRectField(self.rect_data)
regridder.assignRectField()
# Test without flags
regridder.createRectGrid(self.rect_center_lons, self.rect_center_lats,
None, self.rect_corner_lons, self.rect_corner_lats)
regridder.assignRectField()
regridder.assignRectField(self.rect_data)
# Test without corners
regridder.createRectGrid(self.rect_center_lons, self.rect_center_lats,
self.rect_center_ignr)
regridder.assignRectField()
regridder.assignRectField(self.rect_data)
# Test without corners or flags
regridder.createRectGrid(self.rect_center_lons, self.rect_center_lats)
regridder.assignRectField(self.rect_data)
regridder.assignRectField()
# TODO: Test invalid cases
# Done with this regridder
regridder.finalize()
def test06RegridCurvToRectConserve(self):
'''
Tests the CurvRectRegridder.regridCurvToRect method using conservative regridding
'''
regridder = CurvRectRegridder()
# Test with all corner and center data, using conservative regridding
regridder.createCurvGrid(self.curv_center_lons, self.curv_center_lats,
self.curv_center_ignr, self.curv_corner_lons,
self.curv_corner_lats, self.curv_corner_ignr)
regridder.assignCurvField(self.curv_data)
regridder.createRectGrid(self.rect_center_lons, self.rect_center_lats,
self.rect_center_ignr, self.rect_corner_lons,
self.rect_corner_lats, self.rect_corner_ignr)
regridder.assignRectField()
regrid_data = regridder.regridCurvToRect(self.undef_val,
ESMP.ESMP_REGRIDMETHOD_CONSERVE)
expect_data = numpy.array(self.rect_data, dtype=numpy.float64)
undef_flags = numpy.array(self.rect_center_ignr, dtype=numpy.bool)
expect_data[undef_flags] = self.undef_val
mismatch_found = False
# Couple "good" points next to ignored data area are a bit wonky
expect_data[2, 0] = self.undef_val
regrid_data[2, 0] = self.undef_val
expect_data[2, 1] = self.undef_val
regrid_data[2, 1] = self.undef_val
for i in range(expect_data.shape[0]):
for j in range(expect_data.shape[1]):
if numpy.abs(expect_data[i, j] - regrid_data[i, j]) > 0.0007:
mismatch_found = True
print("expect = %#6.4f, found = %#6.4f for lon = %5.1f, " \
"lat = %5.1f" % (expect_data[i, j], regrid_data[i, j],
self.rect_center_lons[i], self.rect_center_lats[j]))
if mismatch_found:
self.fail("data mismatch found")
def test07RegridCurvToRectBilinear(self):
'''
Tests the CurvRectRegridder.regridCurvToRect method using bilinear regridding
'''
regridder = CurvRectRegridder()
# Test with only center data and no flags, using bilinear regridding
regridder.createCurvGrid(self.curv_center_lons, self.curv_center_lats)
regridder.assignCurvField(self.curv_data)
regridder.createRectGrid(self.rect_center_lons, self.rect_center_lats)
regridder.assignRectField()
regrid_data = regridder.regridCurvToRect(self.undef_val,
ESMP.ESMP_REGRIDMETHOD_BILINEAR)
expect_data = numpy.array(self.rect_data, dtype=numpy.float64)
mismatch_found = False
# one point falls outside the curvilinear centerpoints grid?
expect_data[5, 0] = self.undef_val
for i in range(expect_data.shape[0]):
for j in range(expect_data.shape[1]):
if numpy.abs(expect_data[i, j] - regrid_data[i, j]) > 0.0003:
mismatch_found = True
print("expect = %#6.4f, found = %#6.4f for lon = %5.1f, " \
"lat = %5.1f" % (expect_data[i, j], regrid_data[i, j],
self.rect_center_lons[i], self.rect_center_lats[j]))
if mismatch_found:
self.fail("data mismatch found")
def test08RegridCurvToRectPatch(self):
'''
Tests the CurvRectRegridder.regridCurvToRect method using patch regridding
'''
regridder = CurvRectRegridder()
# Test with only center data, and flags only on rectilinear centers,
# using patch regridding
regridder.createCurvGrid(self.curv_center_lons, self.curv_center_lats)
regridder.assignCurvField(self.curv_data)
regridder.createRectGrid(self.rect_center_lons, self.rect_center_lats,
self.rect_center_ignr)
regridder.assignRectField()
regrid_data = regridder.regridCurvToRect(self.undef_val,
ESMP.ESMP_REGRIDMETHOD_PATCH)
expect_data = numpy.array(self.rect_data, dtype=numpy.float64)
undef_flags = numpy.array(self.rect_center_ignr, dtype=numpy.bool)
expect_data[undef_flags] = self.undef_val
# one point falls outside the curvilinear centerpoints grid?
expect_data[5, 0] = self.undef_val
mismatch_found = False
for i in range(expect_data.shape[0]):
for j in range(expect_data.shape[1]):
if numpy.abs(expect_data[i, j] - regrid_data[i, j]) > 0.0011:
mismatch_found = True
print("expect = %#6.4f, found = %#6.4f for lon = %5.1f, " \
"lat = %5.1f" % (expect_data[i, j], regrid_data[i, j],
self.rect_center_lons[i], self.rect_center_lats[j]))
if mismatch_found:
self.fail("data mismatch found")
def test09RegridRectToCurvConserve(self):
'''
Tests the CurvRectRegridder.regridRectToCurv method using conservative regridding
'''
regridder = CurvRectRegridder()
# Test with all corner and center data, using conservative regridding
regridder.createCurvGrid(self.curv_center_lons, self.curv_center_lats,
self.curv_center_ignr, self.curv_corner_lons,
self.curv_corner_lats, self.curv_corner_ignr)
regridder.assignCurvField()
regridder.createRectGrid(self.rect_center_lons, self.rect_center_lats,
self.rect_center_ignr, self.rect_corner_lons,
self.rect_corner_lats, self.rect_corner_ignr)
regridder.assignRectField(self.rect_data)
regrid_data = regridder.regridRectToCurv(self.undef_val,
ESMP.ESMP_REGRIDMETHOD_CONSERVE)
expect_data = | numpy.array(self.curv_data, dtype=numpy.float64) | numpy.array |
import numpy as np
import scipy.linalg
def elastic_net(A, B, x=None, l1=1, l2=1, lam=1, tol=1e-6, maxiter=10000):
"""Performs elastic net regression by ADMM
minimize ||A*x - B|| + l1*|x| + l2*||x||
Args:
A (ndarray) : m x n matrix
B (ndarray) : m x k matrix
x (ndarray) : optional, n x k matrix (initial guess for solution)
l1 (float) : optional, strength of l1 penalty
l2 (float) : optional, strength of l2 penalty
lam (float) : optional, admm penalty parameter
tol (float) : optional, relative tolerance for stopping
maxiter(int) : optional, max number of iterations
Returns:
X (ndarray) : n x k matrix, minimizing the objective
References:
<NAME>, <NAME>, <NAME>, <NAME>, <NAME> (2011). Distributed Optimization and Statistical
Learning via the Alternating Direction Method of Multipliers. Foundations and Trends in Machine
Learning.
"""
n = A.shape[1]
k = B.shape[1]
# admm penalty param
lam1 = l1*lam
lam2 = l2*lam
# cache lu factorization for fast prox operator
AtA = | np.dot(A.T, A) | numpy.dot |
#!/usr/bin/python3
import numpy as np
from numpy import matlib
from numpy import random
import sys
import copy
import scipy.signal
import scipy.stats.stats
from matplotlib import pyplot as plt
import unittest
def Norm(t):
while t > np.pi:
t -= 2 * np.pi
while t < -np.pi:
t += 2 * np.pi
return t
def Sign(n):
return 1.0 if n >= 0.0 else -1.0
class Airfoil(object):
def __init__(self, A, rho, lifting=5.0, cmax=1.2):
self.A = A # Cross-sectional area, m^2
self.rho = rho # Density of medium, kg / m^2
self.lifting = lifting
self.Cmax = cmax
def ClipAlpha(self, alpha):
return np.clip(Norm(alpha), -np.pi / 2, np.pi / 2)
def atanClCd(self, alpha):
"""
Based on playing around with some common profiles,
assuming a linear relationship to calculate
atan2(Cl(alpha), Cd(alpha)) w.r.t. alpha
seems reasonable.
"""
clipalpha = self.ClipAlpha(alpha)
deltaatan = -Sign(alpha) if abs(alpha) < np.pi / 2.0 else 0.0
return (np.pi / 2.0 - abs(clipalpha)) * np.sign(clipalpha), deltaatan
def normClCd(self, alpha):
"""
Calculates sqrt(Cl^2 + Cd^2). This
doesn't seem to capture typical profiles
at particularly high angles of attack, but
it seems a fair approximation. This may
cause us to be more incliuned to sail
straight downwind than we really should be.
True profiles have a dip ~70-80 deg angle of attack.
Returns norm, deltanorm/deltaalpha
"""
alpha = self.ClipAlpha(alpha)
exp = np.exp(-self.lifting * abs(alpha))
norm = self.Cmax * (1.0 - exp)
deltanorm = self.Cmax * self.lifting * exp * Sign(alpha)
return norm, deltanorm
def F(self, alpha, v):
"""
Arguments:
alpha: Airfoil angle of attack
v: Relative speed in medium
Returns:
F, deltaF/deltaalpha: Note: deltaF does not account for heel
"""
clipalpha = self.ClipAlpha(alpha)
S = 0.5 * self.rho * self.A * v ** 2
norm, deltanorm = self.normClCd(clipalpha)
F = S * norm
deltaF = S * deltanorm
# Account for stupid angles of attack
deltaF *= -1.0 if abs(alpha) > np.pi / 2.0 else 1.0
return F, deltaF
class DebugForces(object):
def __init__(self):
self.taunet = []
self.Flon = []
self.Flat = []
self.Fs = []
self.Fk = []
self.Fr = []
self.gammas = []
self.gammak = []
self.gammar = []
self.FBlon = []
self.FBlat = []
self.taus = []
self.tauk = []
self.taur = []
self.tauB = []
def UpdateZero(self):
self.Update(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0)
def Update(self, taunet, Flon, Flat, Fs, Fk, Fr, gammas,
gammak, gammar, FBlon, FBlat, taus, tauk, taur, tauB):
self.taunet.append(taunet)
self.Flon.append(Flon)
self.Flat.append(Flat)
self.Fs.append(Fs)
self.Fk.append(Fk)
self.Fr.append(Fr)
self.gammas.append(gammas)
self.gammak.append(gammak)
self.gammar.append(gammar)
self.FBlon.append(FBlon)
self.FBlat.append(FBlat)
self.taus.append(taus)
self.tauk.append(tauk)
self.taur.append(taur)
self.tauB.append(tauB)
def Flonlat(self, F, gamma):
lon = [f * np.cos(g) for f, g in zip(F, gamma)]
lat = [f * np.sin(g) for f, g in zip(F, gamma)]
return lon, lat
def Fslonlat(self):
return self.Flonlat(self.Fs, self.gammas)
def Fklonlat(self):
return self.Flonlat(self.Fk, self.gammak)
def Frlonlat(self):
return self.Flonlat(self.Fr, self.gammar)
class Physics(object):
def __init__(self):
self.hs = 1.5 # Height of sail CoE above origin, m
self.hk = -0.7 # Height of keel CoE above origin, m
self.hr = 0.0 # Height of rudder CoE above origin, m
# Positions longitudinally on the boat relative
# to the origin, in m:
self.rs = 0.1
self.rk = 0.0
self.rr = -0.9
# Distance of the CoE from the rotational point (i.e.,
# 0 would be a rudder that required no force to turn)
self.ls = 0.25
self.lr = 0.0
rhowater = 1000.0 # Density of water, kg / m^3
rhoair = 1.225 # Density of air, kg / m^3
As = 2.0 # Sail Area, m^2
Ak = .3 # Keel Area, m^2
Ar = .04 # Rudder Area, m^2
self.sail = Airfoil(As, rhoair, 5.0, 1.4)
self.keel = Airfoil(Ak, rhowater, 8.0, 1.4)
self.rudder = Airfoil(Ar, rhowater, 4.0, 1.7)
self.Blon = 15.0 # Damping term, N / (m / s)
self.Blat = 25.0 # Lateral damping term, bigger b/c hull long/thin)
# self.Bv = 10.0
self.Bomega = 500 # Damping term, N * m / (rad / sec)
self.hb = -1.0 # Height of CoM of boat ballast, m
self.wb = 14.0 * 9.8 # Weight of boat ballast, N
self.J = 10.0 # Boat Moment of Inertia about yaw, kg * m^2
self.m = 25.0 # Boat mass, kg
def SailForces(self, thetaw, vw, deltas):
"""
Calculates and returns forces from the sail.
Arguments:
thetaw: Wind, 0 = running downwind, +pi / 2 = wind from port
vw: Wind speed, m / s
deltas: Sail angle, 0 = all in, +pi / 2 = sail on starboard
heel: Boat heel, 0 = upright
Returns:
Fs: Magnitude of force from sail (N)
gammas: Angle of force from sail (rad, 0 = forwards, +pi / 2 = pushing to port)
deltaFs: Derivative of Fs w.r.t. deltas
deltagamma: Derivative of gamma w.r.t. deltas
"""
alphas = -Norm(thetaw + deltas + np.pi)
atanC, deltaatan = self.sail.atanClCd(alphas)
Fs, deltaFs = self.sail.F(alphas, vw)
#Fs = Fs if abs(alphas) > 0.08 else 0.0
gammas = Norm(atanC - thetaw)
deltaFs = deltaFs * -1.0 # -1 = dalpha / ddeltas
deltagamma = deltaatan * -1.0 # -1 = dalpha / ddeltas
return Fs, gammas, deltaFs, deltagamma
def KeelForces(self, thetac, vc):
"""
Calculates and returns forces from the sail.
Arguments:
thetac: Current, 0 = Boat going straight, +pi / 2 = Boat drifting to starboard
vc: Speed in water, m / s
heel: Boat heel, 0 = upright
Returns:
Fk: Magnitude of force from keel (N)
gammak: Angle of force from keel (rad, 0 = forwards, +pi / 2 = pushing to port)
"""
alphak = -Norm(thetac)
atanC, _ = self.keel.atanClCd(alphak)
atanC = (np.pi / 2.0 - 0.05) * np.sign(alphak)
Fk, deltaFk = self.keel.F(alphak, vc)
gammak = Norm(atanC - thetac + np.pi)
return Fk, gammak
def RudderForces(self, thetac, vc, deltar):
"""
Calculates and returns forces from the sail.
Arguments:
thetac: Current, 0 = Boat going straight, +pi / 2 = Boat drifting to starboard
vc: Speed in water, m / s
deltar: Rudder angle, 0 = straight, + pi / 2 = rudder on starboard
heel: Boat heel, 0 = upright
Returns:
Fr: Magnitude of force from rudder (N)
gammar: Angle of force from rudder (rad, 0 = forwards, +pi / 2 = pushing to port)
deltaFr: dFr / ddeltar
deltagamma: dgammar / ddeltar
"""
alphar = -Norm(thetac + deltar)
alphar = np.clip(alphar, -.25, .25)
atanC = (np.pi / 2.0 - 0.05) * Sign(alphar)
Fr = 0.5 * self.rudder.A * self.rudder.rho * vc ** 2 * 5.0 * abs(alphar)
gammar = Norm(atanC - thetac + np.pi)
deltaFr = 0.5 * self.rudder.A * self.rudder.rho * vc ** 2 * 5.0 * -Sign(alphar)
deltagamma = 0.0
return Fr, gammar, deltaFr, deltagamma
def SailTorque(self, Fs, gammas, deltas, heel, deltaFs,
deltagammas, deltaheel):
"""
Calculate yaw torque from sail, using output from SailForces
Returns the torque and the derivative of the torque
w.r.t. deltas.
"""
sheel = np.sin(heel)
cheel = np.cos(heel)
cdeltas = np.cos(deltas)
sdeltas = np.sin(deltas)
return Fs * ((self.rs - self.ls * cdeltas) * np.sin(gammas) * cheel
+ self.hk * np.cos(gammas) * sheel), 0.0
r = np.sqrt((self.rs - self.ls * cdeltas) ** 2 + (self.hs * sheel) ** 2)
drds = ((self.rs - self.ls * cdeltas) * (self.ls * sdeltas) \
+ (self.hs * sheel) * (self.hs * cheel) * deltaheel) \
/ r
atany = -self.hs * sheel
atanx = self.rs - self.ls * cdeltas
theta = gammas - np.arctan2(atany, atanx)
stheta = np.sin(theta)
dsthetads = np.cos(theta) * \
(deltagammas -
(atanx * (-self.hs * cheel * deltaheel) -
atany * (self.ls * cdeltas))
/ (atanx ** 2 + atany ** 2))
dcheelds = -sheel * deltaheel
tau = r * Fs * stheta * cheel
dtauds = r * Fs * stheta * dcheelds \
+ r * Fs * dsthetads * cheel \
+ r * deltaFs * stheta * cheel \
+ drds * Fs * stheta * cheel
return tau, dtauds
def KeelTorque(self, Fk, gammak, heel):
"""
Calculate yaw torque from keel, using output from KeelForces
"""
return Fk * (self.rk * np.sin(gammak) * np.cos(heel)
+ self.hk * np.cos(gammak) * np.sin(heel))
r = np.sqrt(self.rk ** 2 + (self.hk * np.sin(heel)) ** 2)
theta = gammak - np.arctan2(-self.hk * np.sin(heel), self.rk)
return r * Fk * np.sin(theta) * np.cos(heel)
def RudderTorque(self, Fr, gammar, heel, deltaFr, deltaheel):
"""
Calculate yaw torque from rudder, using output from RudderForces
Assumes self.hr is negligible.
"""
tau = self.rr * Fr * np.sin(gammar) * np.cos(heel)
dtaudr = self.rr * np.cos(heel) * deltaFr * np.sin(gammar)
dtauds = -self.rr * Fr * np.sin(gammar) * np.sin(heel) * deltaheel
dtauds = 0.0 # Not sure if above dtauds is still good.
return tau, dtaudr, dtauds
def ApproxHeel(self, Fs, gammas, Fk, gammak, deltaFs, deltagammas):
"""
Returns equilibrium heel angle for a given Fs, Fk,
as well as the derivative of the heel with respect
to deltas
"""
tanheel = (Fs * self.hs * np.sin(gammas) + Fk * self.hk * np.sin(gammak)) / (self.hb * self.wb)
heel = np.arctan(tanheel)
dheel = self.hs * (deltaFs * np.sin(gammas) + Fs * np.cos(gammas) * deltagammas) \
/ ((1.0 + tanheel ** 2) * self.hb * self.wb)
return heel, dheel
def NetForce(self, thetaw, vw, thetac, vc, deltas, deltar, heel, omega, debugf=None):
"""
Sum up all the forces and return net longitudinal and lateral forces, and net torque
Arguments:
thetaw: Wind dir
vw: wind speed
thetac: Water dir
vc: Water speed
deltas: sail angle
deltar: rudder angle
heel: Duh.
omega: boat rotational velocity, rad / s
debugf: DebugForces instance for... debugging
Returns: Flon, Flat, taunet, newheel
"""
Fs, gammas, dFsds, dgsds= self.SailForces(thetaw, vw, deltas)
Fk, gammak = self.KeelForces(thetac, vc)
heel, dheelds = self.ApproxHeel(Fs, gammas, Fk, gammak, dFsds, dgsds)
Fr, gammar, dFrdr, dgrdr = self.RudderForces(thetac, vc, deltar)
taus, dtausds = self.SailTorque(Fs, gammas, deltas, heel, dFsds, dgsds, dheelds)
tauk = self.KeelTorque(Fk, gammak, heel)
taur, dtaurdr, dtaurds = self.RudderTorque(Fr, gammar, heel, dFrdr, dheelds)
tauB = -self.Bomega * omega * abs(omega)
FBlon = -self.Blon * vc * abs(vc) * np.cos(thetac)
FBlat = self.Blat * vc * np.sin(thetac)
Flon = Fs * np.cos(gammas) + Fk * np.cos(gammak) + Fr * np.cos(gammar) + FBlon
Flat = (Fs * np.sin(gammas) + Fk * np.sin(gammak) + Fr * np.sin(gammar)) * np.cos(heel) + FBlat
taunet = taus + tauk + taur + tauB
newheel, _ = self.ApproxHeel(Fs, gammas, Fk, gammak, 0, 0)
#print("Flon: ", Flon, " Flat: ", Flat, " Blon: ", -self.Blon * vc * np.cos(thetac),
# " Fs ", Fs, " gammas ", gammas, " Fk ", Fk, " gammak ", gammak, " Fr ", Fr,
# " gammar ", gammar)
#print("taunet ", taunet, " taus ", taus, " tauk ", tauk, " taur ", taur, " Btau",
# -self.Bomega * omega)
if debugf != None:
debugf.Update(taunet, Flon, Flat, Fs, Fk, Fr, gammas,
gammak, gammar, FBlon, FBlat, taus, tauk, taur, tauB)
return Flon, Flat, taunet, newheel
def Yadaptive(self, thetaw, vw, thetac, vc, yaw, omega, deltas, deltar):
"""
Using: u = {F_lon, tau_net}
beta = {Blon, Bomega, Ar, rs, taubias, 1}
"""
YFlonBlon = -vc * abs(vc) * np.cos(thetac)
Fr, gammar, _, _ = self.RudderForces(thetac, vc, deltar)
YFlonAr = Fr * np.cos(gammar) / self.rudder.A
Fs, gammas, _, _= self.SailForces(thetaw, vw, deltas)
Fk, gammak = self.KeelForces(thetac, vc)
YFlonconst = Fs * np.cos(gammas) + Fk * np.cos(gammak)
YFlon = np.matrix([[YFlonBlon, 0.0, YFlonAr, 0.0, 0.0, YFlonconst]])
heel, _ = self.ApproxHeel(Fs, gammas, Fk, gammak, 0.0, 0.0)
taur, _, _ = self.RudderTorque(Fr, gammar, heel, 0.0, 0.0)
tauk = self.KeelTorque(Fk, gammak, heel)
taus, _ = self.SailTorque(Fs, gammas, deltas, heel, 0.0, 0.0, 0.0)
YtauBomega = -omega * abs(omega)
YtauAr = taur / self.rudder.A
Ytaurs = Fs * np.sin(gammas) * np.cos(heel)
Ytauconst = tauk + (taus - Ytaurs * self.rs)
Ytau = np.matrix([[0.0, YtauBomega, YtauAr, Ytaurs, 1.0, Ytauconst]])
#print("Ytau: ", Ytau)
#print("YFlon: ", YFlon)
return np.concatenate((YFlon, Ytau), axis=0)
def Update(self, truewx, truewy, x, y, vx, vy, yaw, omega, deltas, deltar,
heel, dt, flopsail=False, debugf=None):
thetac = -Norm(np.arctan2(vy, vx) - yaw)
vc = np.sqrt(vx ** 2 + vy ** 2)
appwx = truewx - vx
appwy = truewy - vy
thetaw = Norm(-np.arctan2(appwy, appwx) + yaw)
vw = np.sqrt(appwx ** 2 + appwy ** 2) * 1.6 # For wind gradient
if flopsail:
deltas = abs(deltas) if thetaw > 0 else -abs(deltas)
#print("thetac ", thetac, " vc ", vc, " thetaw ", thetaw, " vw ", vw)
Flon, Flat, tau, newheel = self.NetForce(
thetaw, vw, thetac, vc, deltas, deltar, heel, omega, debugf)
if False:
# For approximating damping force, with overall force as input,
# state as [pos, vel]
Ac = np.matrix([[0.0, 1.0],
[0.0, -self.Bv / self.m]])
Bc = np.matrix([[0.0], [1.0 / self.m]])
(Ad, Bd, _, _, _) = scipy.signal.cont2discrete((Ac, Bc, Ac, Bc), dt)
statex = np.matrix([[x], [vx]])
forcex = Flon * np.cos(yaw) - Flat * | np.sin(yaw) | numpy.sin |
import os
import cv2
import pdb
import json
import shutil
import numpy as np
import pandas as pd
import random
from tqdm import tqdm
import argparse
from pycocotools import mask
from pycocotools.coco import COCO
from skimage import measure
try:
import moxing as mox
mox.file.shift('os', 'mox')
except:
pass
WIDTH = 50
COCO_CLASS_NAMES_ID_DIC = {
'person': '1', 'bicycle': '2', 'car': '3', 'motorcycle': '4', 'airplane': '5', 'bus': '6', 'train': '7', 'truck': '8', 'boat': '9', 'traffic light': '10',
'fire hydrant': '11', 'stop sign': '13', 'parking meter': '14', 'bench': '15', 'bird': '16', 'cat': '17', 'dog': '18', 'horse': '19', 'sheep': '20', 'cow': '21',
'elephant': '22', 'bear': '23', 'zebra': '24', 'giraffe': '25', 'backpack': '27', 'umbrella': '28', 'handbag': '31', 'tie': '32', 'suitcase': '33', 'frisbee': '34',
'skis': '35', 'snowboard': '36', 'sports ball': '37', 'kite': '38', 'baseball bat': '39', 'baseball glove': '40', 'skateboard': '41', 'surfboard': '42', 'tennis racket': '43', 'bottle': '44',
'wine glass': '46', 'cup': '47', 'fork': '48', 'knife': '49', 'spoon': '50', 'bowl': '51', 'banana': '52', 'apple': '53', 'sandwich': '54', 'orange': '55',
'broccoli': '56', 'carrot': '57', 'hot dog': '58', 'pizza': '59', 'donut': '60', 'cake': '61', 'chair': '62', 'couch': '63', 'potted plant': '64', 'bed': '65',
'dining table': '67', 'toilet': '70', 'tv': '72', 'laptop': '73', 'mouse': '74', 'remote': '75', 'keyboard': '76', 'cell phone': '77', 'microwave': '78', 'oven': '79',
'toaster': '80', 'sink': '81', 'refrigerator': '82', 'book': '84', 'clock': '85', 'vase': '86', 'scissors': '87', 'teddy bear': '88', 'hair drier': '89', 'toothbrush': '90'
}
COCO_OPENIMAGE_RELATED_CLASSES_NAME_DIC = {
'person': ['Person'], 'bicycle': ['Stationary bicycle', 'Bicycle'], 'car': ['Car', 'Limousine', 'Van', 'Vehicle', 'Land vehicle', 'Ambulance', 'Cart', 'Golf cart'], 'motorcycle': ['Motorcycle'], 'airplane': ['Airplane'], 'bus': ['Bus'], 'train': ['Train'], 'truck': ['Truck'], 'boat': ['Boat', 'Barge', 'Gondola', 'Canoe', 'Jet ski', 'Submarine'], 'traffic light': ['Traffic light'],
'fire hydrant': ['Fire hydrant'], 'stop sign': ['Stop sign'], 'parking meter': ['Parking meter'], 'bench': ['Bench'], 'bird': ['Magpie', 'Woodpecker', 'Blue jay', 'Ostrich', 'Penguin', 'Raven', 'Chicken', 'Eagle', 'Owl', 'Duck', 'Canary', 'Goose', 'Swan', 'Falcon', 'Parrot', 'Sparrow', 'Turkey'], 'cat': ['Cat'], 'dog': ['Dog'], 'horse': ['Horse'], 'sheep': ['Sheep'], 'cow': ['Cattle', 'Bull'],
'elephant': ['Elephant'], 'bear': ['Bear', 'Brown bear', 'Panda', 'Polar bear'], 'zebra': ['Zebra'], 'giraffe': ['Giraffe'], 'backpack': ['Backpack'], 'umbrella': ['Umbrella'], 'handbag': ['Handbag'], 'tie': ['Tie'], 'suitcase': ['Suitcase'], 'frisbee': ['Flying disc'],
'skis': ['Ski'], 'snowboard': ['Snowboard'], 'sports ball': ['Ball', 'Football', 'Cricket ball', 'Volleyball', 'Tennis ball', 'Rugby ball', 'Golf ball'], 'kite': ['Kite'], 'baseball bat': ['Baseball bat'], 'baseball glove': ['Baseball glove'], 'skateboard': ['Skateboard'], 'surfboard': ['Surfboard'], 'tennis racket': ['Tennis racket'], 'bottle': ['Bottle'],
'wine glass': ['Wine glass'], 'cup': ['Coffee cup', 'Measuring cup'], 'fork': ['Fork'], 'knife': ['Kitchen knife', 'Knife'], 'spoon': ['Spoon'], 'bowl': ['Mixing bowl', 'Bowl'], 'banana': ['Banana'], 'apple': ['Apple'], 'sandwich': ['Sandwich', 'Hamburger', 'Submarine sandwich'], 'orange': ['Orange'],
'broccoli': ['Broccoli'], 'carrot': ['Carrot'], 'hot dog': ['Hot dog'], 'pizza': ['Pizza'], 'donut': ['Doughnut'], 'cake': ['Cake'], 'chair': ['WheelChair', 'Chair'], 'couch': ['Couch', 'Sofa bed', 'Loveseat', 'studio couch'], 'potted plant': ['Houseplant'], 'bed': ['Bed', 'Infant bed'],
'dining table': ['Table', 'Coffee table', 'Kitchen & dining room table'], 'toilet': ['Toilet'], 'tv': ['Television'], 'laptop': ['Laptop'], 'mouse': ['Computer mouse'], 'remote': ['Remote control'], 'keyboard': ['Computer keyboard'], 'cell phone': ['Mobile phone'], 'microwave': ['Microwave oven'], 'oven': ['Oven'],
'toaster': ['Toaster'], 'sink': ['Sink'], 'refrigerator': ['Refrigerator'], 'book': ['Book'], 'clock': ['Clock', 'Alarm clock', 'Digital clock', 'Wall clock'], 'vase': ['Vase'], 'scissors': ['Scissors'], 'teddy bear': ['Teddy bear'], 'hair drier': ['Hair dryer'], 'toothbrush': ['Toothbrush']
}
COCO_OPENIMAGE_RELATED_CLASSES_DIC = {
'person': ['/m/01g317'], 'bicycle': ['/m/03kt2w', '/m/0199g'], 'car': ['/m/0k4j', '/m/01lcw4', '/m/0h2r6', '/m/07yv9', '/m/01prls', '/m/012n7d', '/m/018p4k', '/m/0323sq'], 'motorcycle': ['/m/04_sv'], 'airplane': ['/m/0cmf2'], 'bus': ['/m/01bjv'], 'train': ['/m/07jdr'], 'truck': ['/m/07r04'], 'boat': ['/m/019jd', '/m/01btn', '/m/02068x', '/m/0ph39', '/m/01xs3r', '/m/074d1'], 'traffic light': ['/m/015qff'],
'fire hydrant': ['/m/01pns0'], 'stop sign': ['/m/02pv19'], 'parking meter': ['/m/015qbp'], 'bench': ['/m/0cvnqh'], 'bird': ['/m/012074', '/m/01dy8n', '/m/01f8m5', '/m/05n4y', '/m/05z6w', '/m/06j2d', '/m/09b5t', '/m/09csl', '/m/09d5_', '/m/09ddx', '/m/0ccs93', '/m/0dbvp', '/m/0dftk', '/m/0f6wt', '/m/0gv1x', '/m/0h23m', '/m/0jly1'], 'cat': ['/m/01yrx'], 'dog': ['/m/0bt9lr'], 'horse': ['/m/03k3r'], 'sheep': ['/m/07bgp'], 'cow': ['/m/01xq0k1', '/m/0cnyhnx'],
'elephant': ['/m/0bwd_0j'], 'bear': ['/m/01dws', '/m/01dxs', '/m/03bj1', '/m/0633h'], 'zebra': ['/m/0898b'], 'giraffe': ['/m/03bk1'], 'backpack': ['/m/01940j'], 'umbrella': ['/m/0hnnb'], 'handbag': ['/m/080hkjn'], 'tie': ['/m/01rkbr'], 'suitcase': ['/m/01s55n'], 'frisbee': ['/m/02wmf'],
'skis': ['/m/071p9'], 'snowboard': ['/m/06__v'], 'sports ball': ['/m/018xm', '/m/01226z', '/m/02ctlc', '/m/05ctyq', '/m/0wdt60w', '/m/044r5d'], 'kite': ['/m/02zt3'], 'baseball bat': ['/m/03g8mr'], 'baseball glove': ['/m/03grzl'], 'skateboard': ['/m/06_fw'], 'surfboard': ['/m/019w40'], 'tennis racket': ['/m/0h8my_4'], 'bottle': ['/m/04dr76w'],
'wine glass': ['/m/09tvcd'], 'cup': ['/m/02p5f1q', '/m/07v9_z'], 'fork': ['/m/0dt3t'], 'knife': ['/m/058qzx', '/m/04ctx'], 'spoon': ['/m/0cmx8'], 'bowl': ['/m/03hj559', '/m/04kkgm'], 'banana': ['/m/09qck'], 'apple': ['/m/014j1m'], 'sandwich': ['/m/0l515', '/m/0cdn1', '/m/06pcq'], 'orange': ['/m/0cyhj_'],
'broccoli': ['/m/0hkxq'], 'carrot': ['/m/0fj52s'], 'hot dog': ['/m/01b9xk'], 'pizza': ['/m/0663v'], 'donut': ['/m/0jy4k'], 'cake': ['/m/0fszt'], 'chair': ['/m/01mzpv'], 'couch': ['/m/02crq1', '/m/03m3pdh', '/m/0703r8'], 'potted plant': ['/m/03fp41'], 'bed': ['/m/03ssj5', '/m/061hd_'],
'dining table': ['/m/04bcr3', '/m/078n6m', '/m/0h8n5zk'], 'toilet': ['/m/09g1w'], 'tv': ['/m/07c52'], 'laptop': ['/m/01c648'], 'mouse': ['/m/020lf'], 'remote': ['/m/0qjjc'], 'keyboard': ['/m/01m2v'], 'cell phone': ['/m/050k8'], 'microwave': ['/m/0fx9l'], 'oven': ['/m/029bxz'],
'toaster': ['/m/01k6s3'], 'sink': ['/m/0130jx'], 'refrigerator': ['/m/040b_t'], 'book': ['/m/0bt_c3'], 'clock': ['/m/01x3z', '/m/046dlr', '/m/06_72j', '/m/0h8mzrc'], 'vase': ['/m/02s195'], 'scissors': ['/m/01lsmm'], 'teddy bear': ['/m/0kmg4'], 'hair drier': ['/m/03wvsk'], 'toothbrush': ['/m/012xff']
}
def convert_dic(dic):
new_dic = dict()
for k, v in dic.items():
for _v in v:
if type(_v) == str:
new_dic[_v] = k
elif type(_v) == tuple:
new_dic[_v[0]] = k
return new_dic
COCO_OPENIMAGE_RELATED_CLASSES_DIC_CONVERT = convert_dic(COCO_OPENIMAGE_RELATED_CLASSES_DIC)
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('--im_root', type=str, required=True)
parser.add_argument('--seg_im_root', type=str, required=True)
parser.add_argument('--op_bbox_anno', type=str, default=None)
parser.add_argument('--op_segm_anno', type=str, default=None)
parser.add_argument('--op_cls_info', type=str, default=None, required=True)
parser.add_argument('--which_set', type=str, default='train', choices=['train', 'test', 'val', 'all'])
parser.add_argument('--not_conv_cls', default=False, action='store_true')
args = parser.parse_args()
return args
class OpenImage2COCO(object):
def __init__(self,
image_root=None,
segm_image_root=None,
openimage_bbox_file=None,
openimage_seg_file=None,
openimage_cls_info_file=None,
which_set='val',
convert_cls_into_coco=True):
if 'train' in which_set:
filling_info = 'training'
elif 'val' in which_set:
filling_info = 'validation'
elif 'test' in which_set:
filling_info = 'testing'
else:
exit()
self.info = {
'description': 'This is the {} set of Open Images V5.'.format(filling_info),
'url' : 'https://storage.googleapis.com/openimages/web/index.html',
'version': '1.0',
'year': 2019,
'contributor': 'Google',
'date_created': '2019-07-30'
}
self.which_set = which_set
self.image_root = image_root
self.segm_image_root = segm_image_root
self.openimage_bbox_file = openimage_bbox_file
self.openimage_seg_file = openimage_seg_file
self.openimage_cls_info_file = openimage_cls_info_file
self.convert_cls_into_coco = convert_cls_into_coco
self.cls_id = 0
self.cls_dic = dict()
self.cls_id_dic = dict()
cls_info = self.__read_csv(openimage_cls_info_file)
for ci in cls_info:
if convert_cls_into_coco:
if ci[0] in COCO_OPENIMAGE_RELATED_CLASSES_DIC_CONVERT:
self.cls_dic.update({ci[0]: ci[1]})
self.cls_id_dic.update({ci[0]: COCO_CLASS_NAMES_ID_DIC[COCO_OPENIMAGE_RELATED_CLASSES_DIC_CONVERT[ci[0]]]})
self.cls_id += 1
else:
self.cls_dic.update({ci[0]: ci[1]})
self.cls_id_dic.update({ci[0]: self.cls_id})
self.cls_id += 1
@staticmethod
def __read_csv(name, to_start=0):
return pd.read_csv(name, header=None, low_memory=False).values[to_start: ]
def convert_bbox(self, save_path):
self.save_path = save_path
image_id = 0
box_id = 0
images_dic = dict()
image_info = list()
annos = list()
categories = list()
print('=' * 100)
print('Reading bbox file...')
bbox_annos = self.__read_csv(self.openimage_bbox_file, 1)
print('Counting images...')
counted_annos = list()
for ba in tqdm(bbox_annos, ncols=WIDTH):
# name_key: ImageID
name_key = ba[0]
cls_id = ba[2]
if self.convert_cls_into_coco:
if cls_id in COCO_OPENIMAGE_RELATED_CLASSES_DIC_CONVERT:
counted_annos.append(ba)
if not name_key in images_dic:
images_dic.update({name_key: image_id})
image_id += 1
else:
counted_annos.append(ba)
if not name_key in images_dic:
# ImageID <==> image_id
images_dic.update({name_key: image_id})
image_id += 1
print('Getting image infos...')
name_key_height_width_dic = dict()
for name_key in tqdm(images_dic, ncols=WIDTH):
im = cv2.imread(os.path.join(self.image_root, self.which_set, name_key + '.jpg'))
height, width = im.shape[ :2]
if name_key not in name_key_height_width_dic:
name_key_height_width_dic[name_key] = (height, width)
image = {
'file_name': name_key + '.jpg',
'height': height,
'width': width,
'id': images_dic[name_key]
}
image_info.append(image)
print('Writing annotations...')
for ba in tqdm(counted_annos, ncols=WIDTH):
name_key = ba[0]
height, width = name_key_height_width_dic[name_key]
bbox = [
float(ba[4]) * width,
float(ba[6]) * height,
(float(ba[5]) - float(ba[4])) * width,
(float(ba[7]) - float(ba[6])) * height
]
IsOccluded = int(ba[8])
IsTruncated = int(ba[9])
IsGroupOf = int(ba[10])
IsDepiction = int(ba[11])
IsInside = int(ba[12])
LabelName = ba[2]
if LabelName in self.cls_id_dic:
anno = {
'bbox': bbox,
'area': bbox[2] * bbox[3],
'image_id': images_dic[name_key],
'category_id': self.cls_id_dic[LabelName],
'iscrowd': 0, # ??? == isGroupOf?
'id': int(box_id),
'IsOccluded': IsOccluded,
'IsTruncated': IsTruncated,
'IsGroupOf': IsGroupOf,
'IsDepiction': IsDepiction,
'IsInside': IsInside
}
annos.append(anno)
box_id += 1
if self.convert_cls_into_coco:
for k, v in COCO_CLASS_NAMES_ID_DIC.items():
category = {
'supercategory': k,
'id': v,
'name': k
}
categories.append(category)
else:
for cat in self.cls_dic:
category = {
'supercategory': self.cls_dic[cat],
'id': self.cls_id_dic[cat],
'name': self.cls_dic[cat]
}
categories.append(category)
inputfile = {
'info': self.info,
'images': image_info,
'type': 'instances',
'annotations': annos,
'categories': categories
}
print('Writing into JSON...')
with open(save_path, 'w', encoding='utf8') as f:
json.dump(inputfile,f)
print('=' * 100)
def visualize_bbox(self, sample_num=10, r_seed=3, g_seed=7, b_seed=19, save_path=None):
if save_path:
with open(save_path, 'r', encoding='utf8') as f:
coco_format_file = json.load(f)
else:
with open(self.save_path, 'r', encoding='utf8') as f:
coco_format_file = json.load(f)
selected_images = random.choices(coco_format_file['images'], k=sample_num)
for si in selected_images:
im = cv2.imread(os.path.join(self.image_root, self.which_set, si['file_name']))
for a in coco_format_file['annotations']:
# print(a['image_id'], si['id'])
if a['image_id'] == si['id']:
x, y, w, h = list(map(round, a['bbox']))
cate_id = int(a['category_id'])
color = ((r_seed * cate_id) % 255, (g_seed * cate_id) % 255, (b_seed * cate_id) % 255)
cv2.rectangle(im, (x, y), (x + w, y + h), color, 2)
cls_name = self.cls_dic[[x[0] for x in self.cls_id_dic.items() if x[1] == a['category_id']][0]]
if self.convert_cls_into_coco:
cls_name = convert_dic(COCO_OPENIMAGE_RELATED_CLASSES_NAME_DIC)[cls_name]
cv2.putText(im, cls_name, (x, y), cv2.FONT_HERSHEY_COMPLEX, 1, color=color, thickness=1)
cv2.imshow(si['file_name'], im)
cv2.waitKey(0)
cv2.destroyAllWindows()
def convert_segmentation(self, save_path):
self.seg_save_path = save_path
image_id = 0
box_id = 0
images_dic = dict()
image_info = list()
annos = list()
categories = list()
print('=' * 100)
print('Reading segm file...')
bbox_annos = self.__read_csv(self.openimage_seg_file, 1)
print('Counting images...')
counted_annos = list()
for ba in tqdm(bbox_annos, ncols=WIDTH):
# name_key: ImageID
name_key = ba[1]
cls_id = ba[2]
if self.convert_cls_into_coco:
if cls_id in COCO_OPENIMAGE_RELATED_CLASSES_DIC_CONVERT:
counted_annos.append(ba)
if not name_key in images_dic:
images_dic.update({name_key: image_id})
image_id += 1
else:
counted_annos.append(ba)
if not name_key in images_dic:
# ImageID <==> image_id
images_dic.update({name_key: image_id})
image_id += 1
print('Getting image infos...')
name_key_height_width_dic = dict()
for name_key in tqdm(images_dic, ncols=WIDTH):
im = cv2.imread(os.path.join(self.image_root, self.which_set, name_key + '.jpg'))
height, width = im.shape[ :2]
if name_key not in name_key_height_width_dic:
name_key_height_width_dic[name_key] = (height, width)
image = {
'file_name': name_key + '.jpg',
'height': height,
'width': width,
'id': images_dic[name_key]
}
image_info.append(image)
print('Writing annotations...')
for ba in tqdm(counted_annos, ncols=WIDTH):
mask_key = ba[0]
mask_img = cv2.imread(os.path.join(self.segm_image_root, self.which_set, mask_key), 0)
name_key = ba[1]
height, width = name_key_height_width_dic[name_key]
mask_img = cv2.resize(mask_img, (width, height))
mask_img[0,: ] = 0
mask_img[-1,: ] = 0
mask_img[:, 0] = 0
mask_img[:, -1] = 0
fortran_ground_truth_binary_mask = np.asfortranarray(mask_img)
encoded_ground_truth = mask.encode(fortran_ground_truth_binary_mask)
ground_truth_area = mask.area(encoded_ground_truth)
contours = measure.find_contours(mask_img, 0.5)
bbox = [
float(ba[4]) * width,
float(ba[6]) * height,
(float(ba[5]) - float(ba[4])) * width,
(float(ba[7]) - float(ba[6])) * height
]
LabelName = ba[2]
if LabelName in self.cls_id_dic:
anno = {
'bbox': bbox,
'area': ground_truth_area.tolist(),
'image_id': images_dic[name_key],
'category_id': self.cls_id_dic[LabelName],
'iscrowd': 0,
'id': int(box_id),
'segmentation': []
}
for contour in contours:
contour = np.flip(contour, axis=1)
segmentation = contour.ravel().tolist()
anno["segmentation"].append(segmentation)
annos.append(anno)
box_id += 1
if self.convert_cls_into_coco:
for k, v in COCO_CLASS_NAMES_ID_DIC.items():
category = {
'supercategory': k,
'id': v,
'name': k
}
categories.append(category)
else:
for cat in self.cls_dic:
category = {
'supercategory': self.cls_dic[cat],
'id': self.cls_id_dic[cat],
'name': self.cls_dic[cat]
}
categories.append(category)
inputfile = {
'info': self.info,
'images': image_info,
'type': 'instances',
'annotations': annos,
'categories': categories
}
print('Writing into JSON...')
with open(save_path, 'w', encoding='utf8') as f:
json.dump(inputfile,f)
print('=' * 100)
def visualize_segmentation(self, sample_num=10, r_seed=3, g_seed=7, b_seed=19, save_path=None):
coco = COCO(save_path if save_path else self.seg_save_path)
selected_images = random.choices(coco.loadImgs(coco.getImgIds()), k=sample_num)
for si in selected_images:
img_id = si['id']
annos = coco.loadAnns(coco.getAnnIds(imgIds=img_id))
for a in annos:
im = cv2.imread(os.path.join(self.image_root, self.which_set, si['file_name']))
mask_img = coco.annToMask(a)
im = im * | np.stack([mask_img] * 3, axis=-1) | numpy.stack |
from math import sin
import numpy as np
import sympy as sp
from .dynamic_model import DynamicModelBase
from utils.Logger import logger
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import matplotlib as mpl
import math
class QuadCopter(DynamicModelBase):
def __init__(self, is_with_constraints = True, T = 100):
##### Dynamic Function ########
n, m = 12, 4 # number of state = 12, number of action = 4, prediction horizon = 100
h_constant = 0.02 # sampling time
x_u_var = sp.symbols('x_u:16')
ueq = 1.962
# p_x p_y p_z
# v_x v_y v_z
# phi(6) theta(7) psi(8)
# omega_x omega_y omega_z
# f1 f2 f3 f4
Jx = 0.0244
Jy = 0.0244
Jz = 0.0436
mass = 0.8
g_constant = 9.81
L_constant = 0.165 # m
c_constant = 0.002167 # m
cos_phi = sp.cos(x_u_var[6])
sin_phi = sp.sin(x_u_var[6])
cos_theta = sp.cos(x_u_var[7])
sin_theta = sp.sin(x_u_var[7])
cos_psi = sp.cos(x_u_var[8])
sin_psi = sp.sin(x_u_var[8])
e_constant = np.asarray([0,0,1]).reshape(-1,1)
R_matrix = sp.Matrix([[cos_theta*cos_psi, cos_theta*sin_psi, -sin_theta],
[sin_phi*sin_theta*cos_psi-cos_phi*sin_psi, sin_phi*sin_theta*sin_psi+cos_phi*cos_psi, sin_phi*cos_theta],
[cos_phi*sin_theta*cos_psi+sin_phi*sin_psi, cos_phi*sin_theta*sin_psi-sin_phi*cos_psi, cos_phi*cos_theta]])
W_matrix = sp.Matrix([[1.0, sin_phi*sin_theta/cos_theta, cos_phi*sin_theta/cos_theta],
[0.0, cos_phi, -sin_phi],
[0.0, sin_phi/cos_theta, cos_phi/cos_theta]])
J_matrix = np.diag([Jx, Jy, Jz])
pos = sp.Matrix([[x_u_var[0]], [x_u_var[1]], [x_u_var[2]]])
vel = sp.Matrix([[x_u_var[3]], [x_u_var[4]], [x_u_var[5]]])
ang = sp.Matrix([[x_u_var[6]], [x_u_var[7]], [x_u_var[8]]])
ang_vel = sp.Matrix([[x_u_var[9]], [x_u_var[10]], [x_u_var[11]]])
# Dynamics params
pos_dot = R_matrix.T * vel
vel_dot = -ang_vel.cross(vel) + R_matrix @ (g_constant * e_constant)
ang_dot = W_matrix * ang_vel
angvel_dot = | np.linalg.inv(J_matrix) | numpy.linalg.inv |
"""
Copyright (C) 2018-2020 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
import numpy as np
from extensions.ops.split import AttributedSplit
from mo.back.replacement import BackReplacementPattern
from mo.front.common.partial_infer.utils import int64_array
from mo.graph.graph import Graph
class SplitNormalizer(BackReplacementPattern):
enabled = True
graph_condition = [lambda graph: not graph.graph['cmd_params'].generate_experimental_IR_V10]
def find_and_replace_pattern(self, graph: Graph):
for node in graph.get_op_nodes(op='Split'):
name = node.soft_get('name', node.id)
input_shape = node.in_port(0).data.get_shape()
assert input_shape is not None
axis = node.in_port(1).data.get_value()
assert axis is not None
num_splits = node.soft_get('num_splits', None)
assert num_splits is not None
if axis < 0:
axis += input_shape.size
split = AttributedSplit(graph, {'name': name, 'axis': axis, 'num_splits': num_splits}).create_node()
for idx, port in node.out_ports().items():
node.out_port(idx).get_connection().set_source(split.out_port(idx))
node.in_port(0).get_connection().set_destination(split.in_port(0))
graph.remove_node(node.id)
class VariadicSplitNormalizer(BackReplacementPattern):
enabled = True
graph_condition = [lambda graph: not graph.graph['cmd_params'].generate_experimental_IR_V10]
def find_and_replace_pattern(self, graph: Graph):
for node in graph.get_op_nodes(op='VariadicSplit'):
name = node.soft_get('name', node.id)
input_shape = node.in_port(0).data.get_shape()
assert input_shape is not None
axis = node.in_port(1).data.get_value()
assert axis is not None
size_splits = node.in_port(2).data.get_value()
assert size_splits is not None
connected_outputs = {idx: port for idx, port in node.out_ports().items() if not port.disconnected()}
assert len(size_splits) >= len(connected_outputs)
split_size = connected_outputs[list(connected_outputs.keys())[0]].data.get_shape()[axis]
if | np.unique(size_splits) | numpy.unique |
# Practice sites
#https://www.machinelearningplus.com/python/101-numpy-exercises-python/
#http://www.cs.umd.edu/~nayeem/courses/MSML605/files/04_Lec4_List_Numpy.pdf
#https://www.gormanalysis.com/blog/python-numpy-for-your-grandma/
#https://nickmccullum.com/advanced-python/numpy-indexing-assignment/
# 1. Import numpy as np and see the version
# Difficulty Level: L1
# Q. Import numpy as np and print the version number.
##? 1. Import numpy as np and see the version
# Difficulty Level: L1
# Q. Import numpy as np and print the version number.
import numpy as np
print(np.__version__)
##? 2. How to create a 1D array?
# Difficulty Level: L1
# Q. Create a 1D array of numbers from 0 to 9
arr = np.arange(10)
arr
##? 3. How to create a boolean array?
# Difficulty Level: L1
# Q. Create a 3×3 numpy array of all True’s
arr = np.full((3,3), True, dtype=bool)
arr
##? 4. How to extract items that satisfy a given condition from 1D array?
# Difficulty Level: L1
# Q. Extract all odd numbers from arr
arr = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
arr[arr % 2 == 1]
##? 5. How to replace items that satisfy a condition with another value in numpy array?
# Difficulty Level: L1
# Q. Replace all odd numbers in arr with -1
arr = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
arr[arr % 2 == 1] = -1
arr
##? 6. How to replace items that satisfy a condition without affecting the original array?
# Difficulty Level: L2
# Q. Replace all odd numbers in arr with -1 without changing arr
arr = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
#1 np.where
out = np.where(arr % 2 == 1, -1, arr)
out
#2 list comp
out = np.array([-1 if x % 2 == 1 else x for x in arr])
out
##? 7. How to reshape an array?
# Difficulty Level: L1
# Q. Convert a 1D array to a 2D array with 2 rows
arr = np.arange(10)
arr.reshape(2, -1)
# Setting y to -1 automatically decides number of columns.
# Could do the same with
arr.reshape(2, 5)
##? 8. How to stack two arrays vertically?
# Difficulty Level: L2
# Q. Stack arrays a and b vertically
a = np.arange(10).reshape(2, -1)
b = np.repeat(1, 10).reshape(2, -1)
#1
np.vstack([a, b])
#2
np.concatenate([a, b], axis=0)
#3
np.r_[a, b]
# 9. How to stack two arrays horizontally?
# Difficulty Level: L2
# Q. Stack the arrays a and b horizontally.
a = np.arange(10).reshape(2, -1)
b = np.repeat(1, 10).reshape(2, -1)
#1
np.hstack([a, b])
#2
np.concatenate([a, b], axis=1)
#3
np.c_[a, b]
##? 10. How to generate custom sequences in numpy without hardcoding?
# Difficulty Level: L2
# Q. Create the following pattern without hardcoding.
# Use only numpy functions and the below input array a.
a = np.array([1,2,3])
np.r_[np.repeat(a,3), np.tile(a, 3)]
##? 11. How to get the common items between two python numpy arrays?
# Difficulty Level: L2
# Q. Get the common items between a and b
a = np.array([1,2,3,2,3,4,3,4,5,6])
b = np.array([7,2,10,2,7,4,9,4,9,8])
np.intersect1d(a, b)
##? 12. How to remove from one array those items that exist in another?
# Difficulty Level: L2
# Q. From array a remove all items present in array b
a = np.array([1,2,3,4,5])
b = np.array([5,6,7,8,9])
# From 'a' remove all of 'b'
np.setdiff1d(a,b)
##? 13. How to get the positions where elements of two arrays match?
# Difficulty Level: L2
# Q. Get the positions where elements of a and b match
a = np.array([1,2,3,2,3,4,3,4,5,6])
b = np.array([7,2,10,2,7,4,9,4,9,8])
np.where(a==b)
# 14. How to extract all numbers between a given range from a numpy array?
# Difficulty Level: L2
# Q. Get all items between 5 and 10 from a.
a = np.array([2, 6, 1, 9, 10, 3, 27])
#1
idx = np.where((a>=5) & (a<=10))
a[idx]
#2
idx = np.where(np.logical_and(a >= 5, a <= 10))
a[idx]
#3
a[(a >= 5) & (a <= 10)]
##? 15. How to make a python function that handles scalars to work on numpy arrays?
# Difficulty Level: L2
# Q. Convert the function maxx that works on two scalars, to work on two arrays.
def maxx(x:np.array, y:np.array):
"""Get the maximum of two items"""
if x >= y:
return x
else:
return y
a = np.array([5, 7, 9, 8, 6, 4, 5])
b = np.array([6, 3, 4, 8, 9, 7, 1])
pair_max = np.vectorize(maxx, otypes=[float])
pair_max(a, b)
##? 16. How to swap two columns in a 2d numpy array?
# Difficulty Level: L2
# Q. Swap columns 1 and 2 in the array arr.
arr = np.arange(9).reshape(3,3)
arr
arr[:, [1, 0, 2]]
#by putting brackets inside the column slice. You have access to column indices
##? 17. How to swap two rows in a 2d numpy array?
# Difficulty Level: L2
# Q. Swap rows 1 and 2 in the array arr:
arr = np.arange(9).reshape(3,3)
arr
arr[[0, 2, 1], :]
#same goes here for the rows
##? 18. How to reverse the rows of a 2D array?
# Difficulty Level: L2
# Q. Reverse the rows of a 2D array arr.
# Input
arr = np.arange(9).reshape(3,3)
arr
arr[::-1, :]
#or
arr[::-1]
# 19. How to reverse the columns of a 2D array?
# Difficulty Level: L2
# Q. Reverse the columns of a 2D array arr.
# Input
arr = np.arange(9).reshape(3,3)
arr
arr[:,::-1]
##? 20. How to create a 2D array containing random floats between 5 and 10?
# Difficulty Level: L2
# Q. Create a 2D array of shape 5x3 to contain random decimal numbers between 5 and 10.
arr = np.arange(9).reshape(3,3)
#1
rand_arr = np.random.randint(low=5, high=10, size=(5,3)) + np.random.random((5,3))
rand_arr
#2
rand_arr = np.random.uniform(5, 10, size=(5,3))
rand_arr
##? 21. How to print only 3 decimal places in python numpy array?
# Difficulty Level: L1
# Q. Print or show only 3 decimal places of the numpy array rand_arr.
rand_arr = np.random.random((5,3))
rand_arr
rand_arr = np.random.random([5,3])
np.set_printoptions(precision=3)
rand_arr[:4]
##? 22. How to pretty print a numpy array by suppressing the scientific notation (like 1e10)?
# Difficulty Level: L1
# Q. Pretty print rand_arr by suppressing the scientific notation (like 1e10)
#Reset printoptions
np.set_printoptions(suppress=False)
# Create the random array
np.random.seed(100)
rand_arr = np.random.random([3,3])/1e3
rand_arr
#Set precision and suppress e notation
np.set_printoptions(suppress=True, precision=6)
rand_arr
##? 23. How to limit the number of items printed in output of numpy array?
# Difficulty Level: L1
# Q. Limit the number of items printed in python numpy array a to a maximum of 6 elements.
a = np.arange(15)
#set the elements to print in threshold
np.set_printoptions(threshold=6)
a
# reset the threshold to default
np.set_printoptions(threshold=1000)
##? 24. How to print the full numpy array without truncating
# Difficulty Level: L1
# Q. Print the full numpy array a without truncating.
a = np.arange(15)
# reset the threshold to default
np.set_printoptions(threshold=1000)
a
##? 25. How to import a dataset with numbers and texts keeping the text intact in python numpy?
# Difficulty Level: L2
# Q. Import the iris dataset keeping the text intact.
url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'
iris = np.genfromtxt(url, delimiter=',', dtype="object")
names = ('sepallength', 'sepalwidth', 'petallength', 'petalwidth', 'species')
iris[:3]
##? 26. How to extract a particular column from 1D array of tuples?
# Difficulty Level: L2
# Q. Extract the text column species from the 1D iris imported in previous question.
url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'
iris_1d = np.genfromtxt(url, delimiter=',', dtype=None, encoding = "UTF-8")
species = np.array([col[4] for col in iris_1d])
species[:5]
##? 27. How to convert a 1d array of tuples to a 2d numpy array?
# Difficulty Level: L2
# Q. Convert the 1D iris to 2D array iris_2d by omitting the species text field.
url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'
iris_1d = np.genfromtxt(url, delimiter=',', dtype=None, encoding = "UTF-8")
#1
no_species_2d = np.array([row.tolist()[:4] for row in iris_1d])
no_species_2d[:3]
#2
# Can directly specify columns to use with the "usecols" method
url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'
no_species_2d = np.genfromtxt(url, delimiter=',', dtype=None, encoding = "UTF-8", usecols=[0,1,2,3])
no_species_2d[:3]
##? 28. How to compute the mean, median, standard deviation of a numpy array?
# Difficulty: L1
# Q. Find the mean, median, standard deviation of iris's sepallength (1st column)
url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'
iris_1d = np.genfromtxt(url, delimiter=',', dtype=None, encoding="utf-8")
sepal = np.genfromtxt(url, delimiter=',', dtype=float, usecols=[0])
# or
sepal = np.array([col[0] for col in iris_1d])
# or
sepal = np.array([col.tolist()[0] for col in iris_1d])
mu, med, sd = np.mean(sepal), np.median(sepal), np.std(sepal)
np.set_printoptions(precision=2)
print(f'The mean is {mu} \nThe median is {med} \nThe standard deviation is {sd}')
##? 29. How to normalize an array so the values range exactly between 0 and 1?
# Difficulty: L2
# Q. Create a normalized form of iris's sepallength whose values range exactly between 0 and 1 so that the minimum has value 0 and maximum has value 1.
url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'
iris_1d = np.genfromtxt(url, delimiter=',', dtype=None, encoding="utf-8")
sepal = np.genfromtxt(url, delimiter=',', dtype=float, usecols=[0])
#1
smax, smin = np.max(sepal), np.min(sepal)
S = (sepal-smin)/(smax-smin)
S
#2
S = (sepal-smin)/sepal.ptp()
S
##? 30. How to compute the softmax score?
# Difficulty Level: L3
# Q. Compute the softmax score of sepallength.
url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'
sepal = np.genfromtxt(url, delimiter=',', dtype=float, usecols=[0], encoding="utf-8")
#or
sepal = np.genfromtxt(url, delimiter=',', dtype='object')
sepal = np.array([float(row[0]) for row in sepal])
# https://stackoverflow.com/questions/34968722/how-to-implement-the-softmax-function-in-python"""
#1
def softmax(x):
e_x = np.exp(x - np.max(x))
return e_x/ e_x.sum(axis=0)
softmax(sepal)
##? 31. How to find the percentile scores of a numpy array?
# Difficulty Level: L1
# Q. Find the 5th and 95th percentile of iris's sepallength
url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'
sepal = np.genfromtxt(url, delimiter=',', dtype='float', usecols=[0])
np.percentile(sepal, q=[5, 95])
##? 32. How to insert values at random positions in an array?
# Difficulty Level: L2
# Q. Insert np.nan values at 20 random positions in iris_2d dataset
url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'
iris_2d = np.genfromtxt(url, delimiter=',', dtype='float', encoding="utf-8")
#Can change object to float if you want
#1
i, j = np.where(iris_2d)
# i, j contain the row numbers and column numbers of the 600 elements of Irix_x
np.random.seed(100)
iris_2d[np.random.choice(i, 20), np.random.choice((j), 20)] = np.nan
#Checking nans in 2nd column
np.isnan(iris_2d[:, 1]).sum()
#Looking over all rows/columns
np.isnan(iris_2d[:, :]).sum()
#2
np.random.seed(100)
iris_2d[np.random.randint(150, size=20), np.random.randint(4, size=20)]=np.nan
#Looking over all rows/columns
np.isnan(iris_2d[:, :]).sum()
##? 33. How to find the position of missing values in numpy array?
# Difficulty Level: L2
# Q. Find the number and position of missing values in iris_2d's sepallength (1st column)
# ehh already did that? Lol. Using above filtered array from method 2 in
# question 32
np.isnan(iris_2d[:, 0]).sum()
#Indexes of which can be found with
np.where(np.isnan(iris_2d[:, 0]))
##? 34. How to filter a numpy array based on two or more conditions?
# Difficulty Level: L3
# Q. Filter the rows of iris_2d that has petallength (3rd column) > 1.5
# and sepallength (1st column) < 5.0
url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'
iris_2d = np.genfromtxt(url, delimiter=',', dtype='float', usecols=[0,1,2,3])
filt_cond = (iris_2d[:,0] < 5.0) & (iris_2d[:, 2] > 1.5)
iris_2d[filt_cond]
##? 35. How to drop rows that contain a missing value from a numpy array?
# Difficulty Level: L3:
# Q. Select the rows of iris_2d that does not have any nan value.
url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'
iris_2d = np.genfromtxt(url, delimiter=',', dtype='float', usecols=[0,1,2,3])
iris_2d[np.random.randint(150, size=20), np.random.randint(4, size=20)] = np.nan
#1
#No direct numpy implementation
iris_drop = np.array([~np.any(np.isnan(row)) for row in iris_2d])
#Look at first 5 rows of drop
iris_2d[iris_drop][:5]
#2
iris_2d[np.sum(np.isnan(iris_2d), axis=1)==0][:5]
##? 36. How to find the correlation between two columns of a numpy array?
# Difficulty Level: L2
# Q. Find the correlation between SepalLength(1st column) and PetalLength(3rd column) in iris_2d
url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'
iris_2d = np.genfromtxt(url, delimiter=',', dtype='float', usecols=[0,1,2,3])
#1
np.corrcoef(iris_2d[:, 0], iris_2d[:, 2])[0, 1]
#2
from scipy.stats.stats import pearsonr
corr, p_val = pearsonr(iris_2d[:, 0], iris_2d[:, 2])
print(corr)
# Correlation coef indicates the degree of linear relationship between two numeric variables.
# It can range between -1 to +1.
# The p-value roughly indicates the probability of an uncorrelated system producing
# datasets that have a correlation at least as extreme as the one computed.
# The lower the p-value (<0.01), greater is the significance of the relationship.
# It is not an indicator of the strength.
#> 0.871754157305
##? 37. How to find if a given array has any null values?
# Difficulty Level: L2
# Q. Find out if iris_2d has any missing values.
url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'
iris_2d = np.genfromtxt(url, delimiter=',', dtype='float', usecols=[0,1,2,3])
np.isnan(iris_2d[:, :]).any()
##? 38. How to replace all missing values with 0 in a numpy array?
# Difficulty Level: L2
# Q. Replace all occurrences of nan with 0 in numpy array
url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'
iris_2d = np.genfromtxt(url, delimiter=',', dtype='float', usecols=[0,1,2,3])
iris_2d[np.random.randint(150, size=20), np.random.randint(4, size=20)] = np.nan
#Check for nans
np.any(~np.isnan(iris_2d[:, :]))
#Set Indexes of of the nans = 0
iris_2d[np.isnan(iris_2d)] = 0
#Check the same indexes
np.where(iris_2d==0)
#Check first 10 rows
iris_2d[:10]
##? 39. How to find the count of unique values in a numpy array?
# Difficulty Level: L2
# Q. Find the unique values and the count of unique values in iris's species
# Input
url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'
iris = np.genfromtxt(url, delimiter=',', dtype='object', encoding="utf-8")
names = ('sepallength', 'sepalwidth', 'petallength', 'petalwidth', 'species')
#1
species = np.array([row.tolist()[4] for row in iris])
np.unique(species, return_counts=True)
#2
np.unique(iris[:, 4], return_counts=True)
##? 40. How to convert a numeric to a categorical (text) array?
# Difficulty Level: L2
# Q. Bin the petal length (3rd) column of iris_2d to form a text array, such that if petal length is:
# Less than 3 --> 'small'
# 3-5 --> 'medium'
# '>=5 --> 'large'
# Input
url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'
iris = np.genfromtxt(url, delimiter=',', dtype='object')
names = ('sepallength', 'sepalwidth', 'petallength', 'petalwidth', 'species')
#1
#Bin the petal length
petal_length_bin = np.digitize(iris[:, 2].astype('float'), [0, 3, 5, 10])
#Map it to respective category.
label_map = {1: 'small', 2: 'medium', 3: 'large', 4: np.nan}
petal_length_cat = [label_map[x] for x in petal_length_bin]
petal_length_cat[:4]
#or
petal_length_cat = np.array(list(map(lambda x: label_map[x], petal_length_bin)))
petal_length_cat[:4]
##? 41. How to create a new column from existing columns of a numpy array?
# Difficulty Level: L2
# Q. Create a new column for volume in iris_2d,
# where volume is (pi x petallength x sepal_length^2)/3
# Input
url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'
iris_2d = np.genfromtxt(url, delimiter=',', dtype='object')
# Compute volume
sepallength = iris_2d[:, 0].astype('float')
petallength = iris_2d[:, 2].astype('float')
volume = (np.pi * petallength*sepallength**2)/3
# Introduce new dimension to match iris_2d's
volume = volume[:, np.newaxis]
# Add the new column
out = np.hstack([iris_2d, volume])
out[:4]
##? 42. How to do probabilistic sampling in numpy?
# Difficulty Level: L3
# Q. Randomly sample iris's species such that setosa
# is twice the number of versicolor and virginica
# Import iris keeping the text column intact
url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'
iris = np.genfromtxt(url, delimiter=',', dtype='object')
#Get species column
species = iris[:, 4]
#1 Generate Probablistically.
np.random.seed(100)
a = np.array(['Iris-setosa', 'Iris-versicolor', 'Iris-virginica'])
out = np.random.choice(a, 150, p=[0.5, 0.25, 0.25])
#Checking counts
np.unique(out[:], return_counts=True)
#2 Probablistic Sampling #preferred
np.random.seed(100)
probs = np.r_[np.linspace(0, 0.500, num=50), np.linspace(0.501, .0750, num=50), np.linspace(.751, 1.0, num=50)]
index = np.searchsorted(probs, np.random.random(150))
species_out = species[index]
print(np.unique(species_out, return_counts=True))
# Approach 2 is preferred because it creates an index variable that can be
# used to sample 2d tabular data.
##? 43. How to get the second largest value of an array when grouped by another array?
# Difficulty Level: L2
# Q. What is the value of second longest petallength of species setosa
# Input
url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'
iris = np.genfromtxt(url, delimiter=',', dtype='object')
names = ('sepallength', 'sepalwidth', 'petallength', 'petalwidth', 'species')
petal_setosa = iris[iris[:, 4]==b'Iris-setosa', [2]].astype('float')
#1
#Note. Option 1 will return the second largest value 1.7, but with no repeats (np.unique()
np.unique(np.sort(petal_setosa))[-2]
#Note, options 2 and 3. these will return 1.9 because that is the second largest value.
#2
petal_setosa[np.argpartition(petal_setosa, -2)[-2]]
#3
petal_setosa[petal_setosa.argsort()[-2]]
#4
unq = np.unique(petal_setosa)
unq[np.argpartition(unq, -2)[-2]]
#Note: This method still gives back 1.9. As that is the 2nd largest value,
#So you'd have to filter for unique values. Then do the argpart on the unq array
##? 44. How to sort a 2D array by a column
# Difficulty Level: L2
# Q. Sort the iris dataset based on sepallength column.
url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'
# dtype = [('sepallength', float), ('sepalwidth', float), ('petallength', float), ('petalwidth', float),('species', 'S10')]
iris = np.genfromtxt(url, delimiter=',', dtype="object")
names = ('sepallength', 'sepalwidth', 'petallength', 'petalwidth', 'species')
#1
print(iris[iris[:,0].argsort()][:20])
#2
#!Only captures first column to sort
np.sort(iris[:, 0], axis=0)
#3
sorted(iris, key=lambda x: x[0])
##? 45. How to find the most frequent value in a numpy array?
# Difficulty Level: L1
# Q. Find the most frequent value of petal length (3rd column) in iris dataset.
url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'
iris = np.genfromtxt(url, delimiter=',', dtype='object')
names = ('sepallength', 'sepalwidth', 'petallength', 'petalwidth', 'species')
vals, counts = np.unique(iris[:, 2], return_counts=True)
print(vals[np.argmax(counts)])
##? 46. How to find the position of the first occurrence of a value greater than a given value?
# Difficulty Level: L2
# Q. Find the position of the first occurrence of a value greater than 1.0 in petalwidth 4th column of iris dataset.
url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'
iris = np.genfromtxt(url, delimiter=',', dtype='object')
#1
np.argwhere(iris[:, 3].astype(float) > 1.0)[0]
# 47. How to replace all values greater than a given value to a given cutoff?
# Difficulty Level: L2
# Q. From the array a, replace all values greater than 30 to 30 and less than 10 to 10.
np.set_printoptions(precision=2)
np.random.seed(100)
a = np.random.uniform(1,50, 20)
#1
np.clip(a, a_min=10, a_max=30)
#2
np.where(a < 10, 10, np.where(a > 30, 30, a))
#Tangent - Filtering condition
#Say we only want the values above 10 and below 30. Or operator | should help there.
filt_cond = (a < 10) | (a > 30)
a[filt_cond]
##? 48. How to get the positions of top n values from a numpy array?
# Difficulty Level: L2
# Q. Get the positions of top 5 maximum values in a given array a.
np.random.seed(100)
a = np.random.uniform(1,50, 20)
#1
a.argsort()[:5]
#2
np.argpartition(-a, 5)[:5]
# or (order is reversed though)
np.argpartition(a, -5)[-5:]
#To get the values.
#1
a[a.argsort()][-5:]
#2
np.sort(a)[-5:]
#3
np.partition(a, kth=-5)[-5:]
#4
a[np.argpartition(-a, 5)][:5]
#or
a[np.argpartition(a, -5)][-5:]
##? 49. How to compute the row wise counts of all possible values in an array?
# Difficulty Level: L4
# Q. Compute the counts of unique values row-wise.
np.random.seed(100)
arr = np.random.randint(1,11,size=(6, 10))
#Add a column of of the counts of each row
#Tangent fun
counts = np.array([np.unique(row).size for row in arr])
counts = counts.reshape(arr.shape[0], 1)
arr = np.hstack([arr, counts])
arr
#1
def row_counts(arr2d):
count_arr = [np.unique(row, return_counts=True) for row in arr2d]
return [[int(b[a==i]) if i in a else 0 for i in np.unique(arr2d)] for a, b in count_arr]
print(np.arange(1, 11))
row_counts(arr)
#2
arr = np.array([np.array(list('<NAME>')), np.array(list('narendramodi')), np.array(list('jjayalalitha'))])
print(np.unique(arr))
row_counts(arr)
##? 50. How to convert an array of arrays into a flat 1d array?
# Difficulty Level: 2
# Q. Convert array_of_arrays into a flat linear 1d array.
# Input:
arr1 = np.arange(3)
arr2 = np.arange(3,7)
arr3 = np.arange(7,10)
array_of_arrays = np.array([arr1, arr2, arr3])
array_of_arrays
#1 - List comp
arr_2d = [a for arr in array_of_arrays for a in arr]
arr_2d
#2 - concatenate
arr_2d = np.concatenate([arr1, arr2, arr3])
arr_2d
#3 - hstack
arr_2d = np.hstack([arr1, arr2, arr3])
arr_2d
#4 - ravel
arr_2d = np.concatenate(array_of_arrays).ravel() #ravel flattens the array
arr_2d
##? 51. How to generate one-hot encodings for an array in numpy?
# Difficulty Level L4
# Q. Compute the one-hot encodings (dummy binary variables for each unique value in the array)
# Input
np.random.seed(101)
arr = np.random.randint(1,11, size=20)
arr
#1
def one_hot_encode(arr):
uniqs = np.unique(arr)
out = np.zeros((arr.shape[0], uniqs.shape[0]))
for i, k in enumerate(arr):
out[i, k-1] = 1
return out
print("\t",np.arange(1, 11))
one_hot_encode(arr)
#2
(arr[:, None] == np.unique(arr)).view(np.int8)
##? 52. How to create row numbers grouped by a categorical variable?
# Difficulty Level: L3
# Q. Create row numbers grouped by a categorical variable.
# Use the following sample from iris species as input.
#Input
url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'
species = np.genfromtxt(url, delimiter=',', dtype='str', usecols=4)
#choose 20 species randomly
species_small = np.sort(np.random.choice(species, size=20))
species_small
#1
print([i for val in np.unique(species_small) for i, grp in enumerate(species_small[species_small==val])])
##? 53. How to create group ids based on a given categorical variable?
# Difficulty Level: L4
# Q. Create group ids based on a given categorical variable.
# Use the following sample from iris species as input.
url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'
species = np.genfromtxt(url, delimiter=',', dtype='str', usecols=4)
species_small = np.sort(np.random.choice(species, size=20))
species_small
#1
[np.argwhere(np.unique(species_small) == s).tolist()[0][0] for val in np.unique(species_small) for s in species_small[species_small==val]]
#2
# Solution: For Loop version
output = []
uniqs = np.unique(species_small)
for val in uniqs: # uniq values in group
for s in species_small[species_small==val]: # each element in group
groupid = np.argwhere(uniqs == s).tolist()[0][0] # groupid
output.append(groupid)
print(output)
##? 54. How to rank items in an array using numpy?
# Difficulty Level: L2
# Q. Create the ranks for the given numeric array a.
#Input
np.random.seed(10)
a = np.random.randint(20, size=10)
print(a)
a.argsort().argsort()
##? 55. How to rank items in a multidimensional array using numpy?
# Difficulty Level: L3
# Q. Create a rank array of the same shape as a given numeric array a.
#Input
np.random.seed(10)
a = np.random.randint(20, size=[5,5])
print(a)
#1
print(a.ravel().argsort().argsort().reshape(a.shape))
#2
#Ranking the rows
tmp = a.argsort()[::-1]
np.arange(len(a))[tmp]+1
#2b
#Alternate ranking of rows (8x faster)
sidx = | np.argsort(a, axis=1) | numpy.argsort |
import numpy as np
import random
import re
ANNOTATIONFILE = 'OpenKPAnnotations.tsv'
def getScoreUnigram(candidate, gold):
#Unigram Levenshtein distance
#First we produce all possible pairs and greedily select
scoring, bestMatch = {}, {}
maxScore = 0
maxLabel = ''
#Generate all possible combinations
for goldLabel in gold:
goldKey = str(goldLabel)
scoring[goldKey] = {}
for candidateLabel in candidate:
candidateKey = str(candidateLabel)
scoring[goldKey][candidateKey] = (len(goldLabel) - len(goldLabel-candidateLabel))/len(goldLabel)
#Greedily select best combination and then remove all related combinations.
while len(scoring) > 0:
maxScore = 0
maxLabel = ''
for goldLabel in scoring:
goldKey = str(goldLabel)
for candidateLabel in scoring[goldKey]:
candidateKey = str(candidateLabel)
score = scoring[goldKey][candidateKey]
if score >= maxScore:
maxScore = score
maxLabel = (goldKey, candidateKey)
bestMatch[maxLabel] = scoring[maxLabel[0]][maxLabel[1]]
scoring.pop(maxLabel[0])#remove all pairs that could
return sum(bestMatch.values())/len(gold)
def getScoreEM(candidate, gold):
#Unigram Levenshtein distance
#First we produce all possible pairs and greedily select
scoring, bestMatch = {}, {}
maxScore = 0
maxLabel = ''
#Generate all possible combinations
for goldLabel in gold:
goldKey = str(goldLabel)
scoring[goldKey] = {}
for candidateLabel in candidate:
candidateKey = str(candidateLabel)
if goldLabel == candidateLabel:
scoring[goldKey][candidateKey] = 1
else:
scoring[goldKey][candidateKey] = 0
#Greedily select best combination and then remove all related combinations.
while len(scoring) > 0:
maxScore = -1
maxLabel = ''
for goldLabel in scoring:
goldKey = str(goldLabel)
for candidateLabel in scoring[goldKey]:
candidateKey = str(candidateLabel)
score = scoring[goldKey][candidateKey]
if score >= maxScore:
maxScore = score
maxLabel = (goldKey, candidateKey)
bestMatch[maxLabel] = scoring[maxLabel[0]][maxLabel[1]]
scoring.pop(maxLabel[0])#remove all pairs that could
return sum(bestMatch.values())/len(gold)
def calculateAgreement(judgements):
scoresUnigram = []
scoresEM = []
for url in judgements:
for i in range(len(judgements[url])):
currentRunsUnigram, currentRunsEM = [], []
for j in range(len(judgements[url])):
if j != i:
currentRunsUnigram.append(getScoreUnigram(judgements[url][i],judgements[url][j]))
currentRunsEM.append(getScoreEM(judgements[url][i],judgements[url][j]))
if len(currentRunsUnigram) > 0:
scoresUnigram.append(np.sum(currentRunsUnigram)/(len(judgements[url])-1))
scoresEM.append(np.sum(currentRunsEM)/(len(judgements[url])-1))
print('Exact Match max:{} min:{} mean:{}'.format(np.max(scoresEM), np.min(scoresEM),np.mean(scoresEM)))
print('Unigram max:{} min:{} mean:{}'.format(np.max(scoresUnigram), np.min(scoresUnigram), | np.mean(scoresUnigram) | numpy.mean |
from src.utils import pdump, pload, bmtv, bmtm
from src.lie_algebra import SO3
from termcolor import cprint
from torch.utils.data.dataset import Dataset
from scipy.interpolate import interp1d
import numpy as np
import matplotlib.pyplot as plt
import pickle
import os
import torch
import sys
class BaseDataset(Dataset):
def __init__(self, predata_dir, train_seqs, val_seqs, test_seqs, mode, N,
min_train_freq=128, max_train_freq=512, dt=0.005):
super().__init__()
# where record pre loaded data
self.predata_dir = predata_dir
self.path_normalize_factors = os.path.join(predata_dir, 'nf.p')
self.mode = mode
# choose between training, validation or test sequences
train_seqs, self.sequences = self.get_sequences(train_seqs, val_seqs,
test_seqs)
# get and compute value for normalizing inputs
self.mean_u, self.std_u = self.init_normalize_factors(train_seqs)
self.mode = mode # train, val or test
self._train = False
self._val = False
# noise density
self.imu_std = torch.Tensor([8e-5, 1e-3]).float()
# bias repeatability (without in-run bias stability)
self.imu_b0 = torch.Tensor([1e-3, 1e-3]).float()
# IMU sampling time
self.dt = dt # (s)
# sequence size during training
self.N = N # power of 2
self.min_train_freq = min_train_freq
self.max_train_freq = max_train_freq
self.uni = torch.distributions.uniform.Uniform(-torch.ones(1),
torch.ones(1))
def get_sequences(self, train_seqs, val_seqs, test_seqs):
"""Choose sequence list depending on dataset mode"""
sequences_dict = {
'train': train_seqs,
'val': val_seqs,
'test': test_seqs,
}
return sequences_dict['train'], sequences_dict[self.mode]
def __getitem__(self, i):
mondict = self.load_seq(i)
N_max = mondict['xs'].shape[0]
if self._train: # random start
n0 = torch.randint(0, self.max_train_freq, (1, ))
nend = n0 + self.N
elif self._val: # end sequence
n0 = self.max_train_freq + self.N
nend = N_max - ((N_max - n0) % self.max_train_freq)
else: # full sequence
n0 = 0
nend = N_max - (N_max % self.max_train_freq)
u = mondict['us'][n0: nend]
x = mondict['xs'][n0: nend]
return u, x
def __len__(self):
return len(self.sequences)
def add_noise(self, u):
"""Add Gaussian noise and bias to input"""
noise = torch.randn_like(u)
noise[:, :, :3] = noise[:, :, :3] * self.imu_std[0]
noise[:, :, 3:6] = noise[:, :, 3:6] * self.imu_std[1]
# bias repeatability (without in run bias stability)
b0 = self.uni.sample(u[:, 0].shape).cuda()
b0[:, :, :3] = b0[:, :, :3] * self.imu_b0[0]
b0[:, :, 3:6] = b0[:, :, 3:6] * self.imu_b0[1]
u = u + noise + b0.transpose(1, 2)
return u
def init_train(self):
self._train = True
self._val = False
def init_val(self):
self._train = False
self._val = True
def length(self):
return self._length
def load_seq(self, i):
return pload(self.predata_dir, self.sequences[i] + '.p')
def load_gt(self, i):
return pload(self.predata_dir, self.sequences[i] + '_gt.p')
def init_normalize_factors(self, train_seqs):
if os.path.exists(self.path_normalize_factors):
mondict = pload(self.path_normalize_factors)
return mondict['mean_u'], mondict['std_u']
path = os.path.join(self.predata_dir, train_seqs[0] + '.p')
if not os.path.exists(path):
print("init_normalize_factors not computed")
return 0, 0
print('Start computing normalizing factors ...')
cprint("Do it only on training sequences, it is vital!", 'yellow')
# first compute mean
num_data = 0
for i, sequence in enumerate(train_seqs):
pickle_dict = pload(self.predata_dir, sequence + '.p')
us = pickle_dict['us']
sms = pickle_dict['xs']
if i == 0:
mean_u = us.sum(dim=0)
num_positive = sms.sum(dim=0)
num_negative = sms.shape[0] - sms.sum(dim=0)
else:
mean_u += us.sum(dim=0)
num_positive += sms.sum(dim=0)
num_negative += sms.shape[0] - sms.sum(dim=0)
num_data += us.shape[0]
mean_u = mean_u / num_data
pos_weight = num_negative / num_positive
# second compute standard deviation
for i, sequence in enumerate(train_seqs):
pickle_dict = pload(self.predata_dir, sequence + '.p')
us = pickle_dict['us']
if i == 0:
std_u = ((us - mean_u) ** 2).sum(dim=0)
else:
std_u += ((us - mean_u) ** 2).sum(dim=0)
std_u = (std_u / num_data).sqrt()
normalize_factors = {
'mean_u': mean_u,
'std_u': std_u,
}
print('... ended computing normalizing factors')
print('pos_weight:', pos_weight)
print('This values most be a training parameters !')
print('mean_u :', mean_u)
print('std_u :', std_u)
print('num_data :', num_data)
pdump(normalize_factors, self.path_normalize_factors)
return mean_u, std_u
def read_data(self, data_dir):
raise NotImplementedError
@staticmethod
def interpolate(x, t, t_int):
"""
Interpolate ground truth at the sensor timestamps
"""
# vector interpolation
x_int = np.zeros((t_int.shape[0], x.shape[1]))
for i in range(x.shape[1]):
if i in [4, 5, 6, 7]:
continue
x_int[:, i] = np.interp(t_int, t, x[:, i])
# quaternion interpolation
t_int = torch.Tensor(t_int - t[0])
t = torch.Tensor(t - t[0])
qs = SO3.qnorm(torch.Tensor(x[:, 4:8]))
x_int[:, 4:8] = SO3.qinterp(qs, t, t_int).numpy()
return x_int
class EUROCDataset(BaseDataset):
"""
Dataloader for the EUROC Data Set.
"""
def __init__(self, data_dir, predata_dir, train_seqs, val_seqs,
test_seqs, mode, N, min_train_freq, max_train_freq, dt=0.005):
super().__init__(predata_dir, train_seqs, val_seqs, test_seqs, mode, N, min_train_freq, max_train_freq, dt)
# convert raw data to pre loaded data
self.read_data(data_dir)
def read_data(self, data_dir):
r"""Read the data from the dataset"""
f = os.path.join(self.predata_dir, 'MH_01_easy.p')
if True and os.path.exists(f):
return
print("Start read_data, be patient please")
def set_path(seq):
path_imu = os.path.join(data_dir, seq, "mav0", "imu0", "data.csv")
path_gt = os.path.join(data_dir, seq, "mav0", "state_groundtruth_estimate0", "data.csv")
return path_imu, path_gt
sequences = os.listdir(data_dir)
# read each sequence
for sequence in sequences:
print("\nSequence name: " + sequence)
path_imu, path_gt = set_path(sequence)
imu = np.genfromtxt(path_imu, delimiter=",", skip_header=1)
gt = np.genfromtxt(path_gt, delimiter=",", skip_header=1)
# time synchronization between IMU and ground truth
t0 = np.max([gt[0, 0], imu[0, 0]])
t_end = np.min([gt[-1, 0], imu[-1, 0]])
# start index
idx0_imu = np.searchsorted(imu[:, 0], t0)
idx0_gt = np.searchsorted(gt[:, 0], t0)
# end index
idx_end_imu = np.searchsorted(imu[:, 0], t_end, 'right')
idx_end_gt = np.searchsorted(gt[:, 0], t_end, 'right')
# subsample
imu = imu[idx0_imu: idx_end_imu]
gt = gt[idx0_gt: idx_end_gt]
ts = imu[:, 0]/1e9
# interpolate
gt = self.interpolate(gt, gt[:, 0]/1e9, ts)
# take ground truth position
p_gt = gt[:, 1:4]
p_gt = p_gt - p_gt[0]
# take ground true quaternion pose
q_gt = torch.Tensor(gt[:, 4:8]).double()
q_gt = q_gt / q_gt.norm(dim=1, keepdim=True)
Rot_gt = SO3.from_quaternion(q_gt.cuda(), ordering='wxyz').cpu()
# convert from numpy
p_gt = torch.Tensor(p_gt).double()
v_gt = torch.tensor(gt[:, 8:11]).double()
imu = torch.Tensor(imu[:, 1:]).double()
# compute pre-integration factors for all training
mtf = self.min_train_freq
dRot_ij = bmtm(Rot_gt[:-mtf], Rot_gt[mtf:])
dRot_ij = SO3.dnormalize(dRot_ij.cuda())
dxi_ij = SO3.log(dRot_ij).cpu()
# save for all training
mondict = {
'xs': dxi_ij.float(),
'us': imu.float(),
}
pdump(mondict, self.predata_dir, sequence + ".p")
# save ground truth
mondict = {
'ts': ts,
'qs': q_gt.float(),
'vs': v_gt.float(),
'ps': p_gt.float(),
}
pdump(mondict, self.predata_dir, sequence + "_gt.p")
class TUMVIDataset(BaseDataset):
"""
Dataloader for the TUM-VI Data Set.
"""
def __init__(self, data_dir, predata_dir, train_seqs, val_seqs,
test_seqs, mode, N, min_train_freq, max_train_freq, dt=0.005):
super().__init__(predata_dir, train_seqs, val_seqs, test_seqs, mode, N,
min_train_freq, max_train_freq, dt)
# convert raw data to pre loaded data
self.read_data(data_dir)
# noise density
self.imu_std = torch.Tensor([8e-5, 1e-3]).float()
# bias repeatability (without in-run bias stability)
self.imu_b0 = torch.Tensor([1e-3, 1e-3]).float()
def read_data(self, data_dir):
r"""Read the data from the dataset"""
f = os.path.join(self.predata_dir, 'dataset-room1_512_16_gt.p')
if True and os.path.exists(f):
return
print("Start read_data, be patient please")
def set_path(seq):
path_imu = os.path.join(data_dir, seq, "mav0", "imu0", "data.csv")
path_gt = os.path.join(data_dir, seq, "mav0", "mocap0", "data.csv")
return path_imu, path_gt
sequences = os.listdir(data_dir)
# read each sequence
for sequence in sequences:
print("\nSequence name: " + sequence)
if 'room' not in sequence:
continue
path_imu, path_gt = set_path(sequence)
imu = np.genfromtxt(path_imu, delimiter=",", skip_header=1)
gt = np.genfromtxt(path_gt, delimiter=",", skip_header=1)
# time synchronization between IMU and ground truth
t0 = | np.max([gt[0, 0], imu[0, 0]]) | numpy.max |
import ctypes
import os
import warnings
import numpy as np
from nengo_loihi.inputs import ChipProcess
class DVSFileChipProcess(ChipProcess):
"""Process for DVS input to Loihi chip from a pre-recorded file.
Parameters
----------
file_path : string
The path of the file to read from. Can be a ``.aedat`` or ``.events`` file.
file_fmt : "aedat" or "events" or None, optional
The format of the file. If ``None`` (default), this will be detected from the
file extension.
t_start : float, optional
Offset for the time in the file to start at, in seconds.
rel_time : bool, optional
Whether to make all times relative to the first event, or not. Defaults
to True for ``.aedat`` files and False otherwise.
pool : (int, int), optional
Number of pixels to pool over in the vertical and horizontal
directions, respectively.
channels_last : bool, optional
Whether to make the channels (i.e. the polarity) the least-significant
index (True) or the most-significant index (False).
dvs_height : int, optional
The actual height (in pixels) of the DVS sensor. Only change this if your
sensor has a non-standard height. If you wish to make the output of this node
smaller, use the ``pool`` argument instead.
dvs_width : int, optional
The actual width (in pixels) of the DVS sensor. Only change this if your
sensor has a non-standard width. If you wish to make the output of this node
smaller, use the ``pool`` argument instead.
**kwargs
Extra arguments to pass to the `nengo.Process` constructor.
Examples
--------
This example shows how to create the process, use it in a `~nengo.Node`, and
connect it to neurons on the Loihi chip. The DVS events loaded from the file will
be transferred immediately to the Loihi chip; none of the simulation is on the host.
.. testcode::
with nengo.Network() as net:
dvs_process = nengo_loihi.dvs.DVSFileChipProcess("my-dvs-events.aedat")
u = nengo.Node(dvs_process)
ens = nengo.Ensemble(dvs_process.size, dimensions=1)
nengo.Connection(u, ens.neurons)
"""
def __init__(
self,
file_path,
file_fmt=None,
t_start=0,
rel_time=None,
pool=(1, 1),
channels_last=True,
dvs_height=180,
dvs_width=240,
**kwargs,
):
self.file_path = file_path
self.file_fmt = file_fmt
self.t_start = t_start
self.rel_time = rel_time
self.dvs_height = dvs_height
self.dvs_width = dvs_width
self.dvs_polarity = 2
self.channels_last = channels_last
self.pool = pool
self.height = int(np.ceil(self.dvs_height / self.pool[0]))
self.width = int(np.ceil(self.dvs_width / self.pool[1]))
self.polarity = self.dvs_polarity
self.size = self.height * self.width * self.polarity
super().__init__(default_size_in=0, default_size_out=self.size, **kwargs)
def make_step(self, shape_in, shape_out, dt, rng, state):
"""Make the step function to display the DVS events as image frames.
This step function is only called when using this process in a
`nengo.Simulator`. When using it in a `nengo_loihi.Simulator`, the events
are transferred directly to the Loihi board.
"""
assert shape_in == (0,)
assert len(shape_out) == 1
height = self.height
width = self.width
polarity = self.polarity
t_start = self.t_start
events_t, events_idx = self._read_events()
def step_dvsfileimage(t):
t = t_start + t
t_lower = (t - dt) * 1e6
t_upper = t * 1e6
idxs = events_idx[(events_t >= t_lower) & (events_t < t_upper)]
image = np.zeros(height * width * polarity)
np.add.at(image, idxs, 1 / dt)
return image
return step_dvsfileimage
def _read_events(self):
"""Helper function to read events from the target file."""
dvs_events = DVSEvents()
dvs_events.read_file(
self.file_path, file_fmt=self.file_fmt, rel_time=self.rel_time
)
events = dvs_events.events
pool_y, pool_x = self.pool
if self.channels_last:
stride_x = self.polarity
stride_y = self.polarity * self.width
stride_p = 1
else:
stride_x = 1
stride_y = self.width
stride_p = self.width * self.height
events_t = events[:]["t"]
events_idx = (
(events[:]["y"].astype(np.int32) // pool_y) * stride_y
+ (events[:]["x"].astype(np.int32) // pool_x) * stride_x
+ events[:]["p"].astype(np.int32) * stride_p
)
return events_t, events_idx
class DVSEvents:
"""A group of events from a Dynamic Vision Sensor (DVS) spiking camera.
Attributes
----------
events : structured `numpy.ndarray`
A structured array with the following fields:
* "y": The vertical coordinate of the event.
* "x": The horizontal coordinate of the event.
* "p": The polarity of the event (``0`` for off, ``1`` for on).
* "v": The event trigger (``0`` for DVS events, ``1`` for external events).
* "t": The event timestamp in microseconds.
n_events : int
The number of events.
"""
events_dtype = np.dtype(
[("y", "u2"), ("x", "u2"), ("p", "u1"), ("v", "u1"), ("t", "u4")]
)
def __init__(self):
self.events = None
@property
def n_events(self):
"""The number of events (equals ``len(self.events)``)."""
return len(self.events)
@staticmethod
def from_file(file_path, **kwargs):
"""Create a new `.DVSEvents` object with events from a file.
Parameters
----------
file_path : str
The path to the events file.
**kwargs
Additional keyword arguments to pass to `.DVSEvents.read_file`.
"""
events = DVSEvents()
events.read_file(file_path, **kwargs)
return events
def init_events(self, event_data=None, n_events=None):
"""Initialize ``events`` array.
Only required if configuring events manually (i.e. not reading from a file).
Parameters
----------
event_data : list of tuples, optional
Each tuple is of the form ``(y, x, p, v, t)``. See `.DVSEvents` for the
definitions of these fields.
n_events : int, optional
The number of events in the new (empty) events array, in the case that
``event_data`` is not provided.
"""
assert (event_data is not None) or (n_events is not None)
if event_data is not None:
n_events = len(event_data) if n_events is None else n_events
assert n_events == len(
event_data
), "Specified number of events (%d) does not match length of data (%d)" % (
n_events,
len(event_data),
)
if self.events is not None:
warnings.warn("`events` has already been initialized. Overwriting.")
if event_data is not None:
self.events = np.array(event_data, dtype=self.events_dtype)
else:
self.events = | np.zeros(n_events, dtype=self.events_dtype) | numpy.zeros |
import numpy
import torch
import math
import numpy as np
import time
import operator as op
from functools import reduce
class PLSExplainer():
def __init__(self, objective_function, target_sparsity, eval_budget, dimensionality, restarts=1, temp_decay = .8, search_space='up_to_k', no_duplicates=True):
'''
objective_function : maps from np.ndarray of shape 1 x p -> (suff/comp, suff_woe/comp_woe)
search_space: up_to_k means max sparsity is ceil(dim * target_sparsity). if set to exact_k, then will be exactly k-sparse
no_duplicates: if True, never evaluate an x twice. requires keeping track of all previous x
'''
self.objective_function = objective_function
self.target_sparsity = target_sparsity
self.eval_budget = eval_budget
self.dimensionality = dimensionality
self.search_space = search_space
self.max_sparsity = math.ceil(self.dimensionality*self.target_sparsity)
assert target_sparsity > 0 and target_sparsity < 1
# limit both restarts and per_restart budget based on the number of possible explanations
self.num_possible_explanations = self.ncr(self.dimensionality, self.max_sparsity)
self.restarts = min(restarts, self.num_possible_explanations)
self.n_iters = math.ceil(self.eval_budget / self.restarts)
self.n_iters = min(self.n_iters, math.ceil(self.num_possible_explanations / self.restarts)) # limit n_iters per restart to not add up to more than num_possible_explanations
self.random_masks = self.random_masks(num_masks=eval_budget, max_length=dimensionality, sparsity=target_sparsity, search_space='exact_k')
self.remaining_sample_idx = list(range(len(self.random_masks)))
self.no_duplicates = no_duplicates
self.T = 1.
self.temp_decay = temp_decay
self.seen_masks = set()
def balanced_array(self, size, prop):
# make array of 0s and 1s of len=size and mean ~= prop
array = np.zeros(size)
where_ones = np.random.choice(np.arange(size), size=math.ceil(size*prop), replace=False)
array[where_ones] = 1
return array
def ncr(self, n, r):
r = min(r, n-r)
numer = reduce(op.mul, range(n, n-r, -1), 1)
denom = reduce(op.mul, range(1, r+1), 1)
return numer // denom # or / in Python 2
def run(self):
(all_masks, all_obj, all_woe_obj) = self.parallel_local_search()
return_masks = all_masks[-1].reshape(1, -1) # single best mask
return_obj = all_obj
return_woe_obj = all_woe_obj
self.objective_at_t = self.create_objective_over_time(return_obj)
self.objective_at_t_woe = self.create_objective_over_time(return_woe_obj)
return (return_masks, return_obj, return_woe_obj)
def create_objective_over_time(self, obj):
# takes obj, array of length n, and repeats each element in obj self.restarts time
# e.g., [0,1,2], with self.restarts=2, becomes [0,0,1,1,2,2]
return obj.repeat(self.restarts, axis=0)
def sample_single_x(self, old_x=None, add_to_seen=True):
# sample new_x from old_x, nparray of length n_vars, or from self.random_masks
# first of all, if no new explanations left to sample, generate random one
if len(self.seen_masks) >= self.num_possible_explanations:
new_x = self.balanced_array(size=self.dimensionality, prop=self.target_sparsity)
elif old_x is None:
sample_idx = np.random.choice(self.remaining_sample_idx)
if self.no_duplicates:
self.remaining_sample_idx.remove(sample_idx)
new_x = self.random_masks[sample_idx]
else:
if self.search_space == 'up_to_k':
flip_bit = | np.random.randint(self.dimensionality) | numpy.random.randint |
import solver.algorithms as alg
import numpy as np
def problem4(t0, tf, NA0, NB0, tauA, tauB, n, returnlist=False):
"""Uses Euler's method to model the solution to a radioactive decay problem where dNA/dt = -NA/tauA and dNB/dt = NA/tauA - NB/tauB.
Args:
t0 (float): Start time
tf (float): End time
NA0 (int): Initial number of NA nuclei
NB0 (int): Initial number of NB nuclei
tauA (float): Decay time constant for NA
tauB (float): Decay time constant for NB
n (int): Number of points to sample at
returnlist (bool) = Controls whether the function returns the list of points or not. Defaults to false
Returns:
solution (list): Points on the graph of the approximate solution. Each element in the list has the form (t, array([NA, NB]))
In the graph, NA is green and NB is blue
"""
print("Problem 4: ~Radioactive Decay~ dNA/dt = -NA/tauA & dNB/dt = NA/tauA - NB/tauA - NB/tauB")
N0 = | np.array([NA0, NB0]) | numpy.array |
# -*- coding: utf-8 -*-
""" PatchGP on Snelson
"""
import argparse
import numpy as np
import torch
import gpytorch
import itertools
from moegplib.datasets.toydata import SnelsonDataset
from moegplib.utils.logger import SaveAndLoad, BoardLogger
from moegplib.networks.toydata import SnelsonPrimeNet
from moegplib.networks.modelquantiles import ModelQuantiles
from moegplib.clustering.quantiles import quantiles1d
from moegplib.moegp.gkernels import NTK1DGP
import matplotlib.pyplot as plt
CUDA_LAUNCH_BLOCKING="1"
def parse_args(args):
"""Parse command line parameters
Args:
args ([str]): command line parameters as list of strings
Returns:
:obj:`argparse.Namespace`: command line parameters namespace
"""
parser = argparse.ArgumentParser(
description="An example with Snelson data-set.")
parser.add_argument('--seed', default=1234, type=int,
help='seed for numpy and pytorch (default: 1234)')
parser.add_argument('--ckp_dir', default="./",
help='directory of the check point file.')
parser.add_argument('--data_dir', default="./",
help='directory of the data')
return parser.parse_args(args)
def main(args):
"""Main entry point allowing external calls
Args:
args ([str]): command line parameter list
"""
# arguments
args = parse_args(args)
# device
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
print("available devides:", device)
# initialization
lr = 0.1
delta = 1.5
cluster_nr = 7
# create the dataset and data loader
dataset = SnelsonDataset(data_dir = args.data_dir, inbetween=True)
dataloader = torch.utils.data.DataLoader(dataset, batch_size=dataset.__len__(), shuffle=True, num_workers=4)
# create the model
model = SnelsonPrimeNet(D_in=1, H=32, D_out=1, n_layers=2, activation='sigmoid')
logger = SaveAndLoad(checkpth=args.ckp_dir)
checkpoint = logger.load_ckp(is_best=True)
model.load_state_dict(checkpoint['state_dict'])
model.to(device)
# output the datasets and clustering
xtrain = dataloader.dataset.X
ytrain = dataloader.dataset.Y
xtest = dataloader.dataset.Xtest
idx, idx_t, lidx, lidx_t, bnd_x, bidx, nb, CONN = quantiles1d(xtrain, xtest, cluster_nr)
xtrain = xtrain[lidx].squeeze(-1)
ytrain = ytrain[lidx].squeeze(-1)
xtest = xtest[lidx_t].squeeze(-1)
# put the data into a gpu.
xtrain = torch.from_numpy(xtrain).to(device)
ytrain = torch.from_numpy(ytrain).unsqueeze(-1).to(device)
xtest = torch.from_numpy(xtest).to(device)
bnd_x = torch.from_numpy(bnd_x).unsqueeze(-1).to(device)
# compute the Jacobians with a gpu incl. boundary points (note: the input shapes should match)
mq = ModelQuantiles(model=model, data=(xtrain.unsqueeze(-1), ytrain.unsqueeze(-1)), delta=delta, devices=device)
(Jtrain, yhat, s_noise, m_0, S_0) = mq.projection()
(Jtest, _, _, _, _) = mq.projection(xtest.unsqueeze(-1))
(Jbnd, _, _, _, _) = mq.projection(bnd_x.unsqueeze(-1))
dnnpred = list()
gpsig2 = list()
xtestlist = list()
for i in range(len(idx)):
# per experts, extract neighbors
experts = list()
# list neighborhoods (only valid for 2-D case)
if not len(CONN):
lst = list()
else:
lst_a = list() if np.nonzero(CONN[0] == i)[0].size == 0 else (np.nonzero(CONN[0] == i)[0]).astype(int)
lst_b = list() if np.nonzero(CONN[1] == i)[0].size == 0 else (np.nonzero(CONN[1] == i)[0]).astype(int)
if len(lst_a) and len(lst_b):
lst = [lst_a, lst_b] # note this is only for 2-D case!
elif len(lst_a) and not len(lst_b):
lst = [lst_a]
elif not len(lst_a) and len(lst_b):
lst = [lst_b]
else:
print("no neighbor! - is it even possible?")
lst = list()
lst = sorted(list(itertools.chain(*lst)))
experts.append([i])
experts.append(CONN[1][lst_a].tolist())
experts.append(CONN[0][lst_b].tolist())
experts = list(itertools.chain(*experts))
experts = [x+1 for x in experts]
experts = list(filter(None, experts))
experts = list(set(experts))
experts = [x-1 for x in experts]
experts = sorted(experts)
bidx_e = list(np.asarray(bidx)[lst])
# cut the matrices based on neighbors
Xtrainhat = Jtrain[0][np.concatenate([idx[ei] for ei in experts])]
Ytrainhat = yhat[0][np.concatenate([idx[ei] for ei in experts])]
Xtesthat = Jtest[0][np.concatenate([idx_t[ei] for ei in experts])]
# patchwork gp build train covariance VIA initiate likelihood and model.
likelihood = gpytorch.likelihoods.GaussianLikelihood().to(device)
gpmodel = NTK1DGP(Xtrainhat, Ytrainhat, likelihood).to(device)
# a new list comprehension
idx_e = list()
idx_t_e = list()
cnt = 0
cnt_t = 0
lidx_e = np.arange(0, len([np.concatenate([idx[ei] for ei in experts])][0]))
lidx_t_e = np.arange(0, len([np.concatenate([idx_t[ei] for ei in experts])][0]))
for ei in experts:
idx_e.append(np.arange(cnt, cnt+len(idx[ei])))
idx_t_e.append(np.arange(cnt_t, cnt_t+len(idx_t[ei])))
if ei == i:
idx_ce = np.arange(cnt_t, cnt_t+len(idx_t[ei]), 1)
cnt = cnt + len(idx[ei])
cnt_t = cnt_t + len(idx_t[ei])
bidxe_e = list(np.arange(0, len(bidx_e)))
CONN_e = [CONN[0][bidx_e], CONN[1][bidx_e]]
minus = CONN_e[0][0]
CONN_e[0] = CONN_e[0] - minus
CONN_e[1] = CONN_e[1] - minus
# training a gp model
training_iter = 100
gpmodel.train()
likelihood.train()
optimizer = torch.optim.Adam(gpmodel.parameters(), lr=0.1)
mll = gpytorch.mlls.ExactMarginalLogLikelihood(likelihood, gpmodel)
# entering training loop
for i in range(training_iter):
optimizer.zero_grad()
output = gpmodel(Xtrainhat)
loss = -mll(output, Ytrainhat)
loss.backward(retain_graph=True)
if i%5==0:
print('Iter %d/%d - Loss: %.3f delta: %.3f noise: %.3f' % (
i + 1, training_iter, loss.item(),
gpmodel.covar_module.variance.item(),
gpmodel.likelihood.noise.item()
))
optimizer.step()
# Get into evaluation (predictive posterior) mode
#patchkwargs['is_train'] = False
gpmodel.eval()
likelihood.eval()
with torch.no_grad(), gpytorch.settings.fast_pred_var():
observed_pred = likelihood(gpmodel(Xtesthat))
sig2 = observed_pred.stddev.mul_(2)
dnn_pred = model(xtest[ | np.concatenate([idx_t[ei] for ei in experts]) | numpy.concatenate |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import numpy as np
import astropy.units as u
from astropy.table import Table
from astropy.utils import lazyproperty
from astropy.wcs.utils import pixel_to_skycoord
from .core import SegmentationImage
from ..utils.convolution import filter_data
__all__ = ['SourceProperties', 'source_properties', 'properties_table']
__doctest_requires__ = {('SourceProperties', 'SourceProperties.*',
'source_properties', 'properties_table'):
['scipy', 'skimage']}
class SourceProperties(object):
"""
Class to calculate photometry and morphological properties of a
single labeled source.
Parameters
----------
data : array_like or `~astropy.units.Quantity`
The 2D array from which to calculate the source photometry and
properties. If ``filtered_data`` is input, then it will be used
instead of ``data`` to calculate the source centroid and
morphological properties. Source photometry is always measured
from ``data``. For accurate source properties and photometry,
``data`` should be background-subtracted.
segment_img : `SegmentationImage` or array_like (int)
A 2D segmentation image, either as a `SegmentationImage` object
or an `~numpy.ndarray`, with the same shape as ``data`` where
sources are labeled by different positive integer values. A
value of zero is reserved for the background.
label : int
The label number of the source whose properties to calculate.
filtered_data : array-like or `~astropy.units.Quantity`, optional
The filtered version of the background-subtracted ``data`` from
which to calculate the source centroid and morphological
properties. The kernel used to perform the filtering should be
the same one used in defining the source segments (e.g., see
:func:`~photutils.detect_sources`). If `None`, then the
unfiltered ``data`` will be used instead. Note that
SExtractor's centroid and morphological parameters are
calculated from the filtered "detection" image.
error : array_like or `~astropy.units.Quantity`, optional
The pixel-wise Gaussian 1-sigma errors of the input ``data``.
``error`` is assumed to include *all* sources of error,
including the Poisson error of the sources (see
`~photutils.utils.calc_total_error`) . ``error`` must have the
same shape as the input ``data``. See the Notes section below
for details on the error propagation.
mask : array_like (bool), optional
A boolean mask with the same shape as ``data`` where a `True`
value indicates the corresponding element of ``data`` is masked.
Masked data are excluded from all calculations.
background : float, array_like, or `~astropy.units.Quantity`, optional
The background level that was *previously* present in the input
``data``. ``background`` may either be a scalar value or a 2D
image with the same shape as the input ``data``. Inputting the
``background`` merely allows for its properties to be measured
within each source segment. The input ``background`` does *not*
get subtracted from the input ``data``, which should already be
background-subtracted.
wcs : `~astropy.wcs.WCS`
The WCS transformation to use. If `None`, then
`~photutils.SourceProperties.icrs_centroid`,
`~photutils.SourceProperties.ra_icrs_centroid`, and
`~photutils.SourceProperties.dec_icrs_centroid` will be `None`.
Notes
-----
`SExtractor`_'s centroid and morphological parameters are always
calculated from the filtered "detection" image. The usual downside
of the filtering is the sources will be made more circular than they
actually are. If you wish to reproduce `SExtractor`_ results, then
use the ``filtered_data`` input. If ``filtered_data`` is `None`,
then the unfiltered ``data`` will be used for the source centroid
and morphological parameters.
Negative (background-subtracted) data values within the source
segment are set to zero when measuring morphological properties
based on image moments. This could occur, for example, if the
segmentation image was defined from a different image (e.g.,
different bandpass) or if the background was oversubtracted. Note
that `~photutils.SourceProperties.source_sum` includes the
contribution of negative (background-subtracted) data values.
The input ``error`` is assumed to include *all* sources of error,
including the Poisson error of the sources.
`~photutils.SourceProperties.source_sum_err` is simply the
quadrature sum of the pixel-wise total errors over the non-masked
pixels within the source segment:
.. math:: \\Delta F = \\sqrt{\\sum_{i \\in S}
\\sigma_{\\mathrm{tot}, i}^2}
where :math:`\Delta F` is
`~photutils.SourceProperties.source_sum_err`, :math:`S` are the
non-masked pixels in the source segment, and
:math:`\sigma_{\mathrm{tot}, i}` is the input ``error`` array.
Custom errors for source segments can be calculated using the
`~photutils.SourceProperties.error_cutout_ma` and
`~photutils.SourceProperties.background_cutout_ma` properties, which
are 2D `~numpy.ma.MaskedArray` cutout versions of the input
``error`` and ``background``. The mask is `True` for both pixels
outside of the source segment and masked pixels from the ``mask``
input.
.. _SExtractor: http://www.astromatic.net/software/sextractor
"""
def __init__(self, data, segment_img, label, filtered_data=None,
error=None, mask=None, background=None, wcs=None):
if not isinstance(segment_img, SegmentationImage):
segment_img = SegmentationImage(segment_img)
if segment_img.shape != data.shape:
raise ValueError('segment_img and data must have the same shape.')
if error is not None:
error = np.atleast_1d(error)
if len(error) == 1:
error = np.zeros(data.shape) + error
if error.shape != data.shape:
raise ValueError('error and data must have the same shape.')
if mask is np.ma.nomask:
mask = np.zeros(data.shape).astype(bool)
if mask is not None:
if mask.shape != data.shape:
raise ValueError('mask and data must have the same shape.')
if background is not None:
background = np.atleast_1d(background)
if len(background) == 1:
background = np.zeros(data.shape) + background
if background.shape != data.shape:
raise ValueError('background and data must have the same '
'shape.')
# data and filtered_data should be background-subtracted
# for accurate source photometry and properties
self._data = data
if filtered_data is None:
self._filtered_data = data
else:
self._filtered_data = filtered_data
self._error = error # total error; 2D array
self._background = background # 2D array
segment_img.check_label(label)
self.label = label
self._slice = segment_img.slices[label - 1]
self._segment_img = segment_img
self._mask = mask
self._wcs = wcs
def __getitem__(self, key):
return getattr(self, key, None)
def make_cutout(self, data, masked_array=False):
"""
Create a (masked) cutout array from the input ``data`` using the
minimal bounding box of the source segment.
Parameters
----------
data : array-like (2D)
The data array from which to create the masked cutout array.
``data`` must have the same shape as the segmentation image
input into `SourceProperties`.
masked_array : bool, optional
If `True` then a `~numpy.ma.MaskedArray` will be created
where the mask is `True` for both pixels outside of the
source segment and any masked pixels. If `False`, then a
`~numpy.ndarray` will be generated.
Returns
-------
result : `~numpy.ndarray` or `~numpy.ma.MaskedArray` (2D)
The 2D cutout array or masked array.
"""
if data is None:
return None
data = np.asanyarray(data)
if data.shape != self._data.shape:
raise ValueError('data must have the same shape as the '
'segmentation image input to SourceProperties')
if masked_array:
return np.ma.masked_array(data[self._slice],
mask=self._cutout_total_mask)
else:
return data[self._slice]
def to_table(self, columns=None, exclude_columns=None):
"""
Create a `~astropy.table.Table` of properties.
If ``columns`` or ``exclude_columns`` are not input, then the
`~astropy.table.Table` will include all scalar-valued
properties. Multi-dimensional properties, e.g.
`~photutils.SourceProperties.data_cutout`, can be included in
the ``columns`` input.
Parameters
----------
columns : str or list of str, optional
Names of columns, in order, to include in the output
`~astropy.table.Table`. The allowed column names are any of
the attributes of `SourceProperties`.
exclude_columns : str or list of str, optional
Names of columns to exclude from the default properties list
in the output `~astropy.table.Table`. The default
properties are those with scalar values.
Returns
-------
table : `~astropy.table.Table`
A single-row table of properties of the source.
"""
return properties_table(self, columns=columns,
exclude_columns=exclude_columns)
@lazyproperty
def _cutout_segment_bool(self):
"""
_cutout_segment_bool is `True` only for pixels in the source
segment of interest. Pixels from other sources within the
rectangular cutout are not included.
"""
return self._segment_img.data[self._slice] == self.label
@lazyproperty
def _cutout_total_mask(self):
"""
_cutout_total_mask is `True` for regions outside of the source
segment or where the input mask is `True`.
"""
mask = ~self._cutout_segment_bool
if self._mask is not None:
mask |= self._mask[self._slice]
return mask
@lazyproperty
def data_cutout(self):
"""
A 2D cutout from the (background-subtracted) data of the source
segment.
"""
return self.make_cutout(self._data, masked_array=False)
@lazyproperty
def data_cutout_ma(self):
"""
A 2D `~numpy.ma.MaskedArray` cutout from the
(background-subtracted) data, where the mask is `True` for both
pixels outside of the source segment and masked pixels.
"""
return self.make_cutout(self._data, masked_array=True)
@lazyproperty
def _data_cutout_maskzeroed_double(self):
"""
A 2D cutout from the (background-subtracted) (filtered) data,
where pixels outside of the source segment and masked pixels are
set to zero.
Invalid values (e.g. NaNs or infs) are set to zero. Negative
data values are also set to zero because negative pixels
(especially at large radii) can result in image moments that
result in negative variances. The cutout image is double
precision, which is required for scikit-image's Cython-based
moment functions.
"""
cutout = self.make_cutout(self._filtered_data, masked_array=False)
cutout = np.where(np.isfinite(cutout), cutout, 0.)
cutout = np.where(cutout > 0, cutout, 0.) # negative pixels -> 0
return (cutout * ~self._cutout_total_mask).astype(np.float64)
@lazyproperty
def error_cutout_ma(self):
"""
A 2D `~numpy.ma.MaskedArray` cutout from the input ``error``
image, where the mask is `True` for both pixels outside of the
source segment and masked pixels. If ``error`` is `None`, then
``error_cutout_ma`` is also `None`.
"""
return self.make_cutout(self._error, masked_array=True)
@lazyproperty
def background_cutout_ma(self):
"""
A 2D `~numpy.ma.MaskedArray` cutout from the input
``background``, where the mask is `True` for both pixels outside
of the source segment and masked pixels. If ``background`` is
`None`, then ``background_cutout_ma`` is also `None`.
"""
return self.make_cutout(self._background, masked_array=True)
@lazyproperty
def coords(self):
"""
A tuple of `~numpy.ndarray`\s containing the ``y`` and ``x``
pixel coordinates of the source segment. Masked pixels are not
included.
"""
yy, xx = | np.nonzero(self.data_cutout_ma) | numpy.nonzero |
import numpy as np
import ksc
from ksc.tracing.functions import math, nn
@ksc.trace
def dense(weights, x):
W, b = weights
return math.broadcast_add(math.dot(x, W), b)
@ksc.trace
def mlp(weights, x):
weights1, weights2 = weights
return dense(weights2, nn.relu(dense(weights1, x)))
def test_dense():
W = | np.random.normal(0, 1, (3, 4)) | numpy.random.normal |
import numpy as np
from matplotlib import pyplot as plt
from mpl_toolkits import mplot3d
import neural_net
import utils
def plot_lra_random_weight_losses(linear_regressor_ann, input_dim, output_dim, train1_x, train1_nb_examples, train1_y):
min_lra_loss = np.inf
random_weights = np.arange(-10,11)
fig = plt.figure()
fig.set_facecolor('w')
for i in random_weights:
linear_regressor_ann.set_weights(i.reshape((output_dim, input_dim)))
lra_output = linear_regressor_ann.forward(train1_x.reshape((train1_nb_examples, input_dim, output_dim)))
lra_loss = np.mean(linear_regressor_ann.loss(train1_y))
if lra_loss < min_lra_loss:
min_lra_loss = lra_loss
plt.scatter(i, lra_loss, color="blue")
plt.title('Loss for Linear regressor ANN')
plt.xlabel('weights')
plt.ylabel('loss')
print(f"Minimum loss:{min_lra_loss:.2f}")
plt.show()
def plot_tla_random_weight_losses(two_layer_ann, input_dim, output_dim, nb_of_hiddenunits, train1_x, train1_nb_examples, train1_y, randomize_first_layer):
random_weights = np.arange(-10,11)
fig = plt.figure(figsize=(12, 6))
ax = fig.add_subplot(111, projection='3d')
for i in random_weights:
for j in random_weights:
if randomize_first_layer:
two_layer_ann.set_weights_1(np.array([i, j]).reshape((nb_of_hiddenunits, input_dim)))
else:
two_layer_ann.set_weights_2(np.array([i, j]).reshape((output_dim, nb_of_hiddenunits)))
tla_output = two_layer_ann.forward(train1_x.reshape((train1_nb_examples, input_dim, output_dim)))
tla_loss = np.mean(two_layer_ann.loss(train1_y))
ax.scatter(i, j, tla_loss, color="blue")
plt.title('Loss for Two Layer ANN')
if randomize_first_layer:
ax.set_xlabel('weights_1')
ax.set_ylabel('weights_1')
else:
ax.set_xlabel('weights_2')
ax.set_ylabel('weights_2')
ax.set_zlabel('loss')
plt.show()
def train_lra(hyperparams, linear_regressor_ann, train_x, train_y, input_dim, output_dim, train_nb_examples, train_uniform_x_samples, label="train"):
learning_rate, nb_of_epochs, batch_size = hyperparams
fig = plt.figure()
min_lra_loss = np.inf
for epoch in range(nb_of_epochs):
for i in range(train_nb_examples//batch_size):
linear_regressor_ann.forward(train_x[i*batch_size:i*batch_size+batch_size].reshape((batch_size, input_dim, output_dim)))
linear_regressor_ann.loss(train_y[i*batch_size:i*batch_size+batch_size])
linear_regressor_ann.backward(learning_rate)
lra_output = linear_regressor_ann.forward(train_x.reshape((train_nb_examples, input_dim, output_dim)))
lra_loss = np.mean(linear_regressor_ann.loss(train_y))
print(f"Epoch:{epoch+1}, Linear regressor ANN loss:{lra_loss:.4f}")
plt.scatter(train_x, train_y)
lra_output = linear_regressor_ann.forward(train_uniform_x_samples.reshape((train_nb_examples, input_dim, output_dim)))
plt.plot(train_uniform_x_samples, lra_output.reshape((train_nb_examples, 1)), linewidth=3)
plt.title(f'Linear regressor ANN, Epoch:{epoch+1}, Training Set, Loss:{lra_loss:.4f}')
plt.xlabel('x')
plt.ylabel('y')
plt.savefig(f'gif/lra_{epoch+1:03d}.png')
plt.close()
if min_lra_loss - lra_loss > 1e-5:
min_lra_loss = lra_loss
else:
print("Stopped training")
plt.scatter(train_x, train_y)
lra_output = linear_regressor_ann.forward(train_uniform_x_samples.reshape((train_nb_examples, input_dim, output_dim)))
plt.plot(train_uniform_x_samples, lra_output.reshape((train_nb_examples, 1)), linewidth=3)
plt.title(f'Linear regressor ANN, Epoch:{epoch+1}, Training Set, Loss:{lra_loss:.4f}')
plt.xlabel('x')
plt.ylabel('y')
plt.savefig(f'output/lra_{label}.png')
plt.close()
break
def evaluate_lra(linear_regressor_ann, x, nb_examples, input_dim, output_dim, y, mode_str):
lra_output = linear_regressor_ann.forward(x.reshape((nb_examples, input_dim, output_dim)))
lra_loss = np.mean(linear_regressor_ann.loss(y))
lra_loss_std = np.std(linear_regressor_ann.loss(y))
print(f"Linear regressor ANN, {mode_str} set loss:{lra_loss:.4f}, std:{lra_loss_std:.4f}")
return lra_loss
def plot_lra_evaluation(linear_regressor_ann, x, input_dim, output_dim, y, mode_str, lra_loss, train_uniform_x_samples, train_nb_examples, label):
fig = plt.figure()
fig.set_facecolor('w')
plt.scatter(x, y)
lra_output = linear_regressor_ann.forward(train_uniform_x_samples.reshape((train_nb_examples, input_dim, output_dim)))
plt.plot(train_uniform_x_samples, lra_output.reshape((train_nb_examples, 1)), linewidth=3)
plt.title(f'Linear regressor ANN, {mode_str} Set, Loss:{np.mean(lra_loss):.4f}')
plt.xlabel('x')
plt.ylabel('y')
plt.savefig(f'output/lra_{label}.png')
plt.show()
def train_tla(data_ix, train_x, train_y, input_dim, output_dim, train_nb_examples, train_uniform_x_samples):
if data_ix == 1:
lr_config = {2: 8e-3, 4: 1e-2, 8: 1e-2, 16: 5e-3}
epoch_config = {2: 5500, 4: 8000, 8: 7500, 16: 9000}
batchsize_config = {2: 2, 4: 2, 8: 2, 16: 3}
activation_config = {2: "sigmoid", 4: "sigmoid", 8: "sigmoid", 16: "sigmoid"}
loss_config = {2: "mse", 4: "mse", 8: "mse", 16: "mse"}
momentum_config = {2: 0.75, 4: 0.75, 8: 0.9, 16: 0.6}
stop_loss_config = {2: 0.05795, 4: 0.02025, 8: 0.02045, 16: 0.02065}
plot_color = {2: "red", 4: "cyan", 8: "magenta", 16: "black"}
elif data_ix == 2:
lr_config = {2: 9e-3, 4: 9e-3, 8: 1e-2, 16: 9e-3}
epoch_config = {2: 7500, 4: 6500, 8: 8000, 16: 30000}
batchsize_config = {2: 3, 4: 3, 8: 2, 16: 2}
activation_config = {2: "sigmoid", 4: "sigmoid", 8: "sigmoid", 16: "sigmoid"}
loss_config = {2: "mse", 4: "mse", 8: "mse", 16: "mse"}
momentum_config = {2: 0.4, 4: 0.4, 8: 0.5, 16: 0.3}
stop_loss_config = {2: 0.28005, 4: 0.14305, 8: 0.05975, 16: 0.05915}
plot_color = {2: "red", 4: "cyan", 8: "magenta", 16: "black"}
trained_nets = []
anim_files = []
for nb_of_hiddenunits in (2, 4, 8, 16):
np.random.seed(550)
learning_rate = lr_config[nb_of_hiddenunits]
nb_of_epochs = epoch_config[nb_of_hiddenunits]
batch_size = batchsize_config[nb_of_hiddenunits]
two_layer_ann = neural_net.TwoLayerANN(nb_of_hiddenunits,
activation_function=activation_config[nb_of_hiddenunits],
loss_function=loss_config[nb_of_hiddenunits],
use_momentum=True, momentum_factor=momentum_config[nb_of_hiddenunits])
fig = plt.figure()
print(f"Training two layer ANN with {nb_of_hiddenunits} units")
for epoch in range(nb_of_epochs):
for i in range(train_nb_examples//batch_size):
two_layer_ann.forward(train_x[i*batch_size:i*batch_size+batch_size].reshape((batch_size, input_dim, output_dim)))
two_layer_ann.loss(train_y[i*batch_size:i*batch_size+batch_size])
two_layer_ann.backward(learning_rate)
tla_output = two_layer_ann.forward(train_x.reshape((train_nb_examples, input_dim, output_dim)))
tla_loss = np.mean(two_layer_ann.loss(train_y))
if (data_ix == 1 and (epoch == 0 or (epoch+1) % 500 == 0)) or (data_ix == 2 and epoch == 0 or (epoch+1) % (1500 if nb_of_hiddenunits == 16 else 500) == 0):
print(f"Epoch:{epoch+1}, Two layer ANN loss:{tla_loss:.4f}")
plt.scatter(train_x, train_y)
tla_output = two_layer_ann.forward(train_uniform_x_samples.reshape((train_nb_examples, input_dim, output_dim)))
plt.plot(train_uniform_x_samples, tla_output.reshape((train_nb_examples, 1)),
color=plot_color[nb_of_hiddenunits], linewidth=3)
plt.title(f'Two layer ANN ({nb_of_hiddenunits} units), Epoch:{epoch+1}, Training Set, Loss:{tla_loss:.4f}')
plt.xlabel('x')
plt.ylabel('y')
plt.savefig(f'gif/tla_{nb_of_hiddenunits}_{epoch+1:05d}.png')
plt.close()
if tla_loss < stop_loss_config[nb_of_hiddenunits]:
print(f"Stopped training, Epoch:{epoch+1}, Two layer ANN loss:{tla_loss:.4f}")
plt.scatter(train_x, train_y)
tla_output = two_layer_ann.forward(train_uniform_x_samples.reshape((train_nb_examples, input_dim, output_dim)))
plt.plot(train_uniform_x_samples, tla_output.reshape((train_nb_examples, 1)),
color=plot_color[nb_of_hiddenunits], linewidth=3)
plt.title(f'Two layer ANN ({nb_of_hiddenunits} units), Epoch:{epoch+1}, Training Set, Loss:{tla_loss:.4f}')
plt.xlabel('x')
plt.ylabel('y')
plt.savefig(f'output/tla_{nb_of_hiddenunits}_train{"_2" if data_ix == 2 else ""}.png')
plt.close()
break
anim_file = f'gif/tla_{nb_of_hiddenunits}_training{"_2" if data_ix == 2 else ""}.gif'
utils.create_animation(anim_file, f'gif/tla_{nb_of_hiddenunits}_*.png', fps=4 if data_ix == 1 else 8)
trained_nets.append(two_layer_ann)
anim_files.append(anim_file)
return trained_nets, anim_files
def evaluate_tla(trained_nets, train_x, train_y, test_x, test_y, train_nb_examples, test_nb_examples, train_uniform_x_samples, input_dim, output_dim, label=""):
ann_hidden_units = [2, 4, 8, 16]
plot_color = {2: "red", 4: "cyan", 8: "magenta", 16: "black"}
for i in range(4):
two_layer_ann = trained_nets[i]
tla_output = two_layer_ann.forward(train_x.reshape((train_nb_examples, input_dim, output_dim)))
tla_loss = np.mean(two_layer_ann.loss(train_y))
tla_loss_std = np.std(two_layer_ann.loss(train_y))
print(f"Two layer ANN, {ann_hidden_units[i]} units, training set loss:{tla_loss:.4f}, std:{tla_loss_std:.4f}")
fig = plt.figure()
fig.set_facecolor('w')
plt.scatter(train_x, train_y)
tla_output = two_layer_ann.forward(train_uniform_x_samples.reshape((train_nb_examples, input_dim, output_dim)))
plt.plot(train_uniform_x_samples, tla_output.reshape((train_nb_examples, 1)),
color=plot_color[ann_hidden_units[i]], linewidth=3)
plt.title(f'Two layer ANN, {ann_hidden_units[i]} units, Training Set, Loss:{np.mean(tla_loss):.4f}')
plt.xlabel('x')
plt.ylabel('y')
plt.savefig(f'output/tla_{ann_hidden_units[i]}_train_curve{label}.png')
plt.show()
tla_output = two_layer_ann.forward(test_x.reshape((test_nb_examples, input_dim, output_dim)))
tla_loss = np.mean(two_layer_ann.loss(test_y))
tla_loss_std = np.std(two_layer_ann.loss(test_y))
print(f"Two layer ANN, {ann_hidden_units[i]} units, test set loss:{tla_loss:.4f}, std:{tla_loss_std:.4f}")
fig = plt.figure()
fig.set_facecolor('w')
plt.scatter(test_x, test_y)
tla_output = two_layer_ann.forward(train_uniform_x_samples.reshape((train_nb_examples, input_dim, output_dim)))
plt.plot(train_uniform_x_samples, tla_output.reshape((train_nb_examples, 1)),
color=plot_color[ann_hidden_units[i]], linewidth=3)
plt.title(f'Two layer ANN, {ann_hidden_units[i]} units, Test Set, Loss:{ | np.mean(tla_loss) | numpy.mean |
""" Model Description """
"-----------------------------------------------------------------------------"
"""This model is a half cell model of of PEM fuel cell cathode. The model uses
a core-shell type catalyst layer geometry. The core-shell geometry involves a
Pt-covered carbon core covered with a thin shell of Nafion."""
""" Model Assumptions """
"-----------------------------------------------------------------------------"
" 1.) Gas properties are constant -> parameters"
" 2.) Temperature is constant -> parameter"
" 3.) Variables are Phi_dl [V] -> only difference important,"
" Nafion/gas species mass densities [kg/m^3], and surface coverages [-]"
" 4.) The proton density in Nafion is constant due to its structure"
" 5.) The C/Pt phases at every node have the same potential"
" 6.) The ionic conductivity of Nafion is a function of its RH, temperature,"
" and thickness. It can be modeled via various sub models described in"
" detail in the pemfc_property_funcs file."
# Note: Interpolations can only be done within the ranges given by the above
# mentioned paper [1]; therefore, this model only works for properties of
# Nafion RH, temperature, and thickness of 20-95 %, 30-60 C, and 4-300 nm
# respectively. Values outside of these ranges with result in an unknown
# value of ionic conductivity.
# Note: Another valuable paper for model inputs is "An improved two-dimensional
# agglomerate cathode model to study the influence of catalyst layer
# structural parameters" by Sun, Peppley, and Karan from 2005 [2]. This
# includes GDL and CL thickness, porosities, and more.
# Note: Permeability values taken as scaled values from Zenyuk, Das, Weber
# paper that reported saturated values for GDL and CL at reported
# porosities. Title "Understanding Impacts of Catalyst Layer Thickness
# on Fuel Cell Performance via Mathematical Modeling" (2016) [3].
# Note: Oxygen diffusion through Nafion was taken from Sethuraman et al. paper
# and scaled by water volume fraction as a function of t_naf. Titled
# "Measuring Oxygen, Carbon Monoxide, Hydrogen Sulfide Diffusion
# Coefficients and Solubility in Nafion Membranes" (2009) [4].
# Note: Knowledge of O2 diffusion scaling with water volume fraction used to
# scale values. Interpolations from DeCaluwe et al. taken to evaluate
# water fraction as function of t_naf. Titled "Structure-property
# relationships at Nafion thin-film interfaces:..." (2018) [5]
# Note: Nafion conducitivity treatment as bulk material was added as an option.
# This method assumes the thin shell has the same conductivity as bulk
# material and that there are no confinement or microstructure effects
# when it gets too thin. The relationship is taken from Yadav et al. in
# their 2012 publication of "Analysis of EIS Technique and Nafion 117
# Conductivity as a Function of Temperature and Relative Humidity" [6]
# Note: Low Pt loading data and modeling results are present with operating
# conditions in "Modeling and Experimental Validation of Pt Loading and
# Electrode Composition Efects in PEM Fuel Cells" by L. Hao et. al. [7]
# This paper was published in 2015 and makes it recent enough to validate
# against.
# Note: In order to validate the model, results for the full cell are needed.
# The anode was added by determining the steady-state potential via
# Gibb's free energy correlations. The PEM was simply modeled as a V=IR
# relationship where the resistance (Ohm*cm^2) was taken from [8] (2002).
""" Import needed modules """
"-----------------------------------------------------------------------------"
import os, time
import numpy as np
import cantera as ct
""" User Input Parameters """
"-----------------------------------------------------------------------------"
" External currents "
i_OCV = 0. # 0 [A/cm^2] -> or single run if != 0
i_ext0 = np.linspace(1e-3,0.1,10) # currents in kinetic region [A/cm^2]
i_ext1 = | np.linspace(2e-1,1.5,10) | numpy.linspace |
import os
import scipy.misc
import numpy as np
def get_data(pardir, max_size=None, debug=False):
file_list = os.listdir(pardir)
if max_size is None:
max_size = len(file_list)
x_data = list()
y_data = list()
for f in file_list[:max_size]:
data_path = os.path.join(pardir, f)
im = scipy.misc.imread(data_path, flatten=False, mode='RGB')
ims = scipy.misc.imresize(im,(60, 160, 3))
x_data.append(ims)
num = f.split('.')[0]
N = len(num)
y = np.zeros((N, 10))
for n, i in enumerate(num):
y[n][int(i)] = 1
y_data.append(y)
x_data = np.array(x_data)
y_data = | np.array(y_data) | numpy.array |
import sklearn
from .base import ExcursionModel
from .utils import get_kernel
import numpy as np
class SKLearnGP(ExcursionModel, sklearn.gaussian_process.GaussianProcessRegressor):
"""This is a guassian process used to compute the excursion model. Most if not all excursion models will be a
gaussian process.
"""
def __init__(self, ndim, kernel_type='const_rbf', alpha=10**-7):
kernel = get_kernel(ndim, kernel_type)
self.gp_params = {
'alpha': alpha,
'n_restarts_optimizer': 10,
'random_state': 1234
}
super(SKLearnGP, self).__init__(kernel=kernel, **self.gp_params)
self.epsilon = 0.0
def update_model(self, x, y):
"""
Updates training data (does not re-fit model hyper-parameters).
"""
inputs = x
targets = y if x.shape[1] != 1 else y.flatten()
if self.epsilon > 0.0:
# Add noise if the likelihood had included epsilon>0 in algo options
raise NotImplementedError("The current package only supports noiseless models for sklearn models")
if not hasattr(self, "X_train_") and not hasattr(self, "y_train_"): # No data; add it
self.X_train_ = inputs
self.y_train_ = targets.ravel()
else:
self.X_train_ = | np.concatenate((self.X_train_, inputs), axis=0) | numpy.concatenate |
import cv2
import imutils
import numpy as np
from shared.sort_cont import sort_cont
from skimage import measure
from skimage.filters import threshold_local
def segment_chars(plate_img, fixed_width):
"""
extract Value channel from the HSV format of image and apply adaptive thresholding
to reveal the characters on the license plate
"""
V = cv2.split(cv2.cvtColor(plate_img, cv2.COLOR_BGR2HSV))[2]
T = threshold_local(V, 29, offset=15, method='gaussian')
thresh = (V > T).astype('uint8') * 255
thresh = cv2.bitwise_not(thresh)
# resize the license plate region to a canonical size
plate_img = imutils.resize(plate_img, width=fixed_width)
thresh = imutils.resize(thresh, width=fixed_width)
bgr_thresh = cv2.cvtColor(thresh, cv2.COLOR_GRAY2BGR)
# perform a connected components analysis and initialize the mask to store the locations
# of the character candidates
labels = measure.label(thresh, connectivity=2, background=0)
charCandidates = | np.zeros(thresh.shape, dtype='uint8') | numpy.zeros |
import numpy as np
from scipy.integrate import quad
from scipy.special import binom
from scipy.special import gamma
from scipy.special import gammainc
from scipy.stats import binom
from numba import njit
def get_thetami_mat(mmax, beta, f=lambda m: 1, K=1, alpha=2, tmin=1, T=np.inf):
#uses an exponential dose distribution
#thetami = thetam(i/m-1)
thetami = np.zeros((mmax+1,mmax+1))
Z = (tmin**(-alpha)-T**(-alpha))/alpha
for m in range(2,mmax+1):
for i in range(1,m):
tau_c = K*(m-1)/(beta*i*f(m))
thetami[m,i] += np.exp(-tau_c)-np.exp(-tau_c/T)*T**(-alpha)
thetami[m,i] += tau_c**(-alpha)*gamma(alpha+1)*(\
gammainc(alpha+1,tau_c)-
gammainc(alpha+1,tau_c/T))
return thetami/(Z*alpha)
@njit
def get_binom(N,p):
if N > 0:
pmf = | np.zeros(N+1) | numpy.zeros |
from dataclasses import dataclass
from typing import Sequence
import sympy
import numpy as np
from numpy import zeros, diag, eye, ones, array
from numpy.linalg import cholesky
from numpy.random import multivariate_normal
@dataclass
class SimulationParams:
ymvars: Sequence[sympy.Symbol] # manifest endogenous variables
xmean_true: Sequence[float] # mean of exogeneous data
sigx_theo: float # true scalar error variance of xvars
sigym_theo: float # true scalar error variance of ymvars
rho: float # true correlation within y and within x vars
tau: int # nr. of simulated observations
def simulate(m, sim_params):
"""simulate exogeneous x and corresponding endogeneous y data for example equations"""
# dimensions
ndim = len(m.yvars)
mdim = len(m.xvars)
selvec = zeros(ndim)
selvec[[list(m.yvars).index(el) for el in sim_params.ymvars]] = 1
selmat = diag(selvec)
selvecc = selvec.reshape(ndim, 1)
fym = eye(ndim)[diag(selmat) == 1]
# compute theoretical RAM covariance matrices # ToDo: needed? # yyy
sigmax_theo = sim_params.sigx_theo * (
sim_params.rho * ones((mdim, mdim)) + (1 - sim_params.rho) * eye(mdim)
)
sigmau_theo = sim_params.sigym_theo * (
sim_params.rho * selvecc @ selvecc.T + (1 - sim_params.rho) * selmat
)
# symmetrize covariance matrices, such that numerically well conditioned
sigmax_theo = (sigmax_theo + sigmax_theo.T) / 2
sigmau_theo = (sigmau_theo + sigmau_theo.T) / 2
# simulate x data
# use cholesky to avoid numerical random normal posdef problem, old:
# xdat = multivariate_normal(sim_params.xmean_true, sigmax_theo, sim_params.tau).T
xdat = multivariate_normal(zeros(mdim), eye(mdim), sim_params.tau).T
xdat = array(sim_params.xmean_true).reshape(mdim, 1) + cholesky(sigmax_theo) @ xdat
# ymdat from yhat with enndogenous errors
yhat = m.compute(xdat)
ymdat = fym @ (
yhat + multivariate_normal(zeros(ndim), sigmau_theo, sim_params.tau).T
)
# delete nan columns
colind = ~np.any( | np.isnan(ymdat) | numpy.isnan |
import tensorflow as tf
from os import path
import numpy as np
from scipy import misc
from styx_msgs.msg import TrafficLight
import cv2
import rospy
import tensorflow as tf
class CarlaModel(object):
def __init__(self, model_checkpoint):
self.sess = None
self.checkpoint = model_checkpoint
self.prob_thr = 0.90
self.TRAFFIC_LIGHT_CLASS = 10
self.image_no = 10000
tf.reset_default_graph()
def predict(self, img):
if self.sess == None:
gd = tf.GraphDef()
gd.ParseFromString(tf.gfile.GFile(self.checkpoint, "rb").read())
tf.import_graph_def(gd, name="object_detection_api")
self.sess = tf.Session()
g = tf.get_default_graph()
self.image = g.get_tensor_by_name("object_detection_api/image_tensor:0")
self.boxes = g.get_tensor_by_name("object_detection_api/detection_boxes:0")
self.scores = g.get_tensor_by_name("object_detection_api/detection_scores:0")
self.classes = g.get_tensor_by_name("object_detection_api/detection_classes:0")
img_h, img_w = img.shape[:2]
self.image_no = self.image_no+1
cv2.imwrite("full_"+str(self.image_no)+".png", img)
for h0 in [img_h//3, (img_h//3)-150]:
for w0 in [0, img_w//3, img_w*2//3]:
grid = img[h0:h0+img_h//3+50, w0:w0+img_w//3, :] # grid
pred_boxes, pred_scores, pred_classes = self.sess.run([self.boxes, self.scores, self.classes],
feed_dict={self.image: | np.expand_dims(grid, axis=0) | numpy.expand_dims |
#!/usr/bin/env python
"""Very simple SVG rasterizer
NOT SUPPORTED:
- markers
- symbol
- color-interpolation and filter-color-interpolation attributes
PARTIALLY SUPPORTED:
- text (textPath is not supported)
- fonts
- font resolution logic is very basic
- style font attribute is not parsed only font-* attrs are supported
KNOWN PROBLEMS:
- multiple pathes over going over the same pixels are breakin antialising
(would draw all pixels with multiplied AA coverage (clamped)).
"""
from __future__ import annotations
import builtins
import gzip
import io
import math
import numpy as np
import numpy.typing as npt
import os
import re
import struct
import sys
import textwrap
import time
import warnings
import xml.etree.ElementTree as etree
import zlib
from functools import reduce, partial
from typing import Any, Callable, NamedTuple, List, Tuple, Optional, Dict
EPSILON = sys.float_info.epsilon
FLOAT_RE = re.compile(r"[-+]?(?:(?:\d*\.\d+)|(?:\d+\.?))(?:[Ee][+-]?\d+)?")
FLOAT = np.float64
# ------------------------------------------------------------------------------
# Layer
# ------------------------------------------------------------------------------
COMPOSE_OVER = 0
COMPOSE_OUT = 1
COMPOSE_IN = 2
COMPOSE_ATOP = 3
COMPOSE_XOR = 4
COMPOSE_PRE_ALPHA = {COMPOSE_OVER, COMPOSE_OUT, COMPOSE_IN, COMPOSE_ATOP, COMPOSE_XOR}
BBox = Tuple[float, float, float, float]
FNDArray = npt.NDArray[FLOAT]
class Layer(NamedTuple):
image: np.ndarray[Tuple[int, int, int], FLOAT]
offset: Tuple[int, int]
pre_alpha: bool
linear_rgb: bool
@property
def x(self) -> int:
return self.offset[0]
@property
def y(self) -> int:
return self.offset[1]
@property
def width(self) -> int:
return self.image.shape[1]
@property
def height(self) -> int:
return self.image.shape[0]
@property
def channels(self) -> int:
return self.image.shape[2]
@property
def bbox(self) -> BBox:
return (*self.offset, *self.image.shape[:2])
def translate(self, x: int, y: int) -> Layer:
offset = (self.x + x, self.y + y)
return Layer(self.image, offset, self.pre_alpha, self.linear_rgb)
def color_matrix(self, matrix: np.ndarray) -> Layer:
"""Apply color matrix transformation"""
if not isinstance(matrix, np.ndarray) or matrix.shape != (4, 5):
raise ValueError("expected 4x5 matrix")
layer = self.convert(pre_alpha=False, linear_rgb=True)
M = matrix[:, :4]
B = matrix[:, 4]
image = np.matmul(layer.image, M.T) + B
np.clip(image, 0, 1, out=image)
return Layer(image, layer.offset, pre_alpha=False, linear_rgb=True)
def convolve(self, kernel: np.ndarray) -> Layer:
"""Convlve layer"""
try:
from scipy.signal import convolve
layer = self.convert(pre_alpha=False, linear_rgb=True)
kw, kh = kernel.shape
image = convolve(layer.image, kernel[..., None])
x, y = int(layer.x - kw / 2), int(layer.y - kh / 2)
return Layer(image, (x, y), pre_alpha=False, linear_rgb=True)
except ImportError:
warnings.warn("Layer::convolve requires `scipy`")
return self
def morphology(self, x: int, y: int, method: str) -> Layer:
"""Morphology filter operation
Morphology is essentially {min|max} pooling with [1, 1] stride
"""
layer = self.convert(pre_alpha=True, linear_rgb=True)
image = pooling(layer.image, ksize=(x, y), stride=(1, 1), method=method)
return Layer(image, layer.offset, pre_alpha=True, linear_rgb=True)
def convert(self, pre_alpha=None, linear_rgb=None) -> Layer:
"""Convert image if needed to specified alpha and colorspace"""
pre_alpha = self.pre_alpha if pre_alpha is None else pre_alpha
linear_rgb = self.linear_rgb if linear_rgb is None else linear_rgb
if self.channels == 1:
# single channel value assumed to be alpha
return Layer(self.image, self.offset, pre_alpha, linear_rgb)
in_image, out_offset, out_pre_alpha, out_linear_rgb = self
out_image = None
if out_linear_rgb != linear_rgb:
out_image = in_image.copy()
# convert to straight alpha first if needed
if out_pre_alpha:
out_image = color_pre_to_straight_alpha(out_image)
out_pre_alpha = False
if linear_rgb:
out_image = color_srgb_to_linear(out_image)
else:
out_image = color_linear_to_srgb(out_image)
out_linear_rgb = linear_rgb
if out_pre_alpha != pre_alpha:
if out_image is None:
out_image = in_image.copy()
if pre_alpha:
out_image = color_straight_to_pre_alpha(out_image)
else:
out_image = color_pre_to_straight_alpha(out_image)
out_pre_alpha = pre_alpha
if out_image is None:
return self
return Layer(out_image, out_offset, out_pre_alpha, out_linear_rgb)
def background(self, color: np.ndarray) -> Layer:
layer = self.convert(pre_alpha=True, linear_rgb=True)
image = canvas_compose(COMPOSE_OVER, color[None, None, ...], layer.image)
return Layer(image, layer.offset, pre_alpha=True, linear_rgb=True)
def opacity(self, opacity: float, linear_rgb=False) -> Layer:
"""Apply additinal opacity"""
layer = self.convert(pre_alpha=True, linear_rgb=linear_rgb)
image = layer.image * opacity
return Layer(image, layer.offset, pre_alpha=True, linear_rgb=linear_rgb)
@staticmethod
def compose(layers: List[Layer], method=COMPOSE_OVER, linear_rgb=False) -> Optional[Layer]:
"""Compose multiple layers into one with specified `method`
Composition in linear RGB is correct one but SVG composes in sRGB
by default. Only filter is composing in linear RGB by default.
"""
if not layers:
return None
elif len(layers) == 1:
return layers[0]
images = []
pre_alpha = method in COMPOSE_PRE_ALPHA
for layer in layers:
layer = layer.convert(pre_alpha=pre_alpha, linear_rgb=linear_rgb)
images.append((layer.image, layer.offset))
#print([i[0].shape for i in images])
blend = partial(canvas_compose, method)
if method == COMPOSE_IN:
result = canvas_merge_intersect(images, blend)
elif method == COMPOSE_OVER:
start = time.time()
result = canvas_merge_union(images, full=False, blend=blend)
print("render from image,offset pair take:",time.time()-start)
else:
result = canvas_merge_union(images, full=True, blend=blend)
if result is None:
return None
image, offset = result
return Layer(image, offset, pre_alpha=pre_alpha, linear_rgb=linear_rgb)
def write_png(self, output=None):
if self.channels != 4:
raise ValueError("Only RGBA layers are supported")
layer = self.convert(pre_alpha=False, linear_rgb=False)
return canvas_to_png(layer.image, output)
def __repr__(self):
return "Layer(x={}, y={}, w={}, h={}, pre_alpha={}, linear_rgb={})".format(
self.x, self.y, self.width, self.height, self.pre_alpha, self.linear_rgb
)
def show(self, format=None):
"""Show layer on terminal if `imshow` if available
NOTE: used only for debugging
"""
try:
from imshow import show
layer = self.convert(pre_alpha=False, linear_rgb=False)
show(layer.image, format=format)
except ImportError:
warnings.warn("to be able to show layer on terminal imshow is required")
def canvas_create(width, height, bg=None):
"""Create canvas of a specified size
Returns (canvas, transform) tuple:
canvas - float64 ndarray of (height, width, 4) shape
transform - transform from (x, y) to canvas pixel coordinates
"""
if bg is None:
canvas = np.zeros((height, width, 4), dtype=FLOAT)
else:
canvas = np.broadcast_to(bg, (height, width, 4)).copy()
return canvas, Transform().matrix(0, 1, 0, 1, 0, 0)
def canvas_to_png(canvas, output=None):
"""Convert (height, width, rgba{float64}) to PNG"""
def png_pack(output, tag, data):
checksum = 0xFFFFFFFF & zlib.crc32(data, zlib.crc32(tag))
output.write(struct.pack("!I", len(data)))
output.write(tag)
output.write(data)
output.write(struct.pack("!I", checksum))
height, width, _ = canvas.shape
data = io.BytesIO()
comp = zlib.compressobj(level=9)
for row in np.round(canvas * 255.0).astype(np.uint8):
data.write(comp.compress(b"\x00"))
data.write(comp.compress(row.tobytes()))
data.write(comp.flush())
output = io.BytesIO() if output is None else output
output.write(b"\x89PNG\r\n\x1a\n")
png_pack(output, b"IHDR", struct.pack("!2I5B", width, height, 8, 6, 0, 0, 0)),
png_pack(output, b"IDAT", data.getvalue()),
png_pack(output, b"IEND", b"")
return output
def canvas_compose(mode, dst, src):
"""Compose two alpha premultiplied images
https://ciechanow.ski/alpha-compositing/
http://ssp.impulsetrain.com/porterduff.html
"""
src_a = src[..., -1:] if len(src.shape) == 3 else src
dst_a = dst[..., -1:] if len(dst.shape) == 3 else dst
if mode == COMPOSE_OVER:
return src + dst * (1 - src_a)
elif mode == COMPOSE_OUT:
return src * (1 - dst_a)
elif mode == COMPOSE_IN:
return src * dst_a
elif mode == COMPOSE_ATOP:
return src * dst_a + dst * (1 - src_a)
elif mode == COMPOSE_XOR:
return src * (1 - dst_a) + dst * (1 - src_a)
elif isinstance(mode, tuple) and len(mode) == 4:
k1, k2, k3, k4 = mode
return (k1 * src * dst + k2 * src + k3 * dst + k4).clip(0, 1)
raise ValueError(f"invalid compose mode: {mode}")
canvas_compose_over = partial(canvas_compose, COMPOSE_OVER)
def canvas_merge_at(base, overlay, offset, blend=canvas_compose_over):
"""Alpha blend `overlay` on top of `base` at offset coordintate
Updates `base` with `overlay` in place.
"""
x, y = offset
b_h, b_w = base.shape[:2]
o_h, o_w = overlay.shape[:2]
clip = lambda v, l, h: l if v < l else h if v > h else v
b_x_low, b_x_high = clip(x, 0, b_h), clip(x + o_h, 0, b_h)
b_y_low, b_y_high = clip(y, 0, b_w), clip(y + o_w, 0, b_w)
effected = base[b_x_low:b_x_high, b_y_low:b_y_high]
if effected.size == 0:
return
o_x_low, o_x_high = clip(-x, 0, o_h), clip(b_h - x, 0, o_h)
o_y_low, o_y_high = clip(-y, 0, o_w), clip(b_w - y, 0, o_w)
overlay = overlay[o_x_low:o_x_high, o_y_low:o_y_high]
if overlay.size == 0:
return
effected[...] = blend(effected, overlay).clip(0, 1)
return base
def canvas_merge_union(layers, full=True, blend=canvas_compose_over):
"""Blend multiple `layers` into single large enough image"""
if not layers:
raise ValueError("can not blend zero layers")
elif len(layers) == 1:
return layers[0]
min_x, min_y, max_x, max_y = None, None, None, None
for image, offset in layers:
x, y = offset
w, h = image.shape[:2]
if min_x is None:
min_x, min_y = x, y
max_x, max_y = x + w, y + h
else:
min_x, min_y = min(min_x, x), min(min_y, y)
max_x, max_y = max(max_x, x + w), max(max_y, y + h)
width, height = max_x - min_x, max_y - min_y
if full:
output = None
for image, offset in layers:
x, y = offset
w, h = image.shape[:2]
ox, oy = x - min_x, y - min_y
image_full = np.zeros((width, height, 4), dtype=FLOAT)
image_full[ox : ox + w, oy : oy + h] = image
if output is None:
output = image_full
else:
output = blend(output, image_full)
else:
# this is optimization for method `over` blending
output = np.zeros((max_x - min_x, max_y - min_y, 4), dtype=FLOAT)
for index, (image, offset) in enumerate(layers):
x, y = offset
w, h = image.shape[:2]
ox, oy = x - min_x, y - min_y
effected = output[ox : ox + w, oy : oy + h]
if index == 0:
effected[...] = image
else:
effected[...] = blend(effected, image)
return output, (min_x, min_y)
def canvas_merge_intersect(layers, blend=canvas_compose_over):
"""Blend multiple `layers` into single image coverd by all layers"""
if not layers:
raise ValueError("can not blend zero layers")
elif len(layers) == 1:
return layers[0]
min_x, min_y, max_x, max_y = None, None, None, None
for layer, offset in layers:
x, y = offset
w, h = layer.shape[:2]
if min_x is None:
min_x, min_y = x, y
max_x, max_y = x + w, y + h
else:
min_x, min_y = max(min_x, x), max(min_y, y)
max_x, max_y = min(max_x, x + w), min(max_y, y + h)
if min_x >= max_x or min_y >= max_y:
return None # empty intersection
(first, (fx, fy)), *rest = layers
output = first[min_x - fx : max_x - fx, min_y - fy : max_y - fy]
w, h, c = output.shape
if c == 1:
output = np.broadcast_to(output, (w, h, 4))
output = output.copy()
for layer, offset in rest:
x, y = offset
output[...] = blend(output, layer[min_x - x : max_x - x, min_y - y : max_y - y])
return output, (min_x, min_y)
def pooling(mat, ksize, stride=None, method="max", pad=False):
"""Overlapping pooling on 2D or 3D data.
<mat>: ndarray, input array to pool.
<ksize>: tuple of 2, kernel size in (ky, kx).
<stride>: tuple of 2 or None, stride of pooling window.
If None, same as <ksize> (non-overlapping pooling).
<method>: str, 'max for max-pooling,
'mean' for mean-pooling.
<pad>: bool, pad <mat> or not. If no pad, output has size
(n-f)//s+1, n being <mat> size, f being kernel size, s stride.
if pad, output has size ceil(n/s).
Return <result>: pooled matrix.
"""
m, n = mat.shape[:2]
ky, kx = ksize
if stride is None:
stride = (ky, kx)
sy, sx = stride
if pad:
nx = int(np.ceil(n / float(sx)))
ny = int(np.ceil(m / float(sy)))
size = ((ny - 1) * sy + ky, (nx - 1) * sx + kx) + mat.shape[2:]
mat_pad = np.full(size, np.nan)
mat_pad[:m, :n, ...] = mat
else:
mat_pad = mat[: (m - ky) // sy * sy + ky, : (n - kx) // sx * sx + kx, ...]
# Get a strided sub-matrices view of an ndarray.
s0, s1 = mat_pad.strides[:2]
m1, n1 = mat_pad.shape[:2]
m2, n2 = ksize
view_shape = (1 + (m1 - m2) // stride[0], 1 + (n1 - n2) // stride[1], m2, n2) + mat_pad.shape[
2:
]
strides = (stride[0] * s0, stride[1] * s1, s0, s1) + mat_pad.strides[2:]
view = np.lib.stride_tricks.as_strided(mat_pad, view_shape, strides=strides)
if method == "max":
result = np.nanmax(view, axis=(2, 3))
elif method == "min":
result = np.nanmin(view, axis=(2, 3))
elif method == "mean":
result = np.nanmean(view, axis=(2, 3))
else:
raise ValueError(f"invalid poll method: {method}")
return result
def color_pre_to_straight_alpha(rgba):
"""Convert from premultiplied alpha inplace"""
rgb = rgba[..., :-1]
alpha = rgba[..., -1:]
np.divide(rgb, alpha, out=rgb, where=alpha > 0.0001)
np.clip(rgba, 0, 1, out=rgba)
return rgba
def color_straight_to_pre_alpha(rgba):
"""Convert to premultiplied alpha inplace"""
rgba[..., :-1] *= rgba[..., -1:]
return rgba
def color_linear_to_srgb(rgba):
"""Convert pixels from linear RGB to sRGB inplace"""
rgb = rgba[..., :-1]
small = rgb <= 0.0031308
rgb[small] = rgb[small] * 12.92
large = ~small
rgb[large] = 1.055 * np.power(rgb[large], 1.0 / 2.4) - 0.055
return rgba
def color_srgb_to_linear(rgba):
"""Convert pixels from sRGB to linear RGB inplace"""
rgb = rgba[..., :-1]
small = rgb <= 0.04045
rgb[small] = rgb[small] / 12.92
large = ~small
rgb[large] = np.power((rgb[large] + 0.055) / 1.055, 2.4)
return rgba
# ------------------------------------------------------------------------------
# Transform
# ------------------------------------------------------------------------------
class Transform:
__slots__: List[str] = ["m", "_m_inv"]
m: np.ndarray[Tuple[int, int], FLOAT]
_m_inv: np.ndarray[Tuple[int, int], FLOAT]
def __init__(self, matrix=None, matrix_inv=None):
if matrix is None:
self.m = np.identity(3)
self._m_inv = self.m
else:
self.m = matrix
self._m_inv = matrix_inv
def __matmul__(self, other: Transform) -> Transform:
return Transform(self.m @ other.m)
@property
def invert(self) -> Transform:
if self._m_inv is None:
self._m_inv = np.linalg.inv(self.m)
return Transform(self._m_inv, self.m)
def __call__(self, points: FNDArray) -> FNDArray:
if len(points) == 0:
return points
return points @ self.m[:2, :2].T + self.m[:2, 2]
def apply(self) -> Callable[[FNDArray], FNDArray]:
M = self.m[:2, :2].T
B = self.m[:2, 2]
return lambda points: points @ M + B
def matrix(self, m00, m01, m02, m10, m11, m12):
return Transform(self.m @ np.array([[m00, m01, m02], [m10, m11, m12], [0, 0, 1]]))
def translate(self, tx: float, ty: float) -> Transform:
return Transform(self.m @ np.array([[1, 0, tx], [0, 1, ty], [0, 0, 1]]))
def scale(self, sx, sy=None):
sy = sx if sy is None else sy
return Transform(self.m @ np.array([[sx, 0, 0], [0, sy, 0], [0, 0, 1]]))
def rotate(self, angle):
cos_a = math.cos(angle)
sin_a = math.sin(angle)
return Transform(self.m @ np.array([[cos_a, -sin_a, 0], [sin_a, cos_a, 0], [0, 0, 1]]))
def skew(self, ax, ay):
return Transform(
np.matmul(self.m, np.array([[1, math.tan(ax), 0], [math.tan(ay), 1, 0], [0, 0, 1]]))
)
def __repr__(self):
return str(np.around(self.m, 4).tolist()[:2])
def no_translate(self):
m = self.m.copy()
m[0, 2] = 0
m[1, 2] = 0
return Transform(m)
# ------------------------------------------------------------------------------
# Render scene
# ------------------------------------------------------------------------------
RENDER_FILL = 0
RENDER_STROKE = 1
RENDER_GROUP = 2
RENDER_OPACITY = 3
RENDER_CLIP = 4
RENDER_TRANSFORM = 5
RENDER_FILTER = 6
RENDER_MASK = 7
class Scene(tuple):
__slots__: List[str] = []
def __new__(cls, type, args):
return tuple.__new__(cls, (type, args))
@classmethod
def fill(cls, path, paint, fill_rule=None):
return cls(RENDER_FILL, (path, paint, fill_rule))
@classmethod
def stroke(cls, path, paint, width, linecap=None, linejoin=None):
return cls(RENDER_STROKE, (path, paint, width, linecap, linejoin))
@classmethod
def group(cls, children):
if not children:
raise ValueError("group have to contain at least one child")
if len(children) == 1:
return children[0]
return cls(RENDER_GROUP, children)
def opacity(self, opacity):
if opacity > 0.999:
return self
return Scene(RENDER_OPACITY, (self, opacity))
def clip(self, clip, bbox_units=False):
return Scene(RENDER_CLIP, (self, clip, bbox_units))
def mask(self, mask, bbox_units=False):
return Scene(RENDER_MASK, (self, mask, bbox_units))
def transform(self, transform):
type, args = self
if type == RENDER_TRANSFORM:
target, target_transform = args
return Scene(RENDER_TRANSFORM, (target, transform @ target_transform))
else:
return Scene(RENDER_TRANSFORM, (self, transform))
def filter(self, filter):
return Scene(RENDER_FILTER, (self, filter))
def render(self, transform, mask_only=False, viewport=None, linear_rgb=False):
"""Render graph"""
type, args = self
if type == RENDER_FILL:
path, paint, fill_rule = args
if mask_only:
return path.mask(transform, fill_rule=fill_rule, viewport=viewport)
else:
return path.fill(
transform, paint, fill_rule=fill_rule, viewport=viewport, linear_rgb=linear_rgb
)
elif type == RENDER_STROKE:
path, paint, width, linecap, linejoin = args
stroke = path.stroke(width, linecap, linejoin)
if mask_only:
return stroke.mask(transform, viewport=viewport)
else:
return stroke.fill(transform, paint, viewport=viewport, linear_rgb=linear_rgb)
elif type == RENDER_GROUP:
layers, hulls = [], []
start = time.time()
for child in args:
layer = child.render(transform, mask_only, viewport, linear_rgb)
if layer is None:
continue
layer, hull = layer
layers.append(layer)
hulls.append(hull)
group = Layer.compose(layers, COMPOSE_OVER, linear_rgb)
if not group:
return None
return group, ConvexHull.merge(hulls)
elif type == RENDER_OPACITY:
target, opacity = args
layer = target.render(transform, mask_only, viewport, linear_rgb)
if layer is None:
return None
layer, hull = layer
return layer.opacity(opacity, linear_rgb), hull
elif type == RENDER_CLIP:
target, clip, bbox_units = args
image_result = target.render(transform, mask_only, viewport, linear_rgb)
if image_result is None:
return None
image, hull = image_result
if bbox_units:
transform = hull.bbox_transform(transform)
clip_result = clip.render(transform, True, viewport, linear_rgb)
if clip_result is None:
return None
mask, _ = clip_result
result = Layer.compose([mask, image], COMPOSE_IN, linear_rgb)
if result is None:
return None
return result, hull
elif type == RENDER_TRANSFORM:
target, target_transfrom = args
return target.render(transform @ target_transfrom, mask_only, viewport, linear_rgb)
elif type == RENDER_MASK:
target, mask_scene, bbox_units = args
image_result = target.render(transform, mask_only, viewport, linear_rgb)
if image_result is None:
return None
image, hull = image_result
if bbox_units:
transform = hull.bbox_transform(transform)
mask_result = mask_scene.render(transform, mask_only, viewport, linear_rgb)
if mask_result is None:
return None
mask, _ = mask_result
mask = mask.convert(pre_alpha=False, linear_rgb=linear_rgb)
mask_image = mask.image[..., :3] @ [0.2125, 0.7154, 0.072] * mask.image[..., 3]
mask = Layer(mask_image[..., None], mask.offset, pre_alpha=False, linear_rgb=linear_rgb)
result = Layer.compose([mask, image], COMPOSE_IN, linear_rgb)
if result is None:
return None
return result, hull
elif type == RENDER_FILTER:
target, filter = args
image_result = target.render(transform, mask_only, viewport, linear_rgb)
if image_result is None:
return None
image, hull = image_result
return filter(transform, image), hull
else:
raise ValueError(f"unhandled scene type: {type}")
def to_path(self, transform: Transform):
"""Try to convert whole scene to a path (used only for testing)"""
def to_path(scene, transform):
type, args = scene
if type == RENDER_FILL:
path, _paint, _fill_rule = args
yield path.transform(transform)
elif type == RENDER_STROKE:
path, paint, width, linecap, linejoin = args
yield path.transform(transform).stroke(width, linecap, linejoin)
elif type == RENDER_GROUP:
for child in args:
yield from to_path(child, transform)
elif type == RENDER_OPACITY:
target, _opacity = args
yield from to_path(target, transform)
elif type == RENDER_CLIP:
target, _clip, _bbox_units = args
yield from to_path(target, transform)
elif type == RENDER_TRANSFORM:
target, target_transfrom = args
yield from to_path(target, transform @ target_transfrom)
elif type == RENDER_MASK:
target, _mask_scene, _bbox_units = args
yield from to_path(target, transform)
elif type == RENDER_FILTER:
target, _filter = args
yield from to_path(target, transform)
else:
raise ValueError(f"unhandled scene type: {type}")
subpaths = [spath for path in to_path(self, transform) for spath in path.subpaths]
return Path(subpaths)
def __repr__(self) -> str:
def repr_rec(scene, output, depth):
output.write(indent * depth)
type, args = scene
if type == RENDER_FILL:
path, paint, fill_rule = args
if isinstance(paint, np.ndarray):
paint = format_color(paint)
output.write(f"FILL fill_rule:{fill_rule} paint:{paint}\n")
output.write(textwrap.indent(repr(path), indent * (depth + 1)))
output.write("\n")
elif type == RENDER_STROKE:
path, paint, width, linecap, linejoin = args
if isinstance(paint, np.ndarray):
paint = format_color(paint)
output.write(f"STROKE ")
output.write(f"width:{width} ")
output.write(f"linecap:{linecap} ")
output.write(f"linejoin:{linejoin} ")
output.write(f"paint:{paint}\n")
output.write(textwrap.indent(repr(path), indent * (depth + 1)))
output.write("\n")
elif type == RENDER_GROUP:
output.write("GROUP\n")
for child in args:
repr_rec(child, output, depth + 1)
elif type == RENDER_OPACITY:
target, opacity = args
output.write(f"OPACITY {opacity}\n")
repr_rec(target, output, depth + 1)
elif type == RENDER_CLIP:
target, clip, bbox_units = args
output.write(f"CLIP bbox_units:{bbox_units}\n")
output.write(indent * (depth + 1))
output.write("CLIP_PATH\n")
repr_rec(clip, output, depth + 2)
output.write(indent * (depth + 1))
output.write("CLIP_TARGET\n")
repr_rec(target, output, depth + 2)
elif type == RENDER_MASK:
target, mask, bbox_units = args
output.write(f"MASK bbox_units:{bbox_units}\n")
output.write(indent * (depth + 1))
output.write("MAKS_PATH\n")
repr_rec(mask, output, depth + 2)
output.write(indent * (depth + 1))
output.write("MASK_TARGET\n")
repr_rec(target, output, depth + 2)
elif type == RENDER_TRANSFORM:
target, transform = args
output.write(f"TRANSFORM {transform}\n")
repr_rec(target, output, depth + 1)
elif type == RENDER_FILTER:
target, filter = args
output.write(f"FILTER {filter}\n")
repr_rec(target, output, depth + 1)
else:
raise ValueError(f"unhandled scene type: {type}")
return output
def format_color(cs):
return "#" + "".join(f"{c:0<2x}" for c in (cs * 255).astype(np.uint8))
indent = " "
return repr_rec(self, io.StringIO(), 0).getvalue()[:-1]
# ------------------------------------------------------------------------------
# Path
# ------------------------------------------------------------------------------
PATH_LINE = 0
PATH_QUAD = 1
PATH_CUBIC = 2
PATH_ARC = 3
PATH_CLOSED = 4
PATH_UNCLOSED = 5
PATH_LINES = {PATH_LINE, PATH_CLOSED, PATH_UNCLOSED}
PATH_FILL_NONZERO = "nonzero"
PATH_FILL_EVENODD = "evenodd"
STROKE_JOIN_MITER = "miter"
STROKE_JOIN_ROUND = "round"
STROKE_JOIN_BEVEL = "bevel"
STROKE_CAP_BUTT = "butt"
STROKE_CAP_ROUND = "round"
STROKE_CAP_SQUARE = "square"
class Path:
"""Single rendering unit that can be filled or converted to stroke path
`subpaths` is a list of tuples:
- `(PATH_LINE, (p0, p1))` - line from p0 to p1
- `(PATH_CUBIC, (p0, c0, c1, p1))` - cubic bezier curve from p0 to p1 with control c0, c1
- `(PATH_QUAD, (p0, c0, p1))` - quadratic bezier curve from p0 to p1 with control c0
- `(PATH_ARC, (center, rx, ry, phi, eta, eta_delta)` - arc with a center and to radii rx, ry
rotated to phi angle, going from inital eta to eta + eta_delta angle.
- `(PATH_CLOSED | PATH_UNCLOSED, (p0, p1))` - last segment of subpath `"closed"` if
path was closed and `"unclosed"` if path was not closed. p0 - end subpath
p1 - beggining of this subpath.
"""
__slots__ = ["subpaths"]
subpaths: List[List[Tuple[int, Tuple[Any, ...]]]]
def __init__(self, subpaths):
self.subpaths = subpaths
def __iter__(self):
"""Itearte over subpaths"""
return iter(self.subpaths)
def __bool__(self) -> bool:
return bool(self.subpaths)
def mask(
self,
transform: Transform,
fill_rule: Optional[str] = None,
viewport: Optional[BBox] = None,
):
"""Render path as a mask (alpha channel only image)"""
# convert all curves to cubic curves and lines
lines_defs, cubics_defs = [], []
for path in self.subpaths:
if not path:
continue
for cmd, args in path:
if cmd in PATH_LINES:
lines_defs.append(args)
elif cmd == PATH_CUBIC:
cubics_defs.append(args)
elif cmd == PATH_QUAD:
cubics_defs.append(bezier2_to_bezier3(args))
elif cmd == PATH_ARC:
cubics_defs.extend(arc_to_bezier3(*args))
else:
raise ValueError(f"unsupported path type: `{cmd}`")
#def __call__(self, points: FNDArray) -> FNDArray:
#if len(points) == 0:
#return points
#return points @ self.m[:2, :2].T + self.m[:2, 2]
# transform all curves into presentation coordinate system
lines = transform(np.array(lines_defs, dtype=FLOAT))
cubics = transform(np.array(cubics_defs, dtype=FLOAT))
# flattend (convet to lines) all curves
if cubics.size != 0:
# flatness of 0.1px gives good accuracy
if lines.size != 0:
lines = np.concatenate([lines, bezier3_flatten_batch(cubics, 0.1)])
else:
lines = bezier3_flatten_batch(cubics, 0.1)
if lines.size == 0:
return
# calculate size of the mask
min_x, min_y = np.floor(lines.reshape(-1, 2).min(axis=0)).astype(int) - 1
max_x, max_y = np.ceil(lines.reshape(-1, 2).max(axis=0)).astype(int) + 1
if viewport is not None:
vx, vy, vw, vh = viewport
min_x, min_y = max(vx, min_x), max(vy, min_y)
max_x, max_y = min(vx + vw, max_x), min(vy + vh, max_y)
width = max_x - min_x
height = max_y - min_y
if width <= 0 or height <= 0:
return
# create trace (signed coverage)
trace = np.zeros((width, height), dtype=FLOAT)
for points in lines - np.array([min_x, min_y]):
line_signed_coverage(trace, points)
# render mask
mask = np.cumsum(trace, axis=1)
if fill_rule is None or fill_rule == PATH_FILL_NONZERO:
mask = np.fabs(mask).clip(0, 1)
elif fill_rule == PATH_FILL_EVENODD:
mask = np.fabs(np.remainder(mask + 1.0, 2.0) - 1.0)
else:
raise ValueError(f"Invalid fill rule: {fill_rule}")
mask[mask < 1e-6] = 0 # reound down to zero very small mask values
output = Layer(mask[..., None], (min_x, min_y), pre_alpha=True, linear_rgb=True)
return output, ConvexHull(lines)
def fill(self, transform, paint, fill_rule=None, viewport=None, linear_rgb=True):
"""Render path by fill-ing it."""
if paint is None:
return None
# create a mask
mask = self.mask(transform, fill_rule, viewport)
if mask is None:
return None
mask, hull = mask
# create background with specified paint
if isinstance(paint, np.ndarray) and paint.shape == (4,):
if not linear_rgb:
paint = color_pre_to_straight_alpha(paint.copy())
paint = color_linear_to_srgb(paint)
paint = color_straight_to_pre_alpha(paint)
output = Layer(mask.image * paint, mask.offset, pre_alpha=True, linear_rgb=linear_rgb)
elif isinstance(paint, (GradLinear, GradRadial)):
if paint.bbox_units:
user_tr = hull.bbox_transform(transform).invert
else:
user_tr = transform.invert
# convert grad pixels to user coordinate system
pixels = user_tr(grad_pixels(mask.bbox))
if paint.linear_rgb is not None:
linear_rgb = paint.linear_rgb
image = paint.fill(pixels, linear_rgb=linear_rgb)
# NOTE: consider optimizing calculation of grad only for unmasked points
# masked = mask.image > EPSILON
# painted = paint.fill(
# pixels[np.broadcast_to(masked, pixels.shape)].reshape(-1, 2),
# linear_rgb=linear_rgb,
# )
# image = np.zeros((mask.width, mask.height, 4), dtype=FLOAT)
# image[np.broadcast_to(masked, image.shape)] = painted.reshape(-1)
background = Layer(image, mask.offset, pre_alpha=True, linear_rgb=linear_rgb)
# use `canvas_compose` directly to avoid needless allocation
background = background.convert(pre_alpha=True, linear_rgb=linear_rgb)
mask = mask.convert(pre_alpha=True, linear_rgb=linear_rgb)
image = canvas_compose(COMPOSE_IN, mask.image, background.image)
output = Layer(image, mask.offset, pre_alpha=True, linear_rgb=linear_rgb)
elif isinstance(paint, Pattern):
# render pattern
pat_tr = transform.no_translate()
if paint.scene_view_box:
if paint.bbox_units:
px, py, pw, ph = paint.bbox()
_hx, _hy, hw, hh = hull.bbox(transform)
bbox = (px * hw, py * hh, pw * hw, ph * hh)
else:
bbox = paint.bbox()
pat_tr @= svg_viewbox_transform(bbox, paint.scene_view_box)
elif paint.scene_bbox_units:
pat_tr = hull.bbox_transform(pat_tr)
pat_tr @= paint.transform
result = paint.scene.render(pat_tr, linear_rgb=linear_rgb)
if result is None:
return None
pat_layer, _pat_hull = result
# repeat pattern
repeat_tr = transform
if paint.bbox_units:
repeat_tr = hull.bbox_transform(repeat_tr)
repeat_tr @= paint.transform
repeat_tr = repeat_tr.no_translate()
offsets = repeat_tr.invert(grad_pixels(mask.bbox))
offsets = repeat_tr(
np.remainder(offsets - [paint.x, paint.y], [paint.width, paint.height])
)
offsets = offsets.astype(int)
corners = repeat_tr(
[
[0, 0],
[paint.width, 0],
[0, paint.height],
[paint.width, paint.height],
]
)
max_x, max_y = corners.max(axis=0).astype(int)
min_x, min_y = corners.min(axis=0).astype(int)
w, h = max_x - min_x, max_y - min_y
offsets -= [min_x, min_y]
pat = np.zeros((w + 1, h + 1, 4))
pat = canvas_merge_at(pat, pat_layer.image, (pat_layer.x - min_x, pat_layer.y - min_y))
image = canvas_compose(COMPOSE_IN, mask.image, pat[offsets[..., 0], offsets[..., 1]])
output = Layer(
image, mask.offset, pre_alpha=pat_layer.pre_alpha, linear_rgb=pat_layer.linear_rgb
)
else:
warnings.warn(f"fill method is not implemented: {paint}")
return None
return output, hull
def stroke(self, width, linecap=None, linejoin=None) -> "Path":
"""Convert path to stroked path"""
curve_names = {2: PATH_LINE, 3: PATH_QUAD, 4: PATH_CUBIC}
dist = width / 2
outputs = []
for path in self:
if not path:
continue
# offset curves
forward, backward = [], []
for cmd, args in path:
if cmd == PATH_LINE or cmd == PATH_CLOSED:
line = np.array(args)
line_forward = line_offset(line, dist)
if line_forward is None:
continue
forward.append(line_forward)
backward.append(line_offset(line, -dist))
elif cmd == PATH_CUBIC:
cubic = np.array(args)
forward.extend(bezier3_offset(cubic, dist))
backward.extend(bezier3_offset(cubic, -dist))
elif cmd == PATH_QUAD:
cubic = bezier2_to_bezier3(args)
forward.extend(bezier3_offset(cubic, dist))
backward.extend(bezier3_offset(cubic, -dist))
elif cmd == PATH_ARC:
for cubic in arc_to_bezier3(*args):
forward.extend(bezier3_offset(cubic, dist))
backward.extend(bezier3_offset(cubic, -dist))
elif cmd == PATH_UNCLOSED:
continue
else:
raise ValueError(f"unsupported path type: `{cmd}`")
closed = cmd == PATH_CLOSED
if not forward:
continue
# connect curves
curves = []
for curve in forward:
if not curves:
curves.append(curve)
continue
curves.extend(stroke_line_join(curves[-1], curve, linejoin))
curves.append(curve)
# complete subpath if path is closed or add line cap
if closed:
curves.extend(stroke_line_join(curves[-1], curves[0], linejoin))
outputs.append([(curve_names[len(curve)], np.array(curve)) for curve in curves])
curves = []
else:
curves.extend(stroke_line_cap(curves[-1][-1], backward[-1][-1], linecap))
# extend subpath with backward path
while backward:
curve = list(reversed(backward.pop()))
if not curves:
curves.append(curve)
continue
curves.extend(stroke_line_join(curves[-1], curve, linejoin))
curves.append(curve)
# complete subpath
if closed:
curves.extend(stroke_line_join(curves[-1], curves[0], linejoin))
else:
curves.extend(stroke_line_cap(curves[-1][-1], curves[0][0], linecap))
outputs.append([(curve_names[len(curve)], np.array(curve)) for curve in curves])
return Path(outputs)
def transform(self, transform: Transform) -> "Path":
"""Apply transformation to a path
This method is usually not used directly but rather transformation is
passed to mask/fill method.
"""
paths_out = []
for path_in in self.subpaths:
path_out = []
if not path_in:
continue
for cmd, args in path_in:
if cmd == PATH_ARC:
cubics = arc_to_bezier3(*args)
for cubic in transform(cubics):
path_out.append((PATH_CUBIC, cubic.tolist()))
else:
points = transform(np.array(args)).tolist()
path_out.append((cmd, points))
paths_out.append(path_out)
return Path(paths_out)
def to_svg(self) -> str:
"""Convert to SVG path"""
output = io.StringIO()
for path in self.subpaths:
if not path:
continue
cmd_prev = None
for cmd, args in path:
if cmd == PATH_LINE:
(x0, y0), (x1, y1) = args
if cmd_prev != cmd:
if cmd_prev is None:
output.write(f"M{x0:g},{y0:g} ")
else:
output.write("L")
output.write(f"{x1:g},{y1:g} ")
cmd_prev = PATH_LINE
elif cmd == PATH_QUAD:
(x0, y0), (x1, y1), (x2, y2) = args
if cmd_prev != cmd:
if cmd_prev is None:
output.write(f"M{x0:g},{y0:g} ")
output.write("Q")
output.write(f"{x1:g},{y1:g} {x2:g},{y2:g} ")
cmd_prev = PATH_QUAD
elif cmd in {PATH_CUBIC, PATH_ARC}:
if cmd == PATH_ARC:
cubics = arc_to_bezier3(*args)
else:
cubics = [args]
for args in cubics:
(x0, y0), (x1, y1), (x2, y2), (x3, y3) = args
if cmd_prev != cmd:
if cmd_prev is None:
output.write(f"M{x0:g},{y0:g} ")
output.write("C")
output.write(f"{x1:g},{y1:g} {x2:g},{y2:g} {x3:g},{y3:g} ")
cmd_prev = PATH_CUBIC
elif cmd == PATH_CLOSED:
output.write("Z ")
cmd_prev = None
elif cmd == PATH_UNCLOSED:
cmd_prev = None
else:
raise ValueError("unhandled path type: `{cmd}`")
output.write("\n")
return output.getvalue()[:-1]
@staticmethod
def from_svg(input: str) -> "Path":
"""Parse SVG path
For more info see [SVG spec](https://www.w3.org/TR/SVG11/paths.html)
"""
input_len = len(input)
input_offset = 0
WHITESPACE = set(" \t\r\n,")
COMMANDS = set("MmZzLlHhVvCcSsQqTtAa")
def position(is_relative, pos, dst):
return [pos[0] + dst[0], pos[1] + dst[1]] if is_relative else dst
def smooth(points):
px, py = points[-1]
cx, cy = points[-2]
return [px * 2 - cx, py * 2 - cy]
# parser state
paths = []
path = []
args = []
cmd = None
pos = [0.0, 0.0]
first = True # true if this is a frist command
start = [0.0, 0.0]
smooth_cubic = None
smooth_quad = None
while input_offset <= input_len:
char = input[input_offset] if input_offset < input_len else None
if char in WHITESPACE:
# remove whitespaces
input_offset += 1
elif char is None or char in COMMANDS:
# process current command
cmd_args, args = args, []
if cmd is None:
pass
elif cmd in "Mm":
# terminate current path
if path:
path.append((PATH_UNCLOSED, [pos, start]))
paths.append(path)
path = []
is_relative = cmd == "m"
(move, *lineto) = chunk(cmd_args, 2)
pos = position(is_relative and not first, pos, move)
start = pos
for dst in lineto:
dst = position(is_relative, pos, dst)
path.append((PATH_LINE, [pos, dst]))
pos = dst
# line to
elif cmd in "Ll":
for dst in chunk(cmd_args, 2):
dst = position(cmd == "l", pos, dst)
path.append((PATH_LINE, [pos, dst]))
pos = dst
# vertical line to
elif cmd in "Vv":
if not cmd_args:
raise ValueError(f"command '{cmd}' expects at least one argument")
is_relative = cmd == "v"
for dst in cmd_args:
dst = position(is_relative, pos, [0 if is_relative else pos[0], dst])
path.append((PATH_LINE, [pos, dst]))
pos = dst
# horizontal line to
elif cmd in "Hh":
if not cmd_args:
raise ValueError(f"command '{cmd}' expects at least one argument")
is_relative = cmd == "h"
for dst in cmd_args:
dst = position(is_relative, pos, [dst, 0 if is_relative else pos[1]])
path.append((PATH_LINE, [pos, dst]))
pos = dst
# cubic bezier curve
elif cmd in "Cc":
for points in chunk(cmd_args, 6):
points = [position(cmd == "c", pos, point) for point in chunk(points, 2)]
path.append((PATH_CUBIC, [pos, *points]))
pos = points[-1]
smooth_cubic = smooth(points)
# smooth cubic bezier curve
elif cmd in "Ss":
for points in chunk(cmd_args, 4):
points = [position(cmd == "s", pos, point) for point in chunk(points, 2)]
if smooth_cubic is None:
smooth_cubic = pos
path.append((PATH_CUBIC, [pos, smooth_cubic, *points]))
pos = points[-1]
smooth_cubic = smooth(points)
# quadratic bezier curve
elif cmd in "Qq":
for points in chunk(cmd_args, 4):
points = [position(cmd == "q", pos, point) for point in chunk(points, 2)]
path.append((PATH_QUAD, [pos, *points]))
pos = points[-1]
smooth_quad = smooth(points)
# smooth quadratic bezier curve
elif cmd in "Tt":
for points in chunk(cmd_args, 2):
points = position(cmd == "t", pos, points)
if smooth_quad is None:
smooth_quad = pos
points = [pos, smooth_quad, points]
path.append((PATH_QUAD, points))
pos = points[-1]
smooth_quad = smooth(points)
# elliptical arc
elif cmd in "Aa":
# NOTE: `large_f`, and `sweep_f` are not float but flags which can only be
# 0 or 1 and as the result some svg minimizers merge them with next
# float which may break current parser logic.
for points in chunk(cmd_args, 7):
rx, ry, x_axis_rot, large_f, sweep_f, dst_x, dst_y = points
dst = position(cmd == "a", pos, [dst_x, dst_y])
src, pos = pos, dst
if rx == 0 or ry == 0:
path.append((PATH_LINE, [pos, dst]))
else:
path.append(
(
PATH_ARC,
arc_svg_to_parametric(
src,
dst,
rx,
ry,
x_axis_rot,
large_f > 0.001,
sweep_f > 0.001,
),
)
)
# close current path
elif cmd in "Zz":
if cmd_args:
raise ValueError(f"`z` command does not accept any argmuents: {cmd_args}")
path.append((PATH_CLOSED, [pos, start]))
if path:
paths.append(path)
path = []
pos = start
else:
raise ValueError(f"unsuppported command '{cmd}' at: {input_offset}")
if cmd is not None and cmd not in "CcSs":
smooth_cubic = None
if cmd is not None and cmd not in "QqTt":
smooth_quad = None
first = False
input_offset += 1
cmd = char
else:
# parse float arguments
match = FLOAT_RE.match(input, input_offset)
if match:
match_str = match.group(0)
args.append(float(match_str))
input_offset += len(match_str)
else:
raise ValueError(f"not recognized command '{char}' at: {input_offset}")
if path:
path.append((PATH_UNCLOSED, [pos, start]))
paths.append(path)
return Path(paths)
def is_empty(self):
return not bool(self.subpaths)
def __repr__(self):
if not self.subpaths:
return "EMPTY"
output = io.StringIO()
for subpath in self.subpaths:
for type, coords in subpath:
if type == PATH_LINE:
output.write(f"LINE {repr_coords(coords)}\n")
elif type == PATH_CUBIC:
output.write(f"CUBIC {repr_coords(coords)}\n")
elif type == PATH_QUAD:
output.write(f"QUAD {repr_coords(coords)}\n")
elif type == PATH_ARC:
center, rx, ry, phi, eta, eta_delta = coords
output.write(f"ARC ")
output.write(f"{repr_coords([center])} ")
output.write(f"{rx:.4g} {ry:.4g} ")
output.write(f"{phi:.3g} {eta:.3g} {eta_delta:.3g}\n")
elif type == PATH_CLOSED:
output.write("CLOSE\n")
return output.getvalue()[:-1]
def repr_coords(coords):
return " ".join(f"{x:.4g},{y:.4g}" for x, y in coords)
# offset along tanget to approximate circle with four bezier3 curves
CIRCLE_BEIZER_OFFSET = 4 * (math.sqrt(2) - 1) / 3
def stroke_line_cap(p0, p1, linecap=None):
"""Generate path connecting two curves p0 and p1 with a cap"""
if linecap is None:
linecap = STROKE_CAP_BUTT
if np.allclose(p0, p1):
return []
if linecap == STROKE_CAP_BUTT:
return [np.array([p0, p1])]
elif linecap == STROKE_CAP_ROUND:
seg = p1 - p0
radius = np.linalg.norm(seg) / 2
seg /= 2 * radius
seg_norm = np.array([-seg[1], seg[0]])
offset = CIRCLE_BEIZER_OFFSET * radius
center = (p0 + p1) / 2
midpoint = center + seg_norm * radius
return [
np.array([p0, p0 + seg_norm * offset, midpoint - seg * offset, midpoint]),
np.array([midpoint, midpoint + seg * offset, p1 + seg_norm * offset, p1]),
]
elif linecap == STROKE_CAP_SQUARE:
seg = p1 - p0
seg_norm = np.array([-seg[1], seg[0]])
polyline = [p0, p0 + seg_norm / 2, p1 + seg_norm / 2, p1]
return [np.array([s0, s1]) for s0, s1 in zip(polyline, polyline[1:])]
else:
raise ValueError(f"unkown line cap type: `{linecap}`")
def stroke_line_join(c0, c1, linejoin=None, miterlimit=4):
"""Stroke used at the joints of paths"""
if linejoin is None:
linejoin = STROKE_JOIN_MITER
if linejoin == STROKE_JOIN_BEVEL:
return [np.array([c0[-1], c1[0]])]
_, l0 = stroke_curve_tangent(c0)
l1, _ = stroke_curve_tangent(c1)
if l0 is None or l1 is None:
return [np.array([c0[-1], c1[0]])]
if np.allclose(l0[-1], l1[0]):
return []
p, t0, t1 = line_intersect(l0, l1)
if p is None or (0 <= t0 <= 1 and 0 <= t1 <= 1):
# curves intersect or parallel
return [np.array([c0[-1], c1[0]])]
# FIXME correctly determine miterlength: stroke_width / sin(eta / 2)
if abs(t0) < miterlimit and abs(t1) < miterlimit:
if linejoin == STROKE_JOIN_MITER:
return [np.array([c0[-1], p]), np.array([p, c1[0]])]
elif linejoin == STROKE_JOIN_ROUND:
# FIXME: correctly produce round instead quad curve
return [np.array([c0[-1], p, c1[0]])]
return [np.array([c0[-1], c1[0]])]
def stroke_curve_tangent(curve):
"""Find tangents of a curve at t = 0 and at t = 1 points"""
segs = []
for p0, p1 in zip(curve, curve[1:]):
if np.allclose(p0, p1):
continue
segs.append([p0, p1])
if not segs:
return None, None
return segs[0], segs[-1]
def chunk(vs, size):
"""Chunk list `vs` into chunk of size `size`"""
chunks = [vs[i : i + size] for i in range(0, len(vs), size)]
if not chunks or len(chunks[-1]) != size:
raise ValueError(f"list {vs} can not be chunked in {size}s")
return chunks
# ------------------------------------------------------------------------------
# Gradients
# ------------------------------------------------------------------------------
class GradLinear(NamedTuple):
p0: np.ndarray
p1: np.ndarray
stops: List[Tuple[float, np.ndarray]]
transform: Optional[Transform]
spread: str
bbox_units: bool
linear_rgb: Optional[bool]
def fill(self, pixels, linear_rgb=True):
"""Fill pixels (array of coordinates) with gradient
Returns new array same size as pixels filled with gradient
"""
if self.transform is not None:
pixels = self.transform.invert(pixels)
vec = self.p1 - self.p0
offset = (pixels - self.p0) @ vec / np.dot(vec, vec)
return grad_interpolate(grad_spread(offset, self.spread), self.stops, linear_rgb)
class GradRadial(NamedTuple):
center: np.ndarray
radius: float
fcenter: Optional[np.ndarray]
fradius: float
stops: List[Tuple[float, np.ndarray]]
transform: Optional[Transform]
spread: str
bbox_units: bool
linear_rgb: Optional[bool]
def fill(self, pixels, linear_rgb=True):
"""Fill pixels (array of coordinates) with gradient
Returns new array same size as pixels filled with gradient.
Two circle gradient is an interpolation between two cirles (c0, r0) and (c1, r1),
with center `c(t) = (1 - t) * c0 + t * c1`, and radius `r(t) = (1 - t) * r0 + t * r1`.
If we have a pixel with coordinates `p`, we should solve equation for it
`|| c(t) - p || = r(t)` and pick solution corresponding to bigger radius.
Solving this equation for `t`:
|| c(t) - p || = r(t) -> At² - 2Bt + C = 0
where:
cd = c2 - c1
pd = p - c1
rd = r2 - r1
A = cdx ^ 2 + cdy ^ 2 - rd ^ 2
B = pdx * cdx + pdy * cdy + r1 * rd
C = pdx ^2 + pdy ^ 2 - r1 ^ 2
results in:
t = (B +/- (B ^ 2 - A * C).sqrt()) / A
[reference]: https://cgit.freedesktop.org/pixman/tree/pixman/pixman-radial-gradient.c
"""
mask = None
if self.transform is not None:
pixels = self.transform.invert(pixels)
if self.fcenter is None and self.fradius is None:
offset = (pixels - self.center) / self.radius
offset = np.sqrt((offset * offset).sum(axis=-1))
else:
fcenter = self.center if self.fcenter is None else self.fcenter
fradius = self.fradius or 0
# This is SVG 1.1 behaviour. If focal center is outside of circle it
# should be moved inside. But in SVG 2.0 it should produce a cone
# shaped gradient.
# fdist = np.linalg.norm(fcenter - self.center)
# if fdist > self.radius:
# fcenter = self.center + (fcenter - self.center) * self.radius / fdist
cd = self.center - fcenter
pd = pixels - fcenter
rd = self.radius - fradius
a = (cd ** 2).sum() - rd ** 2
b = (pd * cd).sum(axis=-1) + fradius * rd
c = (pd ** 2).sum(axis=-1) - fradius ** 2
det = b * b - a * c
if (det < 0).any():
mask = det >= 0
det = det[mask]
b = b[mask]
c = c[mask]
t0 = np.sqrt(det)
t1 = (b + t0) / a
t2 = (b - t0) / a
if mask is None:
offset = np.maximum(t1, t2)
else:
offset = np.zeros(mask.shape, dtype=FLOAT)
offset[mask] = np.maximum(t1, t2)
if fradius != self.radius:
# exclude negative `r(t)`
mask &= offset > (fradius / (fradius - self.radius))
overlay = grad_interpolate(grad_spread(offset, self.spread), self.stops, linear_rgb)
if mask is not None:
overlay[~mask] = np.array([0, 0, 0, 0])
return overlay
def grad_pixels(viewport):
"""Create pixels matrix to be filled by gradient"""
off_x, off_y, width, height = viewport
xs, ys = np.indices((width, height)).astype(FLOAT)
offset = [off_x + 0.5, off_y + 0.5]
return np.concatenate([xs[..., None], ys[..., None]], axis=2) + offset
def grad_spread(offsets, spread):
if spread == "pad":
return offsets
elif spread == "repeat":
return np.modf(offsets)[0]
elif spread == "reflect":
return np.fabs(np.remainder(offsets + 1.0, 2.0) - 1.0)
raise ValueError(f"invalid spread method: {spread}")
def grad_interpolate(offset, stops, linear_rgb):
"""Create gradient by interpolating offsets from stops"""
stops = grad_stops_colorspace(stops, linear_rgb)
output = np.zeros((*offset.shape, 4), dtype=FLOAT)
o_min, c_min = stops[0]
output[offset <= o_min] = c_min
o_max, c_max = stops[-1]
output[offset > o_max] = c_max
for (o0, c0), (o1, c1) in zip(stops, stops[1:]):
mask = np.logical_and(offset > o0, offset <= o1)
ratio = ((offset[mask] - o0) / (o1 - o0))[..., None]
output[mask] += (1 - ratio) * c0 + ratio * c1
return output
def grad_stops_colorspace(stops, linear_rgb=False):
if linear_rgb:
return stops
output = []
for offset, color in stops:
color = color_pre_to_straight_alpha(color.copy())
color = color_linear_to_srgb(color)
color = color_straight_to_pre_alpha(color)
output.append((offset, color))
return output
class Pattern(NamedTuple):
scene: Scene
scene_bbox_units: bool
scene_view_box: Optional[Tuple[float, float, float, float]]
x: float
y: float
width: float
height: float
transform: Transform
bbox_units: bool
def bbox(self):
return (self.x, self.y, self.width, self.height)
# ------------------------------------------------------------------------------
# Filter
# ------------------------------------------------------------------------------
FE_BLEND = 0
FE_COLOR_MATRIX = 1
FE_COMPONENT_TRANSFER = 2
FE_COMPOSITE = 3
FE_CONVOLVE_MATRIX = 4
FE_DIFFUSE_LIGHTING = 5
FE_DISPLACEMENT_MAP = 6
FE_FLOOD = 7
FE_GAUSSIAN_BLUR = 8
FE_MERGE = 9
FE_MORPHOLOGY = 10
FE_OFFSET = 11
FE_SPECULAR_LIGHTING = 12
FE_TILE = 13
FE_TURBULENCE = 14
FE_SOURCE_ALPHA = "SourceAlpha"
FE_SOURCE_GRAPHIC = "SourceGraphic"
COLOR_MATRIX_LUM = np.array(
[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0.2125, 0.7154, 0.0721, 0, 0]], dtype=FLOAT
)
COLOR_MATRIX_HUE = np.array(
[
[[0.213, 0.715, 0.072], [0.213, 0.715, 0.072], [0.213, 0.715, 0.072]],
[[0.787, -0.715, -0.072], [-0.213, 0.285, -0.072], [-0.213, -0.715, 0.928]],
[[-0.213, -0.715, 0.928], [0.143, 0.140, -0.283], [-0.787, 0.715, 0.072]],
],
dtype=FLOAT,
)
class Filter(NamedTuple):
names: Dict[str, int] # {name: index}
filters: List[Tuple[int, List[Any], List[int]]] # [(type, attrs, inputs)]
@classmethod
def empty(cls):
return cls({FE_SOURCE_ALPHA: 0, FE_SOURCE_GRAPHIC: 1}, [])
def add_filter(self, type, attrs, inputs, result):
names = self.names.copy()
filters = self.filters.copy()
args = []
for input in inputs:
if input is None:
args.append(len(filters) + 1) # use previous result
else:
arg = self.names.get(input)
if arg is None:
warnings.warn(f"unknown filter result name: {input}")
args.append(len(filters) + 1) # use previous result
else:
args.append(arg)
if result is not None:
names[result] = len(filters) + 2
filters.append((type, attrs, args))
return Filter(names, filters)
def offset(self, dx, dy, input=None, result=None):
return self.add_filter(FE_OFFSET, (dx, dy), [input], result)
def merge(self, inputs, result=None):
return self.add_filter(FE_MERGE, tuple(), inputs, result)
def blur(self, std_x, std_y=None, input=None, result=None):
return self.add_filter(FE_GAUSSIAN_BLUR, (std_x, std_y), [input], result)
def blend(self, in1, in2, mode=None, result=None):
return self.add_filter(FE_BLEND, (mode,), [in1, in2], result)
def composite(self, in1, in2, mode=None, result=None):
return self.add_filter(FE_COMPOSITE, (mode,), [in1, in2], result)
def color_matrix(self, input, matrix, result=None):
return self.add_filter(FE_COLOR_MATRIX, (matrix,), [input], result)
def morphology(self, rx, ry, method, input, result=None):
return self.add_filter(FE_MORPHOLOGY, (rx, ry, method), [input], result)
def __call__(self, transform, source):
"""Execute fiter on the provided source"""
alpha = Layer(
source.image[..., -1:] * np.array([0, 0, 0, 1]),
source.offset,
pre_alpha=True,
linear_rgb=True,
)
stack = [alpha, source.convert(pre_alpha=False, linear_rgb=True)]
for filter in self.filters:
type, attrs, inputs = filter
if type == FE_OFFSET:
fn = filter_offset(transform, *attrs)
elif type == FE_MERGE:
fn = filter_merge(transform, *attrs)
elif type == FE_BLEND:
fn = filter_blend(transform, *attrs)
elif type == FE_COMPOSITE:
fn = filter_composite(transform, *attrs)
elif type == FE_GAUSSIAN_BLUR:
fn = filter_blur(transform, *attrs)
elif type == FE_COLOR_MATRIX:
fn = filter_color_matrix(transform, *attrs)
elif type == FE_MORPHOLOGY:
fn = filter_morphology(transform, *attrs)
else:
raise ValueError(f"unsupported filter type: {type}")
stack.append(fn(*(stack[input] for input in inputs)))
return stack[-1]
def filter_color_matrix(_transform, matrix):
def filter_color_matrix_apply(input):
if not isinstance(matrix, np.ndarray) or matrix.shape != (4, 5):
warnings.warn(f"invalid color matrix: {matrix}")
return input
return input.color_matrix(matrix)
return filter_color_matrix_apply
def filter_offset(transform, dx, dy):
def filter_offset_apply(input):
x, y = input.offset
tx, ty = transform(transform.invert([x, y]) + [dx, dy])
return input.translate(int(tx) - x, int(ty) - y)
return filter_offset_apply
def filter_morphology(transform, rx, ry, method):
def filter_morphology_apply(input):
# NOTE:
# I have no idea how to account for rotation, except to roate
# apply morphology and rotate back, but it is slow, so I'm not doing it
ux, uy = transform([[rx, 0], [0, ry]]) - transform([[0, 0], [0, 0]])
x = int(np.linalg.norm(ux) * 2)
y = int(np.linalg.norm(uy) * 2)
if x < 1 or y < 1:
return input
return input.morphology(x, y, method)
return filter_morphology_apply
def filter_merge(_transform):
def filter_merge_apply(*inputs):
return Layer.compose(inputs, linear_rgb=True)
return filter_merge_apply
def filter_blend(_transform, mode):
def filter_blend_apply(in1, in2):
warnings.warn("feBlend is not properly supported")
return Layer.compose([in2, in1], linear_rgb=True)
return filter_blend_apply
def filter_composite(_transform, mode):
def filter_composite_apply(in1, in2):
return Layer.compose([in2, in1], mode, linear_rgb=True)
return filter_composite_apply
def filter_blur(transform, std_x, std_y=None):
if std_y is None:
std_y = std_x
def filter_blur_apply(input):
kernel = blur_kernel(transform, (std_x, std_y))
if kernel is None:
return input
return input.convolve(kernel)
return filter_blur_apply
def blur_kernel(transform, sigma):
"""Gaussian blur convolution kerenel
Gaussiange kernel ginven presentation transformation and sigma in user
coordinate system.
"""
sigma_x, sigma_y = sigma
# if one of the sigmas is smaller then a pixel rotatetion produces
# incorrect degenerate state when the whole convolution is the same as over
# a delta function. So we need to adjust it. If both simgas are smallerd
# then a pixel then gaussian blur is a nonop.
scale_x, scale_y = np.linalg.norm(transform(np.eye(2)) - transform([0, 0]), axis=1)
if scale_x * sigma_x < 0.5 and scale_y * sigma_y < 0.5:
return None
elif scale_x * sigma_x < 0.5:
sigma_x = 0.5 / scale_x
elif scale_y * sigma_y < 0.5:
sigma_y = 0.5 / scale_y
sigma = np.array([sigma_x, sigma_y])
sigmas = 2.5
user_box = [
[-sigmas * sigma_x, -sigmas * sigma_y],
[-sigmas * sigma_x, sigmas * sigma_y],
[sigmas * sigma_x, sigmas * sigma_y],
[sigmas * sigma_x, -sigmas * sigma_y],
]
box = transform(user_box) - transform([0, 0])
min_x, min_y = box.min(axis=0).astype(int)
max_x, max_y = box.max(axis=0).astype(int)
kernel_w, kernel_h = max_x - min_x, max_y - min_y
kernel_w += ~kernel_w & 1 # make it odd
kernel_h += ~kernel_h & 1
user_tr = transform.invert
kernel = user_tr(grad_pixels([-kernel_w / 2, -kernel_h / 2, kernel_w, kernel_h]))
kernel -= user_tr([0, 0]) # remove translation
kernel = np.exp(-np.square(kernel) / (2 * np.square(sigma)))
kernel = kernel.prod(axis=-1)
return kernel / kernel.sum()
def color_matrix_hue_rotate(angle):
"""Hue rotation matrix for speicified angle in radians"""
matrix = np.eye(4, 5)
matrix[:3, :3] = np.dot(COLOR_MATRIX_HUE.T, [1, math.cos(angle), math.sin(angle)]).T
return matrix
def color_matrix_saturate(value):
matrix = np.eye(4, 5)
matrix[:3, :3] = np.dot(COLOR_MATRIX_HUE.T, [1, value, 0]).T
return matrix
# ------------------------------------------------------------------------------
# Convex Hull
# ------------------------------------------------------------------------------
class ConvexHull:
"""Convex hull using graham scan
Points are stored in presenetation coordinate system, so we would not have
to convert them back and force when merging.
"""
__slots__ = ["points"]
def __init__(self, points):
"""Construct convex hull of a set of points using graham scan"""
if isinstance(points, np.ndarray):
points = points.reshape(-1, 2).tolist()
def turn(p, q, r):
return (q[0] - p[0]) * (r[1] - p[1]) - (r[0] - p[0]) * (q[1] - p[1])
def keep_left(hull, p):
while len(hull) > 1 and turn(hull[-2], hull[-1], p) <= 0:
hull.pop()
if not hull or hull[-1] != p:
hull.append(p)
return hull
points = sorted(points)
left = reduce(keep_left, points, [])
right = reduce(keep_left, reversed(points), [])
left.extend(right[1:-1])
self.points = left
@classmethod
def merge(cls, hulls):
"""Merge multiple convex hulls into one"""
points = []
for hull in hulls:
points.extend(hull.points)
return cls(points)
def bbox(self, transform):
"""Bounding box in user coordinate system"""
points = transform.invert(np.array(self.points))
min_x, min_y = points.min(axis=0)
max_x, max_y = points.max(axis=0)
return [min_x, min_y, max_x - min_x, max_y - min_y]
def bbox_transform(self, transform):
"""Transformation matrix for `objectBoundingBox` units
Create bounding box transfrom for `objectBoundingBox`, using convex hull in the
canvas coordinate system and current user space transformation.
`objectBoundingBox` is a coordinate system where bounding box is a unit square.
Returns `objectBoundingBox` transform.
FIXME: In case of stroke we should use bounding box of the original path,
not the stroked path.
"""
x, y, w, h = self.bbox(transform)
if w <= 0 and h <= 0:
return transform
return transform.translate(x, y).scale(w, h)
def path(self):
points = self.points
lines = [(PATH_LINE, l) for l in zip(points, points[1:])]
lines.append((PATH_CLOSED, [points[-1], points[0]]))
return Path([lines])
# ------------------------------------------------------------------------------
# Bezier
# ------------------------------------------------------------------------------
BEZIER3_FLATNESS = np.array([[-2, 3, 0, -1], [-1, 0, 3, -2]], dtype=FLOAT)
BEZIER3_SPLIT = np.array(
[
[1, 0, 0, 0],
[0.5, 0.5, 0, 0],
[0.25, 0.5, 0.25, 0],
[0.125, 0.375, 0.375, 0.125],
[0.125, 0.375, 0.375, 0.125],
[0, 0.25, 0.5, 0.25],
[0, 0, 0.5, 0.5],
[0, 0, 0, 1],
],
dtype=FLOAT,
)
BEZIER3_MAT = np.array([[1, 0, 0, 0], [-3, 3, 0, 0], [3, -6, 3, 0], [-1, 3, -3, 1]], dtype=FLOAT)
BEZIER2_MAT = np.array([[1, 0, 0], [-2, 2, 0], [1, -2, 1]], dtype=FLOAT)
BEZIER3_ABC = np.array([[-3, 9, -9, 3], [6, -12, 6, 0], [-3, 3, 0, 0]], dtype=FLOAT)
BEZIER2_TO_BEZIER3 = np.array(
[[1, 0, 0], [1.0 / 3, 2.0 / 3, 0], [0, 2.0 / 3.0, 1.0 / 3], [0, 0, 1]], dtype=FLOAT
)
BEZIER = {2: [[0, 1], [1, -1]], 3: BEZIER2_MAT, 4: BEZIER3_MAT}
def bezier3_split(points):
"""Split bezier3 curve in two bezier3 curves at t=0.5
Using de Castelju construction at t=0.5
"""
return np.matmul(BEZIER3_SPLIT, points).reshape(2, 4, 2)
def bezier3_split_batch(batch):
"""Split N bezier3 curves in 2xN bezier3 curves at t=0.5"""
return np.moveaxis(np.dot(BEZIER3_SPLIT, batch), 0, -2).reshape((-1, 4, 2))
def bezier3_flatness_batch(batch):
"""Flattness criteria for a batch of bezier3 curves
It is equal to `f = maxarg d(t) where d(t) = |b(t) - l(t)|, l(t) = (1 - t) * b0 + t * b3`
for b(t) bezier3 curve with b{0..3} control points, in other words maximum distance
from parametric line to bezier3 curve for the same parameter t. It is proven in the article
that:
f^2 <= 1/16 (max{u_x^2, v_x^2} + max{u_y^2, v_y^2})
where:
u = 3 * b1 - 2 * b0 - b3
v = 3 * b2 - b0 - 2 * b3
`f == 0` means completely flat so estimating upper bound is sufficient as spliting more
than needed is not a problem for rendering.
[Linear Approximation of Bezier Curve](https://hcklbrrfnn.files.wordpress.com/2012/08/bez.pdf)
"""
uv = np.moveaxis(np.square(np.dot(BEZIER3_FLATNESS, batch)), 0, -1)
return uv.max(-2).sum(-1)
def bezier3_flatten_batch(batch, flatness):
lines = []
flatness = (flatness ** 2) * 16
while batch.size > 0:
flat_mask = bezier3_flatness_batch(batch) < flatness
lines.append(batch[flat_mask][..., [0, 3], :])
batch = bezier3_split_batch(batch[~flat_mask])
return np.concatenate(lines)
def bezier3_bbox(points):
a, b, c = BEZIER3_ABC @ points
det = b ** 2 - 4 * a * c
t0 = (-b + np.sqrt(det)) / (2 * a)
t1 = (-b - np.sqrt(det)) / (2 * a)
curve = bezier_parametric(points)
exterm = np.array([curve(t) for t in [0, 1, *t0, *t1] if 0 <= t <= 1])
min_x, min_y = exterm.min(axis=0)
max_x, max_y = exterm.max(axis=0)
return (min_x, min_y, max_x - min_x, max_y - min_y)
def bezier3_offset(curve, distance):
"""Offset beizer3 curve with a list of bezier3 curves
Offset bezier curve using Tiller-Hanson method. In short, just offset line
segement corresponding to control points, find intersection of this lines
and treat them as new control points.
"""
def should_split(curve):
c0, c1, c2, c3 = curve
# angle(c3 - c0, c2 - c1) > 90 or < -90
if np.dot(c3 - c0, c2 - c1) < 0:
return True
# control points should be on the same side of the baseline
a0 = np.cross(c3 - c0, c1 - c0)
a1 = np.cross(c3 - c0, c2 - c0)
if a0 * a1 < 0:
return True
# distance between center mass and midpoint of a cruve,
# bigger then .1 of bounding box diagonal.
c_mass = curve.sum(0) / 4 # center mass
c_mid = [0.125, 0.375, 0.375, 0.125] @ curve # t = 0.5
dist = ((c_mass - c_mid) ** 2).sum()
bbox_diag = ((curve.max(0) - curve.min(0)) ** 2).sum()
return dist * 100 > bbox_diag
outputs = []
curves = [curve]
while curves:
curve = curves.pop()
if should_split(curve) and len(outputs) < 16:
curves.extend(reversed(bezier3_split(curve)))
continue
output = []
repeat = 0
line = None
for p0, p1 in zip(curve, curve[1:]):
# skip non-offsetable lines
if np.allclose(p0, p1):
repeat += 1
continue
# offset and intersect with previous
o0, o1 = line_offset([p0, p1], distance)
if line is not None:
x0, _t0, _t1 = line_intersect(line, (o0, o1))
if x0 is not None:
o0 = x0
else:
o0 = (line[-1] + o0) / 2
# repeat points if needed
for _ in range(repeat + 1):
output.append(o0)
repeat = 0
line = (o0, o1)
if line is not None:
# insert last points
for _ in range(repeat + 1):
output.append(o1)
if outputs and not np.allclose(output[0], outputs[-1][-1]):
# hack for a curve like "M0,0 C100,50 0,50 100,0"
outputs.extend(stroke_line_cap(output[0], outputs[-1][-1], STROKE_CAP_ROUND))
outputs.append(output)
return np.array(outputs)
def bezier2_to_bezier3(points):
"""Convert bezier2 to bezier3 curve"""
return BEZIER2_TO_BEZIER3 @ points
def bezier_parametric(points):
points = np.array(points, dtype=FLOAT)
points_count, _ = points.shape
matrix = BEZIER.get(points_count)
if matrix is None:
raise ValueError("unsupported bezier curve order: {}", points_count)
powers = np.array(range(points_count), dtype=FLOAT)
matrix = np.dot(matrix, points)
return lambda t: np.power(t, powers) @ matrix
def bezier_deriv_parametric(points):
points = np.array(points, dtype=FLOAT)
points_count, _ = points.shape
matrix = BEZIER.get(points_count)
if matrix is None:
raise ValueError("unsupported bezier curve order: {}", points_count)
powers = np.array(range(points_count - 1), dtype=FLOAT)
deriv_matrix = (matrix * np.array(range(points_count))[..., None])[1:]
deriv_matrix = np.dot(deriv_matrix, points)
return lambda t: np.power(t, powers) @ deriv_matrix
# ------------------------------------------------------------------------------
# Line
# ------------------------------------------------------------------------------
def line_signed_coverage(canvas, line):
"""Trace line on a canvas rendering signed coverage
Implementation details:
Line must be specified in the canvas coordinate system (that is one
unit of length is equal to one pixel). Line is always traversed with
scan line along `x` coordinates from lowest value to largest, and
scan lines are going from lowest `y` value to larges.
Based on https://github.com/raphlinus/font-rs/blob/master/src/raster.rs
"""
floor, ceil = math.floor, math.ceil
min, max = builtins.min, builtins.max
h, w = canvas.shape
X, Y = 1, 0
p0, p1 = line[0], line[1]
if p0[Y] == p1[Y]:
return # does not introduce any signed converage
dir, p0, p1 = (1.0, p0, p1) if p0[Y] < p1[Y] else (-1.0, p1, p0)
dxdy = (p1[X] - p0[X]) / (p1[Y] - p0[Y])
# Find first point to trace. Since we are going to interate over Y's
# we should pick min(y , p0.y) as a starting y point, and adjust x
# accordingly
x, y = p0[X], int(max(0, p0[Y]))
if p0[Y] < 0:
x -= p0[Y] * dxdy
x_next = x
for y in range(y, min(h, ceil(p1[Y]))):
x = x_next
dy = min(y + 1, p1[Y]) - max(y, p0[Y])
d = dir * dy # signed y difference
# find next x position
x_next = x + dxdy * dy
# order (x, x_next) from smaller value x0 to bigger x1
x0, x1 = (x, x_next) if x < x_next else (x_next, x)
# lower bound of effected x pixels
x0_floor = floor(x0)
x0i = int(x0_floor)
# uppwer bound of effected x pixels
x1_ceil = ceil(x1)
x1i = int(x1_ceil)
if x1i <= x0i + 1:
# only goes through one pixel
xmf = 0.5 * (x + x_next) - x0_floor # effective height
if x0i >= w:
continue
canvas[y, x0i if x0i > 0 else 0] += d * (1 - xmf)
xi = x0i + 1
if xi >= w:
continue
canvas[y, xi if xi > 0 else 0] += d * xmf # next pixel is fully shaded
else:
s = 1 / (x1 - x0)
x0f = x0 - x0_floor # fractional part of x0
x1f = x1 - x1_ceil + 1.0 # fraction part of x1
a0 = 0.5 * s * (1 - x0f) ** 2 # area of the smallest x pixel
am = 0.5 * s * x1f ** 2 # area of the largest x pixel
# first pixel
if x0i >= w:
continue
canvas[y, x0i if x0i > 0 else 0] += d * a0
if x1i == x0i + 2:
# only two pixels are covered
xi = x0i + 1
if xi >= w:
continue
canvas[y, xi if xi > 0 else 0] += d * (1.0 - a0 - am)
else:
# second pixel
a1 = s * (1.5 - x0f)
xi = x0i + 1
if xi >= w:
continue
canvas[y, xi if xi > 0 else 0] += d * (a1 - a0)
# second .. last pixels
for xi in range(x0i + 2, x1i - 1):
if xi >= w:
continue
canvas[y, xi if xi > 0 else 0] += d * s
# last pixel
a2 = a1 + (x1i - x0i - 3) * s
xi = x1i - 1
if xi >= w:
continue
canvas[y, xi if xi > 0 else 0] += d * (1.0 - a2 - am)
if x1i >= w:
continue
canvas[y, x1i if x1i > 0 else 0] += d * am
return canvas
def line_intersect(l0, l1):
"""Find intersection betwee two line segments
Solved by solving l(t) for both lines:
l(t) = (1 - t) * l[0] + t * l[1]
v ~ l[1] - l[0]
l0(ta) == l1(tb)
l0[0] - l1[0] = [v1, -v0] @ [tb, ta]
inv([v1, -v0]) @ (l0[0] - l1[0]) = [tb, ta]
"""
((x1, y1), (x2, y2)) = l0
((x3, y3), (x4, y4)) = l1
det = (x4 - x3) * (y1 - y2) - (x1 - x2) * (y4 - y3)
if abs(det) < EPSILON:
return None, 0, 0
t0 = ((y3 - y4) * (x1 - x3) + (x4 - x3) * (y1 - y3)) / det
t1 = ((y1 - y2) * (x1 - x3) + (x2 - x1) * (y1 - y3)) / det
return [x1 * (1 - t0) + x2 * t0, y1 * (1 - t0) + y2 * t0], t0, t1
def line_offset(line, distance):
((x1, y1), (x2, y2)) = line
(vx, vy) = (x2 - x1, y2 - y1)
line_len = vx * vx + vy * vy
if line_len < EPSILON:
return None
line_len = math.sqrt(line_len)
dx = -vy * distance / line_len
dy = vx * distance / line_len
return np.array([[x1 + dx, y1 + dy], [x2 + dx, y2 + dy]])
def line_offset_batch(batch, distance):
"""Offset a batch of line segments to specified distance"""
norms = np.matmul([-1, 1], batch) @ [[0, 1], [-1, 0]]
norms_len = np.sqrt((norms ** 2).sum(-1))[..., None]
offset = norms * distance / norms_len
return batch + offset[..., None, :]
def line_parametric(points):
return bezier_parametric(points)
# ------------------------------------------------------------------------------
# Arc
# ------------------------------------------------------------------------------
def arc_to_bezier3(center, rx, ry, phi, eta, eta_delta):
"""Approximate arc with a sequnce of cubic bezier curves
[Drawing an elliptical arc using polylines, quadraticor cubic Bezier curves]
(http://www.spaceroots.org/documents/ellipse/elliptical-arc.pdf)
[Approximating Arcs Using Cubic Bézier Curves]
(https://www.joecridge.me/content/pdf/bezier-arcs.pdf)
We are using following formula to split arc segment from `eta_1` to `eta_2`
to achieve good approximation arc is split in segments smaller then `pi / 2`.
P0 = A(eta_1)
P1 = P0 + alpha * A'(eta_1)
P2 = P3 - alpha * A'(eta_2)
P3 = A(eta_2)
where
A - arc parametrized by angle
A' - derivative of arc parametrized by angle
eta_1 = eta
eta_2 = eta + eta_delta
alpha = sin(eta_2 - eta_1) * (sqrt(4 + 3 * tan((eta_2 - eta_1) / 2) ** 2) - 1) / 3
"""
M = np.array([[math.cos(phi), -math.sin(phi)], [math.sin(phi), math.cos(phi)]])
arc = lambda a: M @ [rx * math.cos(a), ry * math.sin(a)] + center
arc_d = lambda a: M @ [-rx * math.sin(a), ry * math.cos(a)]
segment_max_angle = math.pi / 4 # maximum `eta_delta` of a segment
segments = []
segments_count = math.ceil(abs(eta_delta) / segment_max_angle)
etas = np.linspace(eta, eta + eta_delta, segments_count + 1)
for eta_1, eta_2 in zip(etas, etas[1:]):
sq = math.sqrt(4 + 3 * math.tan((eta_2 - eta_1) / 2) ** 2)
alpha = math.sin(eta_2 - eta_1) * (sq - 1) / 3
p0 = arc(eta_1)
p3 = arc(eta_2)
p1 = p0 + alpha * arc_d(eta_1)
p2 = p3 - alpha * arc_d(eta_2)
segments.append([p0, p1, p2, p3])
return np.array(segments)
def arc_svg_to_parametric(src, dst, rx, ry, x_axis_rot, large_flag, sweep_flag):
"""Convert arc from SVG arguments to parametric curve
This code mostly comes from arc implementation notes from svg sepc
(Arc to Parametric)[https://www.w3.org/TR/SVG/implnote.html#ArcImplementationNotes]
Returns arc parameters in parameteric form:
- `src`, `dst` - usefull if implementation wants to know stat and end without recomputation
- `center` - center of an elpise
- `rx`, `ry` - elipse radii
- `phi` - eplise rotation with regard to x axis
- `eta` - initial parameter anple
- `eta_delta` - differentse between final and initial `eta` values
Curve is specified in a following form:
eta(t) = eta + t * eta_delta
arc(t) = [[cos(phi), -sin(phi)], [sin(phi), cos(phi)]] @ [rx * cos(eta(t)), ry * sin(eta(t))] + [cx, cy]
"""
rx, ry = abs(rx), abs(ry)
src, dst = np.array(src), np.array(dst)
phi = x_axis_rot * math.pi / 180
cos_phi, sin_phi = math.cos(phi), math.sin(phi)
M = np.array([[cos_phi, sin_phi], [-sin_phi, cos_phi]])
# Eq 5.1
x1, y1 = np.matmul(M, (src - dst) / 2)
# scale/normalize radii (Eq 6.2)
s = (x1 / rx) ** 2 + (y1 / ry) ** 2
if s > 1:
s = math.sqrt(s)
rx *= s
ry *= s
# Eq 5.2
sq = math.sqrt(max(0, (rx * ry) ** 2 / ((rx * y1) ** 2 + (ry * x1) ** 2) - 1))
if large_flag == sweep_flag:
sq = -sq
center = sq * np.array([rx * y1 / ry, -ry * x1 / rx])
cx, cy = center
# Eq 5.3 convert center to initail coordinates
center = np.matmul(M.T, center) + (dst + src) / 2
# Eq 5.5-6
v0 = np.array([1, 0])
v1 = np.array([(x1 - cx) / rx, (y1 - cy) / ry])
v2 = np.array([(-x1 - cx) / rx, (-y1 - cy) / ry])
# initial angle
eta = angle_between(v0, v1)
# delta angle to be covered when t changes from 0..1
eta_delta = math.fmod(angle_between(v1, v2), 2 * math.pi)
if not sweep_flag and eta_delta > 0:
eta_delta -= 2 * math.pi
if sweep_flag and eta_delta < 0:
eta_delta += 2 * math.pi
return center, rx, ry, phi, eta, eta_delta
def arc_parametric(center, rx, ry, phi, eta, eta_delta):
def arc(t):
"""Parametric arc curve"""
angle = eta + t * eta_delta
return M @ [rx * math.cos(angle), ry * math.sin(angle)] + center
M = np.array([[math.cos(phi), -math.sin(phi)], [math.sin(phi), math.cos(phi)]])
return arc
def arc_deriv_parametric(center, rx, ry, phi, eta, eta_delta):
def arc_deriv(t):
angle = eta + t * eta_delta
return M @ [-rx * math.sin(angle), ry * math.cos(angle)] * eta_delta
M = np.array([[math.cos(phi), -math.sin(phi)], [math.sin(phi), math.cos(phi)]])
return arc_deriv
def angle_between(v0, v1):
"""Calculate angle between two vectors"""
angle_cos = | np.dot(v0, v1) | numpy.dot |
import logging
import numpy as np
from scipy.optimize import minimize
from sklearn.model_selection import KFold
from .Kernel import Kernel
from .Kernel import RBF
from .Plotting import plot_BayOpt
logger = logging.getLogger(__name__)
class GP():
"""
Gaussian Process class
...
Attributes
----------
dim_input : int
Dimension of the input space
dim_output : int
Dimension of the output space
dimension : int
Number of the training points
X : np.array
Training sample points written as column vector. 5 Training points of 2 dimensions -> shape(5,2)
1 Training point of 2 dimensions -> shape(1,1)
Y : np.array
Training target points written as column vector. 5 Target points of 1 dimension -> shape(5,1)
1 Target point of 1 dimension -> shape(1,1)
data : dict
Dictionary with X and Y as keys that holds the values of the respective array
kernel : Kernel object (default RBF)
Chosen kernel for the Gaussian Process
cov : np.array (default None)
Covariance of the GP
normalize_y : bool (default True)
Flag to normalize the target values to 0 mean and 1 variance
marg : float (default None)
Log Marginal Likelihood value
_stat : bool (default False)
Flag for the fit
Example
---------
x=np.random.uniform(0,3,10)[:,None]
y=np.sin(x)
gp = GP(x, y)
gp.optimize()
Methods
---------
"""
def __init__(self, X: np.ndarray, Y: np.ndarray, kernel: Kernel = RBF(), cov: np.ndarray = None, normalize_y=True):
"""
X : np.array
Training sample points written as column vector.
Y : np.array
Training target points written as column vector.
kernel : Kernel object
cov : np.array (default None)
Covariance of the GP after the fit. A covariance matrix can be passed to use for the prediction.
normalize_y : bool (default True)
Flag to normalize the target values to 0 mean and 1 variance
"""
self.dim_input = X[0].shape[0]
self.dim_output = Y[0].shape[0]
self.dimension = X.shape[0]
self.X_train = X
self.Y_train = Y
self.data = {"X": self.X_train, "Y": self.Y_train}
self.kernel = kernel
self.cov = cov
self.normalize_y = normalize_y
self.marg = None
self._stat = False
def log_marginal_likelihood(self):
"""
Compute the Log Marginal Likelihood for the current set of Training points and the current
hyperparameters while storing the result value in __marg.
By default it tries to use the cholesky decomposition to compute the log marginal likelihood.
If there is some numerical error (usually by too litlle noise) it tries to use the standard
inversion routine of the Graham Matrix. If it happens the noise of the GP should be increased.
"""
Y = self.get_Y()
if self.normalize_y:
self._mean_y = np.mean(self.get_Y(), axis=0)
self._std_y = np.std(self.get_Y(), axis=0)
Y = (self.get_Y() - self._mean_y) / self._std_y
kernel = self.get_kernel().kernel_product(self.get_X(), self.get_X())
kernel[np.diag_indices_from(kernel)] += self.get_noise() ** 2
try:
if self._stat:
K = self.get_cov()
else:
K = np.linalg.cholesky(kernel)
marg = - .5 * Y.T.dot(np.linalg.lstsq(K.T, np.linalg.lstsq(K, Y, rcond=None)[0], rcond=None)[0]) \
- .5 * np.log(np.diag(K)).sum() \
- .5 * K.shape[0] * np.log(2 * np.pi)
except np.linalg.LinAlgError as exc:
logging.info("\nComputing as a normal inverse\n%s",exc)
K = np.linalg.inv(kernel)
marg = - .5 * Y.T.dot(K.dot(Y)) \
- .5 * np.log(np.diag(K)).sum() \
- .5 * K.shape[0] * np.log(2 * np.pi)
self.set_marg(marg.flatten())
def compute_log_marginal_likelihood(self, X, Y, pair_matrix, hyper, verbose=False):
"""
Routine to calculate the negative log marginal likelihood for a given set of hyperparameters.
:param X: np.array
Training points for the calculation of the Log Marginal likelihood
:param Y: np.array
Target points for the calculation
:param pair_matrix: np.array
Distance matrix between X and Y
:param hyper: array-like
Array of hyperparameters
:param verbose: bool (default False)
print the process of the optimizers on the console
:return: The value of the negative log marginal likelihood
If eval_grad attribute of the kernel is set on True, the method will use the gradient informations.
With eval_grad=True it will return an array of the negative value for the log marginal likelihood and the
needed derivates.
It tries to calculate using the Cholesky decomposition. If it fails it also tries to
compute the normal inversion of the Graham matrix. If the set of hyperparameters causes the calculations to fail
for a np.linalg.error, it sets the marginal likelihood to infinity to discard the set of parameters.
"""
logger.debug(hyper)
if self.normalize_y:
self._mean_y = np.mean(self.get_Y(), axis=0)
self._std_y = np.std(self.get_Y(), axis=0)
Y = (self.get_Y() - self._mean_y) / self._std_y
kernel = self.kernel.kernel_(*hyper, pair_matrix)
try:
K = np.linalg.cholesky(kernel)
marg = - .5 * Y.T.dot(np.linalg.lstsq(K.T, np.linalg.lstsq(K, Y, rcond=None)[0], rcond=None)[0]) \
- .5 * np.log(np.diag(K)).sum() \
- .5 * K.shape[0] * np.log(2 * np.pi)
except np.linalg.LinAlgError as exc:
try:
logger.info("\nComputing as a normal inverse\n %s",exc)
K = np.linalg.inv(kernel)
marg = - .5 * Y.T.dot(K.dot(Y)) \
- .5 * np.log(np.diag(K)).sum() \
- .5 * K.shape[0] * np.log(2 * np.pi)
except np.linalg.LinAlgError as exc2:
if verbose:
logger.warning(exc2)
marg = np.inf
if self.get_kernel().get_eval():
marg_grad = self.compute_log_marginal_likelihood_gradient(X, Y, pair_matrix, hyper, verbose=False)
return -marg.flatten(), marg_grad.flatten()
else:
return -np.array(marg).flatten()
def compute_log_marginal_likelihood_gradient(self, X, Y, pair_matrix, hyper, verbose=False):
"""
Routine to calculate the gradient of log marginal likelihood for a set of hyperparameters.
:param X: np.array
Training points for the calculation of the Log Marginal likelihood
:param Y: np.array
Target points for the calculation
:param pair_matrix: np.array
Distance matrix between X and Y
:param hyper: array-like
Array of hyperparameters
:param verbose: bool (default False)
print the process of the optimizers on the console
:return: The value of the gradients of negative log marginal likelihood.
"""
logger.debug("GRADIENT mode\t%s", hyper)
hyper = np.squeeze(hyper)
m_g = lambda h: -(.5 * Y.T.dot(K.dot(h.dot(K.dot(Y)))) - .5 * np.diag(K.dot(h)).sum())
kernel = self.kernel.kernel_eval_grad_(*hyper, pair_matrix)
K = np.linalg.inv(kernel[0])
try:
grad_kernel = [m_g(i) for i in kernel[1:]]
except np.linalg.LinAlgError as exc:
if verbose:
logger.warning(exc)
return np.array(grad_kernel)
def grid_search_optimization(self, constrains, n_points, function=np.linspace, verbose=False):
"""
Routine called by optimize_grid to handle the optimization.
:param constrains: list
Array-like with the constrains for the hyperparameters. Ex: [[lb,ub],[lb,ub],[lb,ub]]
:param n_points: int
Number of points sampled in each dimension. The number of total evaluations will be n_points^d(hyper)
:param function: callable (default np.linspace)
function that will be used to generate the sampling point.
np.random.uniform : randomized grid search
np.linspace : normal grid search
:param verbose: bool (default False)
print the process of the optimizers on the console
"""
self.__optimizer = "Grid search"
def check_best(best, new):
return best["marg"] < new
def set_dict(new_marg, new_hyper):
best["marg"] = new_marg
best["hyper"] = new_hyper
if self.get_marg() is not None:
best = {"marg": self.get_marg(), "hyper": self.get_kernel().gethyper()}
else:
self.log_marginal_likelihood()
best = {"marg": self.get_marg(), "hyper": self.get_kernel().gethyper()}
X, Y = self.get_X(), self.get_Y()
pair_matrix = np.sum(X ** 2, axis=1)[:, None] + np.sum(X ** 2, axis=1) - 2 * np.dot(X, X.T)
hyper_grid = generate_grid(3, n_points, constrains, function)
for i in hyper_grid:
tmp_marg = self.compute_log_marginal_likelihood(X, Y, pair_matrix, i, verbose)
if check_best(best, -tmp_marg):
set_dict(-tmp_marg, i)
return best
def optimize_grid(self, constrains=[[1e-5, 30], [1e-5, 30], [1e-5, 10]], n_points=100, function=np.linspace,
verbose=False):
"""
Routine for optimizing the hyperparameters by maximizing the log marginal Likelihood by a naive grid search.
:param constrains: list (default [[1e-5, 30], [1e-5, 30], [1e-5, 10]])
Array-like with the constrains for the hyperparameters. Ex: [[lb,ub],[lb,ub],[lb,ub]]
:param n_points: int (default 100)
Number of points sampled in each dimension. The number of total evaluations will be n_points^3
:param function: func (default np.linspace)
function that will be used to generate the sampling point.
np.random.uniform : randomized grid search
np.linspace : normal grid search
:param verbose: bool (default False)
print the process of the optimizers on the console
"""
args = (constrains, n_points, function, verbose)
new = self.grid_search_optimization(*args)
self.set_marg(new["marg"])
# fare un buon metodo set hyper
self.set_hyper(*new["hyper"])
self.fit()
def optimize(self, n_restarts=10, optimizer="L-BFGS-B", verbose=False):
"""
Optimization Routine for the hyperparameters of the GP by Minimizing the negative log Marginal Likelihood.
n_restarts : int (default 10)
Number of restart points for the optimizer
optimizer : str (default L-BFGS-B)
Type of Optimizer chosen for the task. Because the Optimization is bounded, the following
optimizers can be used: L-BFGS-B, SLSCP, TNC
For a better documentation of the optimizers follow the Scipy documentation
verbose : bool (default False)
print the process of the optimizers on the console
If eval_grad of the Kernel is set on True , the
gradient of the Log Marginal Likelihood will be calculated and used for the optimization. This usually speed up
the convergence but it also makes the Optimizer more prone to find local minima.
"""
self.__optimizer = optimizer
self.log_marginal_likelihood()
old_marg = self.get_marg()
old_hyper = self.get_kernel().gethyper()
hyper_dim = len(old_hyper)
boundaries = self.get_boundary()
#print(boundaries)
eval_grad = self.get_kernel().get_eval()
logger.debug("Starting Log Marginal Likelihood Value: %s", old_marg)
X_d, Y_d = self.get_X(), self.get_Y()
pair_matrix = np.sum(X_d ** 2, axis=1)[:, None] + np.sum(X_d ** 2, axis=1) - 2 * np.dot(X_d, X_d.T)
new_hyper = None
new_marg = None
it = 0
# Optimization Loop
for i in np.random.uniform(boundaries[:, 0], boundaries[:, 1], size=(n_restarts, hyper_dim)):
it += 1
logger.debug("RESTART : %s , %s", it, i)
res = minimize(lambda h: self.compute_log_marginal_likelihood(X=X_d,
Y=Y_d,
pair_matrix=pair_matrix,
verbose=verbose,
hyper=(np.squeeze(
h.reshape(-1, hyper_dim)))),
x0=i,
bounds=((1e-5, None), (1e-5, None), (1e-5, None)),
method=self.__optimizer,
jac=eval_grad)
if not res.success:
continue
try:
if new_marg is None or res.fun[0] < new_marg:
new_marg = res.fun[0]
new_hyper = res.x
except:
pass
logger.info(res.fun)
# If the optimization doesn't converge set the value to old parameters
if new_marg is None:
if verbose:
logger.warning("Using Old Log Marg Likelihood")
new_marg = old_marg
new_hyper = old_hyper
logger.info("New Log Marginal Likelihood Value: %s", -new_marg, new_hyper)
# Update and fit the new gp model
self.set_hyper(*new_hyper)
self.set_marg(-new_marg)
self.fit()
def fit(self):
"""
Compute the Graham Matrix for the kernel and the cholesky decomposition required for the prediction.
It stores the result in cov and change the flag of stat in True
"""
ker = self.get_kernel()
n = self.get_dim_data()
try:
kernel = self.get_kernel().kernel_product(self.get_X(), self.get_X())
kernel[np.diag_indices_from(kernel)] += self.get_noise() ** 2
self.cov = np.linalg.cholesky(kernel)
self._stat = True
except np.linalg.LinAlgError as exc:
raise ValueError("Cholesky decomposition encountered a numerical error\nIncrease the Noise Level\n", exc)
def predict(self, X):
"""
Make prediction on X samples
:param X: np.array
:return: tuple of 2 elements
GP mean and GP Variance
"""
# Check if we require to normalize the target values
# normalizer = np.sqrt(2 * np.pi * ker.gethyper()[0] ** 2)
ker = self.get_kernel()
K_sample = ker.kernel_product(self.get_X(), X)
inv_cov = np.linalg.solve(self.get_cov(), K_sample)
if not self.normalize_y:
# cov_sample = ker.kernel_product(X,X)
# Mean
mean = np.dot(inv_cov.T, np.linalg.solve(self.get_cov(), self.get_Y()))
# general case
# Variance
# var = ker.gethyper()[0] ** 2 + ker.gethyper()[2] - np.sum(inv_cov ** 2, axis=0)
var = ker.kernel_var() - np.sum(inv_cov ** 2, axis=0)
var_neg = var < 0
var[var_neg] = 0.
var = np.sqrt(var)[:, None]
return mean, var
else:
# Normalize Y
self._mean_y = np.mean(self.get_Y(), axis=0)
self._std_y = np.std(self.get_Y(), axis=0)
Y = (self.get_Y() - self._mean_y) / self._std_y
# MEAN
y_mean = np.dot(inv_cov.T, np.linalg.solve(self.get_cov(), Y))
# DESTANDARDIZE
y_mean = (self._std_y * y_mean + self._mean_y)
# VARIANCE
# var = ker.gethyper()[0] ** 2 + self.get_noise() - np.sum(inv_cov ** 2, axis=0)
var = ker.kernel_var() - np.sum(inv_cov ** 2, axis=0)
# REMOVE VARIANCE VALUE LESS THAN 0
var_neg = var < 0
var[var_neg] = 0.
# DeStandardize
var = np.sqrt(var * self._std_y ** 2)[:, None]
return y_mean, var
def plot(self, X):
"""
Function that handles the prediction of the GP object and the plotting without returning anything.
For visual reasons it only works with input data of 1 dimension and 2 dimension
:param X: np.array
Data to use to predict and plot
"""
mean, var = self.predict(X)
dim = self.get_dim_data()
args = [self.get_X(), self.get_Y(), X, mean, var]
plt = plot_BayOpt(*args)
plt.show()
def prepare_fold(self, n):
kf = KFold(n_splits=n)
kf.get_n_splits(self.get_dim_data())
folds = []
for train, test in kf.split(self.get_X()):
folds.append([train, test])
return folds
@staticmethod
def RMSE(gp_model, dataset_X, dataset_Y, test_index):
def func(pred, test):
return np.sqrt(np.mean(np.squeeze((pred - test) ** 2)))
gp_model.fit()
test_x = dataset_X[test_index]
test_y = dataset_Y[test_index]
pred = gp_model.predict(test_x)
return func(pred, test_y)
def k_fold_cv(self, n_fold, hyper):
index = self.prepare_fold(n_fold)
RMSE = 0
for i in range(n_fold):
X_train, X_test = self.get_X()[index[i][0]], self.get_X()[index[i][1]]
Y_train, Y_test = self.get_Y()[index[i][0]], self.get_Y()[index[i][1]]
cv_gp = GP(X_train, Y_train, kernel=RBF(*hyper))
RMSE += GP.RMSE(cv_gp, self.get_X(), self.get_Y(), index[i][1])
return RMSE / n_fold
def augment_dataset(self, dataset, new_data):
"""
General function to augment an array with a shape check
:param dataset: Dataset to augment
:param new_data: Data to agument the dataset with
:return: new array
"""
try:
dataset.shape[1] == new_data.shape[1]
return np.concatenate((dataset, new_data))
except:
try:
dataset.shape[1] == new_data.shape[0]
return np.concatenate((dataset, np.expand_dims(new_data, axis=0)))
except:
raise ValueError(f'Data dimensions are wrong: {dataset.shape} != {new_data.shape}')
def augment_X(self, new_data):
self.X_train = self.augment_dataset(self.get_X(), new_data)
def augment_Y(self, new_data):
self.Y_train = self.augment_dataset(self.get_Y(), new_data)
def augment_XY(self, new_data_X, new_data_Y):
self.augment_X(new_data_X)
self.augment_Y(new_data_Y)
def get_kernel(self):
return self.kernel
def get_state(self):
return self._stat
def get_marg(self):
return self.marg
def get_cov(self):
return self.cov
def get_X(self):
return self.X_train
def get_Y(self):
return self.Y_train
def get_dim_data(self):
return self.dimension
def get_dim_outspace(self):
return self.dim_output
def set_marg(self, marg):
self.marg = marg
def get_boundary(self):
"""
Get the boundaries for the hyperparameters optimization routine.
:return: np.array
Array of boundaries
If no boundaries were previously set it creates some dummy boundaries (1e-5,10) for all hyperparameters
in the kernel.
"""
try:
return self._boundary
except AttributeError:
self._boundary = np.asarray([[1e-4, 10] for i in range(len(self.get_kernel().gethyper()))])
return self._boundary
def set_boundary(self, array):
"""
Create the boundaries for the hyperparameters optimization
:param array: list
[lb,ub] type of list to set the boundaries, it can be the same dimensions of the number of hyperparameters
or just have one array inside
If the array has the same length required for the hyperparameters space the space will be bounded.
If the array only has one dimension, then it will set the space as the hypercube of the array lb and ub
All others types of input are not supported
_____________________________________________
Example
set_boundary([[1e-5,4]]) on RBF ---> boundaries: (1e-5,4),(1e-5,4),(1e-5,4)
set_boundary([[1e-5,4],[1,10],[2,3]]) on RBF ---> boundaries: (1e-5,4),(1,10),(2,3)
"""
n = len(self.get_kernel().gethyper())
if len(array) == 2:
self._boundary = np.asarray([array for i in range(n)])
if len(array) == n:
self._boundary = np.asarray(array)
def set_hyper(self, *hypers):
self.get_kernel().sethyper(*hypers)
def get_noise(self):
ker = self.get_kernel()
return ker.get_noise()
def save_model(self, path):
with open(path, "w") as file:
file.write(str(self))
def __str__(self):
header = "#=========================GP===========================\n"
tail = "#======================================================"
X, Y = self.get_X(), self.get_Y()
try:
gp_info = f"Optimizer: {self.__optimizer}\n"
except:
gp_info = f"Optimizer: No Optimized\n"
kernel_info = str(self.get_kernel())
train_info = f'Train values: {self.get_dim_data()}\nInput Dimension: {self.dim_input} Output Dimension: {self.get_dim_outspace()}\n'
train_info += f'\t\t\t\tX_train\t\t\t\tY_train\n'
train_info += f'{np.hstack((X, Y))}\n\n'
gp_info += f'Noise: {self.get_noise()}\nLog Marginal Likelihood: {self.get_marg()}\n'
surprise = "\n░░░░░░░░▄▄▄▀▀▀▄▄███▄░░░░░░░░░░░░░░\n░░░░░▄▀▀░░░░░░░▐░▀██▌░░░░░░░░░░░░░\n░░░▄▀░░░░▄▄███░▌▀▀░▀█░░░░░░░░░░░░░\n░░▄█░░▄▀▀▒▒▒▒▒▄▐░░░░█▌░░░░░░░░░░░░\n░▐█▀▄▀▄▄▄▄▀▀▀▀▌░░░░░▐█▄░░░░░░░░░░░\n░▌▄▄▀▀░░░░░░░░▌░░░░▄███████▄░░░░░░\n░░░░░░░░░░░░░▐░░░░▐███████████▄░░░\n░░░░░le░░░░░░░▐░░░░▐█████████████▄\n░░░░toucan░░░░░░▀▄░░░▐█████████████▄\n░░░░░░has░░░░░░░░▀▄▄███████████████\n░░░░░arrived░░░░░░░░░░░░█▀██████░░\n"
return header + kernel_info + gp_info + train_info + tail + surprise
def __repr__(self):
header = "#=========================GP===========================\n"
tail = "#======================================================"
X, Y = self.get_X(), self.get_Y()
try:
gp_info = f"Optimizer: {self.__optimizer}\n"
except:
gp_info = f"Optimizer: No Optimized\n"
kernel_info = str(self.get_kernel())
train_info = f'Train values: {self.get_dim_data()}\nInput Dimension: {self.dim_input} Output Dimension: {self.get_dim_outspace()}\n'
train_info += f'\t\t\t\tX_train\t\t\t\tY_train\n'
train_info += f'{ | np.hstack((X, Y)) | numpy.hstack |
from http.cookies import CookieError
import numpy as np
import pandas as pd
from panel import state
from sklearn.linear_model import LogisticRegression
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
from sklearn.multiclass import OneVsRestClassifier
from scipy.sparse import csr_matrix
from scipy.spatial.distance import squareform
from group_lasso import LogisticGroupLasso
from tqdm import tqdm
import warnings
from .utils.plot import plot_regularization_path, plot_classifier_complexity_vs_accuracy
from ._configs import *
__all__ = ["Classifier","prepare_training_dataset"]
def prepare_training_dataset(descriptors, states_labels, n_configs, regex_filter = None, states_subset=None):
"""Sample points from trajectory
Args:
n_configs (int): number of points to sample for each metastable state
regex_filter (str, optional): regex to filter the features. Defaults to '.*'.
states_subset (list, optional): list of integers corresponding to the metastable states to sample. Defaults to None take all states.
states_names (list, optional): list of strings corresponding to the name of the states. Defaults to None.
Returns:
(configurations, labels), features_names, states_names
"""
assert len(descriptors) == len(states_labels), "Length mismatch between descriptors and states_labels."
if regex_filter is not None:
features = descriptors.filter(regex=regex_filter).columns.values
else:
features = descriptors.columns.values
config_list = []
labels = []
if isinstance(states_labels, pd.DataFrame):
pass
elif isinstance(states_labels, np.ndarray):
states_labels = np.squeeze(states_labels)
columns = ['labels']
if states_labels.ndim == 2:
columns.append('selection')
states_labels = pd.DataFrame(data=states_labels, columns=columns)
else:
raise TypeError(
f"{states_labels}: Accepted types are 'pandas.Dataframe' or 'numpy.ndarray' "
)
if not ('selection' in states_labels):
states_labels['selection'] = np.ones(len(states_labels), dtype=bool)
# convert labels in string
states_labels['labels'] = states_labels['labels'].astype(str)
if states_subset is None:
states_subset = states_labels['labels'].unique()
states_subset = states_subset[states_subset != 'undefined' ]
for label in states_subset:
#select label
df = descriptors.loc[ (states_labels['labels'] == label) & (states_labels['selection'] == True)]
#select descriptors and sample
replace = False
if n_configs > len(df):
warnings.warn("The asked number of samples is higher than the possible unique values. Sampling with replacement")
replace = True
if regex_filter is not None:
config_i = df.filter(regex=regex_filter).sample(n=n_configs, replace=replace).values
else:
config_i = df.sample(n=n_configs, replace=replace).values
config_list.append(config_i)
labels.extend([label]*n_configs)
labels = np.array(labels)
configurations = np.vstack(config_list)
return (configurations, labels), features
class Classifier():
def __init__(self, dataset, features_names, rescale=True, test_size=0.25):
self._X, self._labels = dataset
_tmp_classes, self._labels = np.unique(self._labels, return_inverse=True)
self.classes = dict()
for _i, _class in enumerate(_tmp_classes):
self.classes[_i] = f"{_class}"
self._rescale = rescale
self._test_size = test_size
if self._rescale:
scaler = StandardScaler(with_mean=True)
scaler.fit(self._X)
self._X = scaler.transform(self._X)
self._train_in, self._val_in, self._train_out, self._val_out = train_test_split(self._X, self._labels, test_size=self._test_size)
self._n_samples = self._train_in.shape[0]
self.features = features_names
self._computed = False
def compute(self, reg, max_iter = 100, quadratic_kernel=False, groups=None, warm_start = True):
if self._computed:
warnings.warn("Warning: deleting old computed data")
self._purge()
if hasattr(reg, '__iter__') == False:
reg = np.array([reg])
_num_reg = len(reg)
_n_basins = len(np.unique(self._train_out))
self._reg = reg
if quadratic_kernel:
train_in, val_in = quadratic_kernel_featuremap(self._train_in), quadratic_kernel_featuremap(self._val_in)
else:
train_in = self._train_in
val_in = self._val_in
_n_features = train_in.shape[1]
if groups is not None:
groups_names, groups = np.unique(groups, return_inverse=True)
if quadratic_kernel:
assert len(groups) == train_in.shape[1], "Length of group array does not match quadratic features number."
else:
assert len(groups) == len(self.features), "Length of group array does not match features number."
_is_group = True
_reg_name = 'estimator__group_reg'
tmp_model = LogisticGroupLasso(groups, group_reg = reg[0], l1_reg=0, n_iter=max_iter, supress_warning=True, scale_reg='none', warm_start=False)
model = OneVsRestClassifier(tmp_model, n_jobs=2)
else:
_is_group = False
_reg_name = 'C'
reg = (reg*self._n_samples)**-1
model = LogisticRegression(penalty='l1', C=reg[0], solver='liblinear', multi_class='ovr', fit_intercept=False, max_iter=max_iter, warm_start=warm_start)
coeffs = np.empty((_num_reg, _n_basins, _n_features))
crossval = np.empty((_num_reg,))
_classes_labels = np.empty((_num_reg, _n_basins), dtype=np.int_)
for reg_idx in tqdm(range(len(reg)), desc='Optimizing Lasso Estimator'):
model.set_params(**{_reg_name: reg[reg_idx]})
model.fit(train_in,self._train_out)
crossval[reg_idx] = model.score(val_in,self._val_out)
_classes_labels[reg_idx] = model.classes_.astype(int)
if _is_group:
assert _n_basins == model.classes_.shape[0]
tmp_coeffs = np.empty((_n_basins, _n_features))
for est_idx, _e in enumerate(model.estimators_):
tmp_coeffs[est_idx] = _e.coef_[:,0]
coeffs[reg_idx] = tmp_coeffs
else:
coeffs[reg_idx] = model.coef_
self._quadratic_kernel=quadratic_kernel
self._coeffs = coeffs
self._crossval = crossval
self._classes_labels = _classes_labels
self._groups = groups
if _is_group:
self._groups_names = groups_names
self._groups_mask = [
self._groups == u
for u in np.unique(self._groups)
]
self._computed = True
# Count number of features for each regularization value.
num_feat = np.empty((_num_reg,),dtype=int)
for i,reg in enumerate(self._reg):
selected = self._get_selected(reg, feature_mode=False)
unique_idxs = set()
for state in selected.values():
for data in state:
unique_idxs.add(data[0])
num_feat[i] = len(unique_idxs)
self._num_feat = num_feat
def _purge(self):
if __DEV__:
print("DEV >>> Purging old data")
if self._computed:
del self._quadratic_kernel
del self._reg
del self._coeffs
del self._crossval
del self._classes_labels
del self._num_feat
if self._groups is not None:
del self._groups_names
del self._groups_mask
del self._groups
self._computed = False
def _closest_reg_idx(self, reg):
assert self._computed, "You have to run Classifier.compute first."
return np.argmin(np.abs(self._reg - reg))
def _get_selected(self, reg, feature_mode=False):
reg_idx = self._closest_reg_idx(reg)
coefficients = self._coeffs[reg_idx]
_classes = self._classes_labels[reg_idx]
selected = dict()
group_mode = (not feature_mode) and (self._groups is not None)
for idx, coef in enumerate(coefficients):
state_name = self.classes[_classes[idx]]
if group_mode:
coef = np.array([np.linalg.norm(coef[b])**2 for b in self._groups_mask])
else:
coef = coef**2
nrm = np.sum(coef)
if nrm < __EPS__:
selected[state_name] = []
else:
coef = csr_matrix(coef/nrm)
sort_perm = | np.argsort(coef.data) | numpy.argsort |
import jax.numpy as jnp
from jax import grad, vmap, hessian, jit
import jax.ops as jop
from jax.config import config;
config.update("jax_enable_x64", True)
# numpy
import numpy as onp
from numpy import random
import scipy.io
import argparse
import logging
import datetime
from time import time
import os
def get_parser():
parser = argparse.ArgumentParser(description='Allen Cahn equation GP solver')
parser.add_argument("--nu", type=float, default = 1e-4)
parser.add_argument("--kernel", type=str, default="gaussian", choices=["gaussian","inv_quadratics"])
parser.add_argument("--sigma", type = float, default = 0.02)
parser.add_argument("--dt", type = float, default = 0.04)
parser.add_argument("--T", type = float, default = 1.0)
parser.add_argument("--N_domain", type = int, default = 512)
parser.add_argument("--nugget", type = float, default = 1e-13)
parser.add_argument("--GNsteps", type = int, default = 2)
parser.add_argument("--logroot", type=str, default='./logs/')
parser.add_argument("--randomseed", type=int, default=9999)
args = parser.parse_args()
return args
def sample_points(num_pts, dt, T, option = 'grid'):
Nt = int(T/dt)+1
X_domain = onp.zeros((Nt,num_pts,2))
if option == 'grid':
for i in range(Nt):
X_domain[i,:,0] = i*dt
X_domain[i,:,1] = onp.linspace(-1.0,1.0, num_pts)
return X_domain
def assembly_Theta(X_domain, sigma):
N_domain = onp.shape(X_domain)[0]
N_boundary = 0
Theta = onp.zeros((3*N_domain+N_boundary, 3*N_domain+N_boundary))
# auxiliary vector for construncting Theta
# domain-domain
XdXd = onp.tile(X_domain, (N_domain,1))
XdXd_T = onp.transpose(XdXd)
XdXb1 = onp.transpose(onp.tile(X_domain,(N_domain+N_boundary,1)))
X_all = X_domain
XdXb2 = onp.tile(X_all,(N_domain,1))
XdbXdb = onp.tile(X_all,(N_domain+N_boundary,1))
XdbXdb_T = onp.transpose(XdbXdb)
val = vmap(lambda x1,y1: Delta_x1_Delta_y1_kappa(x1,y1, sigma))(XdXd_T.flatten(), XdXd.flatten())
Theta[:N_domain,:N_domain] = onp.reshape(val, (N_domain,N_domain))
val = vmap(lambda x1,y1: Delta_x1_D_y1_kappa(x1,y1, sigma))(XdXd_T.flatten(), XdXd.flatten())
Theta[:N_domain,N_domain:2*N_domain] = onp.reshape(val, (N_domain,N_domain))
Theta[N_domain:2*N_domain,:N_domain] = onp.transpose(onp.reshape(val, (N_domain,N_domain)))
val = vmap(lambda x1,y1: Delta_x1_kappa(x1,y1, sigma))(XdXb1.flatten(), XdXb2.flatten())
Theta[:N_domain,2*N_domain:] = onp.reshape(val,(N_domain,N_domain+N_boundary))
Theta[2*N_domain:,:N_domain] = onp.transpose(onp.reshape(val,(N_domain,N_domain+N_boundary)))
val = vmap(lambda x1,y1: D_x1_D_y1_kappa(x1,y1, sigma))(XdXd_T.flatten(), XdXd.flatten())
Theta[N_domain:2*N_domain,N_domain:2*N_domain] = onp.reshape(val, (N_domain,N_domain))
val = vmap(lambda x1,y1: D_x1_kappa(x1,y1, sigma))(XdXb1.flatten(), XdXb2.flatten())
Theta[N_domain:2*N_domain,2*N_domain:] = onp.reshape(val,(N_domain,N_domain+N_boundary))
Theta[2*N_domain:,N_domain:2*N_domain] = onp.transpose(onp.reshape(val,(N_domain,N_domain+N_boundary)))
val = vmap(lambda x1,y1: kappa(x1,y1, sigma))(XdbXdb_T.flatten(), XdbXdb.flatten())
Theta[2*N_domain:,2*N_domain:] = onp.reshape(val, (N_domain+N_boundary,N_domain+N_boundary))
return Theta
@jit
def J_loss(v, rhs_f, L,dt):
N_domain = onp.shape(rhs_f)[0]
vec_u = jnp.append(v[:N_domain-1],v[0])
vec_u_x = jnp.append(v[N_domain-1:],v[N_domain-1])
vec_u_xx = (2/dt*vec_u+5*vec_u**3-5*vec_u-rhs_f)/nu
vv = jnp.append(vec_u_xx,vec_u_x)
vv = jnp.append(vv,vec_u)
temp = jnp.linalg.solve(L,vv)
return jnp.dot(temp, temp)
grad_J = grad(J_loss)
@jit
def GN_J(v, rhs_f, L, dt, v_old):
N_domain = onp.shape(rhs_f)[0]
vec_u_old = jnp.append(v_old[:N_domain-1],v_old[0])
vec_u = jnp.append(v[:N_domain-1],v[0])
vec_u_x = jnp.append(v[N_domain-1:],v[N_domain-1])
vec_u_xx = (2/dt*vec_u+15*vec_u_old**2*vec_u-5*vec_u-rhs_f)/nu
vv = jnp.append(vec_u_xx,vec_u_x)
vv = jnp.append(vv,vec_u)
temp = jnp.linalg.solve(L,vv)
return jnp.dot(temp, temp)
Hessian_GN=jit(hessian(GN_J))
def time_steping_solve(X_domain, dt,T,num_pts, step_size = 1, nugget = 1e-10, sigma=0.2, GN_iteration = 4):
Nt = int(T/dt)+1
sol_u = onp.zeros((Nt,num_pts))
sol_u_x = onp.zeros((Nt,num_pts))
sol_u_xx = onp.zeros((Nt,num_pts))
sol_u[0,:]=vmap(u)(X_domain[0,:,0],X_domain[0,:,1])
sol_u_x[0,:]=vmap(u_x)(X_domain[0,:,0],X_domain[0,:,1])
sol_u_xx[0,:]=vmap(u_xx)(X_domain[0,:,0],X_domain[0,:,1])
Theta = assembly_Theta(X_domain[0,:,1], sigma)
N_domain = num_pts
# adaptive nugget term
trace1 = jnp.trace(Theta[:N_domain, :N_domain])
trace2 = jnp.trace(Theta[N_domain:2*N_domain, N_domain:2*N_domain])
trace3 = jnp.trace(Theta[2*N_domain:, 2*N_domain:])
ratio = [trace1/trace3, trace2/trace3]
temp=jnp.concatenate((ratio[0]*jnp.ones((1,N_domain)),ratio[1]*jnp.ones((1,N_domain)),jnp.ones((1,N_domain))), axis=1)
Theta = Theta + nugget*jnp.diag(temp[0])
L = jnp.linalg.cholesky(Theta)
time_begin = time()
for iter_i in range(Nt-1):
# solve at t = (iter_i+1)*dt
# get rhs_f and bdy_g
rhs_f = 2/dt*sol_u[iter_i,:]+nu*sol_u_xx[iter_i,:]-5*sol_u[iter_i,:]**3+5*sol_u[iter_i,:]
sol = jnp.append(sol_u[iter_i,0:N_domain-1],sol_u_x[iter_i,0:N_domain-1]) # initialization
for iter_step in range(GN_iteration):
temp = jnp.linalg.solve(Hessian_GN(sol,rhs_f,L,dt,sol), grad_J(sol,rhs_f,L,dt))
sol = sol - step_size*temp
total_mins = (time() - time_begin) / 60
logging.info(f'[Timer] GP iteration {iter_step+1}/{GN_step}, finished in {total_mins:.2f} minutes')
sol_u[iter_i+1,:] = onp.append(sol[:num_pts-1],sol[0])
sol_u_x[iter_i+1,:] = onp.append(sol[num_pts-1:],sol[num_pts-1])
sol_u_xx[iter_i+1,:] = (2/dt*sol_u[iter_i+1,:]+5*sol_u[iter_i+1,:]**3-5*sol_u[iter_i+1,:]-rhs_f)/nu
t = (iter_i+1)*dt
logging.info(f'[Time marching] at iteration {iter_i+1}/{Nt-1}, solving eqn at time t = {t:.2f}')
return sol_u
# log the results
def logger(args, level = 'INFO'):
log_root = args.logroot + 'Allen_Cahn'
log_name = 'kernel' + str(args.kernel)
logdir = os.path.join(log_root, log_name)
os.makedirs(logdir, exist_ok=True)
log_para = 'nu' + f'{args.nu:.3f}' + 'sigma' + str(args.sigma) + '_Ndomain' + str(args.N_domain) + '_nugget' + str(args.nugget).replace(".","")
date = str(datetime.datetime.now())
log_base = date[date.find("-"):date.rfind(".")].replace("-", "").replace(":", "").replace(" ", "_")
filename = log_para + '_' + log_base + '.log'
logging.basicConfig(level=logging.__dict__[level],
format="%(asctime)s [%(levelname)s] %(message)s",
handlers=[
logging.FileHandler(logdir+'/'+filename),
logging.StreamHandler()]
)
def set_random_seeds(args):
random_seed = args.randomseed
random.seed(random_seed)
# boundary condition
def u(x1, x2):
return (x2**2)*jnp.cos(jnp.pi*x2)
def u_x(x1, x2):
return grad(u,1)(x1,x2)
def u_xx(x1, x2):
return grad(u_x,1)(x1,x2)
# right hand side
def f(x1, x2):
return 0
# plot parameters
def set_plot():
fsize = 15
tsize = 15
tdir = 'in'
major = 5.0
minor = 3.0
lwidth = 0.8
lhandle = 2.0
plt.style.use('default')
plt.rcParams['text.usetex'] = True
plt.rcParams['font.size'] = fsize
plt.rcParams['legend.fontsize'] = tsize
plt.rcParams['xtick.direction'] = tdir
plt.rcParams['ytick.direction'] = tdir
plt.rcParams['xtick.major.size'] = major
plt.rcParams['xtick.minor.size'] = minor
plt.rcParams['ytick.major.size'] = 5.0
plt.rcParams['ytick.minor.size'] = 3.0
plt.rcParams['axes.linewidth'] = lwidth
plt.rcParams['legend.handlelength'] = lhandle
fmt = ticker.ScalarFormatter(useMathText=True)
fmt.set_powerlimits((0, 0))
return fmt
if __name__ == '__main__':
# get argument parser
args = get_parser()
logger(args, level = 'INFO')
logging.info(f'argument is {args}')
nu = args.nu
logging.info(f"[Equation] nu: {nu}")
set_random_seeds(args)
logging.info(f"[Seeds] random seeds: {args.randomseed}")
if args.kernel == "gaussian":
from kernels_Gaussian import *
N_domain = args.N_domain
dt = args.dt
T = args.T
X_domain = sample_points(N_domain, dt, T, option = 'grid')
sigma = args.sigma
nugget = args.nugget
GN_step = args.GNsteps
logging.info(f'GN step: {GN_step}, sigma: {sigma}, number of points: N_domain {N_domain}, kernel: {args.kernel}, nugget: {args.nugget}')
# solve the equation
sol_domain = time_steping_solve(X_domain, dt, T, N_domain, step_size = 1, nugget = nugget, sigma=sigma, GN_iteration = GN_step)
logging.info('[Calculating errs at collocation points ...]')
# # true solution:
# # obtain the ground truth solution via the Cole-Hopf transformation
# # we use numerical integration to get the true solution
data = scipy.io.loadmat('./Allen-Cahn/AC.mat')
# T = 1/0.005+1
# N = 2/2^(-8)
t = data['tt'].flatten()[:,None] # T x 1
x = data['x'].flatten()[:,None] # N x 1
Exact = | onp.real(data['uu']) | numpy.real |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Dec 26 17:12:49 2020
@author: niccolodiana
"""
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from scipy.stats import norm
from scipy.stats import mode
from scipy.stats import multivariate_normal
np.random.seed(1920)
import time
###### METROPOLIS ALGORITHM ##########
##### Simulate data
# Gaussian covariates
p = 5
n = 1000
X = np.ones(n, dtype=int)
X = np.reshape(X, (n, 1))
X = np.hstack((X, np.random.normal(size=(n, p))))
#True betas
true_beta = np.random.uniform(0, 1, size=p+1)
#print("True betas:", true_beta)
#Probit link
p_success = norm.cdf( | np.dot(X, true_beta) | numpy.dot |
import os,sys
import igraph as ig
import numpy as np
import matplotlib.pyplot as plt
import plotly.offline as py
import math
import random
import matplotlib.pyplot as plt
import feather
import pandas as pd
import pygeos as pyg
import logging
from codetiming import Timer
import geopandas as gpd
from timeit import default_timer as timer
from tqdm import tqdm
from pathlib import Path
from plotly.graph_objs import *
import traceback
from numpy import inf
from numpy.ma import masked
from population_OD import create_bbox,create_grid
data_path = Path(__file__).resolve().parents[2].joinpath('data','percolation')
code_timer = Timer("time_code", text="Time spent: {:.2f}")
from pathos.multiprocessing import Pool,cpu_count
from itertools import repeat
from functools import reduce
import operator
#import warnings
#warnings.filterwarnings("ignore")
def metrics(graph):
"""This method prints some basic network metrics of an iGraph
Args:
graph (iGraph.Graph object):
Returns:
m:
"""
g = graph
return pd.DataFrame([[g.ecount(),g.vcount(),g.density(),g.omega(),g.average_path_length(directed=False),g.assortativity_degree(False),g.diameter(directed=False),g.edge_connectivity(),g.maxdegree(),np.sum(g.es['distance'])]],columns=["Edge_No","Node_No","Density","Clique_No", "Ave_Path_Length", "Assortativity","Diameter","Edge_Connectivity","Max_Degree","Total_Edge_Length"])
def metrics_Print(graph):
"""This method prints some basic network metrics of an iGraph
Args:
graph (iGraph.Graph object):
Returns:
m:
"""
g = graph
m = []
print("Number of edges: ", g.ecount())
print("Number of nodes: ", g.vcount())
print("Density: ", g.density())
print("Number of cliques: ", g.omega())#omega or g.clique_number()
print("Average path length: ", g.average_path_length(directed=False))
print("Assortativity: ", g.assortativity_degree(False))
print("Diameter: ",g.diameter(directed=False))
print("Edge Connectivity: ", g.edge_connectivity())
print("Maximum degree: ", g.maxdegree())
print("Total Edge length ", np.sum(g.es['distance']))
#Creates a graph
def graph_load(edges):
"""Creates
Args:
edges (pandas.DataFrame) : containing road network edges, with from and to ids, and distance / time columns
Returns:
igraph.Graph (object) : a graph with distance and time attributes
"""
#return ig.Graph.TupleList(gdfNet.edges[['from_id','to_id','distance']].itertuples(index=False),edge_attrs=['distance'])
edges = edges.reindex(['from_id','to_id'] + [x for x in list(edges.columns) if x not in ['from_id','to_id']],axis=1)
graph = ig.Graph.TupleList(edges.itertuples(index=False), edge_attrs=list(edges.columns)[2:],directed=False)
graph.vs['id'] = graph.vs['name']
# graph = ig.Graph(directed=False)
# max_node_id = max(max(edges.from_id),max(edges.to_id))
# graph.add_vertices(max_node_id+1)
# edge_tuples = zip(edges.from_id,edges.to_id)
# graph.add_edges(edge_tuples)
# graph.es['distance'] = edges.distance
# graph.es['time'] = edges.time
return graph
def graph_load_largest(edges):
"""Returns the largest component of a graph given an edge dataframe
Args:
edges (pandas.DataFrame): A dataframe containing from, to ids; time and distance attributes for each edge
Returns:
igraph.Graph (object) : a graph with distance and time attributes
"""
graph = graph_load(gdfNet)
return graph.clusters().giant()
def largest_component_df(edges,nodes):
"""Returns the largest component of a network object (network.edges pd
and network.nodes pd) with reset ids. Uses igraphs built in function, while adding ids as attributes
Args:
edges (pandas.DataFrame): A dataframe containing from and to ids
nodes (pandas.DataFrame): A dataframe containing node ids
Returns:
edges, nodes (pandas.DataFrame) : 2 dataframes containing only those edges and nodes belonging to the giant component
"""
edges = edges
nodes = nodes
edge_tuples = zip(edges['from_id'],edges['to_id'])
graph = ig.Graph(directed=False)
graph.add_vertices(len(nodes))
graph.vs['id'] = nodes['id']
graph.add_edges(edge_tuples)
graph.es['id'] = edges['id']
graph = graph.clusters().giant()
edges_giant = edges.loc[edges.id.isin(graph.es()['id'])]
nodes_giant = nodes.loc[nodes.id.isin(graph.vs()['id'])]
return reset_ids(edges_giant,nodes_giant)
def create_demand(OD_nodes, OD_orig, node_pop):
"""This function creates a demand matrix from the equation:
Demand_a,b = Population_a * Population_b * e^ [-p * Distance_a,b]
-p is set to 1, populations represent the grid square of the origin,
Args:
OD_nodes (list): a list of nodes to use for the OD, a,b
OD_orig (np.matrix): A shortest path matrix used for the distance calculation
node_pop (list): population per OD node
Returns:
demand (np.ndarray) : A matrix with demand calculations for each OD pair
"""
demand = np.zeros((len(OD_nodes), len(OD_nodes)))
dist_decay = 1
maxtrips = 100
for o in range(0, len(OD_nodes)):
for d in range(0, len(OD_nodes)):
if o == d:
demand[o][d] = 0
else:
normalized_dist = OD_orig[o,d] / OD_orig.max()
demand[o][d] = ((node_pop[o] * node_pop[d]) * np.exp(-1 * dist_decay * normalized_dist))
demand = ((demand / demand.max()) * maxtrips)
demand = np.ceil(demand).astype(int)
return demand
def choose_OD(pos_OD, OD_no):
"""Chooses nodes for OD matrix according to their population size stochastically and probabilistically
Args:
pos_OD (list): a list of tuples representing the nodes and their population
OD_no (int): Number of OD pairs to create
Returns:
OD_nodes [list]: The nodes chosen for the OD
mapped_pops [list]: Population for nodes chosen
"""
#creates 2 tuples of the node ids and their total representative population
node_ids, tot_pops = zip(*pos_OD)
#Assigns a probability by population size
pop_probs = [x/sum(tot_pops) for x in tot_pops]
#OD nodes chosen
OD_nodes = list(np.random.choice(node_ids, size=OD_no, replace = False, p=pop_probs))
#Population counts in a mapped list
node_positions = [node_ids.index(i) for i in OD_nodes]
mapped_pops = [tot_pops[j] for j in node_positions]
#returns the nodes, and their populations, should this be zipped?
return OD_nodes, mapped_pops
def prepare_possible_OD(gridDF, nodes, tolerance = 1):
"""Returns an array of tuples, with the first value the node ID to consider, and the
second value the total population associated with this node.
The tolerance is the size of the bounding box to search for nodes within
Args:
gridDF (pandas.DataFrame): A dataframe with the grid centroids and their population
nodes (pandas.DataFrame): A dataframe of the road network nodes
tolerance (float, optional): size of the bounding box . Defaults to 0.1.
Returns:
final_possible_pop (list): a list of tuples representing the nodes and their population
"""
nodeIDs = []
sindex = pyg.STRtree(nodes['geometry'])
pos_OD_nodes = []
pos_tot_pop = []
for i in gridDF.itertuples():
ID = nearest(i.geometry, nodes, sindex, tolerance)
#If a node was found
if ID > -1:
pos_OD_nodes.append(ID)
pos_tot_pop.append(i.tot_pop)
a = nodes.loc[nodes.id.isin(pos_OD_nodes)]
#Create a geopackage of the possible ODs
#with Geopackage('nodyBGR.gpkg', 'w') as out:
# out.add_layer(a, name='finanod', crs='EPSG:4326')
nodes = np.array([pos_OD_nodes])
node_unique = np.unique(nodes)
count = np.array([pos_tot_pop])
#List comprehension to add total populations of recurring nodes
final_possible_pop = [(i, count[nodes==i].sum()) for i in node_unique]
return final_possible_pop
def nearest(geom, gdf,sindex, tolerance):
"""Finds the nearest node
Args:
geom (pygeos.Geometry) : Geometry to find nearest
gdf (pandas.index): Node dataframe to provide possible nodes
sindex (pygeos.Sindex): Spatial index for faster lookup
tolerance (float): Size of buffer to use to find nodes
Returns:
nearest_geom.id [int]: The node id that is closest to the geom
"""
matches_idx = sindex.query(geom)
if not matches_idx.any():
buf = pyg.buffer(geom, tolerance)
matches_idx = sindex.query(buf,'contains').tolist()
try:
nearest_geom = min(
[gdf.iloc[match_idx] for match_idx in matches_idx],
key=lambda match: pyg.measurement.distance(match.geometry,geom)
)
except:
#print("Couldn't find node")
return -1
return nearest_geom.id
def simple_OD_calc(OD, comparisonOD,pos_trip_no):
"""An alternative OD calculation that counts how many trips exceed threshold length
Args:
OD ([type]): [description]
comparisonOD ([type]): [description]
pos_trip_no ([type]): [description]
Returns:
[type]: [description]
"""
compare_thresh = np.greater(OD,comparisonOD)
over_thresh_no = np.sum(compare_thresh) / 2
return over_thresh_no / pos_trip_no
def reset_ids(edges, nodes):
"""Resets the ids of the nodes and edges, editing
the references in edge table using dict masking
Args:
edges (pandas.DataFrame): edges to re-reference ids
nodes (pandas.DataFrame): nodes to re-reference ids
Returns:
edges, nodes (pandas.DataFrame) : The re-referenced edges and nodes.
"""
nodes = nodes.copy()
edges = edges.copy()
to_ids = edges['to_id'].to_numpy()
from_ids = edges['from_id'].to_numpy()
new_node_ids = range(len(nodes))
#creates a dictionary of the node ids and the actual indices
id_dict = dict(zip(nodes.id,new_node_ids))
nt = np.copy(to_ids)
nf = np.copy(from_ids)
#updates all from and to ids, because many nodes are effected, this
#is quite optimal approach for large dataframes
for k,v in id_dict.items():
nt[to_ids==k] = v
nf[from_ids==k] = v
edges.drop(labels=['to_id','from_id'],axis=1,inplace=True)
edges['from_id'] = nf
edges['to_id'] = nt
nodes.drop(labels=['id'],axis=1,inplace=True)
nodes['id'] = new_node_ids
edges['id'] = range(len(edges))
edges.reset_index(drop=True,inplace=True)
nodes.reset_index(drop=True,inplace=True)
return edges,nodes
def get_metrics_and_split(x):
try:
data_path = Path(r'/scistor/ivm/data_catalogue/open_street_map/')
#data_path = Path(r'C:/data/')
if data_path.joinpath("percolation_metrics","{}_0_metrics.csv".format(x)).is_file():
print("{} already finished!".format(x))
return None
print(x+' has started!')
edges = feather.read_dataframe(data_path.joinpath("road_networks","{}-edges.feather".format(x)))
nodes = feather.read_dataframe(data_path.joinpath("road_networks","{}-nodes.feather".format(x)))
#edges = edges.drop('geometry',axis=1)
edges = edges.reindex(['from_id','to_id'] + [x for x in list(edges.columns) if x not in ['from_id','to_id']],axis=1)
graph= ig.Graph.TupleList(edges.itertuples(index=False), edge_attrs=list(edges.columns)[2:],directed=False)
graph.vs['id'] = graph.vs['name']
#all_df = metrics(graph)
#all_df.to_csv(data_path.joinpath("percolation_metrics","{}_all_metrics.csv".format(x)))
cluster_sizes = graph.clusters().sizes()
cluster_sizes.sort(reverse=True)
cluster_loc = [graph.clusters().sizes().index(x) for x in cluster_sizes[:5]]
main_cluster = graph.clusters().giant()
main_edges = edges.loc[edges.id.isin(main_cluster.es()['id'])]
main_nodes = nodes.loc[nodes.id.isin(main_cluster.vs()['id'])]
main_edges, main_nodes = reset_ids(main_edges,main_nodes)
feather.write_dataframe(main_edges,data_path.joinpath("percolation_networks","{}_0-edges.feather".format(x)))
feather.write_dataframe(main_nodes,data_path.joinpath("percolation_networks","{}_0-nodes.feather".format(x)))
main_df = metrics(main_cluster)
main_df.to_csv(data_path.joinpath("percolation_metrics","{}_0_metrics.csv".format(x)))
skipped_giant = False
counter = 1
for y in cluster_loc:
if not skipped_giant:
skipped_giant=True
continue
if len(graph.clusters().subgraph(y).vs) < 500:
break
g = graph.clusters().subgraph(y)
g_edges = edges.loc[edges.id.isin(g.es()['id'])]
g_nodes = nodes.loc[nodes.id.isin(g.vs()['id'])]
if len(g_edges) == len(main_edges) & len(g_nodes) == len(main_nodes):
continue
g_edges, g_nodes = reset_ids(g_edges,g_nodes)
feather.write_dataframe(g_edges,data_path.joinpath("percolation_networks","{}_{}-edges.feather".format(x,str(counter))))
feather.write_dataframe(g_nodes,data_path.joinpath("percolation_networks","{}_{}-nodes.feather".format(x,str(counter))))
g_df = metrics(g)
g_df.to_csv("/scistor/ivm/data_catalogue/open_street_map/percolation_metrics/"+x+"_"+str(counter)+"_metrics.csv")
counter += 1
print(x+' has finished!')
except Exception as e:
print(x+" failed because of {}".format(e))
def SummariseOD(OD, fail_value, demand, baseline, GDP_per_capita, frac_counter,distance_disruption, time_disruption):
"""Function returns the % of total trips between origins and destinations that exceed fail value
Almost verbatim from world bank /GOSTnets world_files_criticality_v2.py
Args:
OD (np.matrix): Current OD matrix times (during percolation)
fail_value (int): Came form GOSTNETS , seems just to be a huge int
demand (np.ndarray): Demand matrix
baseline (np.matrix): OD matrix before percolation
GDP_per_capita (int): GDP of relevant area
frac_counter (float): Keeps track of current fraction for ease of results storage
Returns:
frac_counter, pct_isolated, average_time_disruption, pct_thirty_plus, pct_twice_plus, pct_thrice_plus,total_surp_loss_e1, total_pct_surplus_loss_e1, total_surp_loss_e2, total_pct_surplus_loss_e2
"""
#adjusted time
adj_time = OD-baseline
# total trips
total_trips = (baseline.shape[0]*baseline.shape[1])-baseline.shape[0]
#isolated_trips = np.ma.masked_array(masked_demand,~masked_OD.mask)
isolated_trips_sum = OD[OD == fail_value].shape[1]
# get percentage of isolated trips
pct_isolated = (isolated_trips_sum / total_trips)*100
## get travel times for remaining trips
time_unaffected_trips = OD[OD == baseline]
# get unaffected trips travel times
if not (np.isnan(np.array(time_unaffected_trips)).all()):
unaffected_percentiles = []
unaffected_percentiles.append(np.nanpercentile(np.array(time_unaffected_trips),10))
unaffected_percentiles.append(np.nanpercentile(np.array(time_unaffected_trips),25))
unaffected_percentiles.append(np.nanpercentile(np.array(time_unaffected_trips),50))
unaffected_percentiles.append(np.nanpercentile(np.array(time_unaffected_trips),75))
unaffected_percentiles.append(np.nanpercentile(np.array(time_unaffected_trips),90))
unaffected_percentiles.append(np.nanmean((time_unaffected_trips)))
else:
unaffected_percentiles = [np.nan,np.nan,np.nan,np.nan,np.nan,np.nan]
# save delayed trips travel times
delayed_trips_time = adj_time[(OD != baseline) & (np.nan_to_num(np.array(OD),nan=fail_value) != fail_value)]
unaffected_trips = np.array(time_unaffected_trips).shape[1]
delayed_trips = np.array(delayed_trips_time).shape[1]
# save percentage unaffected and delayed
pct_unaffected = (unaffected_trips/total_trips)*100
pct_delayed = (delayed_trips/total_trips)*100
# get delayed trips travel times
if not (np.isnan(np.array(delayed_trips_time)).all()):
delayed_percentiles = []
delayed_percentiles.append(np.nanpercentile(np.array(delayed_trips_time),10))
delayed_percentiles.append(np.nanpercentile(np.array(delayed_trips_time),25))
delayed_percentiles.append(np.nanpercentile(np.array(delayed_trips_time),50))
delayed_percentiles.append(np.nanpercentile(np.array(delayed_trips_time),75))
delayed_percentiles.append(np.nanpercentile(np.array(delayed_trips_time),90))
delayed_percentiles.append(np.nanmean(np.array(delayed_trips_time)))
average_time_disruption = np.nanmean(np.array(delayed_trips_time))
else:
delayed_percentiles = [np.nan,np.nan,np.nan,np.nan,np.nan,np.nan]
average_time_disruption = np.nan
# Flexing demand with trip cost
def surplus_loss(e, C2, C1, D1):
"""[summary]
Args:
e ([type]): [description]
C2 ([type]): [description]
C1 ([type]): [description]
D1 ([type]): [description]
Returns:
[type]: [description]
"""
Y_intercept_max_cost = C1 - (e * D1)
C2 = np.minimum(C2, Y_intercept_max_cost)
delta_cost = C2 - C1
delta_demand = (delta_cost / e)
D2 = (D1 + delta_demand)
surplus_loss_ans = ((delta_cost * D2) + ((delta_cost * -delta_demand) / 2))
triangle = (D1 * (Y_intercept_max_cost - C1) ) / 2
total_surp_loss = surplus_loss_ans.sum()
total_pct_surplus_loss = total_surp_loss / triangle.sum()
return total_surp_loss, total_pct_surplus_loss*100
adj_cost = (OD * GDP_per_capita) / (365 * 8 ) #* 3600) time is in hours, so not sure why we do this multiplications with 3600? and minutes would be times 60?
baseline_cost = (baseline * GDP_per_capita) / (365 * 8 ) #* 3600) time is in hours, so not sure why we do this multiplications with 3600? and minutes would be times 60?
adj_cost = np.nan_to_num(np.array(adj_cost),nan=np.nanmax(adj_cost))
total_surp_loss_e1, total_pct_surplus_loss_e1 = surplus_loss(-0.15, adj_cost, baseline_cost, demand)
total_surp_loss_e2, total_pct_surplus_loss_e2 = surplus_loss(-0.36, adj_cost, baseline_cost, demand)
return frac_counter, pct_isolated, pct_unaffected, pct_delayed, average_time_disruption, total_surp_loss_e1, total_pct_surplus_loss_e1, total_surp_loss_e2, total_pct_surplus_loss_e2, distance_disruption, time_disruption, unaffected_percentiles, delayed_percentiles
def percolation_random_attack(edges, del_frac=0.01, OD_list=[], pop_list=[], GDP_per_capita=50000):
"""Final version of percolation, runs a simulation on the network provided, to give an indication of network resilience.
Args:
edges (pandas.DataFrame): A dataframe containing edge information: the nodes to and from, the time and distance of the edge
del_frac (float): The fraction to increment the percolation. Defaults to 0.01. e.g.0.01 removes 1 percent of edges at each step
OD_list (list, optional): OD nodes to use for matrix and calculations. Defaults to [].
pop_list (list, optional): Corresponding population sizes for ODs for demand calculations. Defaults to [].
GDP_per_capita (int, optional): The GDP of the country/area for surplus cost calculations. Defaults to 50000.
Returns:
result_df [pandas.DataFrame]: The results! 'frac_counter', 'pct_isolated', 'average_time_disruption', 'pct_thirty_plus', 'pct_twice_plus', 'pct_thrice_plus','total_surp_loss_e1', 'total_pct_surplus_loss_e1', 'total_surp_loss_e2', 'total_pct_surplus_loss_e2' """
edges.geometry = pyg.from_wkb(edges.geometry)
result_df = []
g = graph_load(edges)
#These if statements allow for an OD and population list to be randomly generated
if OD_list == []:
OD_nodes = random.sample(range(g.vcount()-1),100)
else:
OD_nodes = OD_list
edge_no = g.ecount()
OD_node_no = len(OD_nodes)
if pop_list == []:
node_pop = random.sample(range(4000), OD_node_no)
else:
node_pop = pop_list
#Creates a matrix of shortest path times between OD nodes
base_shortest_paths = g.shortest_paths_dijkstra(source=OD_nodes,target = OD_nodes,weights='time')
OD_orig = np.matrix(base_shortest_paths)
demand = create_demand(OD_nodes, OD_orig, node_pop)
exp_g = g.copy()
trips_possible = True
frac_counter = 0
tot_edge_length = np.sum(g.es['distance'])
tot_edge_time = np.sum(g.es['time'])
# add frac 0.00 for better figures and results
result_df.append((0.00, 0, 100, 0, 0.0, 0, 0.0, 0, 0.0, 0.0, 0.0,
[0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
[0.0,0.0, 0.0, 0.0, 0.0, 0.0]))
while trips_possible:
if frac_counter > 0.3 and frac_counter <= 0.5: del_frac = 0.02
if frac_counter > 0.5: del_frac = 0.05
exp_edge_no = exp_g.ecount()
#sample_probabilities = np.array(exp_g.es['distance'])/sum(exp_g.es['distance'])
#The number of edges to delete
no_edge_del = max(1,math.floor(del_frac * edge_no))
try:
edges_del = random.sample(range(exp_edge_no),no_edge_del)
#edges_del = np.random.choice(range(exp_edge_no), size=no_edge_del, replace = False, p=sample_probabilities)
except:
edges_del = range(exp_edge_no)
exp_g.delete_edges(edges_del)
frac_counter += del_frac
cur_dis_length = 1 - (np.sum(exp_g.es['distance'])/tot_edge_length)
cur_dis_time = 1 - (np.sum(exp_g.es['time'])/tot_edge_time)
new_shortest_paths = exp_g.shortest_paths_dijkstra(source=OD_nodes,target = OD_nodes,weights='time')
perc_matrix = np.matrix(new_shortest_paths)
perc_matrix[perc_matrix == inf] = 99999999999
perc_matrix[perc_matrix == 0] = np.nan
results = SummariseOD(perc_matrix, 99999999999, demand, OD_orig, GDP_per_capita,round(frac_counter,3),cur_dis_length,cur_dis_time)
result_df.append(results)
#If the frac_counter goes past 0.99
if results[0] >= 0.99: break
#If there are no edges left to remove
if exp_edge_no < 1: break
result_df = pd.DataFrame(result_df, columns=['frac_counter', 'pct_isolated','pct_unaffected', 'pct_delayed',
'average_time_disruption','total_surp_loss_e1',
'total_pct_surplus_loss_e1', 'total_surp_loss_e2', 'total_pct_surplus_loss_e2',
'distance_disruption','time_disruption','unaffected_percentiles','delayed_percentiles'])
result_df = result_df.replace('--',0)
return result_df
def percolation_random_attack_od_buffer(edges, nodes,grid_height, del_frac=0.01, OD_list=[], pop_list=[], GDP_per_capita=50000):
"""Final version of percolation, runs a simulation on the network provided, to give an indication of network resilience.
Args:
edges (pandas.DataFrame): A dataframe containing edge information: the nodes to and from, the time and distance of the edge
del_frac (float): The fraction to increment the percolation. Defaults to 0.01. e.g.0.01 removes 1 percent of edges at each step
OD_list (list, optional): OD nodes to use for matrix and calculations. Defaults to [].
pop_list (list, optional): Corresponding population sizes for ODs for demand calculations. Defaults to [].
GDP_per_capita (int, optional): The GDP of the country/area for surplus cost calculations. Defaults to 50000.
Returns:
result_df [pandas.DataFrame]: The results! 'frac_counter', 'pct_isolated', 'average_time_disruption', 'pct_thirty_plus', 'pct_twice_plus', 'pct_thrice_plus','total_surp_loss_e1', 'total_pct_surplus_loss_e1', 'total_surp_loss_e2', 'total_pct_surplus_loss_e2' """
nodes.geometry = pyg.from_wkb(nodes.geometry)
edges.geometry = pyg.from_wkb(edges.geometry)
result_df = []
g = graph_load(edges)
#These if statements allow for an OD and population list to be randomly generated
if OD_list == []:
OD_nodes = random.sample(range(g.vcount()-1),100)
else:
OD_nodes = OD_list
edge_no = g.ecount()
OD_node_no = len(OD_nodes)
if pop_list == []:
node_pop = random.sample(range(4000), OD_node_no)
else:
node_pop = pop_list
buffer_centroids = pyg.buffer(nodes.loc[nodes.id.isin(OD_list)].geometry,grid_height*0.05).values
OD_buffers = dict(zip(OD_nodes,buffer_centroids))
edges_per_OD = {}
for OD_buffer in OD_buffers:
get_list_edges = list(edges.id.loc[pyg.intersects(pyg.make_valid(OD_buffers[OD_buffer]),pyg.make_valid(edges.geometry.values))].values)
edges_per_OD[OD_buffer] = get_list_edges,get_list_edges
#Creates a matrix of shortest path times between OD nodes
base_shortest_paths = g.shortest_paths_dijkstra(source=OD_nodes,target=OD_nodes,weights='time')
OD_orig = np.matrix(base_shortest_paths)
OD_thresh = OD_orig * 10
demand = create_demand(OD_nodes, OD_orig, node_pop)
exp_g = g.copy()
trips_possible = True
pos_trip_no = (((OD_node_no**2) - OD_node_no) / 2) - ((np.count_nonzero(np.isinf(OD_orig)))/2)
counter = 0
frac_counter = 0
tot_edge_length = np.sum(g.es['distance'])
tot_edge_time = np.sum(g.es['time'])
total_edges = exp_g.ecount()
# add frac 0.00 for better figures and results
result_df.append((0.00, 0, 100, 0, 0.0, 0, 0.0, 0, 0.0, 0.0, 0.0,
[0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
[0.0,0.0, 0.0, 0.0, 0.0, 0.0]))
while trips_possible:
if frac_counter > 0.3 and frac_counter <= 0.5: del_frac = 0.02
if frac_counter > 0.5: del_frac = 0.05
exp_edge_no = exp_g.ecount()
sample_probabilities = np.array(exp_g.es['distance'])/sum(exp_g.es['distance'])
#The number of edges to delete
no_edge_del = max(1,math.floor(del_frac * edge_no))
edges_dict = dict(zip(exp_g.es['id'],exp_g.es.indices))
edges_dict_reversed = {v: k for k, v in edges_dict.items()}
try:
edges_del = random.sample(range(exp_edge_no),no_edge_del)
#edges_del = np.random.choice(range(exp_edge_no), size=no_edge_del, replace = False, p=sample_probabilities)
except:
edges_del = range(exp_edge_no)
#If there are no edges left to remove
if exp_edge_no < 1:
break
collect_empty_ones = []
for OD_point in edges_per_OD:
compared = list(set([edges_dict[x] for x in edges_per_OD[OD_point][1]]) - set(edges_del))
if len(compared) == 0:
edges_del = list(set(edges_del).union(set([edges_dict[x] for x in edges_per_OD[OD_point][0]])))
collect_empty_ones.append(OD_point)
else:
edges_del = list(set(edges_del) - (set([edges_dict[x] for x in edges_per_OD[OD_point][0]])))
edges_per_OD[OD_point] = edges_per_OD[OD_point][0],[edges_dict_reversed[x] for x in compared]
for e in collect_empty_ones:
edges_per_OD.pop(e)
# only edges around node if all edges are gone
if (exp_edge_no != 0) | (no_edge_del-len(edges_del) > 0) | (exp_edge_no>len(edges_del)):
while len(edges_del) < no_edge_del < exp_edge_no:
edges_del += random.sample(range(exp_edge_no),no_edge_del-len(edges_del))
collect_empty_ones = []
for OD_point in edges_per_OD:
compared = list(set([edges_dict[x] for x in edges_per_OD[OD_point][1]]) - set(edges_del))
if len(compared) == 0:
edges_del = list(set(edges_del).union(set([edges_dict[x] for x in edges_per_OD[OD_point][0]])))
collect_empty_ones.append(OD_point)
else:
edges_del = list(set(edges_del) - (set([edges_dict[x] for x in edges_per_OD[OD_point][0]])))
edges_per_OD[OD_point] = edges_per_OD[OD_point][0],[edges_dict_reversed[x] for x in compared]
for e in collect_empty_ones:
edges_per_OD.pop(e)
exp_g.delete_edges(edges_del)
frac_counter += del_frac
cur_dis_length = 1 - (np.sum(exp_g.es['distance'])/tot_edge_length)
cur_dis_time = 1 - (np.sum(exp_g.es['time'])/tot_edge_time)
new_shortest_paths = exp_g.shortest_paths_dijkstra(source=OD_nodes,target = OD_nodes,weights='time')
perc_matrix = np.matrix(new_shortest_paths)
perc_matrix[perc_matrix == inf] = 99999999999
perc_matrix[perc_matrix == 0] = np.nan
results = SummariseOD(perc_matrix, 99999999999, demand, OD_orig, GDP_per_capita,round(frac_counter,3),cur_dis_length,cur_dis_time)
result_df.append(results)
#If the frac_counter goes past 0.99
if results[0] >= 0.99: break
result_df = pd.DataFrame(result_df, columns=['frac_counter', 'pct_isolated','pct_unaffected', 'pct_delayed',
'average_time_disruption','total_surp_loss_e1',
'total_pct_surplus_loss_e1', 'total_surp_loss_e2', 'total_pct_surplus_loss_e2',
'distance_disruption','time_disruption','unaffected_percentiles','delayed_percentiles'])
result_df = result_df.replace('--',0)
return result_df
def percolation_targeted_attack(edges,country,network,OD_list=[], pop_list=[], GDP_per_capita=50000):
"""Final version of percolation, runs a simulation on the network provided, to give an indication of network resilience.
Args:
edges (pandas.DataFrame): A dataframe containing edge information: the nodes to and from, the time and distance of the edge
del_frac (float): The fraction to increment the percolation. Defaults to 0.01. e.g.0.01 removes 1 percent of edges at each step
OD_list (list, optional): OD nodes to use for matrix and calculations. Defaults to [].
pop_list (list, optional): Corresponding population sizes for ODs for demand calculations. Defaults to [].
GDP_per_capita (int, optional): The GDP of the country/area for surplus cost calculations. Defaults to 50000.
Returns:
result_df [pandas.DataFrame]: The results! 'frac_counter', 'pct_isolated', 'average_time_disruption', 'pct_thirty_plus', 'pct_twice_plus', 'pct_thrice_plus','total_surp_loss_e1', 'total_pct_surplus_loss_e1', 'total_surp_loss_e2', 'total_pct_surplus_loss_e2' """
result_df = []
g = graph_load(edges)
#These if statements allow for an OD and population list to be randomly generated
if OD_list == []:
OD_nodes = random.sample(range(g.vcount()-1),100)
else:
OD_nodes = OD_list
edge_no = g.ecount()
OD_node_no = len(OD_nodes)
if pop_list == []:
node_pop = random.sample(range(4000), OD_node_no)
else:
node_pop = pop_list
#Creates a matrix of shortest path times between OD nodes
base_shortest_paths = g.shortest_paths_dijkstra(source=OD_nodes,target = OD_nodes,weights='time')
OD_orig = np.matrix(base_shortest_paths)
demand = create_demand(OD_nodes, OD_orig, node_pop)
exp_g = g.copy()
tot_edge_length = | np.sum(g.es['distance']) | numpy.sum |
import numpy as np
import matplotlib.pyplot as plt
import scipy.sparse as sp
import scipy.sparse.linalg as la
from functools import partial
import time
from mpl_toolkits.mplot3d import Axes3D
# logging stuff
iterations = []
last_iter = {}
norms = []
def make_L(Nx, Ny):
Dx = sp.diags((Nx-1)*[1.])
Dx += sp.diags((Nx-2)*[-1.],-1)
rowx = sp.csr_matrix((1,Nx-1))
rowx[0,-1] = -1
Dx = sp.vstack((Dx, rowx))
Lx = Dx.transpose().dot(Dx)
Dy = sp.diags((Ny-1)*[1])
Dy += sp.diags((Ny-2)*[-1],-1)
rowy = sp.csr_matrix((1,Ny-1))
rowy[0,-1] = -1
Dy = sp.vstack((Dy, rowy))
Ly = Dy.transpose().dot(Dy)
return sp.kronsum(Lx,Ly)
def rect_mask(xx, yy ,x1, x2, y1, y2):
maskx1 = np.zeros(xx.shape, dtype=bool)
maskx1[xx>=x1] = True
maskx2 = np.zeros(xx.shape, dtype=bool)
maskx2[xx<=x2] = True
masky1 = np.zeros(xx.shape, dtype=bool)
masky1[yy>=y1] = True
masky2 = np.zeros(xx.shape, dtype=bool)
masky2[yy<=y2] = True
return np.logical_and(np.logical_and(maskx1, masky1), np.logical_and(maskx2, masky2))
def discretize(x_d, y_d, h):
nx = int(x_d/h)
ny = int(y_d/h)
return make_L(nx,ny)/h/h
def get_grid(x_d, y_d, h):
grid = np.mgrid[h:y_d:h, h:x_d:h]
return (grid[1,:,:], grid[0,:,:])
def k(xx, yy):
alpha = 1
masker = lambda x1, x2, y1, y2: rect_mask(xx, yy, x1, x2, y1, y2)
r1 = masker(1,2,1,2)
r2 = masker(1,3,3,5)
r3 = masker(4,7,4,7)
r4 = masker(9,12,4,6)
r5 = masker(13,15,1,3)
# Combinate
R = np.logical_or(r1,r2)
R = np.logical_or(R,r3)
R = np.logical_or(R,r4)
R = np.logical_or(R,r5)
return np.reshape(np.where(R, alpha*np.ones(xx.shape), np.zeros(xx.shape)), xx.shape[0]*xx.shape[1])
def newton_raphson(u0, A, k, dt, epsilon):
ui = u0.copy()
i = 0
while True:
i += 1
jacobian = A + sp.diags(k)*sp.eye(A.shape[0]) - 2*sp.diags(ui)*sp.diags(k)
v = la.spsolve(sp.eye(A.shape[0])-dt*jacobian, ui - u0 - dt*(A@ui+k*ui*(1-ui)))
ui = ui - v
norms.append(np.linalg.norm(np.abs(v)))
iterations.append(i)
if np.linalg.norm(np.abs(v))<epsilon:
if i in last_iter:
last_iter[i] += 1
else:
last_iter[i] = 1
return ui
def picard(u0, A, k, dt, epsilon):
f = lambda u: A@u+k*u*(1-u)
ui = u0.copy()
i = 0
while np.linalg.norm(ui-dt*f(ui)-u0) > epsilon:
i+=1
ui = dt*f(ui)+u0
norms.append(np.linalg.norm(ui-dt*f(ui)-u0))
iterations.append(i)
if i in last_iter:
last_iter[i] += 1
else:
last_iter[i] = 1
return ui
def step_FE(u0, A, k, dt):
return u0+dt*A@u0+dt*k*u0*(1-u0)
def step_BE(u0, A, k, dt):
if not use_picard:
return newton_raphson(u0, A, k, dt, 0.001)
else:
return picard(u0, A, k, dt, 0.00001)
def stable_dt(h):
return (h**2)/4
def unsteady_solver(u0, A, dt, T, saves, k, method="FE"):
step = step_FE
if method == "BE":
step = step_BE
if not use_picard:
dt = 1.1
else:
dt = dt/2
t = 0
un = u0
us = []
if 0 in save_points:
us.append(u0)
global_start = time.time();
while t < T:
start = time.time()
un = step(un, A, k, dt)
t += dt
for s in saves:
if abs(s-t) <= dt/2:
us.append(un)
print("\rAt time %2.5f s, Last step took %2.8f s, expected time left: %3.0f s, total time: %3.2fs"%(t, time.time()-start, (time.time()-global_start)/t*T-(time.time()-global_start), time.time()-global_start), end='')
print("")
return us
def initial(xx, yy):
f = np.exp(-2*(np.square(xx-1.5*np.ones(xx.shape))+np.square(yy-1.5*np.ones(yy.shape))))
return | np.reshape(f, xx.shape[0]*xx.shape[1]) | numpy.reshape |
# coding: utf-8
# # M* vs Mhalo
# Again, galaxy - halo matching is required.
# In[18]:
class Dummy():
def __init__(self):
pass
def region_from_xyz(x,y,z, r=0):
"""
create a region to include all points.
Parameters
----------
x: float array
y: float array
z: float array
r: float array, optional
If given, the region encloses all points as spheres with radius r.
"""
xmi = min(x-0)
xma = max(x+0)
ymi = min(y-0)
yma = max(y+0)
zmi = min(z-0)
zma = max(z+0)
import utils.sampling as smp
return smp.set_region(ranges=[[xmi, xma],[ymi,yma], [zmi,zma]])
def get_tick_points(xmin, xmax):
dx = xmax - xmin
dxx = round(dx/5)
mid = round((xmin + xmax)/2)
xstart = mid - 2*dxx
ticks = np.arange(xstart, xmax, dxx)
pos = ((ticks - xmin)/dx )
return pos, ticks
def ticks_from_region(ranges, ax, npix):
"""
modify ticks of given ax according to region.
xmin, xmax, ymin, ymax must be set according to the region.
"""
xmin = ranges[0][0]
xmax = ranges[0][1]
ymin = ranges[1][0]
ymax = ranges[1][1]
xpos, xticks = get_tick_points(xmin, xmax)
ypos, yticks = get_tick_points(ymin, ymax)
xpos *= npix
ypos *= npix
ax.set_xticks(xpos)
ax.set_yticks(ypos)
ax.set_xticklabels([str(i) for i in xticks])
ax.set_yticklabels([str(i) for i in yticks])
# In[22]:
def distv(halo, center):
norm = np.sqrt(np.square(center['vx'] - halo.vx) +
np.square(center['vy'] - halo.vy) +
np.square(center['vz'] - halo.vz))
return norm
def dist(halo, center):
norm = np.sqrt( | np.square(center['x'] - halo.x) | numpy.square |
#!/bin/python3
import rospy
from sensor_msgs.msg import PointCloud2
import sensor_msgs.point_cloud2 as pc2
import numpy as np
class ptcl_to_height_depth_image:
def __init__(self, Z_RES=100, Z_MAX=5):
self.Z_RES = Z_RES
self.Z_MAX = Z_MAX
def __call__(self, msg: PointCloud2):
point_array = (
np.array(
list(pc2.read_points(msg, field_names=("x", "y", "z"), skip_nans=True))
)
* 1
)
# Delete points with |z| > self.Z_MAX
indices_to_delete = np.array(
np.abs(point_array[:, 2]) >= self.Z_MAX, dtype=bool
)
point_array = | np.delete(point_array, indices_to_delete, 0) | numpy.delete |
from collections import deque
import numpy as np
import pandas as pd
import time
from scipy import optimize
from init import *
class Item:
def __init__(self):
self.SInc = 0
self.R = 0
self.feedback = 0
self.used_ivl = 0
self.S = start_stability
self.last_review = -1
self.ivl_history = []
self.fb_history = []
self.lapse = 0
# self.difficulty = round(random.triangular(), 1)
self.difficulty = 0.5
self.ivl = start_stability
self.r = 0
def review(self, date):
self.__calculate_r(date)
self.feedback = 1 if random.random() < self.R else 0
self.fb_history.append(self.feedback)
self.used_ivl = 0 if self.last_review < 0 else date - self.last_review
self.ivl_history.append(self.used_ivl)
if self.feedback == 0:
self.lapse += 1
self.S = start_stability
self.ivl = start_stability
else:
self.__calculate_sinc()
self.__update_s()
self.__update_ivl()
self.last_review = date
def __calculate_r(self, date):
if self.last_review >= 0:
self.R = np.exp(np.log(0.9) * (date - self.last_review) / self.S)
self.r = np.exp(np.log(0.9) * (date - self.last_review) / self.ivl)
else:
self.R = 1
self.r = 1
def __calculate_sinc(self):
# self.SInc = - a * np.power(self.S, -b) * (np.exp(1 - self.R) - 1) * 1.1 + 1
self.SInc = (1.5 - self.difficulty) * (a * np.power(self.S, -b) * np.log(self.R)) + 1
def __update_s(self):
self.S *= self.SInc
def __update_ivl(self):
self.ivl *= a * np.power(self.ivl, -b) * np.log(self.r) + 1
def interval_threshold(self, threshold):
esinc = threshold * (a * np.power(self.S, -b) * np.log(threshold) + 1)
return int(round(max(1, np.log(threshold) / np.log(0.9) * self.S), 0))
def interval_optimize(self, flag):
def max_expected_s(x):
return - (x * self.S * (a * np.power(self.S, -b) * np.log(x) + 1) + (1 - x))
def min_stress_inverse(x):
return x / (self.S * (a * np.power(self.S, -b) * np.log(x) + 1)) + 1 - x + np.log(0.9) / np.log(x)
def min_stress_sqrt(x):
return - (x * np.power(self.S * (a * np.power(self.S, -b) * np.log(x) + 1), 1 / 2)
+ (1 - x) * np.power(1, 1 / 2)) + np.log(0.9) / np.log(x)
def min_stress_log(x):
return - (x * np.log(self.S * (a * np.power(self.S, -b) * np.log(x) + 1))
+ (1 - x) * np.log(1)) + np.log(0.9) / np.log(x)
r = 0.9
if flag == 0:
r = optimize.fminbound(min_stress_log, 0, 1)
elif flag == -1:
r = optimize.fminbound(min_stress_inverse, 0, 1)
elif flag == -2:
r = optimize.fminbound(min_stress_sqrt, 0, 1)
return int(round(max(1, np.log(r) / np.log(0.9) * self.S), 0))
def interval_spread(self, threshold):
return int(round(max(1, np.log(threshold) / np.log(0.9) * self.ivl), 0))
if __name__ == '__main__':
forget_indexes = [0.2]
period_len = 60 # 滚动平均区间
learn_days = 300 # 模拟时长
deck_size = 25000 # 新卡片总量
for fi in range(len(forget_indexes)):
items_all = [Item() for _ in range(0, deck_size)]
items = deque(items_all)
item_per_day = [[] for _ in range(0, learn_days)]
card_per_day_limit = 10000 # 每日学习总上限
new_card_per_day_limit = 100
card_per_day = [{'forget': 0, 'recall': 0, 'new': 0} for _ in range(0, learn_days)]
end_day = 0
forget_index = forget_indexes[fi] # 遗忘比率
new_card_per_day = np.array([0.0] * learn_days)
new_card_per_day_average_per_period = np.array([0.0] * learn_days)
workload_per_day = np.array([0.0] * learn_days)
workload_per_day_average_per_period = np.array([0.0] * learn_days)
revlog = | np.empty(shape=[0, 7], dtype=object) | numpy.empty |
import numpy as np
import scipy as sp
import pandas as pd
from tqdm import tqdm
import copy
import time
from sklearn.model_selection import train_test_split
from jax.config import config
#config.update("jax_enable_x64", True)
import jax.numpy as jnp
from jax import random
from surv_copula.main_copula_survival import fit_copula_survival,fit_parametric_a0,\
predict_copula_survival,check_convergence_pr,predictive_resample_survival
from surv_copula.parametric_survival_functions import pr_lomax_smc,pr_lomax_IS
#Import data
data = pd.read_csv('./data/pbc.csv')
t = np.array(data['t'])
delta = np.array(data['delta'])
delta[delta ==1.] = 0
delta[delta==2.] = 1
trt = np.array(data['trt'])
#Split into treatments (filtering NA)
t1 = t[trt == 1.]
delta1 = delta[trt==1.]
t2 = t[trt == 2.]
delta2 = delta[trt==2.]
#Initialize cv
rep_cv = 10
n1 = np.shape(t1)[0]
n_train1 = int(n1/2)
n_test1 = n1-n_train1
n2 = np.shape(t2)[0]
n_train2 = int(n2/2)
n_test2 = n2-n_train2
test_ll_cv1 = np.zeros(rep_cv)
test_ll_cv2 = np.zeros(rep_cv)
seed = 100
for i in tqdm(range(rep_cv)):
#Train-test split and save for R
train_ind1,test_ind1 = train_test_split(np.arange(n1),test_size = n_test1,train_size = n_train1,random_state = seed+i)
train_ind2,test_ind2 = train_test_split( | np.arange(n2) | numpy.arange |
#!/usr/bin/env python
#
# Copyright 2020 Xilinx Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Module for testing the pyxir TF executor"""
import unittest
import numpy as np
import pyxir as px
from pyxir.shapes import TensorShape
from pyxir.runtime import base
from pyxir.graph.layer import xlayer
from pyxir.graph.io import xlayer_io
try:
from pyxir.runtime.tensorflow.x_2_tf_registry import X_2_TF
from pyxir.runtime.tensorflow.ops.tf_l0_input_and_other import *
from pyxir.runtime.tensorflow.ops.tf_l3_math_and_transform import *
except ModuleNotFoundError:
raise unittest.SkipTest("Skipping Tensorflow related test because Tensorflow is not available")
from .ops_infra import build_exec_layers, execute_layers
class TestTfL3MathAndTransform(unittest.TestCase):
def test_prelu(self):
def _create_prelu_layer(in_name, in_shape, alpha, axis):
tf.compat.v1.reset_default_graph()
inX = px.ops.input(in_name, shape=in_shape)
alphaX = px.ops.constant("alpha", alpha)
X = px.ops.prelu("prelu", [inX, alphaX], axis=axis)
input_shapes = {in_name: TensorShape(in_shape)}
layers = build_exec_layers([inX, alphaX, X], input_shapes, {})
return layers
def _test_prelu(x, alpha, expected, axis=1):
in_name = "x"
in_shape = list(x.shape)
layers = _create_prelu_layer(in_name, in_shape[:], alpha, axis=axis)
inputs = {in_name: x}
out = execute_layers(layers, inputs)
np.testing.assert_array_equal(out, expected)
_test_prelu(
-1. * np.ones((1, 2, 4, 4), dtype=np.float32),
np.array([.1, .1], dtype=np.float32),
-0.1 * np.ones((1, 2, 4, 4), dtype=np.float32),
)
_test_prelu(
np.ones((1, 2, 4, 4), dtype=np.float32),
np.array([.1, .1], dtype=np.float32),
np.ones((1, 2, 4, 4), dtype=np.float32),
)
_test_prelu(
np.array([1., -1.], dtype=np.float32).reshape(1, 2, 1, 1),
np.array([.1, .2], dtype=np.float32),
| np.array([1., -.2], dtype=np.float32) | numpy.array |
import numpy
import math
import os
import gc
import cv2
import pandas
from tensorflow.keras.utils import Sequence
import girder_client
from sklearn.utils import shuffle
import random
class CNNSequence(Sequence):
def __init__(self,datacsv,indexes,batchSize,labelName,gClient = None,tempFileDir = None,shuffle=True,augmentations = False):
# author <NAME>
if "GirderID" in datacsv.columns:
self.gClient = gClient
self.tempFileDir = tempFileDir
self.inputs = numpy.array([self.downloadGirderData(x,datacsv) for x in indexes])
else:
self.inputs = numpy.array([os.path.join(datacsv["Folder"][x],datacsv["FileName"][x]) for x in indexes])
self.batchSize = batchSize
self.labelName = labelName
self.labels = numpy.array(sorted(datacsv[self.labelName].unique()))
self.targets = numpy.array([self.convertTextToNumericLabels(datacsv[labelName][x]) for x in indexes])
self.shuffle = shuffle
self.augmentations = augmentations
self.on_epoch_end()
def on_epoch_end(self):
if self.shuffle:
shuffledInputs,shuffledTargets = shuffle(self.inputs,self.targets)
self.inputs = shuffledInputs
self.targets = shuffledTargets
def __len__(self):
# author <NAME>
length = len(self.inputs) / self.batchSize
length = math.ceil(length)
return length
def convertTextToNumericLabels(self, textLabel):
label = numpy.zeros(len(self.labels))
labelIndex = numpy.where(self.labels == textLabel)
label[labelIndex] = 1
return label
def rotateImage(self,image,angle = -1):
if angle < 0:
angle = random.randint(1, 359)
center = tuple(numpy.array(image.shape[1::-1])/2)
rot_mat = cv2.getRotationMatrix2D(center,angle,1.0)
rotImage = cv2.warpAffine(image,rot_mat,image.shape[1::-1],flags=cv2.INTER_LINEAR)
return rotImage
def flipImage(self,image,axis):
return cv2.flip(image, axis)
def readImage(self,file):
image = cv2.imread(file)
try:
if "AN01" in file:
croppedImg = image[0:320, 213:640]
image = cv2.resize(croppedImg, (640, 480))
elif "AN0" in file:
croppedImg = image[50:410, 160:640]
image = cv2.resize(croppedImg, (640, 480))
resized_image = cv2.resize(image, (224, 224))
normImg = cv2.normalize(resized_image, None, alpha=0, beta=1, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_32F)
preprocessingMethod = random.randint(0, 3)
del image
del resized_image
if self.augmentations and preprocessingMethod == 0:
# flip along y axis
return cv2.flip(normImg, 1)
elif self.augmentations and preprocessingMethod == 1:
# flip along x axis
return cv2.flip(normImg, 0)
elif self.augmentations and preprocessingMethod == 2:
# rotate
angle = random.randint(1, 359)
rotImage = self.rotateImage(normImg, angle)
return rotImage
else:
return normImg
except:
print(file)
def readExpertImage(self,file):
image = cv2.imread(file)
croppedImg = image[0:360, 160:640]
image = cv2.resize(croppedImg, (640, 480))
resized_image = cv2.resize(image, (224, 224))
normImg = cv2.normalize(resized_image, None, alpha=0, beta=1, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_32F)
return normImg
#resized_image = cv2.resize(image, (299, 299))
def downloadGirderData(self,index,datacsv):
# tempFileDir is a folder in which to temporarily store the files downloaded from Girder
# by default the temporary folder is created in the current working directory, but this can
# be modified as necessary
if not os.path.isdir(self.tempFileDir):
os.mkdir(self.tempFileDir)
fileID = datacsv["GirderID"][index]
fileName = datacsv["FileName"][index]
numFilesWritten = 0
if not os.path.isfile(os.path.join(self.tempFileDir, fileName)):
self.gClient.downloadItem(fileID, self.tempFileDir)
numFilesWritten += 1
if numFilesWritten % 100 == 0:
print(numFilesWritten)
return(os.path.join(self.tempFileDir, fileName))
def __getitem__(self,index):
# author <NAME>
startIndex = index*self.batchSize
indexOfNextBatch = (index + 1)*self.batchSize
inputBatch = [self.readImage(x) for x in self.inputs[startIndex : indexOfNextBatch]]
#inputBatch += [img for x in self.inputs[startIndex : indexOfNextBatch] for img in [self.rotateImage(self.readExpertImage(x)),self.flipImage(self.readExpertImage(x),0),self.flipImage(self.readExpertImage(x),1)] if "AN0" in x]
outputBatch = [x for x in self.targets[startIndex : indexOfNextBatch]]
'''if startIndex < len(self.targets) and indexOfNextBatch >= len(self.targets):
outputBatch += [label for x in range(startIndex, len(self.targets)) for label in
[self.targets[x], self.targets[x], self.targets[x]] if
x < len(self.targets) and "AN0" in self.inputs[x]]
elif indexOfNextBatch <= len(self.targets):
outputBatch += [label for x in range(startIndex,indexOfNextBatch) for label in [self.targets[x], self.targets[x], self.targets[x]] if x<len(self.targets) and "AN0" in self.inputs[x]]'''
inputBatch = numpy.array(inputBatch)
outputBatch = numpy.array(outputBatch)
return (inputBatch,outputBatch)
class LSTMSequence(Sequence):
def __init__(self, datacsv, indexes, sequences, model, batchSize, labelName,tempFileDir = None,shuffle=True):
# author <NAME>
self.cnnModel = model
if tempFileDir == None:
self.inputs = self.readImages([os.path.join(datacsv["Folder"][x], datacsv["FileName"][x]) for x in indexes])
else:
self.inputs = self.readImages([os.path.join(tempFileDir, datacsv["FileName"][x]) for x in indexes])
self.targets = numpy.array([datacsv[labelName][x] for x in indexes])
self.sequences = sequences
self.batchSize = batchSize
self.labelName = labelName
self.labels = numpy.array(sorted(datacsv[self.labelName].unique()))
inputSequences, targetSequences = self.readImageSequences(indexes)
self.inputs = inputSequences
self.targets = targetSequences
print('Class counts:' + str(numpy.sum(self.targets,axis=0)))
self.shuffle = shuffle
self.on_epoch_end()
def on_epoch_end(self):
if self.shuffle:
shuffledInputs,shuffledTargets = shuffle(self.inputs,self.targets)
self.inputs = shuffledInputs
self.targets = shuffledTargets
def __len__(self):
# author <NAME>
length = len(self.inputs) / self.batchSize
length = math.ceil(length)
return length
def readImages(self, files):
images = []
numLoaded = 0
allOutputs = numpy.array([])
for i in range(len(files)):
image = cv2.imread(files[i])
resized_image = cv2.resize(image, (224, 224))
normImg = cv2.normalize(resized_image, None, alpha=0, beta=1, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_32F)
images.append(normImg)
numLoaded += 1
if numLoaded % 500 == 0 or i == (len(files) - 1):
print("loaded " + str(numLoaded) + ' / ' + str(len(files)) + ' images')
if allOutputs.size == 0:
allOutputs = self.cnnModel.predict(numpy.array(images))
else:
cnnOutput = self.cnnModel.predict(numpy.array(images))
allOutputs = numpy.append(allOutputs, cnnOutput, axis=0)
del images
gc.collect()
images = []
del image
del resized_image
del normImg
return allOutputs
def getSequenceLabels(self, sequence,smallestIndex):
'''if sequence[len(sequence)-1] >= len(self.targets):
textLabel = self.targets[-1]
else:'''
try:
textLabel = self.targets[sequence[-1]-smallestIndex]
label = self.convertTextToNumericLabels(textLabel)
return numpy.array(label)
except IndexError:
print(sequence)
def convertTextToNumericLabels(self, textLabel):
label = numpy.zeros(len(self.labels))
labelIndex = numpy.where(self.labels == textLabel)
label[labelIndex] = 1
return label
def readImageSequences(self,indexes):
allSequences = []
allLabels = []
smallestIndex = indexes[0]
for sequence in self.sequences:
predictedSequence = []
label = self.getSequenceLabels(sequence,smallestIndex)
for i in range(len(sequence)):
if sequence[i] == -1:
image = numpy.zeros(self.inputs[0].shape)
labelIndex = | numpy.where(self.labels == "nothing") | numpy.where |
"""Some common utils"""
# pylint: disable = C0301, C0103, C0111
import os
import pickle
import shutil
import torch
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages
from skimage.transform import downscale_local_mean
import sys
import glob
from torchvision import transforms, datasets
import torch
from PIL import Image
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
try:
import tensorflow as tf
except ImportError:
print('did not import tensorflow')
import estimators
font = { 'weight' : 'bold',
'size' : 30}
import matplotlib
matplotlib.rc('font', **font)
matplotlib.rcParams['pdf.fonttype'] = 42
matplotlib.rcParams['ps.fonttype'] = 42
class BestKeeper(object):
"""Class to keep the best stuff"""
def __init__(self, batch_size, n_input):
self.batch_size = batch_size
self.losses_val_best = [1e100 for _ in range(batch_size)]
self.x_hat_batch_val_best = np.zeros((batch_size, n_input))
def report(self, x_hat_batch_val, losses_val):
for i in range(self.batch_size):
if losses_val[i] < self.losses_val_best[i]:
self.x_hat_batch_val_best[i, :] = x_hat_batch_val[i, :]
self.losses_val_best[i] = losses_val[i]
def get_best(self):
return self.x_hat_batch_val_best
def get_l2_loss(image1, image2):
"""Get L2 loss between the two images"""
assert image1.shape == image2.shape
return np.mean((image1 - image2)**2)
def get_measurement_loss(x_hat, A, y, hparams):
"""Get measurement loss of the estimated image"""
y_hat = get_measurements(x_hat, A, 0 , hparams)
# measurements are in a batch of size 1.
y_hat = y_hat.reshape(y.shape)
# if A is None:
# y_hat = x_hat
# else:
# y_hat = np.matmul(x_hat, A)
assert y_hat.shape == y.shape
return np.sum((y - y_hat) ** 2)
def save_to_pickle(data, pkl_filepath):
"""Save the data to a pickle file"""
with open(pkl_filepath, 'wb') as pkl_file:
pickle.dump(data, pkl_file)
def load_if_pickled(pkl_filepath):
"""Load if the pickle file exists. Else return empty dict"""
if os.path.isfile(pkl_filepath):
with open(pkl_filepath, 'rb') as pkl_file:
data = pickle.load(pkl_file)
else:
data = {}
return data
def get_estimator(hparams, model_type):
if model_type == 'map' and hparams.net == 'glow':
estimator = estimators.glow_annealed_map_estimator(hparams)
elif model_type == 'langevin' and hparams.net == 'glow':
estimator = estimators.glow_annealed_langevin_estimator(hparams)
elif model_type == 'langevin' and hparams.net == 'stylegan2':
estimator = estimators.stylegan_langevin_estimator(hparams)
elif model_type == 'pulse':
assert hparams.net.lower() == 'stylegan2'
estimator = estimators.stylegan_pulse_estimator(hparams)
elif model_type == 'map' and hparams.net == 'ncsnv2':
estimator = estimators.ncsnv2_langevin_estimator(hparams, MAP=True)
elif model_type == 'langevin' and hparams.net == 'ncsnv2':
estimator = estimators.ncsnv2_langevin_estimator(hparams, MAP=False)
elif hparams.net == 'dd' or hparams.model_type == 'dd':
estimator = estimators.deep_decoder_estimator(hparams)
else:
raise NotImplementedError
return estimator
def setup_checkpointing(hparams):
# Set up checkpoint directories
checkpoint_dir = get_checkpoint_dir(hparams, hparams.model_type)
set_up_dir(checkpoint_dir)
def save_images(est_images, save_image, hparams):
"""Save a batch of images to png files"""
for image_num, image in est_images.items():
save_path = get_save_path(hparams, image_num)
image = image.reshape(hparams.image_shape)
save_image(image, save_path)
def checkpoint(est_images, measurement_losses, l2_losses, z_hats, likelihoods, hparams):
"""Save images, measurement losses and L2 losses for a batch"""
if not hparams.debug:
save_images(est_images, save_image, hparams)
m_losses_filepath, l2_losses_filepath, z_hats_filepath, likelihoods_filepath = get_pkl_filepaths(hparams, hparams.model_type)
save_to_pickle(measurement_losses, m_losses_filepath)
save_to_pickle(l2_losses, l2_losses_filepath)
save_to_pickle(z_hats, z_hats_filepath)
save_to_pickle(likelihoods, likelihoods_filepath)
def load_checkpoints(hparams):
measurement_losses, l2_losses, z_hats, likelihoods = {}, {}, {}, {}
if not hparams.debug:
# Load pickled loss dictionaries
m_losses_filepath, l2_losses_filepath, z_hats_filepath, likelihoods_filepath = get_pkl_filepaths(hparams, hparams.model_type)
measurement_losses = load_if_pickled(m_losses_filepath)
l2_losses = load_if_pickled(l2_losses_filepath)
z_hats = load_if_pickled(z_hats_filepath)
likelihoods = load_if_pickled(likelihoods_filepath)
else:
measurement_losses = {}
l2_losses = {}
z_hats = {}
likelihoods = {}
return measurement_losses, l2_losses, z_hats, likelihoods
def image_matrix(images, est_images, l2_losses, hparams, alg_labels=True):
"""Display images"""
if hparams.measurement_type in ['inpaint', 'superres']:
figure_height = 2 + len(hparams.model_types)
else:
figure_height = 1 + len(hparams.model_types)
fig = plt.figure(figsize=[4*len(images), 4.3*figure_height])
outer_counter = 0
inner_counter = 0
# Show original images
outer_counter += 1
for image in images.values():
inner_counter += 1
ax = fig.add_subplot(figure_height, 1, outer_counter, frameon=False)
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_ticks([])
if alg_labels:
ax.set_ylabel('Original')#, fontsize=14)
_ = fig.add_subplot(figure_height, len(images), inner_counter)
view_image(image, hparams)
# Show original images with inpainting mask
if hparams.measurement_type == 'inpaint':
mask = get_inpaint_mask(hparams)
outer_counter += 1
for image in images.values():
inner_counter += 1
ax = fig.add_subplot(figure_height, 1, outer_counter, frameon=False)
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_ticks([])
if alg_labels:
ax.set_ylabel('Masked') #, fontsize=14)
_ = fig.add_subplot(figure_height, len(images), inner_counter)
view_image(image, hparams, mask)
# Show original images with blurring
if hparams.measurement_type == 'superres':
factor = hparams.superres_factor
A = get_A_superres(hparams)
outer_counter += 1
for image in images.values():
image_low_res = np.matmul(image, A) / np.sqrt(hparams.n_input/(factor**2)) / (factor**2)
low_res_shape = (int(hparams.image_shape[0]/factor), int(hparams.image_shape[1]/factor), hparams.image_shape[2])
image_low_res = | np.reshape(image_low_res, low_res_shape) | numpy.reshape |
import numpy as np
import os.path
class Scouter:
def __init__(self,ScouterName,MatchestoScouting=[]):
self.Scouter_Name = ScouterName
self.Matches_to_Scouting = np.array(MatchestoScouting)
class Scouters:
def __init__(self,path_to_scouters_lib,EventCode):
self.__lib_path = path_to_scouters_lib
self.__path_to_scouters_lib = str(path_to_scouters_lib) + EventCode + ".npy"
self.EventCode = EventCode
if not os.path.isfile(self.__path_to_scouters_lib ):
self.Remove_All()
self.__scouters_list = np.load(self.__path_to_scouters_lib,allow_pickle=True).tolist()
def update_event_code(self,EventCode):
self.__path_to_scouters_lib = self.__lib_path + EventCode + ".npy"
self.EventCode = EventCode
if not os.path.isfile(self.__path_to_scouters_lib):
self.Remove_All()
self.__scouters_list = | np.load(self.__path_to_scouters_lib,allow_pickle=True) | numpy.load |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Statistic and fit indices."""
from .utils import duplication_matrix
from scipy.stats import norm, chi2
from collections import namedtuple
from .optimizer import Optimizer
from .model_generalized_effects import ModelGeneralizedEffects
from .model_effects import ModelEffects
from .model_means import ModelMeans
from .model import Model
import pandas as pd
import numpy as np
ParameterStatistics = namedtuple('ParametersStatistics',
['value', 'se', 'zscore', 'pvalue'])
SEMStatistics = namedtuple('SEMStatistics', ['dof', 'ml', 'fun',
'chi2', 'dof_baseline',
'chi2_baseline', 'rmsea', 'cfi',
'gfi', 'agfi', 'nfi', 'tli',
'aic', 'bic', 'params'])
def get_baseline_model(model, data=None):
"""
Retrieve a the baseline model from given model.
Baseline model here is an independence model where all variables are
considered to be independent with zero covariance. Only variances are
estimated.
Parameters
----------
model : Model
Model.
data : pd.DataFrame, optional
Data, extracting from model will be attempted if no data provided.
(It's assumed that model.load took place). The default is None.
cov : pd.DataFrame, optional
Covariance matrix can be provided in the lack of presense of data.
The default is None.
Returns
-------
mod : Model
Baseline model.
"""
if type(model) is str:
mod = Model(model, baseline=True)
if data:
mod.load(data)
return mod
desc = model.description
tp = type(model)
tp_name = tp.__name__
if tp_name not in ('Model',):
mod = tp(desc, baseline=True, intercepts=model.intercepts)
else:
mod = tp(desc, baseline=True)
try:
if not data:
if hasattr(model, 'mx_data'):
mx = model.mx_data
vs = model.vars['observed']
if hasattr(model, 'mx_g'):
mx = | np.append(mx, model.mx_g.T, axis=1) | numpy.append |
# Licensed under the MIT License <http://opensource.org/MIT>
#
# Copyright (c) 2021 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
import numpy as np
import toml
import json
from glob import glob
def AddData(directory, storage):
energies = []
samples = glob(directory+'/sample_*.json')
norm_sq_arr = []
ene_arr = []
ene_sq_arr = []
Nsample = 0
for i, sample in enumerate(samples):
data = json.load(open(sample))
if i == 0:
if 'beta' not in storage:
storage['beta'] = np.array(data['beta'])
Nsample += len(data['Samples'])
energies.append(data['LowestEnergy'])
gene = min(energies)
for sample in samples:
data = json.load(open(sample))
for each in data['Samples']:
norm = (np.exp(0.5*storage['beta']*(gene - each['Energy'][-1]))
* np.array(each['Norm']))
ene = np.array(each['Energy'])
ene_sq = np.array(each['SquaredEnergy'])
norm_sq_arr.append(norm*norm)
ene_arr.append(norm*norm*ene)
ene_sq_arr.append(norm*norm*ene_sq)
norm_sq_arr = np.array(norm_sq_arr).T
ene_arr = np.array(ene_arr).T
ene_sq_arr = np.array(ene_sq_arr).T
storage['LowestEnergy'].append(gene)
storage['SquaredNorm'].append(norm_sq_arr)
storage['Energy'].append(ene_arr)
storage['SquaredEnergy'].append(ene_sq_arr)
storage['Nsamples'].append(Nsample)
def Bootstrapped(storage):
bootstrapped = {'SquaredNorm': [], 'Energy': [], 'SquaredEnergy': []}
nset = len(storage['LowestEnergy'])
for n in range(nset):
nsample = storage['Nsamples'][n]
select = np.random.randint(nsample, size=nsample)
bootstrapped['SquaredNorm'].append(
np.average(storage['SquaredNorm'][n][:, select], axis=1)
)
bootstrapped['SquaredEnergy'].append(
np.average(storage['SquaredEnergy'][n][:, select], axis=1)
)
bootstrapped['Energy'].append(
np.average(storage['Energy'][n][:, select], axis=1)
)
return bootstrapped
storage = {'LowestEnergy': [], 'SquaredNorm': [],
'Energy': [], 'SquaredEnergy': [], 'Nsamples': []}
setting = toml.load(open('setting.toml'))
L = setting['System']['Lattice']
for i in range(-L, L+1, 2):
directory = './TwoSz='+str(i)
AddData(directory, storage)
boot_setting = toml.load(open('bootstrap.toml'))
h_low = boot_setting['Bootstrap']['MagneticField']['LowH']
h_high = boot_setting['Bootstrap']['MagneticField']['HighH']
h_num = boot_setting['Bootstrap']['MagneticField']['HNumber']
h_list = np.linspace(h_low, h_high, h_num)
nB = boot_setting['Bootstrap']['BootstrapNumber']
nBeta = storage['beta'].size
result = {
'Beta': storage['beta'].tolist(), 'MagneticField': h_list.tolist(),
'SystemSize': L, 'BootstrapSize': nB,
'Energy': {'Average': [], 'Error': []},
'Magnetization': {'Average': [], 'Error': []},
'Susceptibility': {'Average': [], 'Error': []},
'SpecificHeat': {'Average': [], 'Error': []},
'SpecificHeatFromS': {'Average': [], 'Error': []},
'Entropy': {'Average': [], 'Error': []},
'NormalizedPartitionFunction': {'Average': [], 'Error': []}
}
bootstrap_data = []
for bootstrap in range(nB):
bootstrap_data.append(Bootstrapped(storage))
for h in h_list:
lamb_arr = np.empty(L+1)
for i, gene in enumerate(storage['LowestEnergy']):
lamb_arr[i] = gene - h*(i - L/2)
lamb_min = lamb_arr.min()
weight = np.empty([nBeta, L+1])
for i, beta in enumerate(storage['beta']):
weight[i, :] = np.exp(-beta*(lamb_arr - lamb_min))
energy = np.empty([nBeta, nB])
entropy = np.empty([nBeta, nB])
magnetization = np.empty([nBeta, nB])
susceptibility = np.empty([nBeta, nB])
specificheat = np.empty([nBeta, nB])
specificheat_s = np.empty([nBeta, nB])
partition = np.empty([nBeta, nB])
for idx, data in enumerate(bootstrap_data):
numer_M = np.sum([weight[:, i]*(i-L/2)*x
for i, x in enumerate(data['SquaredNorm'])],
axis=0)
numer_MSq = np.sum([weight[:, i]*(i-L/2)*(i-L/2)*x
for i, x in enumerate(data['SquaredNorm'])],
axis=0)
numer_E = np.sum([weight[:, i]*x
for i, x in enumerate(data['Energy'])],
axis=0)
numer_EM = np.sum([weight[:, i]*(i-L/2)*x
for i, x in enumerate(data['Energy'])],
axis=0)
numer_ESq = np.sum([weight[:, i]*x
for i, x in enumerate(data['SquaredEnergy'])],
axis=0)
denom = np.sum([weight[:, i]*x
for i, x in enumerate(data['SquaredNorm'])],
axis=0)
ene = numer_E / denom
ene_sq = numer_ESq / denom
mag = numer_M / denom
mag_sq = numer_MSq / denom
ene_mag = numer_EM / denom
energy[:, idx] = ene
entropy[:, idx] = (storage['beta']*(ene - h*mag - lamb_min)
+ np.log(denom))
specificheat_s[0, idx] = -storage['beta'][0] * (
(entropy[1, idx] - entropy[0, idx])
/ (storage['beta'][1] - storage['beta'][0])
)
specificheat_s[1:-1, idx] = -storage['beta'][1:-1]*np.array(
[(entropy[i+1, idx] - entropy[i-1, idx])
/ (storage['beta'][i+1] - storage['beta'][i-1])
for i in range(1, nBeta-1)
]
)
specificheat_s[-1, idx] = -storage['beta'][-1] * (
(entropy[-1, idx] - entropy[-2, idx])
/ (storage['beta'][-1] - storage['beta'][-2])
)
partition[:, idx] = denom
magnetization[:, idx] = mag
susceptibility[:, idx] = storage['beta']*(mag_sq - np.square(mag))
specificheat[:, idx] = np.square(storage['beta'])*(
ene_sq - 2*h*ene_mag + h*h*mag_sq - np.square(ene - h*mag)
)
result['Energy']['Average'].append(np.average(energy, axis=1).tolist())
result['Energy']['Error'].append(np.sqrt( | np.var(energy, axis=1) | numpy.var |
import random
import numpy as np
from sklearn.model_selection import StratifiedKFold
def run_neural_network(prepare_input_data, build_neural_network, evaluate_model):
"""
Performs cross validation for the clean classifier, using 5 splits.
:param prepare_input_data: callback to prepare input data
:param build_neural_network: callback to build the neural network
:param evaluate_model: callback to prepare and evaluate the model
:return:
"""
input_data = prepare_input_data()
random.shuffle(input_data)
images = [elem['data'] for elem in input_data]
labels = [elem['image_type'] for elem in input_data]
images = np.array(images)
labels = np.array(labels)
kfold = StratifiedKFold(n_splits=5, shuffle=True, random_state=None)
cvscores = []
cvlosses = []
i = 0
for train, test in kfold.split(images, labels):
i += 1
print("cross validation: ", i)
model = build_neural_network()
val_loss, val_acc = evaluate_model(model, images[test], labels[test], images[train], labels[train])
print('Loss value ' + str(val_loss))
print('Accuracy ' + str(val_acc))
cvscores.append(val_acc * 100)
cvlosses.append(val_loss)
print("%.2f%% (+/- %.2f%%)" % (np.mean(cvscores), np.std(cvscores)))
print("%.2f (+/- %.2f)" % (np.mean(cvlosses), np.std(cvlosses)))
return model
def is_in_range(cell, lower_bound, upper_bound):
return ((lower_bound <= cell).all()) and ((cell < upper_bound).all())
assert is_in_range(
np.array([1, 1, 1]),
np.array([0, 0, 0]),
np.array([2, 2, 2])
)
assert is_in_range(
np.array([0, 0, 0]),
np.array([0, 0, 0]),
np.array([2, 2, 2])
)
assert not is_in_range(
np.array([2, 2, 2]),
np.array([0, 0, 0]),
| np.array([2, 2, 2]) | numpy.array |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.