prompt
stringlengths
19
879k
completion
stringlengths
3
53.8k
api
stringlengths
8
59
# 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])
numpy.array
''' Created on Mar 23, 2012 @author: <NAME> (<EMAIL>) ''' from run_rmhd2d import rmhd2d import numpy as np from numpy import abs import time from petsc4py import PETSc from rmhd.solvers.common.PETScDerivatives import PETScDerivatives from rmhd.solvers.linear.PETScPoissonCFD2 import PETScPoisson from rmhd.solvers.nonlinear.PETScNonlinearSolverArakawaJ1CFD2 import PETScSolver from rmhd.solvers.nonlinear.PETScNonlinearSolverArakawaJ1CFD2DB import PETScSolverDB from rmhd.solvers.preconditioner.PETScPreconditionerArakawaJ1CFD2DOF2Vec import PETScPreconditioner class rmhd2d_ppc(rmhd2d): ''' PETSc/Python Reduced MHD Solver in 2D using physics based preconditioner. ''' def __init__(self, cfgfile): ''' Constructor ''' super().__init__(cfgfile, mode = "ppc") OptDB = PETSc.Options() # OptDB.setValue('ksp_monitor', '') # OptDB.setValue('snes_monitor', '') # # OptDB.setValue('log_info', '') # OptDB.setValue('log_summary', '') # # OptDB.setValue('ksp_initial_guess_nonzero', 1) # OptDB.setValue('pc_type', 'hypre') # OptDB.setValue('pc_hypre_type', 'boomeramg') OptDB.setValue('pc_hypre_boomeramg_max_iter', 2) # OptDB.setValue('pc_hypre_boomeramg_max_levels', 6) # OptDB.setValue('pc_hypre_boomeramg_tol', 1e-7) # create Jacobian, Function, and linear Matrix objects if self.cfg["solver"]["preconditioner"] == 'none' or self.cfg["solver"]["preconditioner"] == None: self.petsc_precon = None else: self.petsc_precon = PETScPreconditioner(self.da1, self.da4, self.nx, self.ny, self.ht, self.hx, self.hy)#, self.de) self.petsc_precon.set_tolerances(poisson_rtol=self.cfg['solver']['pc_poisson_rtol'], poisson_atol=self.cfg['solver']['pc_poisson_atol'], poisson_max_it=self.cfg['solver']['pc_poisson_max_iter'], parabol_rtol=self.cfg['solver']['pc_parabol_rtol'], parabol_atol=self.cfg['solver']['pc_parabol_atol'], parabol_max_it=self.cfg['solver']['pc_parabol_max_iter'], jacobi_max_it=self.cfg['solver']['pc_jacobi_max_iter']) if self.nu != 0.: self.petsc_solver = PETScSolverDB(self.da1, self.da4, self.nx, self.ny, self.ht, self.hx, self.hy, self.de, self.petsc_precon, self.nu) else: self.petsc_solver = PETScSolver(self.da1, self.da4, self.nx, self.ny, self.ht, self.hx, self.hy, self.de, self.petsc_precon) # initialise matrixfree Jacobian self.Jmf = PETSc.Mat().createPython([self.x.getSizes(), self.b.getSizes()], context=self.petsc_solver, comm=PETSc.COMM_WORLD) self.Jmf.setUp() # self.Jmf.setNullSpace(self.solver_nullspace) # create PC shell # self.pc = PETSc.PC().createPython(context=self.petsc_precon, # comm=PETSc.COMM_WORLD) # self.pc.setFromOptions() # self.pc.setUp() # create linear solver self.ksp = PETSc.KSP().create() self.ksp.setFromOptions() self.ksp.setOperators(self.Jmf) self.ksp.setInitialGuessNonzero(True) self.ksp.setType('fgmres') self.ksp.getPC().setType('none') # self.ksp.getPC().setType(PETSc.PC.Type.SHELL) # self.ksp.setPC(PETSc.PCShell(self.petsc_precon)) # self.ksp.setPC(self.pc) # self.ksp.setPC(self.ksp.getPC().createPython(context=self.petsc_precon, comm=PETSc.COMM_WORLD)) # self.ksp.setPCSide(PETSc.KSP.PCSide.RIGHT) self.ksp.setUp() # update solution history self.petsc_solver.update_previous(self.x) def __del__(self): self.ksp.destroy() self.Jmf.destroy() def run(self): run_time = time.time() alpha = 1.5 gamma = 0.9 ksp_rtol_max = 1E-3 for itime in range(1, self.nt+1): if PETSc.COMM_WORLD.getRank() == 0: localtime = time.asctime( time.localtime(time.time()) ) print("\nit = %4d, t = %10.4f, %s" % (itime, self.ht*itime, localtime) ) print # calculate initial guess if self.cfg['solver']['petsc_snes_initial_guess']: self.calculate_initial_guess(initial=itime==1) # self.calculate_initial_guess(initial=True) # update history self.petsc_solver.update_history() # copy initial guess to x if self.cfg['solver']['petsc_snes_initial_guess']: self.copy_x_from_da1_to_da4() # solve i = 0 self.petsc_solver.update_previous(self.x) self.petsc_solver.function(self.f) pred_norm = self.f.norm() prev_norm = pred_norm tolerance = self.tolerance + self.cfg['solver']['petsc_snes_rtol'] * pred_norm if PETSc.COMM_WORLD.getRank() == 0: print(" Nonlinear Solver Iteration %i: residual = %22.16E" % (i, pred_norm)) while True: i+=1 self.f.copy(self.b) self.b.scale(-1.) if self.petsc_precon == None: self.dx.set(0.) else: self.b.copy(self.dy) if self.cfg['solver']['petsc_ksp_adapt_rtol']: if i == 1: zeta_A = 0. zeta_B = 0. zeta_C = 0. zeta_D = 0. ksp_tol = self.cfg['solver']['petsc_ksp_rtol'] else: zeta_A = gamma * np.power(pred_norm / prev_norm , alpha) zeta_B = np.power(ksp_tol, alpha) zeta_C = np.min([ksp_rtol_max, np.max(zeta_A, zeta_B)]) zeta_D = gamma * tolerance / pred_norm ksp_tol = np.min([ksp_rtol_max,
np.max(zeta_C, zeta_D)
numpy.max
#!/usr/bin/env python """ Copyright 2010-2018 University Of Southern California 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. # This is PYTHON port of Walter Imperatori GeoBB_srf.m matlab code # Function to calculate stations position in CompSyn geometry convention. # It also calculates stations and hypocenter positions in BBTool geometry. # Then it provides some parameters useful for subsequent analysis, such # as different type of station-to-fault distances. # INPUT: # # stat_file - file with coordinates (lon/lat) of the stations # flag - flag for plots ('y' or 'n') # Note: Plotting feature is not implemented in this version. # filename - srf input filename # extended - flag for extended fault computations ('y' or 'n') # # OUTPUT: # par - array with several parameters: # par.bbextent - "far-side" for the BBTool code # par.hypo - hypocentral coordinates for BBTool # par.Mw - moment magnitude # par.mecha - general mechanism # par.subfault - subfaults coordinates # # # Remarks: current version work only with positive dip """ from __future__ import division, print_function # Import Python modules import os import sys import math import numpy as np import pyproj # Import Broadband modules import bband_utils from station_list import StationList class GeoBBSRF(object): def __init__(self, sim_id=0): """ Initialize class variables """ self.station_file = '' self.sim_id = sim_id self.mw = 0.0 self.mecha = '' self.f_len = 0.0 self.f_width = 0.0 self.f_dip = 0.0 self.f_strike = 0.0 self.depth = 0.0 self.rake = 0.0 self.hyp = [] self.fault_maxlon = 0.0 self.fault_minlon = 0.0 self.fault_maxlat = 0.0 self.fault_minlat = 0.0 self.corn = [] self.projobj = None self.extended = 'n' def geo2cart(self, lon, lat, lonmin=0, latmin=0): """ # Function to convert geographic coordinates into cartesian ones # Transversal Mercator projection is used # # INPUT: # lon,lat -> input vectors with geographic coordinates # lonmin,latmin -> lower-left-corner (on x-y plane) # of plot box (used for shifting) # OUTPUT: # [x,y] -> computed cartesian coordinates (in meters) """ # m.geoid= [6378135 0.08181881] # print "proj obj in geo2cart", self.projobj [a, b] = self.projobj(lon, lat) # print "[a,b] = self.projobj(lat,lon)", a,b if lonmin == 0: a0 = 0 b0 = 0 else: [a0, b0] = self.projobj(lonmin, latmin) # shift of [a0,b0] x = (a - a0) y = (b - b0) return [x, y] def translation_matrix(self, direction): T = np.identity(4) T[:3, 3] = direction[:3] return T def read_srf(self, srffile): if os.path.exists(srffile): srff = open(srffile, 'r') else: raise bband_utils.ParameterError("Missing SRF file (%s)!" % (srffile)) # Check number of planes version = float(srff.readline().strip().split()[0]) tokens = srff.readline().strip().split() # Make sure we have a valid SRF file if len(tokens) != 2: raise bband_utils.ProcessingError("Invalid SRF file (%s)!" % (srffile)) planes = int(tokens[1]) # Make sure we have only 1 plane if planes > 1: raise bband_utils.ProcessingError("Only one plane is supported!" + " Found %d planes in SRF file!" % (planes)) # Read Fault Data tokens = srff.readline().strip().split() if len(tokens) != 6: raise bband_utils.ProcessingError("Invalid SRF file (%s)!" % (srffile)) self.f_len = float(tokens[4]) self.f_width = float(tokens[5]) tokens = srff.readline().strip().split() if len(tokens) != 5: raise bband_utils.ProcessingError("Invalid SRF file (%s)!" % (srffile)) self.f_strike = float(tokens[0]) self.f_dip = float(tokens[1]) self.f_depth = float(tokens[2]) tokens = srff.readline().strip().split() if len(tokens) != 2: raise bband_utils.ProcessingError("Invalid SRF file (%s)!" % (srffile)) n_cels = int(tokens[1]) # print ("F_len: %f, F_width: %f, F_Strike: %f" % # (self.f_len, self.f_width, self.f_strike)) # print ("F_dip: %f, F_depth: %f, n_cells: %d" % # (self.f_dip, self.f_depth, n_cels)) M0 = 0.0 lon = [] lat = [] dep = [] tinit = [] rake = [] for i in range(0, n_cels): tokens = srff.readline().strip().split() if version == 1.0 and len(tokens) != 8: raise bband_utils.ProcessingError("Invalid SRF version 1 " "file (%s)!" % (srffile)) if version == 2.0 and len(tokens) != 10: raise bband_utils.ProcessingError("Invalid SRF version 2 " "file (%s)!" % (srffile)) lon.append(float(tokens[0])) lat.append(float(tokens[1])) dep.append(float(tokens[2])) area = float(tokens[5]) tinit.append(float(tokens[6])) tokens = srff.readline().strip().split() if len(tokens) != 7: raise bband_utils.ProcessingError("Invalid SRF file (%s)!" % (srffile)) rake.append(float(tokens[0])) slip1 = float(tokens[1]) slip2 = float(tokens[3]) slip3 = float(tokens[5]) nt1 = float(tokens[2]) nt2 = float(tokens[4]) nt3 = float(tokens[6]) if nt1 > 0: for k in range(0, int(math.ceil(nt1 / 6.0))): token = srff.readline() if token == "": raise bband_utils.ProcessingError("Invalid SRF " "file (%s)!" % (srffile)) if nt2 > 0: for k in range(0, int(math.ceil(nt2 / 6.0))): token = srff.readline() if token == "": raise bband_utils.ProcessingError("Invalid SRF " "file (%s)!" % (srffile)) if nt3 > 0: for k in range(0, int(math.ceil(nt3 / 6.0))): token = srff.readline() if token == "": raise bband_utils.ProcessingError("Invalid SRF " "file (%s)!" % (srffile)) M0 = M0 + (area * (math.sqrt(slip1**2 + slip2**2 + slip3**2))*3)*(10**11) srff.close() np_tinit = np.array(tinit) tinit_index = [] [tinit_index] = np.nonzero(np_tinit == np.min(np_tinit)) # Find hypocenter hyp = [] hyp.append(lon[tinit_index[0]]) hyp.append(lat[tinit_index[0]]) hyp.append(dep[tinit_index[0]]) self.hyp = hyp # Find mw mw = (math.log10(M0)) / 1.5 - 10.73 self.mw = mw # Find rake (i.e. mechanism) rake_ave = np.mean(np.array(rake)) self.rake = rake_ave if rake_ave > 45 and rake_ave < 135: mecha = 'rs' if rake_ave >= 135 and rake_ave < 225: mecha = 'ss' if rake_ave >= 225 and rake_ave < 315: mecha = 'ns' if rake_ave <= 45 or rake_ave >= 315: mecha = 'ss' self.mecha = mecha # print "mw: %f, rake_ave: %f, mecha:%s"%(mw, rake_ave, mecha) if self.extended == 'y': # Find fault corners i = [] j = [] k = [] np_dep = np.array(dep) # print np.min(np_dep), len(np_dep) [i] = np.nonzero(np_dep == min(dep)) if len(i) < 1: raise bband_utils.ProcessingError("Invalid SRF file: %s\n" % (srffile) + "len(i)=%d Failed to " % len(i) + "calculate " + "extended fault data!") np_lon = np.array(lon) [j] = np.nonzero(np_lon[i] == np.min(np_lon[i])) if len(j) < 1: raise bband_utils.ProcessingError("Invalid SRF file: %s\n" % (srffile) + "len(j)=%d Failed to " % len(j) + "calculate " + "extended fault data!") np_lat = np.array(lat) [k] = np.nonzero(np_lat[j] == np.min(np_lat[j])) if len(k) == 1: lat_index = k[0] self.corn = [lon[lat_index], lat[lat_index]] # print "Corner:", self.corn else: raise bband_utils.ProcessingError("Invalid SRF file: %s\n" % (srffile) + "len(k)=%d Failed to " % len(k) + "calculate " + "extended fault data!") self.fault_maxlon = np.max(np_lon) self.fault_minlon = np.min(np_lon) self.fault_maxlat = np.max(np_lat) self.fault_minlat = np.min(np_lat) #print ("fault_maxlon: %f, fault_minlon: %f, fault_maxlat: %f, " % # (self.fault_maxlon,self.fault_minlon,self.fault_maxlat) + # "fault_minlat: %f" % (self.fault_minlat)) # par.mw = mw; par.mecha = mecha; return 0 def write_xyz_srf(self, srf_file, xyz_srf_file, T3M): """ Reads the SRF file and converts its lat/lon to XYZ format using self.latmin and self.lonmin as reference points. The T3M matrix is used to shift the coordinates to the new reference point calculated in the run function. """ # Open files infile = open(srf_file, 'r') outfile = open(xyz_srf_file, 'w') # Pick up version number from SRF file version = float(infile.readline().strip().split()[0]) # Now go back to the start infile.seek(0) # Copy lines while True: line = infile.readline() # Cannot mix for line in infile with readline... if line is None: break outfile.write(line) # Until we find the plane line if line.find("PLANE") >= 0: break tokens = line.strip().split() # Make sure we have a valid SRF file if len(tokens) != 2: raise bband_utils.ProcessingError("Invalid SRF file (%s)!" % (srf_file)) planes = int(tokens[1]) # Make sure we have only 1 plane if planes > 1: raise bband_utils.ProcessingError("Only one plane is " + "supported!" + " Found %d " % (planes) + " in SRF file!") line = infile.readline() tokens = line.strip().split() if len(tokens) != 6: raise bband_utils.ProcessingError("Invalid SRF file (%s)!" % (srf_file)) # Convert to XYZ lon = float(tokens[0]) lat = float(tokens[1]) [x_cart, y_cart] = self.geo2cart(lon, lat, self.min_lon, self.min_lat) tmp = T3M * np.mat([x_cart, y_cart, 0, 1]).transpose() tokens[0] = str(float(tmp[0])) tokens[1] = str(float(tmp[1])) outfile.write(" %s\n" % " ".join(tokens)) # Continue copying while True: line = infile.readline() # Cannot mix for line in infile with readline... if line is None: break outfile.write(line) if line.find("POINTS") >= 0: break # Figure out how many cells tokens = line.strip().split() if len(tokens) != 2: raise bband_utils.ProcessingError("Invalid SRF file (%s)!" % (srf_file)) n_cels = int(tokens[1]) # Go through each cell for i in range(0, n_cels): tokens = infile.readline().strip().split() if version == 1.0 and len(tokens) != 8: raise bband_utils.ProcessingError("Invalid SRF version 1 " "file (%s)!" % (srffile)) if version == 2.0 and len(tokens) != 10: raise bband_utils.ProcessingError("Invalid SRF version 2 " "file (%s)!" % (srffile)) lon = float(tokens[0]) lat = float(tokens[1]) [x_cart, y_cart] = self.geo2cart(lon, lat, self.min_lon, self.min_lat) tmp = T3M *
np.mat([x_cart, y_cart, 0, 1])
numpy.mat
import math import os import random import numpy as np import torch import torch.utils.data as data from PIL import Image from lib.utils.functional import read_mat, mapping_function from ..utils.transforms import fliplr_joints, crop, generate_target, transform_pixel class AFLW2000(data.Dataset): def __init__(self, cfg, ds_type="train", transform=None, return_pose=False): # specify annotation file for dataset if ds_type == "train": self.filenames = cfg.DATASET.TRAINSET elif ds_type == "val": self.filenames = cfg.DATASET.VALSET elif ds_type == "test": self.filenames = cfg.DATASET.TESTSET else: raise NotImplementedError("Dataset type %s is not implemented!" % ds_type) self.is_train = (ds_type == "train") self.transform = transform self.return_pose = return_pose self.data_root = cfg.DATASET.ROOT self.input_size = cfg.MODEL.IMAGE_SIZE self.output_size = cfg.MODEL.HEATMAP_SIZE self.sigma = cfg.MODEL.SIGMA self.scale_factor = cfg.DATASET.SCALE_FACTOR self.rot_factor = cfg.DATASET.ROT_FACTOR self.label_type = cfg.MODEL.TARGET_TYPE self.flip = cfg.DATASET.FLIP self.num_joints = cfg.MODEL.NUM_JOINTS # load annotations self.images = [] self.landmarks = [] if self.return_pose: self.pose = [] for filename in open(self.filenames, "r").read().splitlines(): file_path = os.path.join(self.data_root, filename) mat_path = file_path.replace("jpg", "mat") landmarks, pose, _ = read_mat(mat_path, pt3d=True) self.images.append(file_path) self.landmarks.append(landmarks) if self.return_pose: self.pose.append(pose) self.mean = np.array([0.485, 0.456, 0.406], dtype=np.float32) self.std = np.array([0.229, 0.224, 0.225], dtype=np.float32) def __len__(self): return len(self.images) def __getitem__(self, idx): image_path = self.images[idx] if self.return_pose: pose = self.pose[idx] x_min = math.floor(
np.min(self.landmarks[idx][:, 0])
numpy.min
#!/usr/bin/python3 # -*- coding: utf-8 -*- import sys import os from PyQt5.QtGui import * from PyQt5.QtCore import * from PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGui, QtWidgets import cv2 import imutils import numpy as np import torch from PIL import ImageDraw, ImageFont from PIL import Image from torch import nn from data_tool.custom_dataset import CustomImageDataset from torch.utils.data import DataLoader from nets.mobilenet import MobileNet from torchvision.io import read_image from mainWindowLayout import MainLayout # import cv2 # import numpy as np from scipy import ndimage from matplotlib import pyplot as plt class MainWindow(QMainWindow, MainLayout): imagePaths = [] originImages=[] imageList = [] #二维的图像列表 hideLayoutTag=-1 def __init__(self,parent=None): super(MainWindow, self).__init__(parent) self.setupUi(self) self.signalSlots() #button与具体方法关联 def signalSlots(self): #文件按钮相关方法 #打开 self.openAct.triggered.connect(lambda : importImage(self)) #保存 self.saveAct.triggered.connect(lambda : importImage(self)) #退出 self.exitAct.triggered.connect(self.close) #编辑按钮相关方法 #放大 self.largeAct.triggered.connect(lambda : largeImage(self)) #缩小 self.smallAct.triggered.connect(lambda : smallImage(self)) #灰度 self.grayAct.triggered.connect(lambda : grayImage(self)) #亮度 self.brightAct.triggered.connect(lambda : brightImage(self)) #旋转 self.rotateAct.triggered.connect(lambda : rotateImage(self)) #截图 self.screenshotAct.triggered.connect(lambda : screenshotImage(self)) #变换按钮相关方法 #傅里叶变换 self.change1Act.triggered.connect(lambda : change1Image(self)) #离散余弦变换 self.change2Act.triggered.connect(lambda : change2Image(self)) #Radon变换 self.change3Act.triggered.connect(lambda : change3Image(self)) #噪声按钮相关方法 #高斯噪声 self.noise1Act.triggered.connect(lambda : noise1Image(self)) #椒盐噪声 self.noise2Act.triggered.connect(lambda : noise2Image(self)) #斑点噪声 self.noise3Act.triggered.connect(lambda : importImage(self)) #泊松噪声 self.noise4Act.triggered.connect(lambda : importImage(self)) #滤波按钮相关方法 #高通滤波 self.smoothing1Act.triggered.connect(lambda : smoothing1Image(self)) #低通滤波 self.smoothing2Act.triggered.connect(lambda : smoothing2Image(self)) #平滑滤波 self.smoothing3Act.triggered.connect(lambda : smoothing3Image(self)) #锐化滤波 self.smoothing4Act.triggered.connect(lambda : smoothing4Image(self)) #直方图统计按钮相关方法 #R直方图 self.hist1Act.triggered.connect(lambda : hist1Image(self)) #G直方图 self.hist2Act.triggered.connect(lambda : importImage(self)) #B直方图 self.hist3Act.triggered.connect(lambda : importImage(self)) #图像增强按钮相关方法 #伪彩色增强 self.enhance1Act.triggered.connect(lambda : enhance1Image(self)) #真彩色增强 self.enhance2Act.triggered.connect(lambda : enhance2Image(self)) #直方图均衡 self.enhance3Act.triggered.connect(lambda : histNormalized(self)) #NTSC颜色模型 self.enhance4Act.triggered.connect(lambda : enhance4Image(self)) #YCbCr颜色模型 self.enhance5Act.triggered.connect(lambda : enhance5Image(self)) #HSV颜色模型 self.enhance6Act.triggered.connect(lambda : enhance6Image(self)) #阈值分割方法 self.threButton.clicked.connect(lambda : threImage(self)) #形态学处理方法 self.morphologyProcessButton.clicked.connect(lambda : morphologyProcessImage(self)) #特征提取方法 self.featureButton.clicked.connect(lambda : featureImage(self)) #图像分类与识别方法 self.imgButton.clicked.connect(lambda : layoutChange(self)) self.cla_button.clicked.connect(lambda: cla(self)) #底部 #上一张 self.preButton.clicked.connect(lambda : preImage(self)) #下一张 self.nextButton.clicked.connect(lambda : nextImage(self)) #退出 self.exitButton.clicked.connect(self.close) #编辑按钮相关方法 #放大 def largeImage(window): imageList=[] for img in window.originImages: imgs=[] img_info=img[0].shape image_height=img_info[0] image_weight=img_info[1] dstHeight=int(2*image_height) dstWeight=int(2*image_weight) result=cv2.resize(img[0],(dstHeight,dstWeight)) imgs.extend([img[0],result]) imageList.append(imgs) resizeFromList(window, imageList) showImage(window,['原图','放大后']) #缩小 def smallImage(window): imageList=[] for img in window.originImages: imgs=[] img_info=img[0].shape image_height=img_info[0] image_weight=img_info[1] dstHeight=int(0.5*image_height) dstWeight=int(0.5*image_weight) result=cv2.resize(img[0],(dstHeight,dstWeight)) imgs.extend([img[0],result]) imageList.append(imgs) resizeFromList(window, imageList) showImage(window,['原图','缩小后']) #灰度 def grayImage(window): imageList=[] for img in window.originImages: imgs=[] result = cv2.cvtColor(img[0], cv2.COLOR_BGR2RGB) imgs.extend([img[0],result]) imageList.append(imgs) resizeFromList(window, imageList) showImage(window,['原图','灰度处理后']) #亮度 def brightImage(window): imageList=[] for img in window.originImages: imgs=[] rows, cols, chunnel = img[0].shape blank = np.zeros([rows, cols, chunnel], img[0].dtype) result = cv2.addWeighted(img[0], 1.3, blank, 1-1.3, 3) imgs.extend([img[0],result]) imageList.append(imgs) resizeFromList(window, imageList) showImage(window,['原图','调整亮度后']) #旋转 def rotateImage(window): imageList=[] for img in window.originImages: imgs=[] img_info=img[0].shape image_height=img_info[0] image_weight=img_info[1] mat_rotate=cv2.getRotationMatrix2D((image_height*0.5,image_weight*0.5),90,1) #center angle 3scale result=cv2.warpAffine(img[0],mat_rotate,(image_height,image_weight)) imgs.extend([img[0],result]) imageList.append(imgs) resizeFromList(window, imageList) showImage(window,['原图','旋转后']) #截图 def screenshotImage(window): imageList=[] for img in window.originImages: imgs=[] result = img[0][70:170, 440:540] imgs.extend([img[0],result]) imageList.append(imgs) resizeFromList(window, imageList) showImage(window,['原图','截图后']) #变换按钮相关方法 #傅里叶变换 def change1Image(window): imageList=[] for img in window.originImages: imgs=[] b,g,r=cv2.split(img[0]) b_freImg,b_recImg=oneChannelDft(b) g_freImg, g_recImg = oneChannelDft(g) r_freImg, r_recImg = oneChannelDft(r) freImg=cv2.merge([b_freImg,g_freImg,r_freImg]) imgs.extend([img[0],freImg]) imageList.append(imgs) resizeFromList(window, imageList) showImage(window,['原图','傅里叶变换后']) def oneChannelDft(img): width, height = img.shape nwidth = cv2.getOptimalDFTSize(width) nheigth = cv2.getOptimalDFTSize(height) nimg = np.zeros((nwidth, nheigth)) nimg[:width, :height] = img dft = cv2.dft(np.float32(nimg), flags=cv2.DFT_COMPLEX_OUTPUT) ndft = dft[:width, :height] ndshift = np.fft.fftshift(ndft) magnitude = np.log(cv2.magnitude(ndshift[:, :, 0], ndshift[:, :, 1])) result = (magnitude - magnitude.min()) / (magnitude.max() - magnitude.min()) * 255 frequencyImg = result.astype('uint8') ilmg = cv2.idft(dft) ilmg = cv2.magnitude(ilmg[:, :, 0], ilmg[:, :, 1])[:width, :height] ilmg = np.floor((ilmg - ilmg.min()) / (ilmg.max() - ilmg.min()) * 255) recoveredImg = ilmg.astype('uint8') return frequencyImg,recoveredImg #离散余弦变换 def change2Image(window): imageList=[] for img in window.originImages: imgs=[] img1 = cv2.cvtColor(img[0], cv2.COLOR_BGR2RGB) img_dct = cv2.dct(img1) #进行离散余弦变换 imgs.extend([img[0],img_dct]) imageList.append(imgs) resizeFromList(window, imageList) showImage(window,['原图','离散余弦变换后']) #Radon变换 def change3Image(window): imageList=[] for img in window.originImages: imgs=[] img_dct = cv2.dct(img[0]) result = np.log(abs(img_dct)) imgs.extend([img[0],result]) imageList.append(imgs) resizeFromList(window, imageList) showImage(window,['原图','Radon变换后']) #噪声按钮相关方法 #高斯噪声 #定义添加高斯噪声的函数 def addGaussianNoise(image,percetage): G_Noiseimg = image G_NoiseNum=int(percetage*image.shape[0]*image.shape[1]) for i in range(G_NoiseNum): temp_x = np.random.randint(20,40) temp_y = np.random.randint(20,40) G_Noiseimg[temp_x][temp_y] = 255 return G_Noiseimg def noise1Image(window): imageList=[] for img in window.originImages: imgs=[] grayImage = cv2.cvtColor(img[0], cv2.COLOR_BGR2RGB) #灰度变换 result = addGaussianNoise(grayImage,0.01) #添加10%的高斯噪声 imgs.extend([img[0],result]) imageList.append(imgs) resizeFromList(window, imageList) showImage(window,['原图','高斯噪声后']) #椒盐噪声 #定义添加椒盐噪声的函数 def saltpepper(img,n): m=int((img.shape[0]*img.shape[1])*n) for a in range(m): i=int(np.random.random()*img.shape[1]) j=int(np.random.random()*img.shape[0]) if img.ndim==2: img[j,i]=255 elif img.ndim==3: img[j,i,0]=255 img[j,i,1]=255 img[j,i,2]=255 for b in range(m): i=int(np.random.random()*img.shape[1]) j=int(np.random.random()*img.shape[0]) if img.ndim==2: img[j,i]=0 elif img.ndim==3: img[j,i,0]=0 img[j,i,1]=0 img[j,i,2]=0 return img def noise2Image(window): imageList=[] for img in window.originImages: imgs=[] grayImage = cv2.cvtColor(img[0], cv2.COLOR_BGR2RGB) #灰度变换 result = saltpepper(grayImage,0.02) imgs.extend([img[0],result]) imageList.append(imgs) resizeFromList(window, imageList) showImage(window,['原图','椒盐噪声后']) #滤波按钮相关方法 #高通滤波 def smoothing1Image(window): imageList=[] for img in window.originImages: imgs=[] x=cv2.Sobel(img[0],cv2.CV_16S,1,0) y=cv2.Sobel(img[0],cv2.CV_16S,0,1) absx=cv2.convertScaleAbs(x) absy=cv2.convertScaleAbs(y) result = cv2.addWeighted(absx,0.5,absy,0.5,0) imgs.extend([img[0],result]) imageList.append(imgs) resizeFromList(window, imageList) showImage(window,['原图','高通滤波后']) #低通滤波 def smoothing2Image(window): imageList=[] for img in window.originImages: imgs=[] result = cv2.medianBlur(img[0],5) imgs.extend([img[0],result]) imageList.append(imgs) resizeFromList(window, imageList) showImage(window,['原图','低通滤波后']) #平滑滤波 def smoothing3Image(window): imageList=[] for img in window.originImages: imgs=[] result = cv2.blur(img[0], (5, 5)) imgs.extend([img[0],result]) imageList.append(imgs) resizeFromList(window, imageList) showImage(window,['原图','平滑滤波后']) #锐化滤波 def smoothing4Image(window): imageList=[] for img in window.originImages: imgs=[] result = cv2.bilateralFilter(img[0],9,75,75) imgs.extend([img[0],result]) imageList.append(imgs) resizeFromList(window, imageList) showImage(window,['原图','锐化滤波后']) #直方图统计按钮相关方法 #R直方图 def hist1Image(window): imageList=[] for img in window.originImages: imgs=[] color = ('b','g','r') for i,col in enumerate(color): histr = cv2.calcHist([img[0]],[i],None,[256],[0,256]) plt.plot(histr,color = col) plt.xlim([0,256]) plt.savefig("hist1.jpg") result = cv2.imread("hist1.jpg") imgs.extend([img[0],result]) imageList.append(imgs) resizeFromList(window, imageList) showImage(window,['原图','R直方图后']) #图像增强按钮相关方法 #伪彩色增强 def enhance1Image(window): imageList=[] for img in window.originImages: imgs=[] grayImage = cv2.cvtColor(img[0], cv2.COLOR_BGR2RGB) #灰度变换 result = cv2.applyColorMap(grayImage, cv2.COLORMAP_JET) imgs.extend([img[0],result]) imageList.append(imgs) resizeFromList(window, imageList) showImage(window,['原图','伪彩色增强后']) #真彩色增强 def enhance2Image(window): imageList=[] for img in window.originImages: imgs=[] grayImage = cv2.cvtColor(img[0], cv2.COLOR_BGR2RGB) #灰度变换 result = cv2.applyColorMap(grayImage, cv2.COLORMAP_JET) imgs.extend([img[0],result]) imageList.append(imgs) resizeFromList(window, imageList) showImage(window,['原图','真彩色增强后']) #直方图均衡 def histNormalized(window): imageList=[] for img in window.originImages: imgs=[] b, g, r = cv2.split(img[0]) b_equal = cv2.equalizeHist(b) g_equal = cv2.equalizeHist(g) r_equal = cv2.equalizeHist(r) result = cv2.merge([b_equal, g_equal, r_equal]) imgs.extend([img[0],result]) imageList.append(imgs) resizeFromList(window, imageList) showImage(window,['原图','直方图均衡化后']) #NTSC颜色模型 def enhance4Image(window): imageList=[] for img in window.originImages: imgs=[] result = cv2.cvtColor(img[0], cv2.COLOR_BGR2RGB) imgs.extend([img[0],result]) imageList.append(imgs) resizeFromList(window, imageList) showImage(window,['原图','NTSC颜色模型后']) #YCbCr颜色模型 def enhance5Image(window): imageList=[] for img in window.originImages: imgs=[] result = cv2.cvtColor(img[0], cv2.COLOR_BGR2YCR_CB) imgs.extend([img[0],result]) imageList.append(imgs) resizeFromList(window, imageList) showImage(window,['原图','YCbCr颜色模型后']) #HSV颜色模型 def enhance6Image(window): imageList=[] for img in window.originImages: imgs=[] result = cv2.cvtColor(img[0],cv2.COLOR_BGR2HSV) imgs.extend([img[0],result]) imageList.append(imgs) resizeFromList(window, imageList) showImage(window,['原图','HSV颜色模型后']) #阈值分割方法 def threImage(window): imageList=[] for img in window.originImages: print(img.size) imgs=[] grayImage = cv2.cvtColor(img[0], cv2.COLOR_BGR2RGB) #灰度变换 result = cv2.threshold(grayImage, 127, 255, cv2.THRESH_BINARY) imgs.extend([img[0],result]) imageList.append(imgs) # resizeFromList(window, imageList) showImage(window,['原图','阈值分割后']) #形态学处理方法 def morphologyProcessImage(window): imageList=[] for img in window.originImages: imgs=[] kernel = cv2.getStructuringElement(cv2.MORPH_RECT,(3, 3)) result = cv2.erode(img[0],kernel) imgs.extend([img[0],result]) imageList.append(imgs) resizeFromList(window, imageList) showImage(window,['原图','形态学处理后']) #特征提取方法 def featureImage(window): imageList=[] for img in window.originImages: imgs=[] img1 = img[0].copy() gray=cv2.cvtColor(img[0],cv2.COLOR_BGR2GRAY) gray=np.float32(gray) dst=cv2.cornerHarris(gray,2,3,0.04) img[0][dst>0.01*dst.max()]=[0,0,255] imgs.extend([img1,img[0]]) imageList.append(imgs) resizeFromList(window, imageList) showImage(window,['原图','特征提取后']) def resizeFromList(imageList): width=256 height=256 for x_pos in range(len(imageList)): image=cv2.resize(imageList[x_pos], (width, height)) imageList[x_pos]=image #打开图像 def importImage(window): fnames, _ = QFileDialog.getOpenFileNames(window, 'Open file', '.', 'Image Files(*.jpg *.bmp *.png *.jpeg *.rgb *.tif)') window.imagePaths = [] for fname in fnames: if fname!='': window.imagePaths.append(fname) if window.imagePaths!=[]: readIamge(window) resizeFromList(window.originImages) # print(len(window.originImages)) showImage(window) def readIamge(window): window.originImages=[] for path in window.imagePaths: img=cv2.imread(path) window.originImages.append(img) #显示图像 def showImage(window,headers=[]): window.showImageView.clear() window.showImageView.setColumnCount(3) ent=len(window.originImages)//3 dul=len(window.originImages)%3 echo=ent+1 #if dul else ent window.showImageView.setRowCount(echo) window.showImageView.setShowGrid(True) window.showImageView.setEditTriggers(QAbstractItemView.NoEditTriggers) window.showImageView.setHorizontalHeaderLabels(headers) # print(len(window.originImages)) for x in range(echo): circle=3 if x<echo-1 else dul if circle: for y in range(circle): imageView=QGraphicsView() imageView.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) imageView.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) img=window.originImages[3*x+y] img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) width=img.shape[1] height=img.shape[0] window.showImageView.setColumnWidth(y, width) window.showImageView.setRowHeight(x, height) frame = QImage(img, width, height, QImage.Format_RGB888) #调用QPixmap命令,建立一个图像存放框 pix = QPixmap.fromImage(frame) item = QGraphicsPixmapItem(pix) scene = QGraphicsScene() # 创建场景 scene.addItem(item) imageView.setScene(scene) window.showImageView.setCellWidget(x, y, imageView) else: break device = "cuda" test_mode = 0 test_mode_list = ['ori', 'gen', 'comb'] # model = MobileNet().to(device) model.eval() def change_cv2_draw(image, strs, local, sizes, colour): cv2img = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) pilimg = Image.fromarray(cv2img) draw = ImageDraw.Draw(pilimg) font = ImageFont.truetype("SIMYOU.TTF", sizes, encoding="utf-8") draw.text(local, strs, colour, font=font) image = cv2.cvtColor(
np.array(pilimg)
numpy.array
#============================================================================== # WELCOME #============================================================================== # Welcome to RainyDay, a framework for coupling remote sensing precipitation # fields with Stochastic Storm Transposition for assessment of rainfall-driven hazards. # Copyright (C) 2017 <NAME> (<EMAIL>) # #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 DOCUMENT CONTAINS VARIOUS FUNCTIONS NEEDED TO RUN RainyDay #============================================================================== import os import sys import numpy as np import scipy as sp import glob import math from datetime import datetime, date, time, timedelta import time from copy import deepcopy from mpl_toolkits.basemap import Basemap, addcyclic from matplotlib.patches import Polygon from scipy import stats from netCDF4 import Dataset, num2date, date2num #import gdal import rasterio import pandas as pd from numba import prange,jit import shapely import geopandas as gp from scipy.stats import norm from scipy.stats import lognorm # plotting stuff, really only needed for diagnostic plots import matplotlib.pyplot as plt import matplotlib from matplotlib.colors import LogNorm import subprocess try: os.environ.pop('PYTHONIOENCODING') except KeyError: pass import warnings warnings.filterwarnings("ignore") from numba.types import int32,int64,float32,uint32 import linecache GEOG="+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs" # ============================================================================= # Smoother that is compatible with nan values. Adapted from https://stackoverflow.com/questions/18697532/gaussian-filtering-a-image-with-nan-in-python # ============================================================================= def mysmoother(inarray,sigma=[3,3]): if len(sigma)!=len(inarray.shape): sys.exit("there seems to be a mismatch between the sigma dimension and the dimension of the array you are trying to smooth") V=inarray.copy() V[np.isnan(inarray)]=0. VV=sp.ndimage.gaussian_filter(V,sigma=sigma) W=0.*inarray.copy()+1. W[np.isnan(inarray)]=0. WW=sp.ndimage.gaussian_filter(W,sigma=sigma) outarray=VV/WW outarray[np.isnan(inarray)]=np.nan return outarray def my_kde_bandwidth(obj, fac=1): # this 1.5 choice is completely subjective :( #We use Scott's Rule, multiplied by a constant factor return np.power(obj.n, -1./(obj.d+4)) * fac def convert_3D_2D(geometry): ''' Takes a GeoSeries of 3D Multi/Polygons (has_z) and returns a list of 2D Multi/Polygons ''' new_geo = [] for p in geometry: if p.has_z: if p.geom_type == 'Polygon': lines = [xy[:2] for xy in list(p.exterior.coords)] new_p = shapely.geometry.Polygon(lines) new_geo.append(new_p) elif p.geom_type == 'MultiPolygon': new_multi_p = [] for ap in p: lines = [xy[:2] for xy in list(ap.exterior.coords)] new_p = shapely.geometry.Polygon(lines) new_multi_p.append(new_p) new_geo.append(shapely.geometry.MultiPolygon(new_multi_p)) return new_geo #============================================================================== # LOOP TO DO SPATIAL SEARCHING FOR MAXIMUM RAINFALL LOCATION AT EACH TIME STEP # THIS IS THE CORE OF THE STORM CATALOG CREATION TECHNIQUE #============================================================================== #def catalogweave(temparray,trimmask,xlen,ylen,maskheight,maskwidth,rainsum): # rainsum[:]=0. # code= """ # #include <stdio.h> # int i,j,x,y; # for (x=0;x<xlen;x++) { # for (y=0;y<ylen;y++) { # for (j=0;j<maskheight;j++) { # for (i=0;i<maskwidth;i++) { # rainsum(y,x)=rainsum(y,x)+temparray(y+j,x+i)*trimmask(j,i); # } # } # } # } # """ # vars=['temparray','trimmask','xlen','ylen','maskheight','maskwidth','rainsum'] # sp.weave.inline(code,vars,type_converters=converters.blitz,compiler='gcc') # rmax=np.nanmax(rainsum) # wheremax=np.where(rainsum==rmax) # return rmax, wheremax[0][0], wheremax[1][0] # def catalogAlt(temparray,trimmask,xlen,ylen,maskheight,maskwidth,rainsum,domainmask): rainsum[:]=0. for i in range(0,(ylen)*(xlen)): y=i//xlen x=i-y*xlen #print x, rainsum[y,x]=np.nansum(np.multiply(temparray[(y):(y+maskheight),(x):(x+maskwidth)],trimmask)) #wheremax=np.argmax(rainsum) rmax=np.nanmax(rainsum) wheremax=np.where(rainsum==rmax) return rmax, wheremax[0][0], wheremax[1][0] def catalogAlt_irregular(temparray,trimmask,xlen,ylen,maskheight,maskwidth,rainsum,domainmask): rainsum[:]=0. for i in range(0,(ylen)*(xlen)): y=i//xlen x=i-y*xlen #print x,y if np.any(np.equal(domainmask[y+maskheight/2,x:x+maskwidth],1.)) and np.any(np.equal(domainmask[y:y+maskheight,x+maskwidth/2],1.)): rainsum[y,x]=np.nansum(np.multiply(temparray[(y):(y+maskheight),(x):(x+maskwidth)],trimmask)) else: rainsum[y,x]=0. #wheremax=np.argmax(rainsum) rmax=np.nanmax(rainsum) wheremax=np.where(rainsum==rmax) return rmax, wheremax[0][0], wheremax[1][0] @jit(nopython=True,fastmath=True) def catalogNumba_irregular(temparray,trimmask,xlen,ylen,maskheight,maskwidth,rainsum,domainmask): rainsum[:]=0. halfheight=int32(np.ceil(maskheight/2)) halfwidth=int32(np.ceil(maskwidth/2)) for i in range(0,ylen*xlen): y=i//xlen x=i-y*xlen #print x,y if np.any(np.equal(domainmask[y+halfheight,x:x+maskwidth],1.)) and np.any(np.equal(domainmask[y:y+maskheight,x+halfwidth],1.)): rainsum[y,x]=np.nansum(np.multiply(temparray[y:(y+maskheight),x:(x+maskwidth)],trimmask)) else: rainsum[y,x]=0. #wheremax=np.argmax(rainsum) rmax=np.nanmax(rainsum) wheremax=np.where(np.equal(rainsum,rmax)) return rmax, wheremax[0][0], wheremax[1][0] @jit(nopython=True) def catalogNumba(temparray,trimmask,xlen,ylen,maskheight,maskwidth,rainsum): rainsum[:]=0. for i in range(0,(ylen)*(xlen)): y=i//xlen x=i-y*xlen #print x,y rainsum[y,x]=np.nansum(np.multiply(temparray[(y):(y+maskheight),(x):(x+maskwidth)],trimmask)) #wheremax=np.argmax(rainsum) rmax=np.nanmax(rainsum) wheremax=np.where(np.equal(rainsum,rmax)) return rmax, wheremax[0][0], wheremax[1][0] @jit(nopython=True) def DistributionBuilder(intenserain,tempmax,xlen,ylen,checksep): for y in np.arange(0,ylen): for x in np.arange(0,xlen): if np.any(checksep[:,y,x]): #fixind=np.where(checksep[:,y,x]==True) for i in np.arange(0,checksep.shape[0]): if checksep[i,y,x]==True: fixind=i break if tempmax[y,x]>intenserain[fixind,y,x]: intenserain[fixind,y,x]=tempmax[y,x] checksep[:,y,x]=False checksep[fixind,y,x]=True else: checksep[fixind,y,x]=False elif tempmax[y,x]>np.min(intenserain[:,y,x]): fixind=np.argmin(intenserain[:,y,x]) intenserain[fixind,y,x]=tempmax[y,x] checksep[fixind,y,x]=True return intenserain,checksep # slightly faster numpy-based version of above def DistributionBuilderFast(intenserain,tempmax,xlen,ylen,checksep): minrain=np.min(intenserain,axis=0) if np.any(checksep): flatsep=np.any(checksep,axis=0) minsep=np.argmax(checksep[:,flatsep],axis=0) islarger=np.greater(tempmax[flatsep],intenserain[minsep,flatsep]) if np.any(islarger): intenserain[minsep,flatsep][islarger]=tempmax[flatsep][islarger] checksep[:]=False checksep[minsep,flatsep]=True else: checksep[minsep,flatsep]=False elif np.any(np.greater(tempmax,minrain)): #else: fixind=np.greater(tempmax,minrain) minrainind=np.argmin(intenserain,axis=0) intenserain[minrainind[fixind],fixind]=tempmax[fixind] checksep[minrainind[fixind],fixind]=True return intenserain,checksep #def SSTalt(passrain,sstx,ssty,trimmask,maskheight,maskwidth,intense_data=False): # rainsum=np.zeros((len(sstx)),dtype='float32') # nreals=len(rainsum) # # for i in range(0,nreals): # rainsum[i]=np.nansum(np.multiply(passrain[(ssty[i]) : (ssty[i]+maskheight) , (sstx[i]) : (sstx[i]+maskwidth)],trimmask)) # return rainsum @jit(fastmath=True) def SSTalt(passrain,sstx,ssty,trimmask,maskheight,maskwidth,intensemean=None,intensestd=None,intensecorr=None,homemean=None,homestd=None,durcheck=False): maxmultiplier=1.5 rainsum=np.zeros((len(sstx)),dtype='float32') whichstep=np.zeros((len(sstx)),dtype='int32') nreals=len(rainsum) nsteps=passrain.shape[0] multiout=np.empty_like(rainsum) if (intensemean is not None) and (homemean is not None): domean=True else: domean=False if (intensestd is not None) and (intensecorr is not None) and (homestd is not None): #rquant=np.random.random_integers(5,high=95,size=nreals)/100. rquant=np.random.random_sample(size=nreals) doall=True else: doall=False rquant=np.nan if durcheck==False: exprain=np.expand_dims(passrain,0) else: exprain=passrain for k in range(0,nreals): y=int(ssty[k]) x=int(sstx[k]) if np.all(np.less(exprain[:,y:y+maskheight,x:x+maskwidth],0.5)): rainsum[k]=0. multiout[k]=-999. else: if domean: #sys.exit('need to fix short duration part') muR=homemean-intensemean[y,x] if doall: stdR=np.sqrt(np.power(homestd,2)+np.power(intensestd[y,x],2)-2.*intensecorr[y,x]*homestd*intensestd[y,x]) # multiplier=sp.stats.lognorm.ppf(rquant[k],stdR,loc=0,scale=np.exp(muR)) #multiplier=10. #while multiplier>maxmultiplier: # who knows what the right number is to use here... inverrf=sp.special.erfinv(2.*rquant-1.) multiplier=np.exp(muR+np.sqrt(2.*np.power(stdR,2))*inverrf[k]) #multiplier=np.random.lognormal(muR,stdR) if multiplier>maxmultiplier: multiplier=1. else: multiplier=np.exp(muR) if multiplier>maxmultiplier: multiplier=1. else: multiplier=1. # print("still going!") if multiplier>maxmultiplier: sys.exit("Something seems to be going horribly wrong in the multiplier scheme!") else: multiout[k]=multiplier if durcheck==True: storesum=0. storestep=0 for kk in range(0,nsteps): #tempsum=numba_multimask_calc(passrain[kk,:],rsum,train,trimmask,ssty[k],maskheight,sstx[k],maskwidth)*multiplier tempsum=numba_multimask_calc(passrain[kk,:],trimmask,y,x,maskheight,maskwidth)*multiplier if tempsum>storesum: storesum=tempsum storestep=kk rainsum[k]=storesum whichstep[k]=storestep else: rainsum[k]=numba_multimask_calc(passrain,trimmask,y,x,maskheight,maskwidth)*multiplier if domean: return rainsum,multiout,whichstep else: return rainsum,whichstep #@jit(nopython=True,fastmath=True,parallel=True) @jit(nopython=True,fastmath=True) def numba_multimask_calc(passrain,trimmask,ssty,sstx,maskheight,maskwidth): train=np.multiply(passrain[ssty : ssty+maskheight , sstx : sstx+maskwidth],trimmask) rainsum=np.sum(train) return rainsum @jit(fastmath=True) def SSTalt_singlecell(passrain,sstx,ssty,trimmask,maskheight,maskwidth,intensemean=None,intensestd=None,intensecorr=None,homemean=None,homestd=None,durcheck=False): rainsum=np.zeros((len(sstx)),dtype='float32') whichstep=np.zeros((len(sstx)),dtype='int32') nreals=len(rainsum) nsteps=passrain.shape[0] multiout=np.empty_like(rainsum) # do we do deterministic or dimensionless rescaling? if (intensemean is not None) and (homemean is not None): domean=True else: domean=False # do we do stochastic rescaling? if (intensestd is not None) and (intensecorr is not None) and (homestd is not None): rquant=np.random.random_sample(size=nreals) inverrf=sp.special.erfinv(2.*rquant-1.) doall=True else: doall=False #rquant=np.nan if durcheck==False: passrain=np.expand_dims(passrain,0) # deterministic or dimensionless: if domean and doall==False: rain,multi,step=killerloop_singlecell(passrain,rainsum,whichstep,nreals,ssty,sstx,nsteps,durcheck=durcheck,intensemean=intensemean,homemean=homemean,multiout=multiout) return rain,multi,step # stochastic: elif doall: rain,multi,step=killerloop_singlecell(passrain,rainsum,whichstep,nreals,ssty,sstx,nsteps,durcheck=durcheck,intensemean=intensemean,intensestd=intensestd,intensecorr=intensecorr,homemean=homemean,homestd=homestd,multiout=multiout,inverrf=inverrf) return rain,multi,step # no rescaling: else: rain,_,step=killerloop_singlecell(passrain,rainsum,whichstep,nreals,ssty,sstx,nsteps,durcheck=durcheck,multiout=multiout) return rain,step #@jit(nopython=True,fastmath=True,parallel=True) @jit(nopython=True,fastmath=True) def killerloop_singlecell(passrain,rainsum,whichstep,nreals,ssty,sstx,nsteps,durcheck=False,intensemean=None,homemean=None,homestd=None,multiout=None,rquant=None,intensestd=None,intensecorr=None,inverrf=None): maxmultiplier=1.5 # who knows what the right number is to use here... for k in prange(nreals): y=int(ssty[k]) x=int(sstx[k]) # deterministic or dimensionless: if (intensemean is not None) and (homemean is not None) and (homestd is None): if np.less(homemean,0.001) or np.less(intensemean[y,x],0.001): multiplier=1. # or maybe this should be zero else: multiplier=np.exp(homemean-intensemean[y,x]) if multiplier>maxmultiplier: multiplier=1. # or maybe this should be zero # stochastic: elif (intensemean is not None) and (homemean is not None) and (homestd is not None): if np.less(homemean,0.001) or np.less(intensemean[y,x],0.001): multiplier=1. # or maybe this should be zero else: muR=homemean-intensemean[y,x] stdR=np.sqrt(np.power(homestd,2)+np.power(intensestd[y,x],2)-2*intensecorr[y,x]*homestd*intensestd[y,x]) multiplier=np.exp(muR+np.sqrt(2.*np.power(stdR,2))*inverrf[k]) if multiplier>maxmultiplier: multiplier=1. # or maybe this should be zero # no rescaling: else: multiplier=1. if durcheck==False: rainsum[k]=np.nansum(passrain[:,y, x]) else: storesum=0. storestep=0 for kk in range(nsteps): tempsum=passrain[kk,y,x] if tempsum>storesum: storesum=tempsum storestep=kk rainsum[k]=storesum*multiplier multiout[k]=multiplier whichstep[k]=storestep return rainsum,multiout,whichstep #@jit(nopython=True,fastmath=True,parallel=True) #def killerloop(passrain,rainsum,nreals,ssty,sstx,maskheight,maskwidth,trimmask,nsteps,durcheck): # for k in prange(nreals): # spanx=int64(sstx[k]+maskwidth) # spany=int64(ssty[k]+maskheight) # if np.all(np.less(passrain[:,ssty[k]:spany,sstx[k]:spanx],0.5)): # rainsum[k]=0. # else: # if durcheck==False: # rainsum[k]=np.nansum(np.multiply(passrain[ssty[k] : spany , sstx[k] : spanx],trimmask)) # else: # storesum=float32(0.) # for kk in range(nsteps): # tempsum=np.nansum(np.multiply(passrain[kk,ssty[k]:spany,sstx[k]:spanx],trimmask)) # if tempsum>storesum: # storesum=tempsum # rainsum[k]=storesum # return rainsum #whichstep[k]=storestep #return rainsum,whichstep # this function below never worked for some unknown Numba problem-error messages indicated that it wasn't my fault!!! Some problem in tempsum #@jit(nopython=True,fastmath=True,parallel=True) #def killerloop(passrain,rainsum,nreals,ssty,sstx,maskheight,maskwidth,masktile,nsteps,durcheck): # for k in prange(nreals): # spanx=sstx[k]+maskwidth # spany=ssty[k]+maskheight # if np.all(np.less(passrain[:,ssty[k]:spany,sstx[k]:spanx],0.5)): # rainsum[k]=0. # else: # if durcheck==False: # #tempstep=np.multiply(passrain[:,ssty[k] : spany , sstx[k] : spanx],trimmask) # #xnum=int64(sstx[k]) # #ynum=int64(ssty[k]) # #rainsum[k]=np.nansum(passrain[:,ssty[k], sstx[k]]) # rainsum[k]=np.nansum(np.multiply(passrain[:,ssty[k] : spany , sstx[k] : spanx],masktile)) # else: # storesum=float32(0.) # for kk in range(nsteps): # #tempsum=0. # #tempsum=np.multiply(passrain[kk,ssty[k]:spany,sstx[k]:spanx],masktile[0,:,:]) # tempsum=np.nansum(np.multiply(passrain[kk,ssty[k]:spany,sstx[k]:spanx],masktile[0,:,:])) # return rainsum #============================================================================== # THIS VARIANT IS SIMPLER AND UNLIKE SSTWRITE, IT ACTUALLY WORKS RELIABLY! #============================================================================== #def SSTwriteAlt(catrain,rlzx,rlzy,rlzstm,trimmask,xmin,xmax,ymin,ymax,maskheight,maskwidth): # nyrs=np.int(rlzx.shape[0]) # raindur=np.int(catrain.shape[1]) # outrain=np.zeros((nyrs,raindur,maskheight,maskwidth),dtype='float32') # unqstm,unqind,unqcnts=np.unique(rlzstm,return_inverse=True,return_counts=True) # #ctr=0 # for i in range(0,len(unqstm)): # unqwhere=np.where(unqstm[i]==rlzstm)[0] # for j in unqwhere: # #ctr=ctr+1 # #print ctr # outrain[j,:]=np.multiply(catrain[unqstm[i],:,(rlzy[j]) : (rlzy[j]+maskheight) , (rlzx[j]) : (rlzx[j]+maskwidth)],trimmask) # return outrain #============================================================================== # THIS VARIANT IS SAME AS ABOVE, BUT HAS A MORE INTERESTING RAINFALL PREPENDING PROCEDURE #============================================================================== #def SSTwriteAltPreCat(catrain,rlzx,rlzy,rlzstm,trimmask,xmin,xmax,ymin,ymax,maskheight,maskwidth,precat,ptime): # catyears=ptime.astype('datetime64[Y]').astype(int)+1970 # ptime=ptime.astype('datetime64[M]').astype(int)-(catyears-1970)*12+1 # nyrs=np.int(rlzx.shape[0]) # raindur=np.int(catrain.shape[1]+precat.shape[1]) # outrain=np.zeros((nyrs,raindur,maskheight,maskwidth),dtype='float32') # unqstm,unqind,unqcnts=np.unique(rlzstm,return_inverse=True,return_counts=True) # # for i in range(0,len(unqstm)): # unqwhere=np.where(unqstm[i]==rlzstm)[0] # unqmonth=ptime[unqstm[i]] # pretimeind=np.where(np.logical_and(ptime>unqmonth-2,ptime<unqmonth+2))[0] # for j in unqwhere: # temprain=np.concatenate((np.squeeze(precat[np.random.choice(pretimeind, 1),:,(rlzy[j]) : (rlzy[j]+maskheight) , (rlzx[j]) : (rlzx[j]+maskwidth)],axis=0),catrain[unqstm[i],:,(rlzy[j]) : (rlzy[j]+maskheight) , (rlzx[j]) : (rlzx[j]+maskwidth)]),axis=0) # outrain[j,:]=np.multiply(temprain,trimmask) # return outrain # #============================================================================== # SAME AS ABOVE, BUT HANDLES STORM ROTATION #============================================================================== #def SSTwriteAltPreCatRotation(catrain,rlzx,rlzy,rlzstm,trimmask,xmin,xmax,ymin,ymax,maskheight,maskwidth,precat,ptime,delarray,rlzanglebin,rainprop): ##def SSTwriteAltPreCatRotation(catrain,rlzx,rlzy,rlzstm,trimmask,xmin,xmax,ymin,ymax,maskheight,maskwidth,precat,ptime,delarray,rlzanglebin): # catyears=ptime.astype('datetime64[Y]').astype(int)+1970 # ptime=ptime.astype('datetime64[M]').astype(int)-(catyears-1970)*12+1 # nyrs=np.int(rlzx.shape[0]) # raindur=np.int(catrain.shape[1]+precat.shape[1]) # outrain=np.zeros((nyrs,raindur,maskheight,maskwidth),dtype='float32') # unqstm,unqind,unqcnts=np.unique(rlzstm,return_inverse=True,return_counts=True) # unqstm is the storm number # # for i in range(0,len(unqstm)): # unqwhere=np.where(unqstm[i]==rlzstm)[0] # unqmonth=ptime[unqstm[i]] # pretimeind=np.where(np.logical_and(ptime>unqmonth-2,ptime<unqmonth+2))[0] # for j in unqwhere: # inrain=catrain[unqstm[i],:].copy() # # xctr=rlzx[j]+maskwidth/2. # yctr=rlzy[j]+maskheight/2. # xlinsp=np.linspace(-xctr,rainprop.subdimensions[1]-xctr,rainprop.subdimensions[1]) # ylinsp=np.linspace(-yctr,rainprop.subdimensions[0]-yctr,rainprop.subdimensions[0]) # # ingridx,ingridy=np.meshgrid(xlinsp,ylinsp) # ingridx=ingridx.flatten() # ingridy=ingridy.flatten() # outgrid=np.column_stack((ingridx,ingridy)) # # for k in range(0,inrain.shape[0]): # interp=sp.interpolate.LinearNDInterpolator(delarray[unqstm[i]][rlzanglebin[j]-1],inrain[k,:].flatten(),fill_value=0.) # inrain[k,:]=np.reshape(interp(outgrid),rainprop.subdimensions) # #inrain[k,:]=temprain # # temprain=np.concatenate((np.squeeze(precat[np.random.choice(pretimeind, 1),:,(rlzy[j]) : (rlzy[j]+maskheight) , (rlzx[j]) : (rlzx[j]+maskwidth)],axis=0),inrain[:,(rlzy[j]) : (rlzy[j]+maskheight) , (rlzx[j]) : (rlzx[j]+maskwidth)]),axis=0) # # outrain[j,:]=np.multiply(temprain,trimmask) # return outrain @jit(fastmath=True) def SSTspin_write_v2(catrain,rlzx,rlzy,rlzstm,trimmask,maskheight,maskwidth,precat,ptime,rainprop,rlzanglebin=None,delarray=None,spin=False,flexspin=True,samptype='uniform',cumkernel=None,rotation=False,domaintype='rectangular'): catyears=ptime.astype('datetime64[Y]').astype(int)+1970 ptime=ptime.astype('datetime64[M]').astype(int)-(catyears-1970)*12+1 nyrs=np.int(rlzx.shape[0]) raindur=np.int(catrain.shape[1]+precat.shape[1]) outrain=np.zeros((nyrs,raindur,maskheight,maskwidth),dtype='float32') unqstm,unqind,unqcnts=np.unique(rlzstm,return_inverse=True,return_counts=True) # unqstm is the storm number for i in range(0,len(unqstm)): unqwhere=np.where(unqstm[i]==rlzstm)[0] unqmonth=ptime[unqstm[i]] pretimeind=np.where(np.logical_and(ptime>unqmonth-1,ptime<unqmonth+1))[0] # flexspin allows you to use spinup rainfall from anywhere in transposition domain, rather than just storm locations, but it doesn't seem to be very useful based on initial testing if spin==True and flexspin==True: if samptype=='kernel' or domaintype=='irregular': rndloc=np.random.random_sample(len(unqwhere)) shiftprex,shiftprey=numbakernel(rndloc,cumkernel) else: shiftprex=np.random.random_integers(0,np.int(rainprop.subdimensions[1])-maskwidth-1,len(unqwhere)) shiftprey=np.random.random_integers(0,np.int(rainprop.subdimensions[0])-maskheight-1,len(unqwhere)) ctr=0 for j in unqwhere: inrain=catrain[unqstm[i],:].copy() # this doesn't rotate the prepended rainfall if rotation==True: xctr=rlzx[j]+maskwidth/2. yctr=rlzy[j]+maskheight/2. xlinsp=np.linspace(-xctr,rainprop.subdimensions[1]-xctr,rainprop.subdimensions[1]) ylinsp=np.linspace(-yctr,rainprop.subdimensions[0]-yctr,rainprop.subdimensions[0]) ingridx,ingridy=np.meshgrid(xlinsp,ylinsp) ingridx=ingridx.flatten() ingridy=ingridy.flatten() outgrid=np.column_stack((ingridx,ingridy)) for k in range(0,inrain.shape[0]): interp=sp.interpolate.LinearNDInterpolator(delarray[unqstm[i]][rlzanglebin[j]-1],inrain[k,:].flatten(),fill_value=0.) inrain[k,:]=np.reshape(interp(outgrid),rainprop.subdimensions) if spin==True and flexspin==True: temprain=np.concatenate((np.squeeze(precat[np.random.choice(pretimeind, 1),:,(shiftprey[ctr]) : (shiftprey[ctr]+maskheight) , (shiftprex[ctr]) : (shiftprex[ctr]+maskwidth)],axis=0),inrain[:,(rlzy[j]) : (rlzy[j]+maskheight) , (rlzx[j]) : (rlzx[j]+maskwidth)]),axis=0) elif spin==True and flexspin==False: temprain=np.concatenate((np.squeeze(precat[np.random.choice(pretimeind, 1),:,(rlzy[j]) : (rlzy[j]+maskheight) , (rlzx[j]) : (rlzx[j]+maskwidth)],axis=0),inrain[:,(rlzy[j]) : (rlzy[j]+maskheight) , (rlzx[j]) : (rlzx[j]+maskwidth)]),axis=0) elif spin==False: temprain=inrain[:,(rlzy[j]) : (rlzy[j]+maskheight) , (rlzx[j]) : (rlzx[j]+maskwidth)] else: sys.exit("what else is there?") ctr=ctr+1 outrain[j,:]=np.multiply(temprain,trimmask) return outrain ##============================================================================== ## SAME AS ABOVE, BUT A BIT MORE DYNAMIC IN TERMS OF SPINUP ##============================================================================== #def SSTspin_write_v2(catrain,rlzx,rlzy,rlzstm,trimmask,xmin,xmax,ymin,ymax,maskheight,maskwidth,precat,ptime,rainprop,rlzanglebin=None,delarray=None,spin=False,flexspin=True,samptype='uniform',cumkernel=None,rotation=False,domaintype='rectangular',intense_data=False): # catyears=ptime.astype('datetime64[Y]').astype(int)+1970 # ptime=ptime.astype('datetime64[M]').astype(int)-(catyears-1970)*12+1 # nyrs=np.int(rlzx.shape[0]) # raindur=np.int(catrain.shape[1]+precat.shape[1]) # outrain=np.zeros((nyrs,raindur,maskheight,maskwidth),dtype='float32') # unqstm,unqind,unqcnts=np.unique(rlzstm,return_inverse=True,return_counts=True) # unqstm is the storm number # # if intense_data!=False: # sys.exit("Scenario writing for intensity-based resampling not tested!") # intquant=intense_data[0] # fullmu=intense_data[1] # fullstd=intense_data[2] # muorig=intense_data[3] # stdorig=intense_data[4] # # for i in range(0,len(unqstm)): # unqwhere=np.where(unqstm[i]==rlzstm)[0] # unqmonth=ptime[unqstm[i]] # pretimeind=np.where(np.logical_and(ptime>unqmonth-1,ptime<unqmonth+1))[0] # # if transpotype=='intensity': # origmu=np.multiply(murain[caty[i]:caty[i]+maskheight,catx[i]:catx[i]+maskwidth],trimmask) # origstd=np.multiply(stdrain[caty[i]:caty[i]+maskheight,catx[i]:catx[i]+maskwidth],trimmask) # #intense_dat=[intquant[],murain,stdrain,origmu,origstd] # # # flexspin allows you to use spinup rainfall from anywhere in transposition domain, rather than just storm locations, but it doesn't seem to be very useful based on initial testing # if spin==True and flexspin==True: # if samptype=='kernel' or domaintype=='irregular': # rndloc=np.random.random_sample(len(unqwhere)) # shiftprex,shiftprey=numbakernel(rndloc,cumkernel) # else: # shiftprex=np.random.random_integers(0,np.int(rainprop.subdimensions[1])-maskwidth-1,len(unqwhere)) # shiftprey=np.random.random_integers(0,np.int(rainprop.subdimensions[0])-maskheight-1,len(unqwhere)) # # ctr=0 # for j in unqwhere: # inrain=catrain[unqstm[i],:].copy() # # if intense_data!=False: # transmu=np.multiply(fullmu[(rlzy[i]) : (rlzy[i]+maskheight) , (rlzx[i]) : (rlzx[i]+maskwidth)],trimmask) # transtd=np.multiply(fullstd[(rlzy[i]) : (rlzy[i]+maskheight) , (rlzx[i]) : (rlzx[i]+maskwidth)],trimmask) # mu_multi=transmu/muorig # std_multi=np.abs(transtd-stdorig)/stdorig # multipliermask=norm.ppf(intquant[i],loc=mu_multi,scale=std_multi) # multipliermask[multipliermask<0.]=0. # multipliermask[np.isnan(multipliermask)]=0. # # # this doesn't rotate the prepended rainfall # if rotation==True: # xctr=rlzx[j]+maskwidth/2. # yctr=rlzy[j]+maskheight/2. # xlinsp=np.linspace(-xctr,rainprop.subdimensions[1]-xctr,rainprop.subdimensions[1]) # ylinsp=np.linspace(-yctr,rainprop.subdimensions[0]-yctr,rainprop.subdimensions[0]) # # ingridx,ingridy=np.meshgrid(xlinsp,ylinsp) # ingridx=ingridx.flatten() # ingridy=ingridy.flatten() # outgrid=np.column_stack((ingridx,ingridy)) # # for k in range(0,inrain.shape[0]): # interp=sp.interpolate.LinearNDInterpolator(delarray[unqstm[i]][rlzanglebin[j]-1],inrain[k,:].flatten(),fill_value=0.) # inrain[k,:]=np.reshape(interp(outgrid),rainprop.subdimensions) # # if spin==True and flexspin==True: # temprain=np.concatenate((np.squeeze(precat[np.random.choice(pretimeind, 1),:,(shiftprey[ctr]) : (shiftprey[ctr]+maskheight) , (shiftprex[ctr]) : (shiftprex[ctr]+maskwidth)],axis=0),inrain[:,(rlzy[j]) : (rlzy[j]+maskheight) , (rlzx[j]) : (rlzx[j]+maskwidth)]),axis=0) # elif spin==True and flexspin==False: # temprain=np.concatenate((np.squeeze(precat[np.random.choice(pretimeind, 1),:,(rlzy[j]) : (rlzy[j]+maskheight) , (rlzx[j]) : (rlzx[j]+maskwidth)],axis=0),inrain[:,(rlzy[j]) : (rlzy[j]+maskheight) , (rlzx[j]) : (rlzx[j]+maskwidth)]),axis=0) # elif spin==False: # temprain=inrain[:,(rlzy[j]) : (rlzy[j]+maskheight) , (rlzx[j]) : (rlzx[j]+maskwidth)] # else: # sys.exit("what else is there?") # ctr=ctr+1 # if intense_data!=False: # outrain[j,:]=np.multiply(temprain,multipliermask) # else: # outrain[j,:]=np.multiply(temprain,trimmask) # return outrain #============================================================================== # LOOP FOR KERNEL BASED STORM TRANSPOSITION # THIS FINDS THE TRANSPOSITION LOCATION FOR EACH REALIZATION IF YOU ARE USING THE KERNEL-BASED RESAMPLER # IF I CONFIGURE THE SCRIPT SO THE USER CAN PROVIDE A CUSTOM RESAMPLING SCHEME, THIS WOULD PROBABLY WORK FOR THAT AS WELL #============================================================================== #def weavekernel(rndloc,cumkernel): # nlocs=len(rndloc) # nrows=cumkernel.shape[0] # ncols=cumkernel.shape[1] # tempx=np.empty((len(rndloc)),dtype="int32") # tempy=np.empty((len(rndloc)),dtype="int32") # code= """ # #include <stdio.h> # int i,x,y,brklp; # double prevprob; # for (i=0;i<nlocs;i++) { # prevprob=0.0; # brklp=0; # for (y=0; y<nrows; y++) { # for (x=0; x<ncols; x++) { # if ( (rndloc(i)<=cumkernel(y,x)) && (rndloc(i)>prevprob) ) { # tempx(i)=x; # tempy(i)=y; # prevprob=cumkernel(y,x); # brklp=1; # break; # } # } # if (brklp==1) { # break; # } # } # } # """ # vars=['rndloc','cumkernel','nlocs','nrows','ncols','tempx','tempy'] # sp.weave.inline(code,vars,type_converters=converters.blitz,compiler='gcc') # return tempx,tempy def pykernel(rndloc,cumkernel): nlocs=len(rndloc) ncols=cumkernel.shape[1] tempx=np.empty((len(rndloc)),dtype="int32") tempy=np.empty((len(rndloc)),dtype="int32") flatkern=np.append(0.,cumkernel.flatten()) for i in range(0,nlocs): x=rndloc[i]-flatkern x[np.less(x,0.)]=1000. whereind = np.argmin(x) y=whereind//ncols x=whereind-y*ncols tempx[i]=x tempy[i]=y return tempx,tempy @jit def numbakernel(rndloc,cumkernel,tempx,tempy,ncols): nlocs=len(rndloc) #ncols=xdim flatkern=np.append(0.,cumkernel.flatten()) #x=np.zeros_like(rndloc,dtype='float64') for i in np.arange(0,nlocs): x=rndloc[i]-flatkern x[np.less(x,0.)]=10. whereind=np.argmin(x) y=whereind//ncols x=whereind-y*ncols tempx[i]=x tempy[i]=y return tempx,tempy @jit def numbakernel_fast(rndloc,cumkernel,tempx,tempy,ncols): nlocs=int32(len(rndloc)) ncols=int32(cumkernel.shape[1]) flatkern=np.append(0.,cumkernel.flatten()) return kernelloop(nlocs,rndloc,flatkern,ncols,tempx,tempy) #@jit(nopython=True,fastmath=True,parallel=True) @jit(nopython=True,fastmath=True) def kernelloop(nlocs,rndloc,flatkern,ncols,tempx,tempy): for i in prange(nlocs): diff=rndloc[i]-flatkern diff[np.less(diff,0.)]=10. whereind=np.argmin(diff) y=whereind//ncols x=whereind-y*ncols tempx[i]=x tempy[i]=y return tempx,tempy #============================================================================== # FIND THE BOUNDARY INDICIES AND COORDINATES FOR THE USER-DEFINED SUBAREA # NOTE THAT subind ARE THE MATRIX INDICIES OF THE SUBBOX, STARTING FROM UPPER LEFT CORNER OF DOMAIN AS (0,0) # NOTE THAT subcoord ARE THE COORDINATES OF THE OUTSIDE BORDER OF THE SUBBOX # THEREFORE THE DISTANCE FROM THE WESTERN (SOUTHERN) BOUNDARY TO THE EASTERN (NORTHERN) BOUNDARY IS NCOLS (NROWS) +1 TIMES THE EAST-WEST (NORTH-SOUTH) RESOLUTION #============================================================================== def findsubbox(inarea,rainprop): outind=np.empty([4],dtype='int') outextent=np.empty([4]) outdim=np.empty([2]) inbox=deepcopy(inarea) rangex=np.arange(rainprop.bndbox[0],rainprop.bndbox[1]-rainprop.spatialres[0]/1000,rainprop.spatialres[0]) rangey=np.arange(rainprop.bndbox[3],rainprop.bndbox[2]+rainprop.spatialres[1]/1000,-rainprop.spatialres[1]) if rangex.shape[0]<rainprop.dimensions[1]: rangex=np.append(rangex,rangex[-1]) if rangey.shape[0]<rainprop.dimensions[0]: rangey=np.append(rangey,rangey[-1]) if rangex.shape[0]>rainprop.dimensions[1]: rangex=rangex[0:-1] if rangey.shape[0]>rainprop.dimensions[0]: rangey=rangey[0:-1] outextent=inbox # "SNAP" output extent to grid outind[0]=np.abs(rangex-outextent[0]).argmin() outind[1]=np.abs(rangex-outextent[1]).argmin()-1 outind[2]=np.abs(rangey-outextent[2]).argmin()-1 outind[3]=np.abs(rangey-outextent[3]).argmin() outextent[0]=rangex[outind[0]] outextent[1]=rangex[outind[1]+1] outextent[2]=rangey[outind[2]+1] outextent[3]=rangey[outind[3]] outdim[1]=np.shape(np.arange(outind[0],outind[1]+1))[0] outdim[0]=np.shape(np.arange(outind[3],outind[2]+1))[0] outdim=np.array(outdim,dtype='int32') return outextent,outind,outdim #============================================================================== # THIS RETURNS A LOGICAL GRID THAT CAN THEN BE APPLIED TO THE GLOBAL GRID TO EXTRACT # A USEER-DEFINED SUBGRID # THIS HELPS TO KEEP ARRAY SIZES SMALL #============================================================================== def creategrids(rainprop): globrangex=np.arange(0,rainprop.dimensions[1],1) globrangey=np.arange(0,rainprop.dimensions[0],1) subrangex=np.arange(rainprop.subind[0],rainprop.subind[1]+1,1) subrangey=np.arange(rainprop.subind[3],rainprop.subind[2]+1,1) subindx=np.logical_and(globrangex>=subrangex[0],globrangex<=subrangex[-1]) subindy=np.logical_and(globrangey>=subrangey[0],globrangey<=subrangey[-1]) gx,gy=np.meshgrid(subindx,subindy) outgrid=np.logical_and(gx==True,gy==True) return outgrid,subindx,subindy #============================================================================== # FUNCTION TO CREATE A MASK ACCORDING TO A USER-DEFINED POLYGON SHAPEFILE AND PROJECTION # THIS USES GDAL COMMANDS FROM THE OS TO RASTERIZE #============================================================================== def rastermaskGDAL(shpname,shpproj,rainprop,masktype,fullpath,gdalpath=False): bndbox=np.array(rainprop.subind) bndcoords=np.array(rainprop.subextent) if rainprop.projection==GEOG: xdim=np.shape(np.linspace(bndcoords[0],bndcoords[1],rainprop.subind[1]-rainprop.subind[0]+1))[0] ydim=np.shape(np.linspace(bndcoords[2],bndcoords[3],rainprop.subind[2]-rainprop.subind[3]+1))[0] else: sys.exit("unrecognized projection!") rastertemplate=np.zeros((ydim,xdim),dtype='float32') if masktype=='simple': print('creating simple mask (0s and 1s)') #os.system('gdal_rasterize -at -burn 1.0 -te '+str(rainprop.subextent[0])+' '+str(rainprop.subextent[2])+' '+str(rainprop.subextent[1])+' '+str(rainprop.subextent[3])+' -tr '+str(rainprop.spatialres[0])+' '+str(rainprop.spatialres[1])+' -ts '+str(np.int(rainprop.subdimensions[1]))+' '+str(np.int(rainprop.subdimensions[0]))+' -ot Float32 '+shpname+' '+fullpath+'/temp.tiff'); if gdalpath!=False: rasterizecmd=gdalpath+'/gdal_rasterize -at -burn 1.0 -te '+"%.9f"%(rainprop.subextent[0])+' '+"%.9f"%(rainprop.subextent[2])+' '+"%.9f"%(rainprop.subextent[1])+' '+"%.9f"%(rainprop.subextent[3])+' -tr '+"%.9f"%(rainprop.spatialres[0])+' '+"%.9f"%(rainprop.spatialres[1])+' -ts '+"%.9f"%(np.int(rainprop.subdimensions[1]))+' '+"%.9f"%(np.int(rainprop.subdimensions[0]))+' -ot Float32 '+shpname+' '+fullpath+'/temp.tiff' else: rasterizecmd='gdal_rasterize -at -burn 1.0 -te '+"%.9f"%(rainprop.subextent[0])+' '+"%.9f"%(rainprop.subextent[2])+' '+"%.9f"%(rainprop.subextent[1])+' '+"%.9f"%(rainprop.subextent[3])+' -tr '+"%.9f"%(rainprop.spatialres[0])+' '+"%.9f"%(rainprop.spatialres[1])+' -ts '+"%.9f"%(np.int(rainprop.subdimensions[1]))+' '+"%.9f"%(np.int(rainprop.subdimensions[0]))+' -ot Float32 '+shpname+' '+fullpath+'/temp.tiff' os.system(rasterizecmd) ds=rasterio.open(fullpath+'/temp.tiff') rastertemplate=ds.read(1) os.system('rm '+fullpath+'/temp.tiff') elif masktype=="fraction": print('creating fractional mask (range from 0.0-1.0)') #os.system('gdal_rasterize -at -burn 1.0 -te '+str(rainprop.subextent[0])+' '+str(rainprop.subextent[2])+' '+str(rainprop.subextent[1])+' '+str(rainprop.subextent[3])+' -tr '+str(rainprop.spatialres[0]/10.)+' '+str(rainprop.spatialres[1]/10.)+' -ts '+str(np.int(rainprop.subdimensions[1])*10)+' '+str(np.int(rainprop.subdimensions[0])*10)+' -ot Float32 '+shpname+' '+fullpath+'/temp.tiff'); #os.system('gdalwarp -r average -te '+str(rainprop.subextent[0])+' '+str(rainprop.subextent[2])+' '+str(rainprop.subextent[1])+' '+str(rainprop.subextent[3])+' -ts '+str(np.int(rainprop.subdimensions[1]))+' '+str(np.int(rainprop.subdimensions[0]))+' -overwrite '+fullpath+'/temp.tiff '+fullpath+'/tempAGG.tiff'); if gdalpath!=False: rasterizecmd=gdalpath+'/gdal_rasterize -at -burn 1.0 -te '+"%.9f"%(rainprop.subextent[0])+' '+"%.9f"%(rainprop.subextent[2])+' '+"%.9f"%(rainprop.subextent[1])+' '+"%.9f"%(rainprop.subextent[3])+' -tr '+"%.9f"%(rainprop.spatialres[0]/10.)+' '+"%.9f"%(rainprop.spatialres[1]/10.)+' -ts '+"%.9f"%(np.int(rainprop.subdimensions[1])*10)+' '+"%.9f"%(np.int(rainprop.subdimensions[0])*10)+' -ot Float32 '+shpname+' '+fullpath+'/temp.tiff' else: rasterizecmd='gdal_rasterize -at -burn 1.0 -te '+"%.9f"%(rainprop.subextent[0])+' '+"%.9f"%(rainprop.subextent[2])+' '+"%.9f"%(rainprop.subextent[1])+' '+"%.9f"%(rainprop.subextent[3])+' -tr '+"%.9f"%(rainprop.spatialres[0]/10.)+' '+"%.9f"%(rainprop.spatialres[1]/10.)+' -ts '+"%.9f"%(np.int(rainprop.subdimensions[1])*10)+' '+"%.9f"%(np.int(rainprop.subdimensions[0])*10)+' -ot Float32 '+shpname+' '+fullpath+'/temp.tiff' os.system(rasterizecmd) if gdalpath!=False: warpcmd=gdalpath+'/gdalwarp -r average -te '+"%.9f"%(rainprop.subextent[0])+' '+"%.9f"%(rainprop.subextent[2])+' '+"%.9f"%(rainprop.subextent[1])+' '+"%.9f"%(rainprop.subextent[3])+' -ts '+"%.9f"%(np.int(rainprop.subdimensions[1]))+' '+"%.9f"%(np.int(rainprop.subdimensions[0]))+' -overwrite '+fullpath+'/temp.tiff '+fullpath+'/tempAGG.tiff' else: warpcmd='gdalwarp -r average -te '+"%.9f"%(rainprop.subextent[0])+' '+"%.9f"%(rainprop.subextent[2])+' '+"%.9f"%(rainprop.subextent[1])+' '+"%.9f"%(rainprop.subextent[3])+' -ts '+"%.9f"%(np.int(rainprop.subdimensions[1]))+' '+"%.9f"%(np.int(rainprop.subdimensions[0]))+' -overwrite '+fullpath+'/temp.tiff '+fullpath+'/tempAGG.tiff' os.system(warpcmd) ds=rasterio.open(fullpath+'/tempAGG.tiff') rastertemplate=ds.read(1) os.system('rm '+fullpath+'/temp.tiff') os.system('rm '+fullpath+'/tempAGG.tiff') else: sys.exit("You entered an incorrect mask type, options are 'simple' or 'fraction'") rastertemplate=np.array(rastertemplate[:]) return rastertemplate #============================================================================== # WRITE SCENARIOS TO NETCDF ONE REALIZATION AT A TIME #============================================================================== def writerealization(rlz,nrealizations,writename,outrain,writemax,writestorm,writeperiod,writex,writey,writetimes,latrange,lonrange,whichorigstorm): # SAVE outrain AS NETCDF FILE dataset=Dataset(writename, 'w', format='NETCDF4') # create dimensions outlats=dataset.createDimension('outlat',len(latrange)) outlons=dataset.createDimension('outlon',len(lonrange)) time=dataset.createDimension('time',writetimes.shape[1]) nyears=dataset.createDimension('nyears',len(writeperiod)) # create variables times=dataset.createVariable('time',np.float64, ('nyears','time')) latitudes=dataset.createVariable('latitude',np.float32, ('outlat')) longitudes=dataset.createVariable('longitude',np.float32, ('outlon')) rainrate=dataset.createVariable('rainrate',np.float32,('nyears','time','outlat','outlon'),zlib=True,complevel=4,least_significant_digit=2) basinrainfall=dataset.createVariable('basinrainfall',np.float32,('nyears')) xlocation=dataset.createVariable('xlocation',np.int32,('nyears')) ylocation=dataset.createVariable('ylocation',np.int32,('nyears')) returnperiod=dataset.createVariable('returnperiod',np.float32,('nyears')) stormnumber=dataset.createVariable('stormnumber',np.int32,('nyears')) original_stormnumber=dataset.createVariable('original_stormnumber',np.int32,('nyears')) #stormtimes=dataset.createVariable('stormtimes',np.float64,('nyears')) # Global Attributes dataset.description = 'SST Rainfall Scenarios Realization: '+str(rlz+1)+' of '+str(nrealizations) dataset.history = 'Created ' + str(datetime.now()) dataset.source = 'Storm Catalog for (FILL IN THE BLANK)' # Variable Attributes (time since 1970-01-01 00:00:00.0 in numpys) latitudes.units = 'degrees north' longitudes.units = 'degrees east' rainrate.units = 'mm/h' times.units = 'minutes since 1970-01-01 00:00.0' times.calendar = 'gregorian' #print dataset.description #print dataset.history # fill the netcdf file latitudes[:]=latrange longitudes[:]=lonrange rainrate[:]=outrain basinrainfall[:]=writemax times[:]=writetimes xlocation[:]=writex ylocation[:]=writey stormnumber[:]=writestorm returnperiod[:]=writeperiod original_stormnumber[:]=whichorigstorm #stormtimes[:]=writetimes dataset.close() #============================================================================== # WRITE The maximized storm #============================================================================== def writemaximized(writename,outrain,writemax,write_ts,writex,writey,writetimes,latrange,lonrange): # SAVE outrain AS NETCDF FILE dataset=Dataset(writename, 'w', format='NETCDF4') # create dimensions outlats=dataset.createDimension('outlat',len(latrange)) outlons=dataset.createDimension('outlon',len(lonrange)) time=dataset.createDimension('time',len(writetimes)) # create variables times=dataset.createVariable('time',np.float64, ('time')) latitudes=dataset.createVariable('latitude',np.float32, ('outlat')) longitudes=dataset.createVariable('longitude',np.float32, ('outlon')) rainrate=dataset.createVariable('rainrate',np.float32,('time','outlat','outlon'),zlib=True,complevel=4,least_significant_digit=2) basinrainfall=dataset.createVariable('basinrainfall',np.float32) xlocation=dataset.createVariable('xlocation',np.int32) ylocation=dataset.createVariable('ylocation',np.int32) #stormtimes=dataset.createVariable('stormtimes',np.float64,('nyears')) # Global Attributes dataset.description = 'SST Rainfall Maximum Storm' dataset.history = 'Created ' + str(datetime.now()) dataset.source = 'Storm Catalog for (FILL IN THE BLANK)' # Variable Attributes (time since 1970-01-01 00:00:00.0 in numpys) latitudes.units = 'degrees north' longitudes.units = 'degrees east' rainrate.units = 'mm/h' times.units = 'minutes since 1970-01-01 00:00.0' times.calendar = 'gregorian' #print dataset.description #print dataset.history # fill the netcdf file latitudes[:]=latrange longitudes[:]=lonrange rainrate[:]=outrain basinrainfall[:]=writemax times[:]=writetimes xlocation[:]=writex ylocation[:]=writey dataset.close() #============================================================================== # READ RAINFALL FILE FROM NETCDF #============================================================================== def readnetcdf(rfile,inbounds=False): infile=Dataset(rfile,'r') if np.any(inbounds!=False): outrain=np.array(infile.variables['rainrate'][:,inbounds[3]:inbounds[2]+1,inbounds[0]:inbounds[1]+1]) outlatitude=np.array(infile.variables['latitude'][inbounds[3]:inbounds[2]+1]) outlongitude=np.array(infile.variables['longitude'][inbounds[0]:inbounds[1]+1]) else: outrain=np.array(infile.variables['rainrate'][:]) outlatitude=np.array(infile.variables['latitude'][:]) outlongitude=np.array(infile.variables['longitude'][:]) outtime=np.array(infile.variables['time'][:],dtype='datetime64[m]') infile.close() return outrain,outtime,outlatitude,outlongitude #============================================================================== # READ RAINFALL FILE FROM NETCDF #============================================================================== def readcatalog(rfile): infile=Dataset(rfile,'r') outrain=np.array(infile.variables['rainrate'][:]) outtime=np.array(infile.variables['time'][:],dtype='datetime64[m]') outlatitude=np.array(infile.variables['latitude'][:]) outlongitude=np.array(infile.variables['longitude'][:]) outlocx=np.array(infile.variables['xlocation'][:]) outlocy=np.array(infile.variables['ylocation'][:]) outmax=np.array(infile.variables['basinrainfall'][:]) outmask=np.array(infile.variables['gridmask'][:]) domainmask=np.array(infile.variables['domainmask'][:]) try: timeresolution=np.int(infile.variables['timeresolution']) resexists=True except: resexists=False infile.close() if resexists: return outrain,outtime,outlatitude,outlongitude,outlocx,outlocy,outmax,outmask,domainmask,timeresolution return outrain,outtime,outlatitude,outlongitude,outlocx,outlocy,outmax,outmask,domainmask def readtimeresolution(rfile): infile=Dataset(rfile,'r') try: timeresolution=np.int(infile.variables['timeresolution']) except: sys.exit("The time resolution of your storm catalog is ambiguous. This only appears in very specific circumstances. You can contact Dr. <NAME> if you need help!") return timeresolution #============================================================================== # READ RAINFALL FILE FROM NETCDF: LEGACY VERSION! ONLY NEEDED IF READING AN OLDER DATASET #============================================================================== def readcatalog_LEGACY(rfile): infile=Dataset(rfile,'r') outrain=np.array(infile.variables['rainrate'][:]) outtime=np.array(infile.variables['time'][:],dtype='datetime64[m]') outlatitude=np.array(infile.variables['latitude'][:]) outlongitude=np.array(infile.variables['longitude'][:]) outlocx=np.array(infile.variables['xlocation'][:]) outlocy=np.array(infile.variables['ylocation'][:]) outmax=np.array(infile.variables['basinrainfall'][:]) outmask=np.array(infile.variables['gridmask'][:]) #domainmask=np.array(infile.variables['domainmask'][:]) infile.close() return outrain,outtime,outlatitude,outlongitude,outlocx,outlocy,outmax,outmask #============================================================================== # WRITE RAINFALL FILE TO NETCDF #============================================================================== def writecatalog(catrain,catmax,catx,caty,cattime,latrange,lonrange,catalogname,nstorms,gridmask,parameterfile,dmask,timeresolution=False): # SAVE outrain AS NETCDF FILE dataset=Dataset(catalogname, 'w', format='NETCDF4') # create dimensions outlats=dataset.createDimension('outlat',len(latrange)) outlons=dataset.createDimension('outlon',len(lonrange)) time=dataset.createDimension('time',cattime.shape[1]) nstorms=dataset.createDimension('nstorms',nstorms) # create variables times=dataset.createVariable('time',np.float64, ('nstorms','time',)) latitudes=dataset.createVariable('latitude',np.float32, ('outlat',)) longitudes=dataset.createVariable('longitude',np.float32, ('outlon',)) rainrate=dataset.createVariable('rainrate',np.float32,('nstorms','time','outlat','outlon',),zlib=True,complevel=4,least_significant_digit=2) basinrainfall=dataset.createVariable('basinrainfall',np.float32,('nstorms')) xlocation=dataset.createVariable('xlocation',np.int32,('nstorms')) ylocation=dataset.createVariable('ylocation',np.int32,('nstorms')) gmask=dataset.createVariable('gridmask',np.float32,('outlat','outlon',)) domainmask=dataset.createVariable('domainmask',np.float32,('outlat','outlon',)) # Global Attributes with open(parameterfile, "r") as myfile: params=myfile.read() myfile.close dataset.description=params if timeresolution!=False: dataset.timeresolution=timeresolution dataset.history = 'Created ' + str(datetime.now()) dataset.source = 'RainyDay Storm Catalog' # Variable Attributes (time since 1970-01-01 00:00:00.0 in numpys) latitudes.units = 'degrees north' longitudes.units = 'degrees east' rainrate.units = 'mm/h' times.units = 'minutes since 1970-01-01 00:00.0' times.calendar = 'gregorian' gmask.units="N/A" # fill the netcdf file latitudes[:]=latrange longitudes[:]=lonrange rainrate[:]=catrain basinrainfall[:]=catmax times[:]=cattime xlocation[:]=catx ylocation[:]=caty gmask[:]=gridmask domainmask[:]=dmask dataset.close() def writeintensityfile(intenserain,filename,latrange,lonrange,intensetime): # SAVE outrain AS NETCDF FILE dataset=Dataset(filename, 'w', format='NETCDF4') # create dimensions outlats=dataset.createDimension('outlat',intenserain.shape[1]) outlons=dataset.createDimension('outlon',intenserain.shape[2]) nstorms=dataset.createDimension('nstorms',intenserain.shape[0]) # create variables latitudes=dataset.createVariable('latitude',np.float32, ('outlat',)) longitudes=dataset.createVariable('longitude',np.float32, ('outlon',)) stormtotals=dataset.createVariable('stormtotals',np.float32,('nstorms','outlat','outlon',)) times=dataset.createVariable('time',np.float64, ('nstorms','outlat','outlon',)) dataset.history = 'Created ' + str(datetime.now()) dataset.source = 'RainyDay Storm Intensity File' # Variable Attributes (time since 1970-01-01 00:00:00.0 in numpys) latitudes.units = 'degrees north' longitudes.units = 'degrees east' stormtotals.units = 'mm' times.units = 'minutes since 1970-01-01 00:00.0' # fill the netcdf file latitudes[:]=latrange longitudes[:]=lonrange stormtotals[:]=intenserain times[:]=intensetime dataset.close() def readintensityfile(rfile,inbounds=False): infile=Dataset(rfile,'r') if np.any(inbounds!=False): outrain=np.array(infile.variables['stormtotals'][:,inbounds[3]:inbounds[2]+1,inbounds[0]:inbounds[1]+1]) outtime=np.array(infile.variables['time'][:,inbounds[3]:inbounds[2]+1,inbounds[0]:inbounds[1]+1],dtype='datetime64[m]') outlat=np.array(infile.variables['latitude'][inbounds[3]:inbounds[2]+1]) outlon=np.array(infile.variables['longitude'][inbounds[0]:inbounds[1]+1]) else: outrain=np.array(infile.variables['stormtotals'][:]) outtime=np.array(infile.variables['time'][:],dtype='datetime64[m]') outlat=np.array(infile.variables['latitude'][:]) outlon=np.array(infile.variables['longitude'][:]) infile.close() return outrain,outtime,outlat,outlon def readmeanfile(rfile,inbounds=False): infile=Dataset(rfile,'r') if np.any(inbounds!=False): outrain=np.array(infile.variables['stormtotals'][inbounds[3]:inbounds[2]+1,inbounds[0]:inbounds[1]+1]) outlat=
np.array(infile.variables['latitude'][inbounds[3]:inbounds[2]+1])
numpy.array
""" Bayesian network implementation API inspired by SciKit-learn. """ import numpy as np from sklearn.base import BaseEstimator, ClassifierMixin from sklearn.utils.validation import check_X_y, check_array, check_is_fitted ### Checks if the estimator is fitted by verifying the presence of fitted attributes (ending with a trailing underscore) #from sklearn.utils.multiclass import unique_labels, not necessary, can be replaced by array(list(set())) from __future__ import division ###for float operation from collections import Counter import numpy as np from sklearn.metrics import accuracy_score from sklearn.metrics import recall_score ##tp / (tp + fn) from sklearn.metrics import precision_score #tp / (tp + fp) from sklearn.preprocessing import MultiLabelBinarizer from sklearn.model_selection import KFold, StratifiedKFold from pyitlib import discrete_random_variable as drv import time import timeit class Bayes_net(BaseEstimator, ClassifierMixin): def fit(self,X,y): raise NotImplementedError def predict_proba(self, X): ### key prediction methods, all other prediction methods will use it first. raise NotImplementedError def predict_binary(self,X): """ Perform classification on an array of test vectors X, predict P(C1|X), works only for binary classifcation Parameters ---------- X : array-like of shape (n_samples, n_features) Returns ------- C : ndarray of shape (n_samples,) Predicted P(C1|X) """ Prob_C = self.predict_proba(X) ### Prob_C is n*|C| np.array return(Prob_C[:,0]) def predict(self, X): """ Perform classification on an array of test vectors X. Parameters ---------- X : array-like of shape (n_samples, n_features) Returns ------- C : ndarray of shape (n_samples,) Predicted target values for X """ Prob_C = self.predict_proba(X) ## Prob_C is |C|*n np.array ,C is self.C return( np.array([self.classes_[ele] for ele in np.argmax(Prob_C, axis=1)] ) ) def Conditional_log_likelihood_general(self,y_true,y_pred_prob,C): """Calculate the conditional log likelihood. :param y_true: The true class labels. e.g ['1','1',.....'0','0'] :param y_pred_prob: np.array shows prob of each class for each instance. ith column is the predicted prob for class C[i] :param C: Class labels e.x ['1','0'], C has to use same labels as y_true. :return: CLL. A scalar. """ cll = [] for i in range(len(y_true)): cll.append( y_pred_prob[i,C.index(y_true[i])] ) ## \hat p(c_true|c_true) cll = [np.log2(ele) for ele in cll] cll =
np.array(cll)
numpy.array
# -*- coding: utf-8 -*- """ docstring goes here. :copyright: Copyright 2014 by the Elephant team, see AUTHORS.txt. :license: Modified BSD, see LICENSE.txt for details. """ from __future__ import division, print_function import unittest from itertools import chain from neo.test.generate_datasets import fake_neo import numpy as np from numpy.testing.utils import assert_array_equal import quantities as pq try: import pandas as pd from pandas.util.testing import assert_frame_equal, assert_index_equal except ImportError: HAVE_PANDAS = False else: import elephant.pandas_bridge as ep HAVE_PANDAS = True @unittest.skipUnless(HAVE_PANDAS, 'requires pandas') class MultiindexFromDictTestCase(unittest.TestCase): def test__multiindex_from_dict(self): inds = {'test1': 6.5, 'test2': 5, 'test3': 'test'} targ = pd.MultiIndex(levels=[[6.5], [5], ['test']], labels=[[0], [0], [0]], names=['test1', 'test2', 'test3']) res0 = ep._multiindex_from_dict(inds) self.assertEqual(targ.levels, res0.levels) self.assertEqual(targ.names, res0.names) self.assertEqual(targ.labels, res0.labels) def _convert_levels(levels): """Convert a list of levels to the format pandas returns for a MultiIndex. Parameters ---------- levels : list The list of levels to convert. Returns ------- list The the level in `list` converted to values like what pandas will give. """ levels = list(levels) for i, level in enumerate(levels): if hasattr(level, 'lower'): try: level = unicode(level) except NameError: pass elif hasattr(level, 'date'): levels[i] = pd.DatetimeIndex(data=[level]) continue elif level is None: levels[i] = pd.Index([]) continue levels[i] = pd.Index([level]) return levels @unittest.skipUnless(HAVE_PANDAS, 'requires pandas') class ConvertValueSafeTestCase(unittest.TestCase): def test__convert_value_safe__float(self): targ = 5.5 value = targ res = ep._convert_value_safe(value) self.assertIs(res, targ) def test__convert_value_safe__str(self): targ = 'test' value = targ res = ep._convert_value_safe(value) self.assertIs(res, targ) def test__convert_value_safe__bytes(self): targ = 'test' value = b'test' res = ep._convert_value_safe(value) self.assertEqual(res, targ) def test__convert_value_safe__numpy_int_scalar(self): targ = 5 value = np.array(5) res = ep._convert_value_safe(value) self.assertEqual(res, targ) self.assertFalse(hasattr(res, 'dtype')) def test__convert_value_safe__numpy_float_scalar(self): targ = 5. value = np.array(5.) res = ep._convert_value_safe(value) self.assertEqual(res, targ) self.assertFalse(hasattr(res, 'dtype')) def test__convert_value_safe__numpy_unicode_scalar(self): targ = u'test' value = np.array('test', dtype='U') res = ep._convert_value_safe(value) self.assertEqual(res, targ) self.assertFalse(hasattr(res, 'dtype')) def test__convert_value_safe__numpy_str_scalar(self): targ = u'test' value = np.array('test', dtype='S') res = ep._convert_value_safe(value) self.assertEqual(res, targ) self.assertFalse(hasattr(res, 'dtype')) def test__convert_value_safe__quantity_scalar(self): targ = (10., 'ms') value = 10. * pq.ms res = ep._convert_value_safe(value) self.assertEqual(res, targ) self.assertFalse(hasattr(res[0], 'dtype')) self.assertFalse(hasattr(res[0], 'units')) @unittest.skipUnless(HAVE_PANDAS, 'requires pandas') class SpiketrainToDataframeTestCase(unittest.TestCase): def test__spiketrain_to_dataframe__parents_empty(self): obj = fake_neo('SpikeTrain', seed=0) res0 = ep.spiketrain_to_dataframe(obj) res1 = ep.spiketrain_to_dataframe(obj, child_first=True) res2 = ep.spiketrain_to_dataframe(obj, child_first=False) res3 = ep.spiketrain_to_dataframe(obj, parents=True) res4 = ep.spiketrain_to_dataframe(obj, parents=True, child_first=True) res5 = ep.spiketrain_to_dataframe(obj, parents=True, child_first=False) res6 = ep.spiketrain_to_dataframe(obj, parents=False) res7 = ep.spiketrain_to_dataframe(obj, parents=False, child_first=True) res8 = ep.spiketrain_to_dataframe(obj, parents=False, child_first=False) targvalues = pq.Quantity(obj.magnitude, units=obj.units) targvalues = targvalues.rescale('s').magnitude[np.newaxis].T targindex = np.arange(len(targvalues)) attrs = ep._extract_neo_attrs_safe(obj, parents=True, child_first=True) keys, values = zip(*sorted(attrs.items())) values = _convert_levels(values) self.assertEqual(1, len(res0.columns)) self.assertEqual(1, len(res1.columns)) self.assertEqual(1, len(res2.columns)) self.assertEqual(1, len(res3.columns)) self.assertEqual(1, len(res4.columns)) self.assertEqual(1, len(res5.columns)) self.assertEqual(1, len(res6.columns)) self.assertEqual(1, len(res7.columns)) self.assertEqual(1, len(res8.columns)) self.assertEqual(len(obj), len(res0.index)) self.assertEqual(len(obj), len(res1.index)) self.assertEqual(len(obj), len(res2.index)) self.assertEqual(len(obj), len(res3.index)) self.assertEqual(len(obj), len(res4.index)) self.assertEqual(len(obj), len(res5.index)) self.assertEqual(len(obj), len(res6.index)) self.assertEqual(len(obj), len(res7.index)) self.assertEqual(len(obj), len(res8.index)) assert_array_equal(targvalues, res0.values) assert_array_equal(targvalues, res1.values) assert_array_equal(targvalues, res2.values) assert_array_equal(targvalues, res3.values) assert_array_equal(targvalues, res4.values) assert_array_equal(targvalues, res5.values) assert_array_equal(targvalues, res6.values) assert_array_equal(targvalues, res7.values) assert_array_equal(targvalues, res8.values) assert_array_equal(targindex, res0.index) assert_array_equal(targindex, res1.index) assert_array_equal(targindex, res2.index) assert_array_equal(targindex, res3.index) assert_array_equal(targindex, res4.index) assert_array_equal(targindex, res5.index) assert_array_equal(targindex, res6.index) assert_array_equal(targindex, res7.index) assert_array_equal(targindex, res8.index) self.assertEqual(['spike_number'], res0.index.names) self.assertEqual(['spike_number'], res1.index.names) self.assertEqual(['spike_number'], res2.index.names) self.assertEqual(['spike_number'], res3.index.names) self.assertEqual(['spike_number'], res4.index.names) self.assertEqual(['spike_number'], res5.index.names) self.assertEqual(['spike_number'], res6.index.names) self.assertEqual(['spike_number'], res7.index.names) self.assertEqual(['spike_number'], res8.index.names) self.assertEqual(keys, res0.columns.names) self.assertEqual(keys, res1.columns.names) self.assertEqual(keys, res2.columns.names) self.assertEqual(keys, res3.columns.names) self.assertEqual(keys, res4.columns.names) self.assertEqual(keys, res5.columns.names) self.assertEqual(keys, res6.columns.names) self.assertEqual(keys, res7.columns.names) self.assertEqual(keys, res8.columns.names) for value, level in zip(values, res0.columns.levels): assert_index_equal(value, level) for value, level in zip(values, res1.columns.levels): assert_index_equal(value, level) for value, level in zip(values, res2.columns.levels): assert_index_equal(value, level) for value, level in zip(values, res3.columns.levels): assert_index_equal(value, level) for value, level in zip(values, res4.columns.levels): assert_index_equal(value, level) for value, level in zip(values, res5.columns.levels): assert_index_equal(value, level) for value, level in zip(values, res6.columns.levels): assert_index_equal(value, level) for value, level in zip(values, res7.columns.levels): assert_index_equal(value, level) for value, level in zip(values, res8.columns.levels): assert_index_equal(value, level) def test__spiketrain_to_dataframe__noparents(self): blk = fake_neo('Block', seed=0) obj = blk.list_children_by_class('SpikeTrain')[0] res0 = ep.spiketrain_to_dataframe(obj, parents=False) res1 = ep.spiketrain_to_dataframe(obj, parents=False, child_first=True) res2 = ep.spiketrain_to_dataframe(obj, parents=False, child_first=False) targvalues = pq.Quantity(obj.magnitude, units=obj.units) targvalues = targvalues.rescale('s').magnitude[np.newaxis].T targindex = np.arange(len(targvalues)) attrs = ep._extract_neo_attrs_safe(obj, parents=False, child_first=True) keys, values = zip(*sorted(attrs.items())) values = _convert_levels(values) self.assertEqual(1, len(res0.columns)) self.assertEqual(1, len(res1.columns)) self.assertEqual(1, len(res2.columns)) self.assertEqual(len(obj), len(res0.index)) self.assertEqual(len(obj), len(res1.index)) self.assertEqual(len(obj), len(res2.index)) assert_array_equal(targvalues, res0.values) assert_array_equal(targvalues, res1.values) assert_array_equal(targvalues, res2.values) assert_array_equal(targindex, res0.index) assert_array_equal(targindex, res1.index) assert_array_equal(targindex, res2.index) self.assertEqual(['spike_number'], res0.index.names) self.assertEqual(['spike_number'], res1.index.names) self.assertEqual(['spike_number'], res2.index.names) self.assertEqual(keys, res0.columns.names) self.assertEqual(keys, res1.columns.names) self.assertEqual(keys, res2.columns.names) for value, level in zip(values, res0.columns.levels): assert_index_equal(value, level) for value, level in zip(values, res1.columns.levels): assert_index_equal(value, level) for value, level in zip(values, res2.columns.levels): assert_index_equal(value, level) def test__spiketrain_to_dataframe__parents_childfirst(self): blk = fake_neo('Block', seed=0) obj = blk.list_children_by_class('SpikeTrain')[0] res0 = ep.spiketrain_to_dataframe(obj) res1 = ep.spiketrain_to_dataframe(obj, child_first=True) res2 = ep.spiketrain_to_dataframe(obj, parents=True) res3 = ep.spiketrain_to_dataframe(obj, parents=True, child_first=True) targvalues = pq.Quantity(obj.magnitude, units=obj.units) targvalues = targvalues.rescale('s').magnitude[np.newaxis].T targindex = np.arange(len(targvalues)) attrs = ep._extract_neo_attrs_safe(obj, parents=True, child_first=True) keys, values = zip(*sorted(attrs.items())) values = _convert_levels(values) self.assertEqual(1, len(res0.columns)) self.assertEqual(1, len(res1.columns)) self.assertEqual(1, len(res2.columns)) self.assertEqual(1, len(res3.columns)) self.assertEqual(len(obj), len(res0.index)) self.assertEqual(len(obj), len(res1.index)) self.assertEqual(len(obj), len(res2.index)) self.assertEqual(len(obj), len(res3.index)) assert_array_equal(targvalues, res0.values) assert_array_equal(targvalues, res1.values) assert_array_equal(targvalues, res2.values) assert_array_equal(targvalues, res3.values) assert_array_equal(targindex, res0.index) assert_array_equal(targindex, res1.index) assert_array_equal(targindex, res2.index) assert_array_equal(targindex, res3.index) self.assertEqual(['spike_number'], res0.index.names) self.assertEqual(['spike_number'], res1.index.names) self.assertEqual(['spike_number'], res2.index.names) self.assertEqual(['spike_number'], res3.index.names) self.assertEqual(keys, res0.columns.names) self.assertEqual(keys, res1.columns.names) self.assertEqual(keys, res2.columns.names) self.assertEqual(keys, res3.columns.names) for value, level in zip(values, res0.columns.levels): assert_index_equal(value, level) for value, level in zip(values, res1.columns.levels): assert_index_equal(value, level) for value, level in zip(values, res2.columns.levels): assert_index_equal(value, level) for value, level in zip(values, res3.columns.levels): assert_index_equal(value, level) def test__spiketrain_to_dataframe__parents_parentfirst(self): blk = fake_neo('Block', seed=0) obj = blk.list_children_by_class('SpikeTrain')[0] res0 = ep.spiketrain_to_dataframe(obj, child_first=False) res1 = ep.spiketrain_to_dataframe(obj, parents=True, child_first=False) targvalues = pq.Quantity(obj.magnitude, units=obj.units) targvalues = targvalues.rescale('s').magnitude[np.newaxis].T targindex = np.arange(len(targvalues)) attrs = ep._extract_neo_attrs_safe(obj, parents=True, child_first=False) keys, values = zip(*sorted(attrs.items())) values = _convert_levels(values) self.assertEqual(1, len(res0.columns)) self.assertEqual(1, len(res1.columns)) self.assertEqual(len(obj), len(res0.index)) self.assertEqual(len(obj), len(res1.index)) assert_array_equal(targvalues, res0.values) assert_array_equal(targvalues, res1.values) assert_array_equal(targindex, res0.index) assert_array_equal(targindex, res1.index) self.assertEqual(['spike_number'], res0.index.names) self.assertEqual(['spike_number'], res1.index.names) self.assertEqual(keys, res0.columns.names) self.assertEqual(keys, res1.columns.names) for value, level in zip(values, res0.columns.levels): assert_index_equal(value, level) for value, level in zip(values, res1.columns.levels): assert_index_equal(value, level) @unittest.skipUnless(HAVE_PANDAS, 'requires pandas') class EventToDataframeTestCase(unittest.TestCase): def test__event_to_dataframe__parents_empty(self): obj = fake_neo('Event', seed=42) res0 = ep.event_to_dataframe(obj) res1 = ep.event_to_dataframe(obj, child_first=True) res2 = ep.event_to_dataframe(obj, child_first=False) res3 = ep.event_to_dataframe(obj, parents=True) res4 = ep.event_to_dataframe(obj, parents=True, child_first=True) res5 = ep.event_to_dataframe(obj, parents=True, child_first=False) res6 = ep.event_to_dataframe(obj, parents=False) res7 = ep.event_to_dataframe(obj, parents=False, child_first=True) res8 = ep.event_to_dataframe(obj, parents=False, child_first=False) targvalues = obj.labels[:len(obj.times)][np.newaxis].T.astype('U') targindex = obj.times[:len(obj.labels)].rescale('s').magnitude attrs = ep._extract_neo_attrs_safe(obj, parents=True, child_first=True) keys, values = zip(*sorted(attrs.items())) values = _convert_levels(values) self.assertEqual(1, len(res0.columns)) self.assertEqual(1, len(res1.columns)) self.assertEqual(1, len(res2.columns)) self.assertEqual(1, len(res3.columns)) self.assertEqual(1, len(res4.columns)) self.assertEqual(1, len(res5.columns)) self.assertEqual(1, len(res6.columns)) self.assertEqual(1, len(res7.columns)) self.assertEqual(1, len(res8.columns)) self.assertEqual(min(len(obj.times), len(obj.labels)), len(res0.index)) self.assertEqual(min(len(obj.times), len(obj.labels)), len(res1.index)) self.assertEqual(min(len(obj.times), len(obj.labels)), len(res2.index)) self.assertEqual(min(len(obj.times), len(obj.labels)), len(res3.index)) self.assertEqual(min(len(obj.times), len(obj.labels)), len(res4.index)) self.assertEqual(min(len(obj.times), len(obj.labels)), len(res5.index)) self.assertEqual(min(len(obj.times), len(obj.labels)), len(res6.index)) self.assertEqual(min(len(obj.times), len(obj.labels)), len(res7.index)) self.assertEqual(min(len(obj.times), len(obj.labels)), len(res8.index)) assert_array_equal(targvalues, res0.values) assert_array_equal(targvalues, res1.values) assert_array_equal(targvalues, res2.values) assert_array_equal(targvalues, res3.values) assert_array_equal(targvalues, res4.values) assert_array_equal(targvalues, res5.values) assert_array_equal(targvalues, res6.values) assert_array_equal(targvalues, res7.values) assert_array_equal(targvalues, res8.values) assert_array_equal(targindex, res0.index) assert_array_equal(targindex, res1.index) assert_array_equal(targindex, res2.index) assert_array_equal(targindex, res3.index) assert_array_equal(targindex, res4.index) assert_array_equal(targindex, res5.index) assert_array_equal(targindex, res6.index) assert_array_equal(targindex, res7.index) assert_array_equal(targindex, res8.index) self.assertEqual(['times'], res0.index.names) self.assertEqual(['times'], res1.index.names) self.assertEqual(['times'], res2.index.names) self.assertEqual(['times'], res3.index.names) self.assertEqual(['times'], res4.index.names) self.assertEqual(['times'], res5.index.names) self.assertEqual(['times'], res6.index.names) self.assertEqual(['times'], res7.index.names) self.assertEqual(['times'], res8.index.names) self.assertEqual(keys, res0.columns.names) self.assertEqual(keys, res1.columns.names) self.assertEqual(keys, res2.columns.names) self.assertEqual(keys, res3.columns.names) self.assertEqual(keys, res4.columns.names) self.assertEqual(keys, res5.columns.names) self.assertEqual(keys, res6.columns.names) self.assertEqual(keys, res7.columns.names) self.assertEqual(keys, res8.columns.names) for value, level in zip(values, res0.columns.levels): assert_index_equal(value, level) for value, level in zip(values, res1.columns.levels): assert_index_equal(value, level) for value, level in zip(values, res2.columns.levels): assert_index_equal(value, level) for value, level in zip(values, res3.columns.levels): assert_index_equal(value, level) for value, level in zip(values, res4.columns.levels): assert_index_equal(value, level) for value, level in zip(values, res5.columns.levels): assert_index_equal(value, level) for value, level in zip(values, res6.columns.levels): assert_index_equal(value, level) for value, level in zip(values, res7.columns.levels): assert_index_equal(value, level) for value, level in zip(values, res8.columns.levels): assert_index_equal(value, level) def test__event_to_dataframe__noparents(self): blk = fake_neo('Block', seed=42) obj = blk.list_children_by_class('Event')[0] res0 = ep.event_to_dataframe(obj, parents=False) res1 = ep.event_to_dataframe(obj, parents=False, child_first=False) res2 = ep.event_to_dataframe(obj, parents=False, child_first=True) targvalues = obj.labels[:len(obj.times)][np.newaxis].T.astype('U') targindex = obj.times[:len(obj.labels)].rescale('s').magnitude attrs = ep._extract_neo_attrs_safe(obj, parents=False, child_first=True) keys, values = zip(*sorted(attrs.items())) values = _convert_levels(values) self.assertEqual(1, len(res0.columns)) self.assertEqual(1, len(res1.columns)) self.assertEqual(1, len(res2.columns)) self.assertEqual(min(len(obj.times), len(obj.labels)), len(res0.index)) self.assertEqual(min(len(obj.times), len(obj.labels)), len(res1.index)) self.assertEqual(min(len(obj.times), len(obj.labels)), len(res2.index)) assert_array_equal(targvalues, res0.values) assert_array_equal(targvalues, res1.values) assert_array_equal(targvalues, res2.values) assert_array_equal(targindex, res0.index) assert_array_equal(targindex, res1.index) assert_array_equal(targindex, res2.index) self.assertEqual(['times'], res0.index.names) self.assertEqual(['times'], res1.index.names) self.assertEqual(['times'], res2.index.names) self.assertEqual(keys, res0.columns.names) self.assertEqual(keys, res1.columns.names) self.assertEqual(keys, res2.columns.names) for value, level in zip(values, res0.columns.levels): assert_index_equal(value, level) for value, level in zip(values, res1.columns.levels): assert_index_equal(value, level) for value, level in zip(values, res2.columns.levels): assert_index_equal(value, level) def test__event_to_dataframe__parents_childfirst(self): blk = fake_neo('Block', seed=42) obj = blk.list_children_by_class('Event')[0] res0 = ep.event_to_dataframe(obj) res1 = ep.event_to_dataframe(obj, child_first=True) res2 = ep.event_to_dataframe(obj, parents=True) res3 = ep.event_to_dataframe(obj, parents=True, child_first=True) targvalues = obj.labels[:len(obj.times)][np.newaxis].T.astype('U') targindex = obj.times[:len(obj.labels)].rescale('s').magnitude attrs = ep._extract_neo_attrs_safe(obj, parents=True, child_first=True) keys, values = zip(*sorted(attrs.items())) values = _convert_levels(values) self.assertEqual(1, len(res0.columns)) self.assertEqual(1, len(res1.columns)) self.assertEqual(1, len(res2.columns)) self.assertEqual(1, len(res3.columns)) self.assertEqual(min(len(obj.times), len(obj.labels)), len(res0.index)) self.assertEqual(min(len(obj.times), len(obj.labels)), len(res1.index)) self.assertEqual(min(len(obj.times), len(obj.labels)), len(res2.index)) self.assertEqual(min(len(obj.times), len(obj.labels)), len(res3.index)) assert_array_equal(targvalues, res0.values) assert_array_equal(targvalues, res1.values) assert_array_equal(targvalues, res2.values) assert_array_equal(targvalues, res3.values) assert_array_equal(targindex, res0.index) assert_array_equal(targindex, res1.index) assert_array_equal(targindex, res2.index) assert_array_equal(targindex, res3.index) self.assertEqual(['times'], res0.index.names) self.assertEqual(['times'], res1.index.names) self.assertEqual(['times'], res2.index.names) self.assertEqual(['times'], res3.index.names) self.assertEqual(keys, res0.columns.names) self.assertEqual(keys, res1.columns.names) self.assertEqual(keys, res2.columns.names) self.assertEqual(keys, res3.columns.names) for value, level in zip(values, res0.columns.levels): assert_index_equal(value, level) for value, level in zip(values, res1.columns.levels): assert_index_equal(value, level) for value, level in zip(values, res2.columns.levels): assert_index_equal(value, level) for value, level in zip(values, res3.columns.levels): assert_index_equal(value, level) def test__event_to_dataframe__parents_parentfirst(self): blk = fake_neo('Block', seed=42) obj = blk.list_children_by_class('Event')[0] res0 = ep.event_to_dataframe(obj, child_first=False) res1 = ep.event_to_dataframe(obj, parents=True, child_first=False) targvalues = obj.labels[:len(obj.times)][np.newaxis].T.astype('U') targindex = obj.times[:len(obj.labels)].rescale('s').magnitude attrs = ep._extract_neo_attrs_safe(obj, parents=True, child_first=False) keys, values = zip(*sorted(attrs.items())) values = _convert_levels(values) self.assertEqual(1, len(res0.columns)) self.assertEqual(1, len(res1.columns)) self.assertEqual(min(len(obj.times), len(obj.labels)), len(res0.index)) self.assertEqual(min(len(obj.times), len(obj.labels)), len(res1.index)) assert_array_equal(targvalues, res0.values) assert_array_equal(targvalues, res1.values) assert_array_equal(targindex, res0.index) assert_array_equal(targindex, res1.index) self.assertEqual(['times'], res0.index.names) self.assertEqual(['times'], res1.index.names) self.assertEqual(keys, res0.columns.names) self.assertEqual(keys, res1.columns.names) for value, level in zip(values, res0.columns.levels): assert_index_equal(value, level) for value, level in zip(values, res1.columns.levels): assert_index_equal(value, level) @unittest.skipUnless(HAVE_PANDAS, 'requires pandas') class EpochToDataframeTestCase(unittest.TestCase): def test__epoch_to_dataframe__parents_empty(self): obj = fake_neo('Epoch', seed=42) res0 = ep.epoch_to_dataframe(obj) res1 = ep.epoch_to_dataframe(obj, child_first=True) res2 = ep.epoch_to_dataframe(obj, child_first=False) res3 = ep.epoch_to_dataframe(obj, parents=True) res4 = ep.epoch_to_dataframe(obj, parents=True, child_first=True) res5 = ep.epoch_to_dataframe(obj, parents=True, child_first=False) res6 = ep.epoch_to_dataframe(obj, parents=False) res7 = ep.epoch_to_dataframe(obj, parents=False, child_first=True) res8 = ep.epoch_to_dataframe(obj, parents=False, child_first=False) minlen = min([len(obj.times), len(obj.durations), len(obj.labels)]) targvalues = obj.labels[:minlen][np.newaxis].T.astype('U') targindex = np.vstack([obj.durations[:minlen].rescale('s').magnitude, obj.times[:minlen].rescale('s').magnitude]) targvalues = targvalues[targindex.argsort()[0], :] targindex.sort() attrs = ep._extract_neo_attrs_safe(obj, parents=True, child_first=True) keys, values = zip(*sorted(attrs.items())) values = _convert_levels(values) self.assertEqual(1, len(res0.columns)) self.assertEqual(1, len(res1.columns)) self.assertEqual(1, len(res2.columns)) self.assertEqual(1, len(res3.columns)) self.assertEqual(1, len(res4.columns)) self.assertEqual(1, len(res5.columns)) self.assertEqual(1, len(res6.columns)) self.assertEqual(1, len(res7.columns)) self.assertEqual(1, len(res8.columns)) self.assertEqual(min(len(obj.times), len(obj.durations), len(obj.labels)), len(res0.index)) self.assertEqual(min(len(obj.times), len(obj.durations), len(obj.labels)), len(res1.index)) self.assertEqual(min(len(obj.times), len(obj.durations), len(obj.labels)), len(res2.index)) self.assertEqual(min(len(obj.times), len(obj.durations), len(obj.labels)), len(res3.index)) self.assertEqual(min(len(obj.times), len(obj.durations), len(obj.labels)), len(res4.index)) self.assertEqual(min(len(obj.times), len(obj.durations), len(obj.labels)), len(res5.index)) self.assertEqual(min(len(obj.times), len(obj.durations), len(obj.labels)), len(res6.index)) self.assertEqual(min(len(obj.times), len(obj.durations), len(obj.labels)), len(res7.index)) self.assertEqual(min(len(obj.times), len(obj.durations), len(obj.labels)), len(res8.index)) assert_array_equal(targvalues, res0.values) assert_array_equal(targvalues, res1.values) assert_array_equal(targvalues, res2.values) assert_array_equal(targvalues, res3.values) assert_array_equal(targvalues, res4.values) assert_array_equal(targvalues, res5.values) assert_array_equal(targvalues, res6.values) assert_array_equal(targvalues, res7.values) assert_array_equal(targvalues, res8.values) self.assertEqual(keys, res0.columns.names) self.assertEqual(keys, res1.columns.names) self.assertEqual(keys, res2.columns.names) self.assertEqual(keys, res3.columns.names) self.assertEqual(keys, res4.columns.names) self.assertEqual(keys, res5.columns.names) self.assertEqual(keys, res6.columns.names) self.assertEqual(keys, res7.columns.names) self.assertEqual(keys, res8.columns.names) self.assertEqual([u'durations', u'times'], res0.index.names) self.assertEqual([u'durations', u'times'], res1.index.names) self.assertEqual([u'durations', u'times'], res2.index.names) self.assertEqual([u'durations', u'times'], res3.index.names) self.assertEqual([u'durations', u'times'], res4.index.names) self.assertEqual([u'durations', u'times'], res5.index.names) self.assertEqual([u'durations', u'times'], res6.index.names) self.assertEqual([u'durations', u'times'], res7.index.names) self.assertEqual([u'durations', u'times'], res8.index.names) self.assertEqual(2, len(res0.index.levels)) self.assertEqual(2, len(res1.index.levels)) self.assertEqual(2, len(res2.index.levels)) self.assertEqual(2, len(res3.index.levels)) self.assertEqual(2, len(res4.index.levels)) self.assertEqual(2, len(res5.index.levels)) self.assertEqual(2, len(res6.index.levels)) self.assertEqual(2, len(res7.index.levels)) self.assertEqual(2, len(res8.index.levels)) assert_array_equal(targindex, res0.index.levels) assert_array_equal(targindex, res1.index.levels) assert_array_equal(targindex, res2.index.levels) assert_array_equal(targindex, res3.index.levels) assert_array_equal(targindex, res4.index.levels) assert_array_equal(targindex, res5.index.levels) assert_array_equal(targindex, res6.index.levels) assert_array_equal(targindex, res7.index.levels) assert_array_equal(targindex, res8.index.levels) for value, level in zip(values, res0.columns.levels): assert_index_equal(value, level) for value, level in zip(values, res1.columns.levels): assert_index_equal(value, level) for value, level in zip(values, res2.columns.levels): assert_index_equal(value, level) for value, level in zip(values, res3.columns.levels): assert_index_equal(value, level) for value, level in zip(values, res4.columns.levels): assert_index_equal(value, level) for value, level in zip(values, res5.columns.levels): assert_index_equal(value, level) for value, level in zip(values, res6.columns.levels): assert_index_equal(value, level) for value, level in zip(values, res7.columns.levels): assert_index_equal(value, level) for value, level in zip(values, res8.columns.levels): assert_index_equal(value, level) def test__epoch_to_dataframe__noparents(self): blk = fake_neo('Block', seed=42) obj = blk.list_children_by_class('Epoch')[0] res0 = ep.epoch_to_dataframe(obj, parents=False) res1 = ep.epoch_to_dataframe(obj, parents=False, child_first=True) res2 = ep.epoch_to_dataframe(obj, parents=False, child_first=False) minlen = min([len(obj.times), len(obj.durations), len(obj.labels)]) targvalues = obj.labels[:minlen][np.newaxis].T.astype('U') targindex = np.vstack([obj.durations[:minlen].rescale('s').magnitude, obj.times[:minlen].rescale('s').magnitude]) targvalues = targvalues[targindex.argsort()[0], :] targindex.sort() attrs = ep._extract_neo_attrs_safe(obj, parents=False, child_first=True) keys, values = zip(*sorted(attrs.items())) values = _convert_levels(values) self.assertEqual(1, len(res0.columns)) self.assertEqual(1, len(res1.columns)) self.assertEqual(1, len(res2.columns)) self.assertEqual(min(len(obj.times), len(obj.durations), len(obj.labels)), len(res0.index)) self.assertEqual(min(len(obj.times), len(obj.durations), len(obj.labels)), len(res1.index)) self.assertEqual(min(len(obj.times), len(obj.durations), len(obj.labels)), len(res2.index)) assert_array_equal(targvalues, res0.values) assert_array_equal(targvalues, res1.values) assert_array_equal(targvalues, res2.values) self.assertEqual(keys, res0.columns.names) self.assertEqual(keys, res1.columns.names) self.assertEqual(keys, res2.columns.names) self.assertEqual([u'durations', u'times'], res0.index.names) self.assertEqual([u'durations', u'times'], res1.index.names) self.assertEqual([u'durations', u'times'], res2.index.names) self.assertEqual(2, len(res0.index.levels)) self.assertEqual(2, len(res1.index.levels)) self.assertEqual(2, len(res2.index.levels)) assert_array_equal(targindex, res0.index.levels) assert_array_equal(targindex, res1.index.levels) assert_array_equal(targindex, res2.index.levels) for value, level in zip(values, res0.columns.levels): assert_index_equal(value, level) for value, level in zip(values, res1.columns.levels): assert_index_equal(value, level) for value, level in zip(values, res2.columns.levels): assert_index_equal(value, level) def test__epoch_to_dataframe__parents_childfirst(self): blk = fake_neo('Block', seed=42) obj = blk.list_children_by_class('Epoch')[0] res0 = ep.epoch_to_dataframe(obj) res1 = ep.epoch_to_dataframe(obj, child_first=True) res2 = ep.epoch_to_dataframe(obj, parents=True) res3 = ep.epoch_to_dataframe(obj, parents=True, child_first=True) minlen = min([len(obj.times), len(obj.durations), len(obj.labels)]) targvalues = obj.labels[:minlen][np.newaxis].T.astype('U') targindex = np.vstack([obj.durations[:minlen].rescale('s').magnitude, obj.times[:minlen].rescale('s').magnitude]) targvalues = targvalues[targindex.argsort()[0], :] targindex.sort() attrs = ep._extract_neo_attrs_safe(obj, parents=True, child_first=True) keys, values = zip(*sorted(attrs.items())) values = _convert_levels(values) self.assertEqual(1, len(res0.columns)) self.assertEqual(1, len(res1.columns)) self.assertEqual(1, len(res2.columns)) self.assertEqual(1, len(res3.columns)) self.assertEqual(min(len(obj.times), len(obj.durations), len(obj.labels)), len(res0.index)) self.assertEqual(min(len(obj.times), len(obj.durations), len(obj.labels)), len(res1.index)) self.assertEqual(min(len(obj.times), len(obj.durations), len(obj.labels)), len(res2.index)) self.assertEqual(min(len(obj.times), len(obj.durations), len(obj.labels)), len(res3.index)) assert_array_equal(targvalues, res0.values) assert_array_equal(targvalues, res1.values) assert_array_equal(targvalues, res2.values) assert_array_equal(targvalues, res3.values) self.assertEqual(keys, res0.columns.names) self.assertEqual(keys, res1.columns.names) self.assertEqual(keys, res2.columns.names) self.assertEqual(keys, res3.columns.names) self.assertEqual([u'durations', u'times'], res0.index.names) self.assertEqual([u'durations', u'times'], res1.index.names) self.assertEqual([u'durations', u'times'], res2.index.names) self.assertEqual([u'durations', u'times'], res3.index.names) self.assertEqual(2, len(res0.index.levels)) self.assertEqual(2, len(res1.index.levels)) self.assertEqual(2, len(res2.index.levels)) self.assertEqual(2, len(res3.index.levels)) assert_array_equal(targindex, res0.index.levels) assert_array_equal(targindex, res1.index.levels) assert_array_equal(targindex, res2.index.levels) assert_array_equal(targindex, res3.index.levels) for value, level in zip(values, res0.columns.levels): assert_index_equal(value, level) for value, level in zip(values, res1.columns.levels): assert_index_equal(value, level) for value, level in zip(values, res2.columns.levels): assert_index_equal(value, level) for value, level in zip(values, res3.columns.levels): assert_index_equal(value, level) def test__epoch_to_dataframe__parents_parentfirst(self): blk = fake_neo('Block', seed=42) obj = blk.list_children_by_class('Epoch')[0] res0 = ep.epoch_to_dataframe(obj, child_first=False) res1 = ep.epoch_to_dataframe(obj, parents=True, child_first=False) minlen = min([len(obj.times), len(obj.durations), len(obj.labels)]) targvalues = obj.labels[:minlen][np.newaxis].T.astype('U') targindex = np.vstack([obj.durations[:minlen].rescale('s').magnitude, obj.times[:minlen].rescale('s').magnitude]) targvalues = targvalues[targindex.argsort()[0], :] targindex.sort() attrs = ep._extract_neo_attrs_safe(obj, parents=True, child_first=False) keys, values = zip(*sorted(attrs.items())) values = _convert_levels(values) self.assertEqual(1, len(res0.columns)) self.assertEqual(1, len(res1.columns)) self.assertEqual(min(len(obj.times), len(obj.durations), len(obj.labels)), len(res0.index)) self.assertEqual(min(len(obj.times), len(obj.durations), len(obj.labels)), len(res1.index)) assert_array_equal(targvalues, res0.values) assert_array_equal(targvalues, res1.values) self.assertEqual(keys, res0.columns.names) self.assertEqual(keys, res1.columns.names) self.assertEqual([u'durations', u'times'], res0.index.names) self.assertEqual([u'durations', u'times'], res1.index.names) self.assertEqual(2, len(res0.index.levels)) self.assertEqual(2, len(res1.index.levels)) assert_array_equal(targindex, res0.index.levels) assert_array_equal(targindex, res1.index.levels) for value, level in zip(values, res0.columns.levels): assert_index_equal(value, level) for value, level in zip(values, res1.columns.levels): assert_index_equal(value, level) @unittest.skipUnless(HAVE_PANDAS, 'requires pandas') class MultiSpiketrainsToDataframeTestCase(unittest.TestCase): def setUp(self): if hasattr(self, 'assertItemsEqual'): self.assertCountEqual = self.assertItemsEqual def test__multi_spiketrains_to_dataframe__single(self): obj = fake_neo('SpikeTrain', seed=0, n=5) res0 = ep.multi_spiketrains_to_dataframe(obj) res1 = ep.multi_spiketrains_to_dataframe(obj, parents=False) res2 = ep.multi_spiketrains_to_dataframe(obj, parents=True) res3 = ep.multi_spiketrains_to_dataframe(obj, child_first=True) res4 = ep.multi_spiketrains_to_dataframe(obj, parents=False, child_first=True) res5 = ep.multi_spiketrains_to_dataframe(obj, parents=True, child_first=True) res6 = ep.multi_spiketrains_to_dataframe(obj, child_first=False) res7 = ep.multi_spiketrains_to_dataframe(obj, parents=False, child_first=False) res8 = ep.multi_spiketrains_to_dataframe(obj, parents=True, child_first=False) targ = ep.spiketrain_to_dataframe(obj) keys = ep._extract_neo_attrs_safe(obj, parents=True, child_first=True).keys() keys = list(keys) targwidth = 1 targlen = len(obj) self.assertEqual(targwidth, len(targ.columns)) self.assertEqual(targwidth, len(res0.columns)) self.assertEqual(targwidth, len(res1.columns)) self.assertEqual(targwidth, len(res2.columns)) self.assertEqual(targwidth, len(res3.columns)) self.assertEqual(targwidth, len(res4.columns)) self.assertEqual(targwidth, len(res5.columns)) self.assertEqual(targwidth, len(res6.columns)) self.assertEqual(targwidth, len(res7.columns)) self.assertEqual(targwidth, len(res8.columns)) self.assertEqual(targlen, len(targ.index)) self.assertEqual(targlen, len(res0.index)) self.assertEqual(targlen, len(res1.index)) self.assertEqual(targlen, len(res2.index)) self.assertEqual(targlen, len(res3.index)) self.assertEqual(targlen, len(res4.index)) self.assertEqual(targlen, len(res5.index)) self.assertEqual(targlen, len(res6.index)) self.assertEqual(targlen, len(res7.index)) self.assertEqual(targlen, len(res8.index)) self.assertCountEqual(keys, targ.columns.names) self.assertCountEqual(keys, res0.columns.names) self.assertCountEqual(keys, res1.columns.names) self.assertCountEqual(keys, res2.columns.names) self.assertCountEqual(keys, res3.columns.names) self.assertCountEqual(keys, res4.columns.names) self.assertCountEqual(keys, res5.columns.names) self.assertCountEqual(keys, res6.columns.names) self.assertCountEqual(keys, res7.columns.names) self.assertCountEqual(keys, res8.columns.names) assert_array_equal(targ.values, res0.values) assert_array_equal(targ.values, res1.values) assert_array_equal(targ.values, res2.values) assert_array_equal(targ.values, res3.values) assert_array_equal(targ.values, res4.values) assert_array_equal(targ.values, res5.values) assert_array_equal(targ.values, res6.values) assert_array_equal(targ.values, res7.values) assert_array_equal(targ.values, res8.values) assert_frame_equal(targ, res0) assert_frame_equal(targ, res0) assert_frame_equal(targ, res1) assert_frame_equal(targ, res2) assert_frame_equal(targ, res3) assert_frame_equal(targ, res4) assert_frame_equal(targ, res5) assert_frame_equal(targ, res6) assert_frame_equal(targ, res7) assert_frame_equal(targ, res8) def test__multi_spiketrains_to_dataframe__unit_default(self): obj = fake_neo('Unit', seed=0, n=5) res0 = ep.multi_spiketrains_to_dataframe(obj) objs = obj.spiketrains targ = [ep.spiketrain_to_dataframe(iobj) for iobj in objs] targ = ep._sort_inds(pd.concat(targ, axis=1), axis=1) keys = ep._extract_neo_attrs_safe(objs[0], parents=True, child_first=True).keys() keys = list(keys) targwidth = len(objs) targlen = max(len(iobj) for iobj in objs) self.assertGreater(len(objs), 0) self.assertEqual(targwidth, len(targ.columns)) self.assertEqual(targwidth, len(res0.columns)) self.assertEqual(targlen, len(targ.index)) self.assertEqual(targlen, len(res0.index)) self.assertCountEqual(keys, targ.columns.names) self.assertCountEqual(keys, res0.columns.names) assert_array_equal(targ.values, res0.values) assert_frame_equal(targ, res0) def test__multi_spiketrains_to_dataframe__segment_default(self): obj = fake_neo('Segment', seed=0, n=5) res0 = ep.multi_spiketrains_to_dataframe(obj) objs = obj.spiketrains targ = [ep.spiketrain_to_dataframe(iobj) for iobj in objs] targ = ep._sort_inds(pd.concat(targ, axis=1), axis=1) keys = ep._extract_neo_attrs_safe(objs[0], parents=True, child_first=True).keys() keys = list(keys) targwidth = len(objs) targlen = max(len(iobj) for iobj in objs) self.assertGreater(len(objs), 0) self.assertEqual(targwidth, len(targ.columns)) self.assertEqual(targwidth, len(res0.columns)) self.assertEqual(targlen, len(targ.index)) self.assertEqual(targlen, len(res0.index)) self.assertCountEqual(keys, targ.columns.names) self.assertCountEqual(keys, res0.columns.names) assert_array_equal(targ.values, res0.values) assert_frame_equal(targ, res0) def test__multi_spiketrains_to_dataframe__block_noparents(self): obj = fake_neo('Block', seed=0, n=3) res0 = ep.multi_spiketrains_to_dataframe(obj, parents=False) res1 = ep.multi_spiketrains_to_dataframe(obj, parents=False, child_first=True) res2 = ep.multi_spiketrains_to_dataframe(obj, parents=False, child_first=False) objs = obj.list_children_by_class('SpikeTrain') targ = [ep.spiketrain_to_dataframe(iobj, parents=False, child_first=True) for iobj in objs] targ = ep._sort_inds(pd.concat(targ, axis=1), axis=1) keys = ep._extract_neo_attrs_safe(objs[0], parents=False, child_first=True).keys() keys = list(keys) targwidth = len(objs) targlen = max(len(iobj) for iobj in objs) self.assertGreater(len(objs), 0) self.assertEqual(targwidth, len(targ.columns)) self.assertEqual(targwidth, len(res0.columns)) self.assertEqual(targwidth, len(res1.columns)) self.assertEqual(targwidth, len(res2.columns)) self.assertEqual(targlen, len(targ.index)) self.assertEqual(targlen, len(res0.index)) self.assertEqual(targlen, len(res1.index)) self.assertEqual(targlen, len(res2.index)) self.assertCountEqual(keys, targ.columns.names) self.assertCountEqual(keys, res0.columns.names) self.assertCountEqual(keys, res1.columns.names) self.assertCountEqual(keys, res2.columns.names) assert_array_equal(targ.values, res0.values) assert_array_equal(targ.values, res1.values) assert_array_equal(targ.values, res2.values) assert_frame_equal(targ, res0) assert_frame_equal(targ, res1) assert_frame_equal(targ, res2) def test__multi_spiketrains_to_dataframe__block_parents_childfirst(self): obj = fake_neo('Block', seed=0, n=3) res0 = ep.multi_spiketrains_to_dataframe(obj) res1 = ep.multi_spiketrains_to_dataframe(obj, parents=True) res2 = ep.multi_spiketrains_to_dataframe(obj, child_first=True) res3 = ep.multi_spiketrains_to_dataframe(obj, parents=True, child_first=True) objs = obj.list_children_by_class('SpikeTrain') targ = [ep.spiketrain_to_dataframe(iobj, parents=True, child_first=True) for iobj in objs] targ = ep._sort_inds(pd.concat(targ, axis=1), axis=1) keys = ep._extract_neo_attrs_safe(objs[0], parents=True, child_first=True).keys() keys = list(keys) targwidth = len(objs) targlen = max(len(iobj) for iobj in objs) self.assertGreater(len(objs), 0) self.assertEqual(targwidth, len(targ.columns)) self.assertEqual(targwidth, len(res0.columns)) self.assertEqual(targwidth, len(res1.columns)) self.assertEqual(targwidth, len(res2.columns)) self.assertEqual(targwidth, len(res3.columns)) self.assertEqual(targlen, len(targ.index)) self.assertEqual(targlen, len(res0.index)) self.assertEqual(targlen, len(res1.index)) self.assertEqual(targlen, len(res2.index)) self.assertEqual(targlen, len(res3.index)) self.assertCountEqual(keys, targ.columns.names) self.assertCountEqual(keys, res0.columns.names) self.assertCountEqual(keys, res1.columns.names) self.assertCountEqual(keys, res2.columns.names) self.assertCountEqual(keys, res3.columns.names) assert_array_equal(targ.values, res0.values) assert_array_equal(targ.values, res1.values) assert_array_equal(targ.values, res2.values) assert_array_equal(targ.values, res3.values) assert_frame_equal(targ, res0) assert_frame_equal(targ, res1) assert_frame_equal(targ, res2) assert_frame_equal(targ, res3) def test__multi_spiketrains_to_dataframe__block_parents_parentfirst(self): obj = fake_neo('Block', seed=0, n=3) res0 = ep.multi_spiketrains_to_dataframe(obj, child_first=False) res1 = ep.multi_spiketrains_to_dataframe(obj, parents=True, child_first=False) objs = obj.list_children_by_class('SpikeTrain') targ = [ep.spiketrain_to_dataframe(iobj, parents=True, child_first=False) for iobj in objs] targ = ep._sort_inds(pd.concat(targ, axis=1), axis=1) keys = ep._extract_neo_attrs_safe(objs[0], parents=True, child_first=False).keys() keys = list(keys) targwidth = len(objs) targlen = max(len(iobj) for iobj in objs) self.assertGreater(len(objs), 0) self.assertEqual(targwidth, len(targ.columns)) self.assertEqual(targwidth, len(res0.columns)) self.assertEqual(targwidth, len(res1.columns)) self.assertEqual(targlen, len(targ.index)) self.assertEqual(targlen, len(res0.index)) self.assertEqual(targlen, len(res1.index)) self.assertCountEqual(keys, targ.columns.names) self.assertCountEqual(keys, res0.columns.names) self.assertCountEqual(keys, res1.columns.names) assert_array_equal(targ.values, res0.values) assert_array_equal(targ.values, res1.values) assert_frame_equal(targ, res0) assert_frame_equal(targ, res1) def test__multi_spiketrains_to_dataframe__list_noparents(self): obj = [fake_neo('Block', seed=i, n=3) for i in range(3)] res0 = ep.multi_spiketrains_to_dataframe(obj, parents=False) res1 = ep.multi_spiketrains_to_dataframe(obj, parents=False, child_first=True) res2 = ep.multi_spiketrains_to_dataframe(obj, parents=False, child_first=False) objs = (iobj.list_children_by_class('SpikeTrain') for iobj in obj) objs = list(chain.from_iterable(objs)) targ = [ep.spiketrain_to_dataframe(iobj, parents=False, child_first=True) for iobj in objs] targ = ep._sort_inds(pd.concat(targ, axis=1), axis=1) keys = ep._extract_neo_attrs_safe(objs[0], parents=False, child_first=True).keys() keys = list(keys) targwidth = len(objs) targlen = max(len(iobj) for iobj in objs) self.assertGreater(len(objs), 0) self.assertEqual(targwidth, len(targ.columns)) self.assertEqual(targwidth, len(res0.columns)) self.assertEqual(targwidth, len(res1.columns)) self.assertEqual(targwidth, len(res2.columns)) self.assertEqual(targlen, len(targ.index)) self.assertEqual(targlen, len(res0.index)) self.assertEqual(targlen, len(res1.index)) self.assertEqual(targlen, len(res2.index)) self.assertCountEqual(keys, targ.columns.names) self.assertCountEqual(keys, res0.columns.names) self.assertCountEqual(keys, res1.columns.names) self.assertCountEqual(keys, res2.columns.names) assert_array_equal(targ.values, res0.values) assert_array_equal(targ.values, res1.values) assert_array_equal(targ.values, res2.values) assert_frame_equal(targ, res0) assert_frame_equal(targ, res1) assert_frame_equal(targ, res2) def test__multi_spiketrains_to_dataframe__list_parents_childfirst(self): obj = [fake_neo('Block', seed=i, n=3) for i in range(3)] res0 = ep.multi_spiketrains_to_dataframe(obj) res1 = ep.multi_spiketrains_to_dataframe(obj, parents=True) res2 = ep.multi_spiketrains_to_dataframe(obj, child_first=True) res3 = ep.multi_spiketrains_to_dataframe(obj, parents=True, child_first=True) objs = (iobj.list_children_by_class('SpikeTrain') for iobj in obj) objs = list(chain.from_iterable(objs)) targ = [ep.spiketrain_to_dataframe(iobj, parents=True, child_first=True) for iobj in objs] targ = ep._sort_inds(pd.concat(targ, axis=1), axis=1) keys = ep._extract_neo_attrs_safe(objs[0], parents=True, child_first=True).keys() keys = list(keys) targwidth = len(objs) targlen = max(len(iobj) for iobj in objs) self.assertGreater(len(objs), 0) self.assertEqual(targwidth, len(targ.columns)) self.assertEqual(targwidth, len(res0.columns)) self.assertEqual(targwidth, len(res1.columns)) self.assertEqual(targwidth, len(res2.columns)) self.assertEqual(targwidth, len(res3.columns)) self.assertEqual(targlen, len(targ.index)) self.assertEqual(targlen, len(res0.index)) self.assertEqual(targlen, len(res1.index)) self.assertEqual(targlen, len(res2.index)) self.assertEqual(targlen, len(res3.index)) self.assertCountEqual(keys, targ.columns.names) self.assertCountEqual(keys, res0.columns.names) self.assertCountEqual(keys, res1.columns.names) self.assertCountEqual(keys, res2.columns.names) self.assertCountEqual(keys, res3.columns.names) assert_array_equal(targ.values, res0.values) assert_array_equal(targ.values, res1.values) assert_array_equal(targ.values, res2.values) assert_array_equal(targ.values, res3.values) assert_frame_equal(targ, res0) assert_frame_equal(targ, res1) assert_frame_equal(targ, res2) assert_frame_equal(targ, res3) def test__multi_spiketrains_to_dataframe__list_parents_parentfirst(self): obj = [fake_neo('Block', seed=i, n=3) for i in range(3)] res0 = ep.multi_spiketrains_to_dataframe(obj, child_first=False) res1 = ep.multi_spiketrains_to_dataframe(obj, parents=True, child_first=False) objs = (iobj.list_children_by_class('SpikeTrain') for iobj in obj) objs = list(chain.from_iterable(objs)) targ = [ep.spiketrain_to_dataframe(iobj, parents=True, child_first=False) for iobj in objs] targ = ep._sort_inds(pd.concat(targ, axis=1), axis=1) keys = ep._extract_neo_attrs_safe(objs[0], parents=True, child_first=False).keys() keys = list(keys) targwidth = len(objs) targlen = max(len(iobj) for iobj in objs) self.assertGreater(len(objs), 0) self.assertEqual(targwidth, len(targ.columns)) self.assertEqual(targwidth, len(res0.columns)) self.assertEqual(targwidth, len(res1.columns)) self.assertEqual(targlen, len(targ.index)) self.assertEqual(targlen, len(res0.index)) self.assertEqual(targlen, len(res1.index)) self.assertCountEqual(keys, targ.columns.names) self.assertCountEqual(keys, res0.columns.names) self.assertCountEqual(keys, res1.columns.names) assert_array_equal(targ.values, res0.values) assert_array_equal(targ.values, res1.values) assert_frame_equal(targ, res0) assert_frame_equal(targ, res1) def test__multi_spiketrains_to_dataframe__tuple_default(self): obj = tuple(fake_neo('Block', seed=i, n=3) for i in range(3)) res0 = ep.multi_spiketrains_to_dataframe(obj) objs = (iobj.list_children_by_class('SpikeTrain') for iobj in obj) objs = list(chain.from_iterable(objs)) targ = [ep.spiketrain_to_dataframe(iobj) for iobj in objs] targ = ep._sort_inds(pd.concat(targ, axis=1), axis=1) keys = ep._extract_neo_attrs_safe(objs[0], parents=True, child_first=True).keys() keys = list(keys) targwidth = len(objs) targlen = max(len(iobj) for iobj in objs) self.assertGreater(len(objs), 0) self.assertEqual(targwidth, len(targ.columns)) self.assertEqual(targwidth, len(res0.columns)) self.assertEqual(targlen, len(targ.index)) self.assertEqual(targlen, len(res0.index)) self.assertCountEqual(keys, targ.columns.names) self.assertCountEqual(keys, res0.columns.names) assert_array_equal(targ.values, res0.values) assert_frame_equal(targ, res0) def test__multi_spiketrains_to_dataframe__iter_default(self): obj = [fake_neo('Block', seed=i, n=3) for i in range(3)] res0 = ep.multi_spiketrains_to_dataframe(iter(obj)) objs = (iobj.list_children_by_class('SpikeTrain') for iobj in obj) objs = list(chain.from_iterable(objs)) targ = [ep.spiketrain_to_dataframe(iobj) for iobj in objs] targ = ep._sort_inds(pd.concat(targ, axis=1), axis=1) keys = ep._extract_neo_attrs_safe(objs[0], parents=True, child_first=True).keys() keys = list(keys) targwidth = len(objs) targlen = max(len(iobj) for iobj in objs) self.assertGreater(len(objs), 0) self.assertEqual(targwidth, len(targ.columns)) self.assertEqual(targwidth, len(res0.columns)) self.assertEqual(targlen, len(targ.index)) self.assertEqual(targlen, len(res0.index)) self.assertCountEqual(keys, targ.columns.names) self.assertCountEqual(keys, res0.columns.names) assert_array_equal(targ.values, res0.values) assert_frame_equal(targ, res0) def test__multi_spiketrains_to_dataframe__dict_default(self): obj = dict((i, fake_neo('Block', seed=i, n=3)) for i in range(3)) res0 = ep.multi_spiketrains_to_dataframe(obj) objs = (iobj.list_children_by_class('SpikeTrain') for iobj in obj.values()) objs = list(chain.from_iterable(objs)) targ = [ep.spiketrain_to_dataframe(iobj) for iobj in objs] targ = ep._sort_inds(pd.concat(targ, axis=1), axis=1) keys = ep._extract_neo_attrs_safe(objs[0], parents=True, child_first=True).keys() keys = list(keys) targwidth = len(objs) targlen = max(len(iobj) for iobj in objs) self.assertGreater(len(objs), 0) self.assertEqual(targwidth, len(targ.columns)) self.assertEqual(targwidth, len(res0.columns)) self.assertEqual(targlen, len(targ.index)) self.assertEqual(targlen, len(res0.index)) self.assertCountEqual(keys, targ.columns.names) self.assertCountEqual(keys, res0.columns.names) assert_array_equal(targ.values, res0.values) assert_frame_equal(targ, res0) @unittest.skipUnless(HAVE_PANDAS, 'requires pandas') class MultiEventsToDataframeTestCase(unittest.TestCase): def setUp(self): if hasattr(self, 'assertItemsEqual'): self.assertCountEqual = self.assertItemsEqual def test__multi_events_to_dataframe__single(self): obj = fake_neo('Event', seed=0, n=5) res0 = ep.multi_events_to_dataframe(obj) res1 = ep.multi_events_to_dataframe(obj, parents=False) res2 = ep.multi_events_to_dataframe(obj, parents=True) res3 = ep.multi_events_to_dataframe(obj, child_first=True) res4 = ep.multi_events_to_dataframe(obj, parents=False, child_first=True) res5 = ep.multi_events_to_dataframe(obj, parents=True, child_first=True) res6 = ep.multi_events_to_dataframe(obj, child_first=False) res7 = ep.multi_events_to_dataframe(obj, parents=False, child_first=False) res8 = ep.multi_events_to_dataframe(obj, parents=True, child_first=False) targ = ep.event_to_dataframe(obj) keys = ep._extract_neo_attrs_safe(obj, parents=True, child_first=True).keys() keys = list(keys) targwidth = 1 targlen = min(len(obj.times), len(obj.labels)) self.assertEqual(targwidth, len(targ.columns)) self.assertEqual(targwidth, len(res0.columns)) self.assertEqual(targwidth, len(res1.columns)) self.assertEqual(targwidth, len(res2.columns)) self.assertEqual(targwidth, len(res3.columns)) self.assertEqual(targwidth, len(res4.columns)) self.assertEqual(targwidth, len(res5.columns)) self.assertEqual(targwidth, len(res6.columns)) self.assertEqual(targwidth, len(res7.columns)) self.assertEqual(targwidth, len(res8.columns)) self.assertEqual(targlen, len(targ.index)) self.assertEqual(targlen, len(res0.index)) self.assertEqual(targlen, len(res1.index)) self.assertEqual(targlen, len(res2.index)) self.assertEqual(targlen, len(res3.index)) self.assertEqual(targlen, len(res4.index)) self.assertEqual(targlen, len(res5.index)) self.assertEqual(targlen, len(res6.index)) self.assertEqual(targlen, len(res7.index)) self.assertEqual(targlen, len(res8.index)) self.assertCountEqual(keys, targ.columns.names) self.assertCountEqual(keys, res0.columns.names) self.assertCountEqual(keys, res1.columns.names) self.assertCountEqual(keys, res2.columns.names) self.assertCountEqual(keys, res3.columns.names) self.assertCountEqual(keys, res4.columns.names) self.assertCountEqual(keys, res5.columns.names) self.assertCountEqual(keys, res6.columns.names) self.assertCountEqual(keys, res7.columns.names) self.assertCountEqual(keys, res8.columns.names) assert_array_equal(targ.values, res0.values) assert_array_equal(targ.values, res1.values) assert_array_equal(targ.values, res2.values) assert_array_equal(targ.values, res3.values) assert_array_equal(targ.values, res4.values) assert_array_equal(targ.values, res5.values) assert_array_equal(targ.values, res6.values) assert_array_equal(targ.values, res7.values) assert_array_equal(targ.values, res8.values) assert_frame_equal(targ, res0) assert_frame_equal(targ, res1) assert_frame_equal(targ, res2) assert_frame_equal(targ, res3) assert_frame_equal(targ, res4) assert_frame_equal(targ, res5) assert_frame_equal(targ, res6) assert_frame_equal(targ, res7) assert_frame_equal(targ, res8) def test__multi_events_to_dataframe__segment_default(self): obj = fake_neo('Segment', seed=0, n=5) res0 = ep.multi_events_to_dataframe(obj) objs = obj.events targ = [ep.event_to_dataframe(iobj) for iobj in objs] targ = ep._sort_inds(pd.concat(targ, axis=1), axis=1) keys = ep._extract_neo_attrs_safe(objs[0], parents=True, child_first=True).keys() keys = list(keys) targwidth = len(objs) targlen = [iobj.times[:min(len(iobj.times), len(iobj.labels))] for iobj in objs] targlen = len(np.unique(np.hstack(targlen))) self.assertGreater(len(objs), 0) self.assertEqual(targwidth, len(targ.columns)) self.assertEqual(targwidth, len(res0.columns)) self.assertEqual(targlen, len(targ.index)) self.assertEqual(targlen, len(res0.index)) self.assertCountEqual(keys, targ.columns.names) self.assertCountEqual(keys, res0.columns.names) assert_array_equal(targ.values, res0.values) assert_frame_equal(targ, res0) def test__multi_events_to_dataframe__block_noparents(self): obj = fake_neo('Block', seed=0, n=3) res0 = ep.multi_events_to_dataframe(obj, parents=False) res1 = ep.multi_events_to_dataframe(obj, parents=False, child_first=True) res2 = ep.multi_events_to_dataframe(obj, parents=False, child_first=False) objs = obj.list_children_by_class('Event') targ = [ep.event_to_dataframe(iobj, parents=False, child_first=True) for iobj in objs] targ = ep._sort_inds(pd.concat(targ, axis=1), axis=1) keys = ep._extract_neo_attrs_safe(objs[0], parents=False, child_first=True).keys() keys = list(keys) targwidth = len(objs) targlen = [iobj.times[:min(len(iobj.times), len(iobj.labels))] for iobj in objs] targlen = len(np.unique(np.hstack(targlen))) self.assertGreater(len(objs), 0) self.assertEqual(targwidth, len(targ.columns)) self.assertEqual(targwidth, len(res0.columns)) self.assertEqual(targwidth, len(res1.columns)) self.assertEqual(targwidth, len(res2.columns)) self.assertEqual(targlen, len(targ.index)) self.assertEqual(targlen, len(res0.index)) self.assertEqual(targlen, len(res1.index)) self.assertEqual(targlen, len(res2.index)) self.assertCountEqual(keys, targ.columns.names) self.assertCountEqual(keys, res0.columns.names) self.assertCountEqual(keys, res1.columns.names) self.assertCountEqual(keys, res2.columns.names) assert_array_equal(targ.values, res0.values) assert_array_equal(targ.values, res1.values) assert_array_equal(targ.values, res2.values) assert_frame_equal(targ, res0) assert_frame_equal(targ, res1) assert_frame_equal(targ, res2) def test__multi_events_to_dataframe__block_parents_childfirst(self): obj = fake_neo('Block', seed=0, n=3) res0 = ep.multi_events_to_dataframe(obj) res1 = ep.multi_events_to_dataframe(obj, parents=True) res2 = ep.multi_events_to_dataframe(obj, child_first=True) res3 = ep.multi_events_to_dataframe(obj, parents=True, child_first=True) objs = obj.list_children_by_class('Event') targ = [ep.event_to_dataframe(iobj, parents=True, child_first=True) for iobj in objs] targ = ep._sort_inds(pd.concat(targ, axis=1), axis=1) keys = ep._extract_neo_attrs_safe(objs[0], parents=True, child_first=True).keys() keys = list(keys) targwidth = len(objs) targlen = [iobj.times[:min(len(iobj.times), len(iobj.labels))] for iobj in objs] targlen = len(np.unique(np.hstack(targlen))) self.assertGreater(len(objs), 0) self.assertEqual(targwidth, len(targ.columns)) self.assertEqual(targwidth, len(res0.columns)) self.assertEqual(targwidth, len(res1.columns)) self.assertEqual(targwidth, len(res2.columns)) self.assertEqual(targwidth, len(res3.columns)) self.assertEqual(targlen, len(targ.index)) self.assertEqual(targlen, len(res0.index)) self.assertEqual(targlen, len(res1.index)) self.assertEqual(targlen, len(res2.index)) self.assertEqual(targlen, len(res3.index)) self.assertCountEqual(keys, targ.columns.names) self.assertCountEqual(keys, res0.columns.names) self.assertCountEqual(keys, res1.columns.names) self.assertCountEqual(keys, res2.columns.names) self.assertCountEqual(keys, res3.columns.names) assert_array_equal(targ.values, res0.values) assert_array_equal(targ.values, res1.values) assert_array_equal(targ.values, res2.values) assert_array_equal(targ.values, res3.values) assert_frame_equal(targ, res0) assert_frame_equal(targ, res1) assert_frame_equal(targ, res2) assert_frame_equal(targ, res3) def test__multi_events_to_dataframe__block_parents_parentfirst(self): obj = fake_neo('Block', seed=0, n=3) res0 = ep.multi_events_to_dataframe(obj, child_first=False) res1 = ep.multi_events_to_dataframe(obj, parents=True, child_first=False) objs = obj.list_children_by_class('Event') targ = [ep.event_to_dataframe(iobj, parents=True, child_first=False) for iobj in objs] targ = ep._sort_inds(pd.concat(targ, axis=1), axis=1) keys = ep._extract_neo_attrs_safe(objs[0], parents=True, child_first=False).keys() keys = list(keys) targwidth = len(objs) targlen = [iobj.times[:min(len(iobj.times), len(iobj.labels))] for iobj in objs] targlen = len(np.unique(np.hstack(targlen))) self.assertGreater(len(objs), 0) self.assertEqual(targwidth, len(targ.columns)) self.assertEqual(targwidth, len(res0.columns)) self.assertEqual(targwidth, len(res1.columns)) self.assertEqual(targlen, len(targ.index)) self.assertEqual(targlen, len(res0.index)) self.assertEqual(targlen, len(res1.index)) self.assertCountEqual(keys, targ.columns.names) self.assertCountEqual(keys, res0.columns.names) self.assertCountEqual(keys, res1.columns.names) assert_array_equal(targ.values, res0.values) assert_array_equal(targ.values, res1.values) assert_frame_equal(targ, res0) assert_frame_equal(targ, res1) def test__multi_events_to_dataframe__list_noparents(self): obj = [fake_neo('Block', seed=i, n=3) for i in range(3)] res0 = ep.multi_events_to_dataframe(obj, parents=False) res1 = ep.multi_events_to_dataframe(obj, parents=False, child_first=True) res2 = ep.multi_events_to_dataframe(obj, parents=False, child_first=False) objs = (iobj.list_children_by_class('Event') for iobj in obj) objs = list(chain.from_iterable(objs)) targ = [ep.event_to_dataframe(iobj, parents=False, child_first=True) for iobj in objs] targ = ep._sort_inds(pd.concat(targ, axis=1), axis=1) keys = ep._extract_neo_attrs_safe(objs[0], parents=False, child_first=True).keys() keys = list(keys) targwidth = len(objs) targlen = [iobj.times[:min(len(iobj.times), len(iobj.labels))] for iobj in objs] targlen = len(np.unique(np.hstack(targlen))) self.assertGreater(len(objs), 0) self.assertEqual(targwidth, len(targ.columns)) self.assertEqual(targwidth, len(res0.columns)) self.assertEqual(targwidth, len(res1.columns)) self.assertEqual(targwidth, len(res2.columns)) self.assertEqual(targlen, len(targ.index)) self.assertEqual(targlen, len(res0.index)) self.assertEqual(targlen, len(res1.index)) self.assertEqual(targlen, len(res2.index)) self.assertCountEqual(keys, targ.columns.names) self.assertCountEqual(keys, res0.columns.names) self.assertCountEqual(keys, res1.columns.names) self.assertCountEqual(keys, res2.columns.names) assert_array_equal(targ.values, res0.values) assert_array_equal(targ.values, res1.values) assert_array_equal(targ.values, res2.values) assert_frame_equal(targ, res0) assert_frame_equal(targ, res1) assert_frame_equal(targ, res2) def test__multi_events_to_dataframe__list_parents_childfirst(self): obj = [fake_neo('Block', seed=i, n=3) for i in range(3)] res0 = ep.multi_events_to_dataframe(obj) res1 = ep.multi_events_to_dataframe(obj, parents=True) res2 = ep.multi_events_to_dataframe(obj, child_first=True) res3 = ep.multi_events_to_dataframe(obj, parents=True, child_first=True) objs = (iobj.list_children_by_class('Event') for iobj in obj) objs = list(chain.from_iterable(objs)) targ = [ep.event_to_dataframe(iobj, parents=True, child_first=True) for iobj in objs] targ = ep._sort_inds(pd.concat(targ, axis=1), axis=1) keys = ep._extract_neo_attrs_safe(objs[0], parents=True, child_first=True).keys() keys = list(keys) targwidth = len(objs) targlen = [iobj.times[:min(len(iobj.times), len(iobj.labels))] for iobj in objs] targlen = len(np.unique(np.hstack(targlen))) self.assertGreater(len(objs), 0) self.assertEqual(targwidth, len(targ.columns)) self.assertEqual(targwidth, len(res0.columns)) self.assertEqual(targwidth, len(res1.columns)) self.assertEqual(targwidth, len(res2.columns)) self.assertEqual(targwidth, len(res3.columns)) self.assertEqual(targlen, len(targ.index)) self.assertEqual(targlen, len(res0.index)) self.assertEqual(targlen, len(res1.index)) self.assertEqual(targlen, len(res2.index)) self.assertEqual(targlen, len(res3.index)) self.assertCountEqual(keys, targ.columns.names) self.assertCountEqual(keys, res0.columns.names) self.assertCountEqual(keys, res1.columns.names) self.assertCountEqual(keys, res2.columns.names) self.assertCountEqual(keys, res3.columns.names) assert_array_equal(targ.values, res0.values) assert_array_equal(targ.values, res1.values) assert_array_equal(targ.values, res2.values) assert_array_equal(targ.values, res3.values) assert_frame_equal(targ, res0) assert_frame_equal(targ, res1) assert_frame_equal(targ, res2) assert_frame_equal(targ, res3) def test__multi_events_to_dataframe__list_parents_parentfirst(self): obj = [fake_neo('Block', seed=i, n=3) for i in range(3)] res0 = ep.multi_events_to_dataframe(obj, child_first=False) res1 = ep.multi_events_to_dataframe(obj, parents=True, child_first=False) objs = (iobj.list_children_by_class('Event') for iobj in obj) objs = list(chain.from_iterable(objs)) targ = [ep.event_to_dataframe(iobj, parents=True, child_first=False) for iobj in objs] targ = ep._sort_inds(pd.concat(targ, axis=1), axis=1) keys = ep._extract_neo_attrs_safe(objs[0], parents=True, child_first=False).keys() keys = list(keys) targwidth = len(objs) targlen = [iobj.times[:min(len(iobj.times), len(iobj.labels))] for iobj in objs] targlen = len(np.unique(np.hstack(targlen))) self.assertGreater(len(objs), 0) self.assertEqual(targwidth, len(targ.columns)) self.assertEqual(targwidth, len(res0.columns)) self.assertEqual(targwidth, len(res1.columns)) self.assertEqual(targlen, len(targ.index)) self.assertEqual(targlen, len(res0.index)) self.assertEqual(targlen, len(res1.index)) self.assertCountEqual(keys, targ.columns.names) self.assertCountEqual(keys, res0.columns.names) self.assertCountEqual(keys, res1.columns.names) assert_array_equal(targ.values, res0.values) assert_array_equal(targ.values, res1.values) assert_frame_equal(targ, res0) assert_frame_equal(targ, res1) def test__multi_events_to_dataframe__tuple_default(self): obj = tuple(fake_neo('Block', seed=i, n=3) for i in range(3)) res0 = ep.multi_events_to_dataframe(obj) objs = (iobj.list_children_by_class('Event') for iobj in obj) objs = list(chain.from_iterable(objs)) targ = [ep.event_to_dataframe(iobj) for iobj in objs] targ = ep._sort_inds(pd.concat(targ, axis=1), axis=1) keys = ep._extract_neo_attrs_safe(objs[0], parents=True, child_first=True).keys() keys = list(keys) targwidth = len(objs) targlen = [iobj.times[:min(len(iobj.times), len(iobj.labels))] for iobj in objs] targlen = len(np.unique(np.hstack(targlen))) self.assertGreater(len(objs), 0) self.assertEqual(targwidth, len(targ.columns)) self.assertEqual(targwidth, len(res0.columns)) self.assertEqual(targlen, len(targ.index)) self.assertEqual(targlen, len(res0.index)) self.assertCountEqual(keys, targ.columns.names) self.assertCountEqual(keys, res0.columns.names) assert_array_equal(targ.values, res0.values) assert_frame_equal(targ, res0) def test__multi_events_to_dataframe__iter_default(self): obj = [fake_neo('Block', seed=i, n=3) for i in range(3)] res0 = ep.multi_events_to_dataframe(iter(obj)) objs = (iobj.list_children_by_class('Event') for iobj in obj) objs = list(chain.from_iterable(objs)) targ = [ep.event_to_dataframe(iobj) for iobj in objs] targ = ep._sort_inds(pd.concat(targ, axis=1), axis=1) keys = ep._extract_neo_attrs_safe(objs[0], parents=True, child_first=True).keys() keys = list(keys) targwidth = len(objs) targlen = [iobj.times[:min(len(iobj.times), len(iobj.labels))] for iobj in objs] targlen = len(np.unique(np.hstack(targlen))) self.assertGreater(len(objs), 0) self.assertEqual(targwidth, len(targ.columns)) self.assertEqual(targwidth, len(res0.columns)) self.assertEqual(targlen, len(targ.index)) self.assertEqual(targlen, len(res0.index)) self.assertCountEqual(keys, targ.columns.names) self.assertCountEqual(keys, res0.columns.names) assert_array_equal(targ.values, res0.values) assert_frame_equal(targ, res0) def test__multi_events_to_dataframe__dict_default(self): obj = dict((i, fake_neo('Block', seed=i, n=3)) for i in range(3)) res0 = ep.multi_events_to_dataframe(obj) objs = (iobj.list_children_by_class('Event') for iobj in obj.values()) objs = list(chain.from_iterable(objs)) targ = [ep.event_to_dataframe(iobj) for iobj in objs] targ = ep._sort_inds(pd.concat(targ, axis=1), axis=1) keys = ep._extract_neo_attrs_safe(objs[0], parents=True, child_first=True).keys() keys = list(keys) targwidth = len(objs) targlen = [iobj.times[:min(len(iobj.times), len(iobj.labels))] for iobj in objs] targlen = len(np.unique(np.hstack(targlen))) self.assertGreater(len(objs), 0) self.assertEqual(targwidth, len(targ.columns)) self.assertEqual(targwidth, len(res0.columns)) self.assertEqual(targlen, len(targ.index)) self.assertEqual(targlen, len(res0.index)) self.assertCountEqual(keys, targ.columns.names) self.assertCountEqual(keys, res0.columns.names) assert_array_equal(targ.values, res0.values) assert_frame_equal(targ, res0) @unittest.skipUnless(HAVE_PANDAS, 'requires pandas') class MultiEpochsToDataframeTestCase(unittest.TestCase): def setUp(self): if hasattr(self, 'assertItemsEqual'): self.assertCountEqual = self.assertItemsEqual def test__multi_epochs_to_dataframe__single(self): obj = fake_neo('Epoch', seed=0, n=5) res0 = ep.multi_epochs_to_dataframe(obj) res1 = ep.multi_epochs_to_dataframe(obj, parents=False) res2 = ep.multi_epochs_to_dataframe(obj, parents=True) res3 = ep.multi_epochs_to_dataframe(obj, child_first=True) res4 = ep.multi_epochs_to_dataframe(obj, parents=False, child_first=True) res5 = ep.multi_epochs_to_dataframe(obj, parents=True, child_first=True) res6 = ep.multi_epochs_to_dataframe(obj, child_first=False) res7 = ep.multi_epochs_to_dataframe(obj, parents=False, child_first=False) res8 = ep.multi_epochs_to_dataframe(obj, parents=True, child_first=False) targ = ep.epoch_to_dataframe(obj) keys = ep._extract_neo_attrs_safe(obj, parents=True, child_first=True).keys() keys = list(keys) targwidth = 1 targlen = min(len(obj.times), len(obj.durations), len(obj.labels)) self.assertEqual(targwidth, len(targ.columns)) self.assertEqual(targwidth, len(res0.columns)) self.assertEqual(targwidth, len(res1.columns)) self.assertEqual(targwidth, len(res2.columns)) self.assertEqual(targwidth, len(res3.columns)) self.assertEqual(targwidth, len(res4.columns)) self.assertEqual(targwidth, len(res5.columns)) self.assertEqual(targwidth, len(res6.columns)) self.assertEqual(targwidth, len(res7.columns)) self.assertEqual(targwidth, len(res8.columns)) self.assertEqual(targlen, len(targ.index)) self.assertEqual(targlen, len(res0.index)) self.assertEqual(targlen, len(res1.index)) self.assertEqual(targlen, len(res2.index)) self.assertEqual(targlen, len(res3.index)) self.assertEqual(targlen, len(res4.index)) self.assertEqual(targlen, len(res5.index)) self.assertEqual(targlen, len(res6.index)) self.assertEqual(targlen, len(res7.index)) self.assertEqual(targlen, len(res8.index)) self.assertCountEqual(keys, targ.columns.names) self.assertCountEqual(keys, res0.columns.names) self.assertCountEqual(keys, res1.columns.names) self.assertCountEqual(keys, res2.columns.names) self.assertCountEqual(keys, res3.columns.names) self.assertCountEqual(keys, res4.columns.names) self.assertCountEqual(keys, res5.columns.names) self.assertCountEqual(keys, res6.columns.names) self.assertCountEqual(keys, res7.columns.names) self.assertCountEqual(keys, res8.columns.names) assert_array_equal(targ.values, res0.values) assert_array_equal(targ.values, res1.values) assert_array_equal(targ.values, res2.values) assert_array_equal(targ.values, res3.values) assert_array_equal(targ.values, res4.values) assert_array_equal(targ.values, res5.values) assert_array_equal(targ.values, res6.values) assert_array_equal(targ.values, res7.values) assert_array_equal(targ.values, res8.values) assert_frame_equal(targ, res0) assert_frame_equal(targ, res1) assert_frame_equal(targ, res2) assert_frame_equal(targ, res3) assert_frame_equal(targ, res4) assert_frame_equal(targ, res5) assert_frame_equal(targ, res6) assert_frame_equal(targ, res7) assert_frame_equal(targ, res8) def test__multi_epochs_to_dataframe__segment_default(self): obj = fake_neo('Segment', seed=0, n=5) res0 = ep.multi_epochs_to_dataframe(obj) objs = obj.epochs targ = [ep.epoch_to_dataframe(iobj) for iobj in objs] targ = ep._sort_inds(pd.concat(targ, axis=1), axis=1) keys = ep._extract_neo_attrs_safe(objs[0], parents=True, child_first=True).keys() keys = list(keys) targwidth = len(objs) targlen = [iobj.times[:min(len(iobj.times), len(iobj.durations), len(iobj.labels))] for iobj in objs] targlen = len(np.unique(np.hstack(targlen))) self.assertGreater(len(objs), 0) self.assertEqual(targwidth, len(targ.columns)) self.assertEqual(targwidth, len(res0.columns)) self.assertEqual(targlen, len(targ.index)) self.assertEqual(targlen, len(res0.index)) self.assertCountEqual(keys, targ.columns.names) self.assertCountEqual(keys, res0.columns.names) assert_array_equal(targ.values, res0.values) assert_frame_equal(targ, res0) def test__multi_epochs_to_dataframe__block_noparents(self): obj = fake_neo('Block', seed=0, n=3) res0 = ep.multi_epochs_to_dataframe(obj, parents=False) res1 = ep.multi_epochs_to_dataframe(obj, parents=False, child_first=True) res2 = ep.multi_epochs_to_dataframe(obj, parents=False, child_first=False) objs = obj.list_children_by_class('Epoch') targ = [ep.epoch_to_dataframe(iobj, parents=False, child_first=True) for iobj in objs] targ = ep._sort_inds(pd.concat(targ, axis=1), axis=1) keys = ep._extract_neo_attrs_safe(objs[0], parents=False, child_first=True).keys() keys = list(keys) targwidth = len(objs) targlen = [iobj.times[:min(len(iobj.times), len(iobj.durations), len(iobj.labels))] for iobj in objs] targlen = len(np.unique(np.hstack(targlen))) self.assertGreater(len(objs), 0) self.assertEqual(targwidth, len(targ.columns)) self.assertEqual(targwidth, len(res0.columns)) self.assertEqual(targwidth, len(res1.columns)) self.assertEqual(targwidth, len(res2.columns)) self.assertEqual(targlen, len(targ.index)) self.assertEqual(targlen, len(res0.index)) self.assertEqual(targlen, len(res1.index)) self.assertEqual(targlen, len(res2.index)) self.assertCountEqual(keys, targ.columns.names) self.assertCountEqual(keys, res0.columns.names) self.assertCountEqual(keys, res1.columns.names) self.assertCountEqual(keys, res2.columns.names) assert_array_equal(targ.values, res0.values) assert_array_equal(targ.values, res1.values) assert_array_equal(targ.values, res2.values) assert_frame_equal(targ, res0) assert_frame_equal(targ, res1) assert_frame_equal(targ, res2) def test__multi_epochs_to_dataframe__block_parents_childfirst(self): obj = fake_neo('Block', seed=0, n=3) res0 = ep.multi_epochs_to_dataframe(obj) res1 = ep.multi_epochs_to_dataframe(obj, parents=True) res2 = ep.multi_epochs_to_dataframe(obj, child_first=True) res3 = ep.multi_epochs_to_dataframe(obj, parents=True, child_first=True) objs = obj.list_children_by_class('Epoch') targ = [ep.epoch_to_dataframe(iobj, parents=True, child_first=True) for iobj in objs] targ = ep._sort_inds(pd.concat(targ, axis=1), axis=1) keys = ep._extract_neo_attrs_safe(objs[0], parents=True, child_first=True).keys() keys = list(keys) targwidth = len(objs) targlen = [iobj.times[:min(len(iobj.times), len(iobj.durations), len(iobj.labels))] for iobj in objs] targlen = len(np.unique(np.hstack(targlen))) self.assertGreater(len(objs), 0) self.assertEqual(targwidth, len(targ.columns)) self.assertEqual(targwidth, len(res0.columns)) self.assertEqual(targwidth, len(res1.columns)) self.assertEqual(targwidth, len(res2.columns)) self.assertEqual(targwidth, len(res3.columns)) self.assertEqual(targlen, len(targ.index)) self.assertEqual(targlen, len(res0.index)) self.assertEqual(targlen, len(res1.index)) self.assertEqual(targlen, len(res2.index)) self.assertEqual(targlen, len(res3.index)) self.assertCountEqual(keys, targ.columns.names) self.assertCountEqual(keys, res0.columns.names) self.assertCountEqual(keys, res1.columns.names) self.assertCountEqual(keys, res2.columns.names) self.assertCountEqual(keys, res3.columns.names) assert_array_equal(targ.values, res0.values) assert_array_equal(targ.values, res1.values) assert_array_equal(targ.values, res2.values) assert_array_equal(targ.values, res3.values) assert_frame_equal(targ, res0) assert_frame_equal(targ, res1) assert_frame_equal(targ, res2) assert_frame_equal(targ, res3) def test__multi_epochs_to_dataframe__block_parents_parentfirst(self): obj = fake_neo('Block', seed=0, n=3) res0 = ep.multi_epochs_to_dataframe(obj, child_first=False) res1 = ep.multi_epochs_to_dataframe(obj, parents=True, child_first=False) objs = obj.list_children_by_class('Epoch') targ = [ep.epoch_to_dataframe(iobj, parents=True, child_first=False) for iobj in objs] targ = ep._sort_inds(pd.concat(targ, axis=1), axis=1) keys = ep._extract_neo_attrs_safe(objs[0], parents=True, child_first=False).keys() keys = list(keys) targwidth = len(objs) targlen = [iobj.times[:min(len(iobj.times), len(iobj.durations), len(iobj.labels))] for iobj in objs] targlen = len(np.unique(np.hstack(targlen))) self.assertGreater(len(objs), 0) self.assertEqual(targwidth, len(targ.columns)) self.assertEqual(targwidth, len(res0.columns)) self.assertEqual(targwidth, len(res1.columns)) self.assertEqual(targlen, len(targ.index)) self.assertEqual(targlen, len(res0.index)) self.assertEqual(targlen, len(res1.index)) self.assertCountEqual(keys, targ.columns.names) self.assertCountEqual(keys, res0.columns.names) self.assertCountEqual(keys, res1.columns.names) assert_array_equal(targ.values, res0.values) assert_array_equal(targ.values, res1.values) assert_frame_equal(targ, res0) assert_frame_equal(targ, res1) def test__multi_epochs_to_dataframe__list_noparents(self): obj = [fake_neo('Block', seed=i, n=3) for i in range(3)] res0 = ep.multi_epochs_to_dataframe(obj, parents=False) res1 = ep.multi_epochs_to_dataframe(obj, parents=False, child_first=True) res2 = ep.multi_epochs_to_dataframe(obj, parents=False, child_first=False) objs = (iobj.list_children_by_class('Epoch') for iobj in obj) objs = list(chain.from_iterable(objs)) targ = [ep.epoch_to_dataframe(iobj, parents=False, child_first=True) for iobj in objs] targ = ep._sort_inds(pd.concat(targ, axis=1), axis=1) keys = ep._extract_neo_attrs_safe(objs[0], parents=False, child_first=True).keys() keys = list(keys) targwidth = len(objs) targlen = [iobj.times[:min(len(iobj.times), len(iobj.durations), len(iobj.labels))] for iobj in objs] targlen = len(np.unique(np.hstack(targlen))) self.assertGreater(len(objs), 0) self.assertEqual(targwidth, len(targ.columns)) self.assertEqual(targwidth, len(res0.columns)) self.assertEqual(targwidth, len(res1.columns)) self.assertEqual(targwidth, len(res2.columns)) self.assertEqual(targlen, len(targ.index)) self.assertEqual(targlen, len(res0.index)) self.assertEqual(targlen, len(res1.index)) self.assertEqual(targlen, len(res2.index)) self.assertCountEqual(keys, targ.columns.names) self.assertCountEqual(keys, res0.columns.names) self.assertCountEqual(keys, res1.columns.names) self.assertCountEqual(keys, res2.columns.names) assert_array_equal(targ.values, res0.values) assert_array_equal(targ.values, res1.values) assert_array_equal(targ.values, res2.values) assert_frame_equal(targ, res0) assert_frame_equal(targ, res1) assert_frame_equal(targ, res2) def test__multi_epochs_to_dataframe__list_parents_childfirst(self): obj = [fake_neo('Block', seed=i, n=3) for i in range(3)] res0 = ep.multi_epochs_to_dataframe(obj) res1 = ep.multi_epochs_to_dataframe(obj, parents=True) res2 = ep.multi_epochs_to_dataframe(obj, child_first=True) res3 = ep.multi_epochs_to_dataframe(obj, parents=True, child_first=True) objs = (iobj.list_children_by_class('Epoch') for iobj in obj) objs = list(chain.from_iterable(objs)) targ = [ep.epoch_to_dataframe(iobj, parents=True, child_first=True) for iobj in objs] targ = ep._sort_inds(pd.concat(targ, axis=1), axis=1) keys = ep._extract_neo_attrs_safe(objs[0], parents=True, child_first=True).keys() keys = list(keys) targwidth = len(objs) targlen = [iobj.times[:min(len(iobj.times), len(iobj.durations), len(iobj.labels))] for iobj in objs] targlen = len(np.unique(np.hstack(targlen))) self.assertGreater(len(objs), 0) self.assertEqual(targwidth, len(targ.columns)) self.assertEqual(targwidth, len(res0.columns)) self.assertEqual(targwidth, len(res1.columns)) self.assertEqual(targwidth, len(res2.columns)) self.assertEqual(targwidth, len(res3.columns)) self.assertEqual(targlen, len(targ.index)) self.assertEqual(targlen, len(res0.index)) self.assertEqual(targlen, len(res1.index)) self.assertEqual(targlen, len(res2.index)) self.assertEqual(targlen, len(res3.index)) self.assertCountEqual(keys, targ.columns.names) self.assertCountEqual(keys, res0.columns.names) self.assertCountEqual(keys, res1.columns.names) self.assertCountEqual(keys, res2.columns.names) self.assertCountEqual(keys, res3.columns.names) assert_array_equal(targ.values, res0.values) assert_array_equal(targ.values, res1.values) assert_array_equal(targ.values, res2.values) assert_array_equal(targ.values, res3.values) assert_frame_equal(targ, res0) assert_frame_equal(targ, res1) assert_frame_equal(targ, res2) assert_frame_equal(targ, res3) def test__multi_epochs_to_dataframe__list_parents_parentfirst(self): obj = [fake_neo('Block', seed=i, n=3) for i in range(3)] res0 = ep.multi_epochs_to_dataframe(obj, child_first=False) res1 = ep.multi_epochs_to_dataframe(obj, parents=True, child_first=False) objs = (iobj.list_children_by_class('Epoch') for iobj in obj) objs = list(chain.from_iterable(objs)) targ = [ep.epoch_to_dataframe(iobj, parents=True, child_first=False) for iobj in objs] targ = ep._sort_inds(pd.concat(targ, axis=1), axis=1) keys = ep._extract_neo_attrs_safe(objs[0], parents=True, child_first=False).keys() keys = list(keys) targwidth = len(objs) targlen = [iobj.times[:min(len(iobj.times), len(iobj.durations), len(iobj.labels))] for iobj in objs] targlen = len(np.unique(np.hstack(targlen))) self.assertGreater(len(objs), 0) self.assertEqual(targwidth, len(targ.columns)) self.assertEqual(targwidth, len(res0.columns)) self.assertEqual(targwidth, len(res1.columns)) self.assertEqual(targlen, len(targ.index)) self.assertEqual(targlen, len(res0.index)) self.assertEqual(targlen, len(res1.index)) self.assertCountEqual(keys, targ.columns.names) self.assertCountEqual(keys, res0.columns.names) self.assertCountEqual(keys, res1.columns.names) assert_array_equal(targ.values, res0.values) assert_array_equal(targ.values, res1.values) assert_frame_equal(targ, res0) assert_frame_equal(targ, res1) def test__multi_epochs_to_dataframe__tuple_default(self): obj = tuple(fake_neo('Block', seed=i, n=3) for i in range(3)) res0 = ep.multi_epochs_to_dataframe(obj) objs = (iobj.list_children_by_class('Epoch') for iobj in obj) objs = list(chain.from_iterable(objs)) targ = [ep.epoch_to_dataframe(iobj) for iobj in objs] targ = ep._sort_inds(pd.concat(targ, axis=1), axis=1) keys = ep._extract_neo_attrs_safe(objs[0], parents=True, child_first=True).keys() keys = list(keys) targwidth = len(objs) targlen = [iobj.times[:min(len(iobj.times), len(iobj.durations), len(iobj.labels))] for iobj in objs] targlen = len(np.unique(np.hstack(targlen))) self.assertGreater(len(objs), 0) self.assertEqual(targwidth, len(targ.columns)) self.assertEqual(targwidth, len(res0.columns)) self.assertEqual(targlen, len(targ.index)) self.assertEqual(targlen, len(res0.index)) self.assertCountEqual(keys, targ.columns.names) self.assertCountEqual(keys, res0.columns.names) assert_array_equal(targ.values, res0.values) assert_frame_equal(targ, res0) def test__multi_epochs_to_dataframe__iter_default(self): obj = [fake_neo('Block', seed=i, n=3) for i in range(3)] res0 = ep.multi_epochs_to_dataframe(iter(obj)) objs = (iobj.list_children_by_class('Epoch') for iobj in obj) objs = list(chain.from_iterable(objs)) targ = [ep.epoch_to_dataframe(iobj) for iobj in objs] targ = ep._sort_inds(pd.concat(targ, axis=1), axis=1) keys = ep._extract_neo_attrs_safe(objs[0], parents=True, child_first=True).keys() keys = list(keys) targwidth = len(objs) targlen = [iobj.times[:min(len(iobj.times), len(iobj.durations), len(iobj.labels))] for iobj in objs] targlen = len(np.unique(np.hstack(targlen))) self.assertGreater(len(objs), 0) self.assertEqual(targwidth, len(targ.columns)) self.assertEqual(targwidth, len(res0.columns)) self.assertEqual(targlen, len(targ.index)) self.assertEqual(targlen, len(res0.index)) self.assertCountEqual(keys, targ.columns.names) self.assertCountEqual(keys, res0.columns.names) assert_array_equal(targ.values, res0.values) assert_frame_equal(targ, res0) def test__multi_epochs_to_dataframe__dict_default(self): obj = dict((i, fake_neo('Block', seed=i, n=3)) for i in range(3)) res0 = ep.multi_epochs_to_dataframe(obj) objs = (iobj.list_children_by_class('Epoch') for iobj in obj.values()) objs = list(chain.from_iterable(objs)) targ = [ep.epoch_to_dataframe(iobj) for iobj in objs] targ = ep._sort_inds(pd.concat(targ, axis=1), axis=1) keys = ep._extract_neo_attrs_safe(objs[0], parents=True, child_first=True).keys() keys = list(keys) targwidth = len(objs) targlen = [iobj.times[:min(len(iobj.times), len(iobj.durations), len(iobj.labels))] for iobj in objs] targlen = len(np.unique(np.hstack(targlen))) self.assertGreater(len(objs), 0) self.assertEqual(targwidth, len(targ.columns)) self.assertEqual(targwidth, len(res0.columns)) self.assertEqual(targlen, len(targ.index)) self.assertEqual(targlen, len(res0.index)) self.assertCountEqual(keys, targ.columns.names) self.assertCountEqual(keys, res0.columns.names) assert_array_equal(targ.values, res0.values) assert_frame_equal(targ, res0) @unittest.skipUnless(HAVE_PANDAS, 'requires pandas') class SliceSpiketrainTestCase(unittest.TestCase): def setUp(self): obj = [fake_neo('SpikeTrain', seed=i, n=3) for i in range(10)] self.obj = ep.multi_spiketrains_to_dataframe(obj) def test_single_none(self): targ_start = self.obj.columns.get_level_values('t_start').values targ_stop = self.obj.columns.get_level_values('t_stop').values res0 = ep.slice_spiketrain(self.obj) res1 = ep.slice_spiketrain(self.obj, t_start=None) res2 = ep.slice_spiketrain(self.obj, t_stop=None) res3 = ep.slice_spiketrain(self.obj, t_start=None, t_stop=None) res0_start = res0.columns.get_level_values('t_start').values res1_start = res1.columns.get_level_values('t_start').values res2_start = res2.columns.get_level_values('t_start').values res3_start = res3.columns.get_level_values('t_start').values res0_stop = res0.columns.get_level_values('t_stop').values res1_stop = res1.columns.get_level_values('t_stop').values res2_stop = res2.columns.get_level_values('t_stop').values res3_stop = res3.columns.get_level_values('t_stop').values targ = self.obj self.assertFalse(res0 is targ) self.assertFalse(res1 is targ) self.assertFalse(res2 is targ) self.assertFalse(res3 is targ) assert_frame_equal(targ, res0) assert_frame_equal(targ, res1) assert_frame_equal(targ, res2) assert_frame_equal(targ, res3) assert_array_equal(targ_start, res0_start) assert_array_equal(targ_start, res1_start) assert_array_equal(targ_start, res2_start) assert_array_equal(targ_start, res3_start) assert_array_equal(targ_stop, res0_stop) assert_array_equal(targ_stop, res1_stop) assert_array_equal(targ_stop, res2_stop) assert_array_equal(targ_stop, res3_stop) def test_single_t_start(self): targ_start = .0001 targ_stop = self.obj.columns.get_level_values('t_stop').values res0 = ep.slice_spiketrain(self.obj, t_start=targ_start) res1 = ep.slice_spiketrain(self.obj, t_start=targ_start, t_stop=None) res0_start = res0.columns.get_level_values('t_start').unique().tolist() res1_start = res1.columns.get_level_values('t_start').unique().tolist() res0_stop = res0.columns.get_level_values('t_stop').values res1_stop = res1.columns.get_level_values('t_stop').values targ = self.obj.values targ[targ < targ_start] = np.nan self.assertFalse(res0 is targ) self.assertFalse(res1 is targ) assert_array_equal(targ, res0.values) assert_array_equal(targ, res1.values) self.assertEqual([targ_start], res0_start) self.assertEqual([targ_start], res1_start)
assert_array_equal(targ_stop, res0_stop)
numpy.testing.utils.assert_array_equal
# Authors: <NAME> <<EMAIL>> # License: TBC import numpy as np class EventOrder(object): def __init__(self, ordering=None, n_biomarkers=None, score=None): super(EventOrder, self).__init__() if ordering is None and n_biomarkers is None: raise ValueError('EventOrder __init__ takes one arguement,' ' zero given') if ordering is None: self.ordering = np.arange(n_biomarkers) np.random.shuffle(self.ordering) self.n_biomarkers = n_biomarkers else: self.ordering = ordering self.n_biomarkers = ordering.shape[0] self.score = score def score_ordering(self, prob_mat): k = prob_mat.shape[1]+1 p_perm = self.calc_perm_matrix(prob_mat) likelihood = np.sum(np.log(np.sum((1./k)*p_perm, 1)+1e-250)) self.score = likelihood return likelihood def calc_indiv_likelihoods(self, prob_mat): k = prob_mat.shape[1]+1 p_perm = self.calc_perm_matrix(prob_mat) likelihoods = np.log(np.sum((1./k)*p_perm, 1)+1e-250) return likelihoods def calc_perm_matrix(self, prob_mat): event_order = self.ordering p_yes = np.array(prob_mat[:, event_order, 1]) p_no = np.array(prob_mat[:, event_order, 0]) k = prob_mat.shape[1]+1 p_perm = np.zeros((prob_mat.shape[0], k)) for i in range(k): p_perm[:, i] = np.prod(p_yes[:, :i], 1)*np.prod(p_no[:, i:k-1], 1) return p_perm def stage_data(self, prob_mat): event_order = self.ordering p_yes = np.array(prob_mat[:, event_order, 1]) p_no = np.array(prob_mat[:, event_order, 0]) n_particp, n_biomarkers = p_yes.shape k = n_biomarkers+1 stage_likelihoods = np.empty((n_particp, n_biomarkers+1)) for i in range(k): stage_likelihoods[:, i] = np.prod(p_yes[:, :i], 1)*
np.prod(p_no[:, i:n_biomarkers], 1)
numpy.prod
"""62-make-diffusionmaps-and-geometricharmonicsinterpolator-compatible-with-scikit-learn-api Unit test for the Geometric Harmonics module. """ import unittest import diffusion_maps as legacy_dmap import matplotlib.pyplot as plt import numpy as np from sklearn.datasets import make_swiss_roll from sklearn.model_selection import ParameterGrid from sklearn.utils.estimator_checks import check_estimator from datafold.dynfold.outofsample import ( GeometricHarmonicsInterpolator, LaplacianPyramidsInterpolator, MultiScaleGeometricHarmonicsInterpolator, ) from datafold.dynfold.tests.helper import * from datafold.pcfold.distance import IS_IMPORTED_RDIST from datafold.pcfold.kernels import DmapKernelFixed, GaussianKernel def plot_scatter(points: np.ndarray, values: np.ndarray, **kwargs) -> None: title = kwargs.pop("title", None) if title: plt.title(title) plt.scatter( points[:, 0], points[:, 1], c=values, marker="o", rasterized=True, s=2.5, **kwargs, ) cb = plt.colorbar() cb.set_clim([np.min(values), np.max(values)]) cb.set_ticks(np.linspace(np.min(values), np.max(values), 5)) plt.xlim([-4, 4]) plt.ylim([-4, 4]) plt.xlabel("$x$") plt.ylabel("$y$") plt.gca().set_aspect("equal") def f(points: np.ndarray) -> np.ndarray: """Function to interpolate.""" # return np.ones(points.shape[0]) # return np.arange(points.shape[0]) return np.sin(
np.linalg.norm(points, axis=-1)
numpy.linalg.norm
"""Use GTR to model distribution of future viral sequences """ import numpy as np from scipy.linalg import expm class GTRSubstitutionModel: """GTR Substitution model to model distribution of future viral sequences """ def __init__(self, piA, piC, piG, piT, rAC, rAG, rAT, rCG, rCT, rGT, mu, t): self.piA = piA self.piC = piC self.piG = piG self.piT = piT self.rAC = rAC self.rAG = rAG self.rAT = rAT self.rCG = rCG self.rCT = rCT self.rGT = rGT self.mu = mu self.t = t self.Q = self._construct_rateQ() self.P = self._construct_P() def _construct_rateQ(self): """Computes transition rate matrix Q, given base frequencies and transition rates under GTR model (Tavaré 1986). """ beta = 1 / (2*(self.piA * (self.rAC*self.piC + self.rAG*self.piG + self.rAT*self.piT) + self.piC * (self.rCG*self.piG + self.rCT*self.piT) + self.piG*self.piT)) Q =
np.array( [ [-(self.rAC*self.piC + self.rAG*self.piG + self.rAT*self.piT), self.rAC*self.piC, self.rAG*self.piG, self.rAT*self.piT], [self.rAC*self.piA, -(self.rAC*self.piA + self.rCG*self.piG + self.rCT*self.piT), self.rCG*self.piG, self.rCT*self.piT], [self.rAG*self.piA, self.rCG*self.piC, -(self.rAG*self.piA + self.rCG*self.piC + self.rGT*self.piT), self.rGT*self.piT], [self.rAT*self.piA, self.rCT*self.piC, self.rGT*self.piG, -(self.rAT*self.piA + self.rCT*self.piC + self.rGT*self.piG)] ])
numpy.array
import sys import warnings import numpy as np from tempfile import mkdtemp from astropy.stats import sigma_clipped_stats from sfft.utils.pyAstroMatic.PYSEx import PY_SEx from sfft.utils.HoughDetection import Hough_Detection __author__ = "<NAME> <<EMAIL>>" __version__ = "v1.0" """ # MeLOn Notes # @ Point-Source Extractor # A) A PSFEx suggested Morphological Classifier, based on a 2D distribution diagram # FLUX_RADIUS [X-axis] - MAG_AUTO [Y-axis], A universal but naive approach. # We first draw all isolated sources on the plane, and the typical distribution will form a 'Y' shape. # A nearly vertical branch, A nearly horizontal branch and their cross with a tail at faint side. # # Here I give rough conclusions with comments, note I have compared with Legacy Survety Tractor Catalog. # a. The point sources would be distributed around the nearly vertical stright line. {vertical branch} # NOTE At the faint end, point sources no longer cling to the line, being diffuse in the cross and tail. # b. Close to the bright end of the stright-line are saturated or slight-nonlinear sources, with a deviated direction. # c. The right side of the line are typically extended structure, mainly including various galaxies. {horizontal branch} # NOTE At the faint end, likewise, extended sources also exist, being diffuse in the cross and tail. # d. Scattering points are located at very left side of the line, they are generally hotpix, cosmic-ray or # some small-scale artifacts. Keep in mind, they are typically outlier-like and away from the cross and tail. # # METHOD: For simplicity, we only crudely divide the diagram into 3 regions, w.r.t. the vetical line. # they are, Radius-Mid (FR-M), Radius-Large (FR-L) and Radius-Small (FR-S). # # B) 3 hierarchic groups # > Good Sources: # + NOT in FR-S region (union of FR-M & FR-L) # NOTE Good Sources is consist of the vertical & horizontal branches with their cross (not the tail), # which is roughly equivalent to the set of REAL Point-Sources & Extended Sources # with rejection the samples in the tail (at faint & small-radius end). # NOTE Good Sources are commonly used as FITTING Candidates in Image Subtraction. # It is acceptable to lose the samples in the tail. # # >> {subgroup} Point Sources: # + Restricted into FR-M Region ||| Should be located around the Hough-Line # + Basically Circular-Shape ||| PsfEx-ELLIPTICITY = (A-B) / (A+B) < PS_ELLIPThresh # NOTE At cross region, this identification criteria mis-include some extended source # On the flip side, some REAL PointSource samples are missing in the tail. # NOTE Point Sources are usually employed as FWHM Estimator. # NOTE We may lossen PS_ELLIPThresh if psf itself is significantly asymmetric (e.g. tracking problem). # # >>> {sub-subgroup} High-SNR Point Sources # + SNR_WIN > HPS_SNRThresh, then reject the bright end [typically, 15% (HPS_Reject)] point-sources. # ++ If remaining sources are less than 30 (HPS_NumLowerLimit), # Simply Use the point-sources with highest SNR_WIN. # NOTE In Common, this subset is for Flux-Calibration & Building PSF Model. # NOTE The defult HPS_SNRThresh = 100 might be too high, you may loosen it to # ~ 15 to make sure you have enough samples, especially for psf modeling. # # @ Remarks on the HPS BrightEnd-Cutoff # Assume SExtractor received precise SATURATE, saturated sources should be fully rejected via FLAG constrain. # However, in practice, it's hard to fullfill this condition strictly, that is why we design a simple BrightEnd-Cutoff # to prevent the set from such contaminations. Compared with mentioned usage of GS & PS, that of HPS is more # vulnerable to such situation. FLUX-Calibtation and Building PSF-Model do not require sample completeness, but # likely to be sensitive to the sources with appreiable non-linear response. # # C) Additional WARNINGS # a. This extracor is ONLY designed for sparse field (isolated sources dominated case). # We just take these isloated & non-saturated sources (FLAGS=0) into account in this function. # # b. We employ Hough Transformation to detect the Stright-Line feature in the image, # naturally sampled from the raw scatter diagram. But note such diagram makes sense # only if we could detect enough sources (typically > 200) in the given image. # NOTE Reversed axes employed --- MAG_AUTO [X-axis] - FLUX_RADIUS [Y-axis]. """ class Hough_MorphClassifier: def MakeCatalog(FITS_obj, GAIN_KEY='GAIN', SATUR_KEY='SATURATE', \ BACK_TYPE='AUTO', BACK_VALUE='0.0', BACK_SIZE=64, BACK_FILTERSIZE=3, \ DETECT_THRESH=2.0, DETECT_MINAREA=5, DETECT_MAXAREA=0, \ BACKPHOTO_TYPE='LOCAL', CHECKIMAGE_TYPE='NONE', \ AddRD=False, BoundarySIZE=30, AddSNR=True): # * Trigger SExtractor # NOTE: it is a compromise to adopt XY rather than XYWIN for both point and extended sources. # NOTE: only takes Isolated & Non-Saturated sources (FLAGS = 0) into account. # FIXME: one may need to tune DETECT_THRESH & DETECT_MINAREA for specific program. PL = ['X_IMAGE', 'Y_IMAGE', 'FLUX_AUTO', 'FLUXERR_AUTO', 'MAG_AUTO', 'MAGERR_AUTO', \ 'FLAGS', 'FLUX_RADIUS', 'FWHM_IMAGE', 'A_IMAGE', 'B_IMAGE'] if AddSNR: PL.append('SNR_WIN') PYSEX_OP = PY_SEx.PS(FITS_obj=FITS_obj, PL=PL, GAIN_KEY=GAIN_KEY, SATUR_KEY=SATUR_KEY, \ BACK_TYPE=BACK_TYPE, BACK_VALUE=BACK_VALUE, BACK_SIZE=BACK_SIZE, BACK_FILTERSIZE=BACK_FILTERSIZE, \ DETECT_THRESH=DETECT_THRESH, DETECT_MINAREA=DETECT_MINAREA, DETECT_MAXAREA=DETECT_MAXAREA, \ BACKPHOTO_TYPE=BACKPHOTO_TYPE, CHECKIMAGE_TYPE=CHECKIMAGE_TYPE, AddRD=AddRD, ONLY_FLAG0=True, \ XBoundary=BoundarySIZE, YBoundary=BoundarySIZE, MDIR=None) return PYSEX_OP def Classifier(AstSEx, Hough_FRLowerLimit=0.1, Hough_res=0.05, Hough_count_thresh=1, Hough_peakclip=0.7, \ LineTheta_thresh=0.2, BeltHW=0.2, PS_ELLIPThresh=0.3, Return_HPS=False, \ HPS_SNRThresh=100.0, HPS_Reject=0.15, HPS_NumLowerLimit=30): A_IMAGE = np.array(AstSEx['A_IMAGE']) B_IMAGE = np.array(AstSEx['B_IMAGE']) MA_FR = np.array([AstSEx['MAG_AUTO'], AstSEx['FLUX_RADIUS']]).T ELLIP = (A_IMAGE - B_IMAGE)/(A_IMAGE + B_IMAGE) MASK_ELLIP = ELLIP < PS_ELLIPThresh # * Trigger Hough Dectection # Use Hough-Transformation detect the Point-Source-Line from the scatter points in # diagram X [MAG_AUTO] - Y [FLUX_RADIUS], which is a nearly-horizon stright line. # ** Remarks on the Mask for Hough Transformation # It is s useful to make restriction on FLUX_RADIUS (R) of the scatter points for hough detection. # I. Exclude the sources with unusally large R > 20.0 can speed up the process. # II. The sources with small R (typically ~ 0.5) are likely hot pixels or cosmic rays. # The parameter Hough_FRLowerLimit is the lower bound of FLUX_RATIO for Hough transformation. # Setting a proper lower bound can avoid to detect some line features by chance, # which are not contributed from point sources but resides in the small-FLUX_RATIO region. # NOTE: One need to choose a proper Hough_FRLowerLimit according to the fact if the image is # under/well/over-sampling (depending on the instrumental configuration and typical seeing conditions) # recommended values of Hough_FRLowerLimit range from 0.1 to 1.0 MA, FR = MA_FR[:, 0], MA_FR[:, 1] MA_MID = np.nanmedian(MA) Hmask = np.logical_and.reduce((FR > Hough_FRLowerLimit, FR < 10.0, MA > MA_MID-7.0, MA < MA_MID+7.0)) HDOP = Hough_Detection.HD(XY_obj=MA_FR, Hmask=Hmask, res=Hough_res, \ count_thresh=Hough_count_thresh, peakclip=Hough_peakclip) ThetaPeaks, RhoPeaks, ScaLineDIS = HDOP[1], HDOP[2], HDOP[4] # NOTE: consider the strongest nearly-horizon peak as the one associated with the point source feature. Avmask = np.abs(ThetaPeaks) < LineTheta_thresh AvIDX = np.where(Avmask)[0] if len(AvIDX) == 0: Horindex = None warnings.warn('MeLOn WARNING: NO nearly-horizon peak as Point-Source-Line!') if len(AvIDX) == 1: Horindex = AvIDX[0] print('MeLOn CheckPoint: the UNIQUE nearly-horizon peak as Point-Source-Line!') if len(AvIDX) > 1: Horindex = np.min(AvIDX) warnings.warn('MeLOn WARNING: there are MULTIPLE nearly-horizon peaks and use the STRONGEST as Point-Source-Line!') if Horindex is not None: HorThetaPeak = ThetaPeaks[Horindex] HorRhoPeak = RhoPeaks[Horindex] HorScaLineDIS = ScaLineDIS[:, Horindex] print('MeLOn CheckPoint: the Hough-Detected Point-Source-Line is characterized by (%s, %s)' \ %(HorThetaPeak, HorRhoPeak)) # NOTE: Note that HorThetaPeak is around 0, thus cos(HorThetaPeak) around 1 then >> 0, # thus above-line/FRL region is x_above * sin(HorThetaPeak) + y_above * cos(HorRhoPeak) > rho. MASK_FRM = HorScaLineDIS < BeltHW MASK_FRL = MA_FR[:, 0] * np.sin(HorThetaPeak) + MA_FR[:, 1] * np.cos(HorThetaPeak) > HorRhoPeak MASK_FRL = np.logical_and(MASK_FRL, ~MASK_FRM) else: # NOTE: If we have enough samples, using the bright & small-FR subgroup might be # more appropriate for the estimate. However, it is quite tricky to find a generic # reliable way to find the point sources when the Hough Transformation doesn't work. # Here we only simply reject the samples with low significance. BPmask = AstSEx['MAGERR_AUTO'] < 0.2 Rmid = sigma_clipped_stats(MA_FR[BPmask, 1], sigma=3.0, maxiters=5)[1] MASK_FRM = np.abs(MA_FR[:, 1] - Rmid) < BeltHW MASK_FRL = MA_FR[:, 1] - Rmid > BeltHW warnings.warn('MeLOn WARNING: the STANDBY approach is actived to determine the FRM region!') MASK_FRS = ~np.logical_or(MASK_FRM, MASK_FRL) LABEL_FR = np.array(['FR-S'] * len(AstSEx)) LABEL_FR[MASK_FRM] = 'FR-M' LABEL_FR[MASK_FRL] = 'FR-L' print('MeLOn CheckPoint: count Lables from Hough Transformation [FR-S (%s) / FR-M (%s) / FR-L (%s)] !' \ %(np.sum(MASK_FRS), np.sum(MASK_FRM), np.sum(MASK_FRL))) # * Produce the 3 hierarchic groups # ** Good Sources MASK_GS = ~MASK_FRS # *** Point Sources MASK_PS =
np.logical_and(MASK_FRM, MASK_ELLIP)
numpy.logical_and
import sys import numpy import scipy.ndimage.measurements from skimage.morphology import watershed from clarity.Analysis.Voxelization import voxelizePixel from clarity.ImageProcessing.StackProcessing import writeSubStack from clarity.Utils.Timer import Timer from clarity.Utils.ParameterTools import getParameter, writeParameter from clarity.Visualization.Plot import plotOverlayLabel import clarity.IO as io def detectCellShape(img, peaks, detectCellShapeParameter = None, compactWatershedParameter=0,threshold = None, save = None, verbose = False, subStack = None, out = sys.stdout, **parameter): """Find cell shapes as labeled image Arguments: img (array): image data peaks (array): point data of cell centers / seeds detectCellShape (dict): ============ =================== =========================================================== Name Type Descritption ============ =================== =========================================================== *threshold* (float or None) threshold to determine mask, pixel below this are background if None no mask is generated *save* (tuple) size of the box on which to perform the *method* *verbose* (bool or int) print / plot information about this step ============ =================== =========================================================== verbose (bool): print progress info out (object): object to write progress info to Returns: array: labeled image where each label indicates a cell """ threshold = getParameter(detectCellShapeParameter, "threshold", threshold) save = getParameter(detectCellShapeParameter, "save", save) verbose = getParameter(detectCellShapeParameter, "verbose", verbose) if verbose: writeParameter(out = out, head = 'Cell shape detection:', threshold = threshold, save = save) # extended maxima timer = Timer() if threshold is None: imgmask = None else: imgmask = img > threshold imgpeaks = voxelizePixel(peaks, dataSize = img.shape, weights = numpy.arange(1, peaks.shape[0]+1)) #imgpeaks = voxelizePixel(peaks, dataSize = img.shape, weights = numpy.arange(2, peaks.shape[0]+2)) #imgws = cv2.watershed(img, imgpeaks) imgws = watershed(-img, imgpeaks, mask = imgmask) #imgws = watershed_ift(-img.astype('uint16'), imgpeaks) #imgws[numpy.logical_not(imgmask)] = 0 if not save is None: ''' Edit: WG, 8/4/17: writeSubStack won't work because we can't specify a start slice. ''' writeSubStack(save, imgws.astype('int32'), subStack = subStack) # io.writeData(save, imgws.astype('int32')) if verbose > 1: #plotTiling(img) plotOverlayLabel(img * 0.01, imgws, alpha = False) #plotOverlayLabel(img, imgmax.astype('int64'), alpha = True) if verbose: out.write(timer.elapsedTime(head = 'Cell Shape:') + '\n') return imgws def findCellSize(imglabel, findCelSizeParameter = None, maxLabel = None, verbose = False, out = sys.stdout, **parameter): """Find cell size given cell shapes as labled image Arguments: imglabel (array or str): labeled image, where each cell has its own label findCelSizeParameter (dict): =========== =================== =========================================================== Name Type Descritption =========== =================== =========================================================== *maxLabel* (int or None) maximal label to include, if None determine automatically *verbose* (bool or int) print / plot information about this step =========== =================== =========================================================== verbose (bool): print progress info out (object): object to write progress info to Returns: array: measured intensities """ maxLabel = getParameter(findCelSizeParameter, "maxLabel", maxLabel) verbose = getParameter(findCelSizeParameter, "verbose", verbose) if verbose: writeParameter(out = out, head = 'Cell size detection:', maxLabel = maxLabel) timer = Timer() if maxLabel is None: maxLabel = int(imglabel.max()) size = scipy.ndimage.measurements.sum(numpy.ones(imglabel.shape, dtype = bool), labels = imglabel, index = numpy.arange(1, maxLabel + 1)) if verbose: out.write(timer.elapsedTime(head = 'Cell size detection:') + '\n') return size def findCellIntensity(img, imglabel, findCellIntensityParameter = None, maxLabel = None, method = 'sum', verbose = False, out = sys.stdout, **parameter): """Find integrated cell intensity given cell shapes as labled image Arguments: img (array or str): image data imglabel (array or str): labeled image, where each cell has its own label findCellIntensityParameter (dict): =========== =================== =========================================================== Name Type Descritption =========== =================== =========================================================== *maxLabel* (int or None) maximal label to include, if None determine automatically *method* (str) method to use for measurment: 'Sum', 'Mean', 'Max', 'Min' *verbose* (bool or int) print / plot information about this step =========== =================== =========================================================== verbose (bool): print progress info out (object): object to write progress info to Returns: array: measured intensities """ maxLabel = getParameter(findCellIntensityParameter, "maxLabel", maxLabel) method = getParameter(findCellIntensityParameter, "method", method) verbose = getParameter(findCellIntensityParameter, "verbose", verbose) if verbose: writeParameter(out = out, head = 'Cell intensity detection:', method = method, maxLabel = maxLabel) timer = Timer() if maxLabel is None: maxLabel = imglabel.max() if method.lower() == 'sum': i = scipy.ndimage.measurements.sum(img, labels = imglabel, index =
numpy.arange(1, maxLabel + 1)
numpy.arange
# -*- coding: utf-8 -*- """ Created on Thu Dec 21 14:23:13 2017 @author: mat.mathews """ import numpy as np import matplotlib.pyplot as plt filename1 = './init_field_hit.dat' filename2 = './init_field_hit_2.dat' dataIn1 = np.loadtxt(filename1,dtype=np.double) dataIn2 = np.loadtxt(filename2,dtype=np.double) N = 129 U1 = np.empty((N-1,N-1,N-1),dtype=np.double) V1 = np.empty((N-1,N-1,N-1),dtype=np.double) W1 = np.empty((N-1,N-1,N-1),dtype=np.double) U2 = np.empty((N-1,N-1,N-1),dtype=np.double) V2 = np.empty((N-1,N-1,N-1),dtype=np.double) W2 = np.empty((N-1,N-1,N-1),dtype=np.double) dx = 2*np.pi/N dy = 2*np.pi/N dz = 2*np.pi/N for k in range(0,N-1): for j in range(0,N-1): for i in range(0,N-1): ii = k*N*N + j*N + i U1[i,j,k] = dataIn1[ii,3] V1[i,j,k] = dataIn1[ii,4] W1[i,j,k] = dataIn1[ii,5] U2[i,j,k] = dataIn2[ii,3] V2[i,j,k] = dataIn2[ii,4] W2[i,j,k] = dataIn2[ii,5] #%% uprime1 = 0 uprime2 = 0 q1 = 0 q2 = 0 for k in range(0,N-1): for j in range(0,N-1): for i in range(0,N-1): uprime1 += (U1[i,j,k]**2 + V1[i,j,k]**2 + W1[i,j,k]**2)/3 q1 += (U1[i,j,k]**2 + V1[i,j,k]**2 + W1[i,j,k]**2) uprime2 += (U2[i,j,k]**2 + V2[i,j,k]**2 + W2[i,j,k]**2)/3 q2 += (U2[i,j,k]**2 + V2[i,j,k]**2 + W2[i,j,k]**2) uprime1 = uprime1/(N-1)/(N-1)/(N-1) q1 = q1/(N-1)/(N-1)/(N-1) uprime1 = np.sqrt(uprime1) q1 = np.sqrt(q1) uprime2 = uprime2/(N-1)/(N-1)/(N-1) q2 = q2/(N-1)/(N-1)/(N-1) uprime2 = np.sqrt(uprime2) q2 = np.sqrt(q2) #%% uprimeGoal = 1 U1 = U1*uprimeGoal/uprime1 V1 = V1*uprimeGoal/uprime1 W1 = W1*uprimeGoal/uprime1 U2 = U2*uprimeGoal/uprime2 V2 = V2*uprimeGoal/uprime2 W2 = W2*uprimeGoal/uprime2 #%% #Need to get the source field for the poisson eqn. #these are rough perturbations for the field, 2nd order central should be enough S = np.empty((N-1,N-1,N-1),dtype=np.double) Ux = np.empty((N-1,N-1,N-1),dtype=np.double) Uy = np.empty((N-1,N-1,N-1),dtype=np.double) Uz = np.empty((N-1,N-1,N-1),dtype=np.double) Vx = np.empty((N-1,N-1,N-1),dtype=np.double) Vy = np.empty((N-1,N-1,N-1),dtype=np.double) Vz = np.empty((N-1,N-1,N-1),dtype=np.double) Wx = np.empty((N-1,N-1,N-1),dtype=np.double) Wy = np.empty((N-1,N-1,N-1),dtype=np.double) Wz = np.empty((N-1,N-1,N-1),dtype=np.double) for k in range(0,N-1): for j in range(0, N-1): for i in range(0, N-1): if i==0: Ux[0,j,k] = (U1[1,j,k] - U1[-1,j,k])/(2*dx) Vx[0,j,k] = (V1[1,j,k] - V1[-1,j,k])/(2*dx) Wx[0,j,k] = (W1[1,j,k] - W1[-1,j,k])/(2*dx) elif i==(N-2): Ux[-1,j,k] = (U1[0,j,k] - U1[-2,j,k])/(2*dx) Vx[-1,j,k] = (V1[0,j,k] - V1[-2,j,k])/(2*dx) Wx[-1,j,k] = (W1[0,j,k] - W1[-2,j,k])/(2*dx) else: Ux[i,j,k] = (U1[i+1,j,k] - U1[i-1,j,k])/(2*dx) Vx[i,j,k] = (V1[i+1,j,k] - V1[i-1,j,k])/(2*dx) Wx[i,j,k] = (W1[i+1,j,k] - W1[i-1,j,k])/(2*dx) if j==0: Uy[i,0,k] = (U1[i,1,k] - U1[i,-1,k])/(2*dx) Vy[i,0,k] = (V1[i,1,k] - V1[i,-1,k])/(2*dx) Wy[i,0,k] = (W1[i,1,k] - W1[i,-1,k])/(2*dx) elif j==(N-2): Uy[i,-1,k] = (U1[i,0,k] - U1[i,-2,k])/(2*dx) Vy[i,-1,k] = (V1[i,0,k] - V1[i,-2,k])/(2*dx) Wy[i,-1,k] = (W1[i,0,k] - W1[i,-2,k])/(2*dx) else: Uy[i,j,k] = (U1[i,j+1,k] - U1[i,j-1,k])/(2*dx) Vy[i,j,k] = (V1[i,j+1,k] - V1[i,j-1,k])/(2*dx) Wy[i,j,k] = (W1[i,j+1,k] - W1[i,j-1,k])/(2*dx) if k==0: Uz[i,j,0] = (U1[i,j,1] - U1[i,j,-1])/(2*dx) Vz[i,j,0] = (V1[i,j,1] - V1[i,j,-1])/(2*dx) Wz[i,j,0] = (W1[i,j,1] - W1[i,j,-1])/(2*dx) elif k==(N-2): Uz[i,j,-1] = (U1[i,j,0] - U1[i,j,-2])/(2*dx) Vz[i,j,-1] = (V1[i,j,0] - V1[i,j,-2])/(2*dx) Wz[i,j,-1] = (W1[i,j,0] - W1[i,j,-2])/(2*dx) else: Uz[i,j,k] = (U1[i,j,k+1] - U1[i,j,k-1])/(2*dx) Vz[i,j,k] = (V1[i,j,k+1] - V1[i,j,k-1])/(2*dx) Wz[i,j,k] = (W1[i,j,k+1] - W1[i,j,k-1])/(2*dx) S = -(Ux*Ux + Vy*Vy + Wz*Wz + 2*Uy*Vx + 2*Vz*Wy + 2*Uz*Wx) #%% ptilde1 = np.empty((N-1,N-1,N-1),dtype=np.double) ptilde2 = np.empty((N-1,N-1,N-1),dtype=np.double) ppadtemp = np.empty((N+1,N+1,N+1),dtype=np.double) r = np.empty((N-1,N-1,N-1),dtype=np.double) ptilde1[:,:,:] = 0.0 ptilde2[:,:,:] = 0.0 r[:,:,:] = 0.0 omega = 2 / ( 1 + np.sin(np.pi/(N)) ) for kk in range(0,2000): ppadtemp[:,:,:] = 0.0 ppadtemp[1:-1,1:-1, 1:-1] = ptilde1 ppadtemp[0 ,1:-1, 1:-1] = ptilde1[-1,:,:] ppadtemp[-1 ,1:-1, 1:-1] = ptilde1[ 0,:,:] ppadtemp[1:-1,0 , 1:-1] = ptilde1[:,-1,:] ppadtemp[1:-1,-1 , 1:-1] = ptilde1[:, 0,:] ppadtemp[1:-1,1:-1, 0] = ptilde1[:,:,-1] ppadtemp[1:-1,1:-1, -1] = ptilde1[:,:, 0] r[:,:,:] = 0.0 r -= S*dx*dx #r[i,j,k] -= 0 #6*ptilde1[i,j,k] r[:,:,:] += ppadtemp[0:-2,1:-1,1:-1] r[:,:,:] += ppadtemp[2: ,1:-1,1:-1] r[:,:,:] += ppadtemp[1:-1,0:-2,1:-1] r[:,:,:] += ppadtemp[1:-1,2: ,1:-1] r[:,:,:] += ppadtemp[1:-1,1:-1,0:-2] r[:,:,:] += ppadtemp[1:-1,1:-1,2:] ptilde2 = (1/6)*r res_norm = np.sum((ptilde2-ptilde1)**2) ptilde1 = ptilde2 print(kk) print(res_norm) if res_norm < 0.001: break p1 = ptilde1 #%% for k in range(0,N-1): for j in range(0, N-1): for i in range(0, N-1): if i==0: Ux[0,j,k] = (U2[1,j,k] - U2[-1,j,k])/(2*dx) Vx[0,j,k] = (V2[1,j,k] - V2[-1,j,k])/(2*dx) Wx[0,j,k] = (W2[1,j,k] - W2[-1,j,k])/(2*dx) elif i==(N-2): Ux[-1,j,k] = (U2[0,j,k] - U2[-2,j,k])/(2*dx) Vx[-1,j,k] = (V2[0,j,k] - V2[-2,j,k])/(2*dx) Wx[-1,j,k] = (W2[0,j,k] - W2[-2,j,k])/(2*dx) else: Ux[i,j,k] = (U2[i+1,j,k] - U2[i-1,j,k])/(2*dx) Vx[i,j,k] = (V2[i+1,j,k] - V2[i-1,j,k])/(2*dx) Wx[i,j,k] = (W2[i+1,j,k] - W2[i-1,j,k])/(2*dx) if j==0: Uy[i,0,k] = (U2[i,1,k] - U2[i,-1,k])/(2*dx) Vy[i,0,k] = (V2[i,1,k] - V2[i,-1,k])/(2*dx) Wy[i,0,k] = (W2[i,1,k] - W2[i,-1,k])/(2*dx) elif j==(N-2): Uy[i,-1,k] = (U2[i,0,k] - U2[i,-2,k])/(2*dx) Vy[i,-1,k] = (V2[i,0,k] - V2[i,-2,k])/(2*dx) Wy[i,-1,k] = (W2[i,0,k] - W2[i,-2,k])/(2*dx) else: Uy[i,j,k] = (U2[i,j+1,k] - U2[i,j-1,k])/(2*dx) Vy[i,j,k] = (V2[i,j+1,k] - V2[i,j-1,k])/(2*dx) Wy[i,j,k] = (W2[i,j+1,k] - W2[i,j-1,k])/(2*dx) if k==0: Uz[i,j,0] = (U2[i,j,1] - U2[i,j,-1])/(2*dx) Vz[i,j,0] = (V2[i,j,1] - V2[i,j,-1])/(2*dx) Wz[i,j,0] = (W2[i,j,1] - W2[i,j,-1])/(2*dx) elif k==(N-2): Uz[i,j,-1] = (U2[i,j,0] - U2[i,j,-2])/(2*dx) Vz[i,j,-1] = (V2[i,j,0] - V2[i,j,-2])/(2*dx) Wz[i,j,-1] = (W2[i,j,0] - W2[i,j,-2])/(2*dx) else: Uz[i,j,k] = (U2[i,j,k+1] - U2[i,j,k-1])/(2*dx) Vz[i,j,k] = (V2[i,j,k+1] - V2[i,j,k-1])/(2*dx) Wz[i,j,k] = (W2[i,j,k+1] - W2[i,j,k-1])/(2*dx) S = -(Ux*Ux + Vy*Vy + Wz*Wz + 2*Uy*Vx + 2*Vz*Wy + 2*Uz*Wx) #%% ptilde1 = np.empty((N-1,N-1,N-1),dtype=np.double) ptilde2 = np.empty((N-1,N-1,N-1),dtype=np.double) ppadtemp = np.empty((N+1,N+1,N+1),dtype=np.double) r = np.empty((N-1,N-1,N-1),dtype=np.double) ptilde1[:,:,:] = 0.0 ptilde2[:,:,:] = 0.0 r[:,:,:] = 0.0 omega = 2 / ( 1 + np.sin(np.pi/(N)) ) for kk in range(0,2000): ppadtemp[:,:,:] = 0.0 ppadtemp[1:-1,1:-1, 1:-1] = ptilde1 ppadtemp[0 ,1:-1, 1:-1] = ptilde1[-1,:,:] ppadtemp[-1 ,1:-1, 1:-1] = ptilde1[ 0,:,:] ppadtemp[1:-1,0 , 1:-1] = ptilde1[:,-1,:] ppadtemp[1:-1,-1 , 1:-1] = ptilde1[:, 0,:] ppadtemp[1:-1,1:-1, 0] = ptilde1[:,:,-1] ppadtemp[1:-1,1:-1, -1] = ptilde1[:,:, 0] r[:,:,:] = 0.0 r -= S*dx*dx #r[i,j,k] -= 0 #6*ptilde1[i,j,k] r[:,:,:] += ppadtemp[0:-2,1:-1,1:-1] r[:,:,:] += ppadtemp[2: ,1:-1,1:-1] r[:,:,:] += ppadtemp[1:-1,0:-2,1:-1] r[:,:,:] += ppadtemp[1:-1,2: ,1:-1] r[:,:,:] += ppadtemp[1:-1,1:-1,0:-2] r[:,:,:] += ppadtemp[1:-1,1:-1,2:] ptilde2 = (1/6)*r res_norm = np.sum((ptilde2-ptilde1)**2) ptilde1 = ptilde2 print(kk) print(res_norm) if res_norm < 0.001: break p2 = ptilde1 #%% Pxx = np.empty((N-1,N-1,N-1),dtype=np.double) Pyy = np.empty((N-1,N-1,N-1),dtype=np.double) Pzz = np.empty((N-1,N-1,N-1),dtype=np.double) PS = np.empty((N-1,N-1,N-1),dtype=np.double) for k in range(0,N-1): for j in range(0, N-1): for i in range(0, N-1): if i==0: Pxx[0,j,k] = (ptilde1[1,j,k] -2*ptilde1[0,j,k] + ptilde1[-1,j,k])/(dx*dx) elif i==(N-2): Pxx[-1,j,k] = (ptilde1[0,j,k] -2*ptilde1[-1,j,k] + ptilde1[-2,j,k])/(dx*dx) else: Pxx[i,j,k] = (ptilde1[i+1,j,k] -2*ptilde1[i,j,k] + ptilde1[i-1,j,k])/(dx*dx) if j==0: Pyy[i,0,k] = (ptilde1[i,1,k] -2*ptilde1[i,0,k] + ptilde1[i,-1,k])/(dx*dx) elif j==(N-2): Pyy[i,-1,k] = (ptilde1[i,0,k] -2*ptilde1[i,-1,k] + ptilde1[i,-2,k])/(dx*dx) else: Pyy[i,j,k] = (ptilde1[i,j+1,k] -2*ptilde1[i,j,k] + ptilde1[i,j-1,k])/(dx*dx) if k==0: Pzz[i,j,0] = (ptilde1[i,j,1] -2*ptilde1[i,j,0] + ptilde1[i,j,-1])/(dx*dx) elif k==(N-2): Pzz[i,j,-1] = (ptilde1[i,j,0] -2*ptilde1[i,j,-1] + ptilde1[i,j,-2])/(dx*dx) else: Pzz[i,j,k] = (ptilde1[i,j,k+1] -2*ptilde1[i,j,k] + ptilde1[i,j,k-1])/(dx*dx) PS = Pxx + Pyy + Pzz #%% #Chop the domain into three chunks #Chunk1 U1a = U1[:,:,0:42] V1a = V1[:,:,0:42] W1a = W1[:,:,0:42] P1a = p1[:,:,0:42] #Chunk2 U2a = U1[:,:,42:84] V2a = V1[:,:,42:84] W2a = W1[:,:,42:84] P2a = p1[:,:,42:84] #Chunk3 U3a = U1[:,:,84:126] V3a = V1[:,:,84:126] W3a = W1[:,:,84:126] P3a = p1[:,:,84:126] #Chunk4 U4a = U2[:,:,0:42] V4a = V2[:,:,0:42] W4a = W2[:,:,0:42] P4a = p2[:,:,0:42] #Chunk5 U5a = U2[:,:,42:84] V5a = V2[:,:,42:84] W5a = W2[:,:,42:84] P5a = p2[:,:,42:84] #Chunk6 U6a = U2[:,:,84:126] V6a = V2[:,:,84:126] W6a = W2[:,:,84:126] P6a = p2[:,:,84:126] totalX = 512 currentX = 128*6 totalOverlap = currentX - totalX #%% Ufinal = np.empty((totalX,N-1,42),dtype=np.double) Vfinal = np.empty((totalX,N-1,42),dtype=np.double) Wfinal = np.empty((totalX,N-1,42),dtype=np.double) Pfinal = np.empty((totalX,N-1,42),dtype=np.double) #%% Ufinal[42:86,:,:] = U1a[42:86,:,:] Vfinal[42:86,:,:] = V1a[42:86,:,:] Wfinal[42:86,:,:] = W1a[42:86,:,:] Pfinal[42:86,:,:] = P1a[42:86,:,:] Ufinal[128:172,:,:] = U2a[42:86,:,:] Vfinal[128:172,:,:] = V2a[42:86,:,:] Wfinal[128:172,:,:] = W2a[42:86,:,:] Pfinal[128:172,:,:] = P2a[42:86,:,:] Ufinal[214:258,:,:] = U3a[42:86,:,:] Vfinal[214:258,:,:] = V3a[42:86,:,:] Wfinal[214:258,:,:] = W3a[42:86,:,:] Pfinal[214:258,:,:] = P3a[42:86,:,:] Ufinal[300:344,:,:] = U4a[42:86,:,:] Vfinal[300:344,:,:] = V4a[42:86,:,:] Wfinal[300:344,:,:] = W4a[42:86,:,:] Pfinal[300:344,:,:] = P4a[42:86,:,:] Ufinal[386:430,:,:] = U5a[42:86,:,:] Vfinal[386:430,:,:] = V5a[42:86,:,:] Wfinal[386:430,:,:] = W5a[42:86,:,:] Pfinal[386:430,:,:] = P5a[42:86,:,:] Ufinal[472:512,:,:] = U6a[42:82,:,:] Vfinal[472:512,:,:] = V6a[42:82,:,:] Wfinal[472:512,:,:] = W6a[42:82,:,:] Pfinal[472:512,:,:] = P6a[42:82,:,:] for i in range(0,42): #beta = 1 - np.cos((np.pi/2.0)*float(i)/41.0) beta = float(i)/41.0 theta = (np.pi/2.0)*beta Ufinal[i,:,:] = np.cos(theta)*U6a[82+i,:,:] + np.sin(theta)*U1a[i,:,:] Vfinal[i,:,:] = np.cos(theta)*V6a[82+i,:,:] + np.sin(theta)*V1a[i,:,:] Wfinal[i,:,:] = np.cos(theta)*W6a[82+i,:,:] + np.sin(theta)*W1a[i,:,:] Pfinal[i,:,:] = np.cos(theta)*P6a[82+i,:,:] + np.sin(theta)*P1a[i,:,:] Ufinal[86+i,:,:] = np.cos(theta)*U1a[86+i,:,:] + np.sin(theta)*U2a[i,:,:] Vfinal[86+i,:,:] = np.cos(theta)*V1a[86+i,:,:] + np.sin(theta)*V2a[i,:,:] Wfinal[86+i,:,:] = np.cos(theta)*W1a[86+i,:,:] + np.sin(theta)*W2a[i,:,:] Pfinal[86+i,:,:] = np.cos(theta)*P1a[86+i,:,:] + np.sin(theta)*P2a[i,:,:] Ufinal[172+i,:,:] = np.cos(theta)*U2a[86+i,:,:] + np.sin(theta)*U3a[i,:,:] Vfinal[172+i,:,:] = np.cos(theta)*V2a[86+i,:,:] + np.sin(theta)*V3a[i,:,:] Wfinal[172+i,:,:] = np.cos(theta)*W2a[86+i,:,:] + np.sin(theta)*W3a[i,:,:] Pfinal[172+i,:,:] = np.cos(theta)*P2a[86+i,:,:] + np.sin(theta)*P3a[i,:,:] Ufinal[258+i,:,:] = np.cos(theta)*U3a[86+i,:,:] + np.sin(theta)*U4a[i,:,:] Vfinal[258+i,:,:] = np.cos(theta)*V3a[86+i,:,:] + np.sin(theta)*V4a[i,:,:] Wfinal[258+i,:,:] = np.cos(theta)*W3a[86+i,:,:] + np.sin(theta)*W4a[i,:,:] Pfinal[258+i,:,:] = np.cos(theta)*P3a[86+i,:,:] + np.sin(theta)*P4a[i,:,:] Ufinal[344+i,:,:] = np.cos(theta)*U4a[86+i,:,:] + np.sin(theta)*U5a[i,:,:] Vfinal[344+i,:,:] = np.cos(theta)*V4a[86+i,:,:] + np.sin(theta)*V5a[i,:,:] Wfinal[344+i,:,:] = np.cos(theta)*W4a[86+i,:,:] + np.sin(theta)*W5a[i,:,:] Pfinal[344+i,:,:] = np.cos(theta)*P4a[86+i,:,:] + np.sin(theta)*P5a[i,:,:] Ufinal[430+i,:,:] = np.cos(theta)*U5a[86+i,:,:] + np.sin(theta)*U6a[i,:,:] Vfinal[430+i,:,:] = np.cos(theta)*V5a[86+i,:,:] + np.sin(theta)*V6a[i,:,:] Wfinal[430+i,:,:] = np.cos(theta)*W5a[86+i,:,:] + np.sin(theta)*W6a[i,:,:] Pfinal[430+i,:,:] =
np.cos(theta)
numpy.cos
import numpy as np from scipy import linalg import pathlib, sys file_path = pathlib.Path(__file__).parent.absolute() from pressio4py import logger, solvers, ode, rom from pressio4py.apps.burgers1d import Burgers1d np.set_printoptions(linewidth=140) goldBdf1 = np.array([ 1.23924618529016e+00, 1.00513224142691e+00, 1.00258744050401e+00, 1.00283530274169e+00, 1.00313333759789e+00, 1.00346287207285e+00, 1.00382706443916e+00, 1.00422955914887e+00, 1.00467438433032e+00, 1.00516599192553e+00, 1.00570930192065e+00, 1.00630975185226e+00, 1.00697335112295e+00, 1.00770674109302e+00, 1.00851726134268e+00, 1.00941302387047e+00, 1.01040299320197e+00, 1.01149707707594e+00, 1.01270622473792e+00, 1.01404253728095e+00]) goldBdf2 = np.array([ 1.23947296257898, 1.004911840673181, 1.002583292436882, 1.002835486018458, 1.003133591274698, 1.003463152789714, 1.003827374922797, 1.004229902417551, 1.004674763912067, 1.005166411588689, 1.005709766002342, 1.006310265072025, 1.006973918660976, 1.0077073687177, 1.008517955621836, 1.009413791794709, 1.01040384277086, 1.011498016939365, 1.012707264750251, 1.014043688232101]) #---------------------------- class MyQRSolver: def __init__(self, meshSize, romSize): self.Q_ = np.zeros((meshSize, romSize)) self.R_ = np.zeros((romSize, romSize)) def computeThin(self, A): self.Q_, self.R_ = np.linalg.qr(A, mode='reduced') def applyQTranspose(self, operand, result): result[:] = self.Q_.T.dot(operand) def applyRTranspose(self, operand, result): result[:] = self.R_.T.dot(operand) def solveRxb(self, b, x): x[:] = linalg.solve(self.R_, b) #---------------------------------------- class OdeObserver: def __call__(self, timeStep, time, state): print(state) assert(state.shape[0]==11) #---------------------------- def test_euler(): meshSize = 20 romSize = 11 Nsteps = 10 dt = 0.01 t0 = 0. # create app appObj = Burgers1d(meshSize) # set reference state yRef = np.ones(meshSize) # I have to make phi a column-major array to ensure # pressio does not make a copy of this basisFile = str(file_path) + "/basis_bdf1.txt" phi = np.copy(np.loadtxt(basisFile), order='F') # decoder decoder = rom.Decoder(phi) # LSPG state yRom = np.zeros(romSize) # lspg problem scheme = ode.stepscheme.BDF1 problem = rom.lspg.unsteady.DefaultProblem(scheme, appObj, decoder, yRom, yRef) # qr and non linear solver qrS = MyQRSolver(meshSize, romSize) nlsO = solvers.create_gauss_newton_qr(problem, yRom, qrS) nlsO.setUpdatingCriterion(solvers.update.Standard) nlsO.setMaxIterations(2) nlsO.setStoppingCriterion(solvers.stop.AfterMaxIters) # solve myObs = OdeObserver() ode.advance_n_steps_and_observe(problem, yRom, t0,dt, Nsteps, myObs, nlsO) fomRecon = problem.fomStateReconstructor() yFomFinal = fomRecon(yRom) np.set_printoptions(precision=15) print(yFomFinal) for y1,y2 in zip(goldBdf1, yFomFinal): assert( np.abs(y1-y2) < 1e-10) #---------------------------- def test_bdf2(): meshSize = 20 romSize = 11 Nsteps = 10 dt = 0.01 t0 = 0. logger.initialize(logger.logto.terminal, "null") logger.setVerbosity([logger.loglevel.info]) # create app appObj = Burgers1d(meshSize) # set reference state yRef =
np.ones(meshSize)
numpy.ones
import unittest import numpy as np from feastruct.pre.material import Steel from feastruct.pre.section import Section import feastruct.fea.cases as cases from feastruct.fea.frame_analysis import FrameAnalysis2D from feastruct.solvers.linstatic import LinearStatic class TestUDL(unittest.TestCase): """Tests problems related to 1D beam bending from the American Wood Council: https://www.awc.org/pdf/codes-standards/publications/design-aids/AWC-DA6-BeamFormulas-0710.pdf """ def setUp(self): self.steel = Steel() self.elastic_modulus = self.steel.elastic_modulus self.ixx = np.random.uniform(10e6, 200e6) self.length = np.random.uniform(2e3, 10e3) self.q = -np.random.uniform(1, 10) self.pl = -np.random.uniform(5e3, 50e3) def test_fig1(self): """Simple Beam – Uniformly Distributed Load""" # create 2d frame analysis object analysis = FrameAnalysis2D() # create section section = Section(ixx=self.ixx) # create nodes node_a = analysis.create_node(coords=[0]) node_b = analysis.create_node(coords=[self.length]) # create beam elements element = analysis.create_element( el_type='EB2-2D', nodes=[node_a, node_b], material=self.steel, section=section ) # add supports freedom_case = cases.FreedomCase() freedom_case.add_nodal_support(node=node_a, val=0, dof=0) freedom_case.add_nodal_support(node=node_a, val=0, dof=1) freedom_case.add_nodal_support(node=node_b, val=0, dof=1) # add loads load_case = cases.LoadCase() load_case.add_element_load(element.generate_udl(q=self.q)) # add analysis case analysis_case = cases.AnalysisCase(freedom_case=freedom_case, load_case=load_case) # linear static solver LinearStatic(analysis=analysis, analysis_cases=[analysis_case]).solve() # check displacements def analytical_disp(x): factor = self.q * x / 24 / self.elastic_modulus / self.ixx l0 = self.length return factor * (l0 * l0 * l0 - 2 * l0 * x * x + x * x * x) # get displacements displacements = element.get_displacements(11, analysis_case) # loop through each station for disp in displacements: xi = disp[0] x = self.length * xi v = disp[2] # check displacements self.assertTrue(np.isclose(v, analytical_disp(x), atol=1e-06)) # check max displacement l0 = self.length v_max = 5 * self.q * l0 * l0 * l0 * l0 / 384 / self.elastic_modulus / self.ixx # check value self.assertTrue(np.isclose(abs(v_max), max(np.abs(displacements[:, 2])))) # check position self.assertTrue(np.isclose(0.5, displacements[np.abs(displacements[:, 2]).argmax(), 0], atol=1e-06)) # check bending moments def analytical_bmd(x): return self.q * x / 2 * (self.length - x) # get bmd (xis, bmd) = element.get_bmd(11, analysis_case) # loop through each station for (i, m) in enumerate(bmd): xi = xis[i] x = self.length * xi # check bending moment self.assertTrue(np.isclose(m, analytical_bmd(x), atol=1e-06)) # check max bending moment l0 = self.length m_max = self.q * l0 * l0 / 8 # check value self.assertTrue(np.isclose(abs(m_max), max(np.abs(bmd)), atol=1e-06)) # check position self.assertTrue(np.isclose(0.5, xis[np.abs(bmd).argmax()], atol=1e-06)) # check shear force def analytical_sfd(x): return self.q * (x - self.length / 2) # get sfd (xis, sfd) = element.get_sfd(11, analysis_case) # loop through each station for (i, sf) in enumerate(sfd): xi = xis[i] x = self.length * xi # check shear force self.assertTrue(np.isclose(sf, analytical_sfd(x), atol=1e-06)) def test_fig2(self): """Simple Beam – Uniform Load Partially Distributed""" a = self.length * np.random.uniform(0.1, 0.4) c = self.length * np.random.uniform(0.1, 0.4) b = self.length - a - c # create 2d frame analysis object analysis = FrameAnalysis2D() # create section section = Section(ixx=self.ixx) # create nodes node_a = analysis.create_node(coords=[0]) node_b = analysis.create_node(coords=[a]) node_c = analysis.create_node(coords=[a+b]) node_d = analysis.create_node(coords=[self.length]) # create beam elements element_ab = analysis.create_element( el_type='EB2-2D', nodes=[node_a, node_b], material=self.steel, section=section ) element_bc = analysis.create_element( el_type='EB2-2D', nodes=[node_b, node_c], material=self.steel, section=section ) element_cd = analysis.create_element( el_type='EB2-2D', nodes=[node_c, node_d], material=self.steel, section=section ) # add supports freedom_case = cases.FreedomCase() freedom_case.add_nodal_support(node=node_a, val=0, dof=0) sup1 = freedom_case.add_nodal_support(node=node_a, val=0, dof=1) sup2 = freedom_case.add_nodal_support(node=node_d, val=0, dof=1) # add loads load_case = cases.LoadCase() load_case.add_element_load(element_bc.generate_udl(q=self.q)) # add analysis case analysis_case = cases.AnalysisCase(freedom_case=freedom_case, load_case=load_case) # linear static solver LinearStatic(analysis=analysis, analysis_cases=[analysis_case]).solve() # check reactions r1 = -sup1.get_reaction(analysis_case) r2 = -sup2.get_reaction(analysis_case) self.assertTrue(np.isclose(r1, self.q * b / 2 / self.length * (2 * c + b), atol=1e-06)) self.assertTrue(np.isclose(r2, self.q * b / 2 / self.length * (2 * a + b), atol=1e-06)) # check bending moments def analytical_bmd_ab(x): return r1 * x def analytical_bmd_bc(x): return r1 * x - self.q / 2 * (x - a) * (x - a) def analytical_bmd_cd(x): return r2 * (self.length - x) # get bmds (xis_ab, bmd_ab) = element_ab.get_bmd(11, analysis_case) (xis_bc, bmd_bc) = element_bc.get_bmd(11, analysis_case) (xis_cd, bmd_cd) = element_cd.get_bmd(11, analysis_case) # element_ab - loop through each station for (i, m) in enumerate(bmd_ab): xi = xis_ab[i] x = a * xi # check bending moments self.assertTrue(np.isclose(m, analytical_bmd_ab(x), atol=1e-06)) # element_bc - loop through each station for (i, m) in enumerate(bmd_bc): xi = xis_bc[i] x = b * xi + a # check bending moments self.assertTrue(np.isclose(m, analytical_bmd_bc(x), atol=1e-06)) # element_cd - loop through each station for (i, m) in enumerate(bmd_cd): xi = xis_cd[i] x = c * xi + a + b # check bending moments self.assertTrue(np.isclose(m, analytical_bmd_cd(x), atol=1e-06)) # check max bending moment m_max = r1 * (a + r1 / 2 / self.q) pos = a + r1 / self.q x = 1 / b * (pos - a) # check value self.assertTrue(np.isclose(abs(m_max), max(np.abs(bmd_bc)), atol=1e-06)) # check position self.assertTrue(np.isclose(x, xis_bc[np.abs(bmd_bc).argmax()], atol=1e-06)) # check shear force def analytical_sfd_ab(x): return -r1 def analytical_sfd_bc(x): return -r1 + self.q * (x - a) def analytical_sfd_cd(x): return r2 # get sfds (xis_ab, sfd_ab) = element_ab.get_sfd(11, analysis_case) (xis_bc, sfd_bc) = element_bc.get_sfd(11, analysis_case) (xis_cd, sfd_cd) = element_cd.get_sfd(11, analysis_case) # element_ab - loop through each station for (i, sf) in enumerate(sfd_ab): xi = xis_ab[i] x = a * xi # check shear forces self.assertTrue(np.isclose(sf, analytical_sfd_ab(x), atol=1e-06)) # element_bc - loop through each station for (i, sf) in enumerate(sfd_bc): xi = xis_bc[i] x = b * xi + a # check shear forces self.assertTrue(np.isclose(sf, analytical_sfd_bc(x), atol=1e-06)) # element_cd - loop through each station for (i, sf) in enumerate(sfd_cd): xi = xis_cd[i] x = c * xi + a + b # check shear forces self.assertTrue(np.isclose(sf, analytical_sfd_cd(x), atol=1e-06)) def test_fig3(self): """Simple Beam – Uniform Load Partially Distributed at One End""" a = self.length * np.random.uniform(0.1, 0.9) # create 2d frame analysis object analysis = FrameAnalysis2D() # create section section = Section(ixx=self.ixx) # create nodes node_a = analysis.create_node(coords=[0]) node_b = analysis.create_node(coords=[a]) node_c = analysis.create_node(coords=[self.length]) # create beam elements element_ab = analysis.create_element( el_type='EB2-2D', nodes=[node_a, node_b], material=self.steel, section=section ) element_bc = analysis.create_element( el_type='EB2-2D', nodes=[node_b, node_c], material=self.steel, section=section ) # add supports freedom_case = cases.FreedomCase() freedom_case.add_nodal_support(node=node_a, val=0, dof=0) sup1 = freedom_case.add_nodal_support(node=node_a, val=0, dof=1) sup2 = freedom_case.add_nodal_support(node=node_c, val=0, dof=1) # add loads load_case = cases.LoadCase() load_case.add_element_load(element_ab.generate_udl(q=self.q)) # add analysis case analysis_case = cases.AnalysisCase(freedom_case=freedom_case, load_case=load_case) # linear static solver LinearStatic(analysis=analysis, analysis_cases=[analysis_case]).solve() # check reactions r1 = -sup1.get_reaction(analysis_case) r2 = -sup2.get_reaction(analysis_case) self.assertTrue(np.isclose(r1, self.q * a / 2 / self.length * (2 * self.length - a), atol=1e-06)) self.assertTrue(np.isclose(r2, self.q * a * a / 2 / self.length, atol=1e-06)) # check displacements def analytical_disp_ab(x): l0 = self.length factor = self.q * x / 24 / self.elastic_modulus / self.ixx / l0 return factor * (a * a * (2 * l0 - a) * (2 * l0 - a) - 2 * a * x * x * ( 2 * l0 - a) + l0 * x * x * x) def analytical_disp_bc(x): l0 = self.length factor = self.q * a * a * (l0 - x) / 24 / self.elastic_modulus / self.ixx / l0 return factor * (4 * x * l0 - 2 * x * x - a * a) # get displacements displacements_ab = element_ab.get_displacements(11, analysis_case) displacements_bc = element_bc.get_displacements(11, analysis_case) # loop through each station for disp in displacements_ab: xi = disp[0] x = a * xi v = disp[2] # check displacements self.assertTrue(np.isclose(v, analytical_disp_ab(x), atol=1e-06)) # loop through each station for disp in displacements_bc: xi = disp[0] x = (self.length - a) * xi + a v = disp[2] # check displacements self.assertTrue(np.isclose(v, analytical_disp_bc(x), atol=1e-06)) # check bending moments def analytical_bmd_ab(x): return r1 * x - self.q * x * x / 2 def analytical_bmd_bc(x): return r2 * (self.length - x) # get bmds (xis_ab, bmd_ab) = element_ab.get_bmd(11, analysis_case) (xis_bc, bmd_bc) = element_bc.get_bmd(11, analysis_case) # element_ab - loop through each station for (i, m) in enumerate(bmd_ab): xi = xis_ab[i] x = a * xi # check bending moments self.assertTrue(np.isclose(m, analytical_bmd_ab(x), atol=1e-06)) # element_bc - loop through each station for (i, m) in enumerate(bmd_bc): xi = xis_bc[i] x = (self.length - a) * xi + a # check bending moments self.assertTrue(np.isclose(m, analytical_bmd_bc(x), atol=1e-06)) # check max bending moment m_max = r1 * r1 / 2 / self.q pos = r1 / self.q x = pos / a # check value self.assertTrue(np.isclose(abs(m_max), max(np.abs(bmd_ab)), atol=1e-06)) # check position self.assertTrue(np.isclose(x, xis_ab[np.abs(bmd_ab).argmax()], atol=1e-06)) # check shear force def analytical_sfd_ab(x): return -r1 + self.q * x def analytical_sfd_bc(x): return r2 # get sfds (xis_ab, sfd_ab) = element_ab.get_sfd(11, analysis_case) (xis_bc, sfd_bc) = element_bc.get_sfd(11, analysis_case) # element_ab - loop through each station for (i, sf) in enumerate(sfd_ab): xi = xis_ab[i] x = a * xi # check shear forces self.assertTrue(np.isclose(sf, analytical_sfd_ab(x), atol=1e-06)) # element_bc - loop through each station for (i, sf) in enumerate(sfd_bc): xi = xis_bc[i] x = (self.length - a) * xi + a # check shear forces self.assertTrue(np.isclose(sf, analytical_sfd_bc(x), atol=1e-06)) def test_fig4(self): """Simple Beam – Uniform Load Partially Distributed at Each End""" a = self.length * np.random.uniform(0.1, 0.4) c = self.length * np.random.uniform(0.1, 0.4) b = self.length - a - c q2 = -np.random.uniform(1, 10) # create 2d frame analysis object analysis = FrameAnalysis2D() # create section section = Section(ixx=self.ixx) # create nodes node_a = analysis.create_node(coords=[0]) node_b = analysis.create_node(coords=[a]) node_c = analysis.create_node(coords=[a+b]) node_d = analysis.create_node(coords=[self.length]) # create beam elements element_ab = analysis.create_element( el_type='EB2-2D', nodes=[node_a, node_b], material=self.steel, section=section ) element_bc = analysis.create_element( el_type='EB2-2D', nodes=[node_b, node_c], material=self.steel, section=section ) element_cd = analysis.create_element( el_type='EB2-2D', nodes=[node_c, node_d], material=self.steel, section=section ) # add supports freedom_case = cases.FreedomCase() freedom_case.add_nodal_support(node=node_a, val=0, dof=0) sup1 = freedom_case.add_nodal_support(node=node_a, val=0, dof=1) sup2 = freedom_case.add_nodal_support(node=node_d, val=0, dof=1) # add loads load_case = cases.LoadCase() load_case.add_element_load(element_ab.generate_udl(q=self.q)) load_case.add_element_load(element_cd.generate_udl(q=q2)) # add analysis case analysis_case = cases.AnalysisCase(freedom_case=freedom_case, load_case=load_case) # linear static solver LinearStatic(analysis=analysis, analysis_cases=[analysis_case]).solve() # check reactions r1 = -sup1.get_reaction(analysis_case) r1_ana = (self.q * a * (2 * self.length - a) + q2 * c * c) / (2 * self.length) r2 = -sup2.get_reaction(analysis_case) r2_ana = (q2 * c * (2 * self.length - c) + self.q * a * a) / (2 * self.length) self.assertTrue(np.isclose(r1, r1_ana, atol=1e-06)) self.assertTrue(np.isclose(r2, r2_ana, atol=1e-06)) # check bending moments def analytical_bmd_ab(x): return r1 * x - self.q * 0.5 * x * x def analytical_bmd_bc(x): return r1 * x - self.q * a * 0.5 * (2 * x - a) def analytical_bmd_cd(x): return r2 * (self.length - x) - q2 * (self.length - x) * (self.length - x) * 0.5 # get bmds (xis_ab, bmd_ab) = element_ab.get_bmd(11, analysis_case) (xis_bc, bmd_bc) = element_bc.get_bmd(11, analysis_case) (xis_cd, bmd_cd) = element_cd.get_bmd(11, analysis_case) # element_ab - loop through each station for (i, m) in enumerate(bmd_ab): xi = xis_ab[i] x = a * xi # check bending moments self.assertTrue(np.isclose(m, analytical_bmd_ab(x), atol=1e-06)) # element_bc - loop through each station for (i, m) in enumerate(bmd_bc): xi = xis_bc[i] x = b * xi + a # check bending moments self.assertTrue(np.isclose(m, analytical_bmd_bc(x), atol=1e-06)) # element_cd - loop through each station for (i, m) in enumerate(bmd_cd): xi = xis_cd[i] x = c * xi + a + b # check bending moments self.assertTrue(np.isclose(m, analytical_bmd_cd(x), atol=1e-06)) # check max bending moment if abs(r1) < abs(self.q * a): m_max = r1 * r1 / 2 / self.q pos = r1 / self.q x = pos / a # check value self.assertTrue(np.isclose(abs(m_max), max(np.abs(bmd_ab)), atol=1e-06)) # check position self.assertTrue(np.isclose(x, xis_ab[np.abs(bmd_ab).argmax()], atol=1e-06)) if abs(r2) < abs(q2 * c): m_max = r2 * r2 / 2 / q2 pos = self.length - r2 / q2 x = 1 / c * (pos - a - b) # check value self.assertTrue(np.isclose(abs(m_max), max(np.abs(bmd_cd)), atol=1e-06)) # check position self.assertTrue(np.isclose(x, xis_cd[np.abs(bmd_cd).argmax()], atol=1e-06)) # check shear force def analytical_sfd_ab(x): return -r1 + self.q * x def analytical_sfd_bc(x): return -r1 + self.q * a def analytical_sfd_cd(x): return r2 - q2 * (self.length - x) # get sfds (xis_ab, sfd_ab) = element_ab.get_sfd(11, analysis_case) (xis_bc, sfd_bc) = element_bc.get_sfd(11, analysis_case) (xis_cd, sfd_cd) = element_cd.get_sfd(11, analysis_case) # element_ab - loop through each station for (i, sf) in enumerate(sfd_ab): xi = xis_ab[i] x = a * xi # check shear forces self.assertTrue(np.isclose(sf, analytical_sfd_ab(x), atol=1e-06)) # element_bc - loop through each station for (i, sf) in enumerate(sfd_bc): xi = xis_bc[i] x = b * xi + a # check shear forces self.assertTrue(np.isclose(sf, analytical_sfd_bc(x), atol=1e-06)) # element_cd - loop through each station for (i, sf) in enumerate(sfd_cd): xi = xis_cd[i] x = c * xi + a + b # check shear forces self.assertTrue(np.isclose(sf, analytical_sfd_cd(x), atol=1e-06)) def test_fig5(self): """Simple Beam – Load Increasing Uniformly to One End""" # not yet implemented pass def test_fig6(self): """Simple Beam – Load Increasing Uniformly to Center""" # not yet implemented pass def test_fig7(self): """Simple Beam – Concentrated Load at Center""" # create 2d frame analysis object analysis = FrameAnalysis2D() # create section section = Section(ixx=self.ixx) # create nodes node_a = analysis.create_node(coords=[0]) node_b = analysis.create_node(coords=[self.length * 0.5]) node_c = analysis.create_node(coords=[self.length]) # create beam elements element_ab = analysis.create_element( el_type='EB2-2D', nodes=[node_a, node_b], material=self.steel, section=section ) element_bc = analysis.create_element( el_type='EB2-2D', nodes=[node_b, node_c], material=self.steel, section=section ) # add supports freedom_case = cases.FreedomCase() freedom_case.add_nodal_support(node=node_a, val=0, dof=0) freedom_case.add_nodal_support(node=node_a, val=0, dof=1) freedom_case.add_nodal_support(node=node_c, val=0, dof=1) # add loads load_case = cases.LoadCase() load_case.add_nodal_load(node=node_b, val=self.pl, dof=1) # add analysis case analysis_case = cases.AnalysisCase(freedom_case=freedom_case, load_case=load_case) # linear static solver LinearStatic(analysis=analysis, analysis_cases=[analysis_case]).solve() # check displacements def analytical_disp_ab(x): factor = self.pl * x / 48 / self.elastic_modulus / self.ixx l0 = self.length return factor * (3 * l0 * l0 - 4 * x * x) def analytical_disp_bc(x): x = self.length - x factor = self.pl * x / 48 / self.elastic_modulus / self.ixx l0 = self.length return factor * (3 * l0 * l0 - 4 * x * x) # get displacements displacements_ab = element_ab.get_displacements(11, analysis_case) displacements_bc = element_bc.get_displacements(11, analysis_case) # loop through each station for disp in displacements_ab: xi = disp[0] x = self.length * 0.5 * xi v = disp[2] # check displacements self.assertTrue(np.isclose(v, analytical_disp_ab(x), atol=1e-06)) # loop through each station for disp in displacements_bc: xi = disp[0] x = self.length * 0.5 + self.length * 0.5 * xi v = disp[2] # check displacements self.assertTrue(np.isclose(v, analytical_disp_bc(x), atol=1e-06)) # check max displacement l0 = self.length v_max = self.pl * l0 * l0 * l0 / 48 / self.elastic_modulus / self.ixx # check value self.assertTrue(np.isclose(abs(v_max), max(np.abs(displacements_ab[:, 2])), atol=1e-06)) # check position self.assertTrue( np.isclose(1, displacements_ab[np.abs(displacements_ab[:, 2]).argmax(), 0], atol=1e-06)) # check bending moments def analytical_bmd_ab(x): return self.pl * x / 2 def analytical_bmd_bc(x): x = self.length - x return self.pl * x / 2 # get bmd (xis_ab, bmd_ab) = element_ab.get_bmd(11, analysis_case) (xis_bc, bmd_bc) = element_bc.get_bmd(11, analysis_case) # loop through each station for (i, m) in enumerate(bmd_ab): xi = xis_ab[i] x = self.length * 0.5 * xi # check bending moment self.assertTrue(np.isclose(m, analytical_bmd_ab(x), atol=1e-06)) # loop through each station for (i, m) in enumerate(bmd_bc): xi = xis_bc[i] x = self.length * 0.5 + self.length * 0.5 * xi # check bending moment self.assertTrue(np.isclose(m, analytical_bmd_bc(x), atol=1e-06)) # check max bending moment l0 = self.length m_max = self.pl * l0 / 4 # check value self.assertTrue(np.isclose(abs(m_max), max(
np.abs(bmd_ab)
numpy.abs
""" Calculation of Earth layers and electron densities. """ from __future__ import division import numpy as np try: import numba except ImportError: numba = None from pisa import FTYPE from pisa.utils.fileio import from_file from pisa.utils.log import logging, set_verbosity __all__ = ['extCalcLayers', 'Layers'] __author__ = '<NAME>' __license__ = '''Copyright (c) 2014-2017, The IceCube Collaboration 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.''' if numba is None: class jit(object): """Decorator class to mimic Numba's `jit` when Numba is missing""" def __init__(self, *args, **kwargs): pass def __call__(self, *args): return args[0] else: jit = numba.jit ftype = numba.typeof(FTYPE(1)) @jit(nopython=True, nogil=True, cache=True) def extCalcLayers( cz, r_detector, prop_height, detector_depth, max_layers, min_detector_depth, rhos, YeFrac, YeOuterRadius, default_elec_frac, coszen_limit, radii): """Layer density/distance calculator for each coszen specified. Accelerated with Numba if present. Parameters ---------- cz r_detector prop_height detector_depth max_layers min_detector_depth rhos YeFrac YeOuterRadius default_elec_frac coszen_limit Returns ------- n_layers : int number of layers density : array of densities, flattened from (cz, max_layers) distance : array of distances per layer, flattened from (cz, max_layers) """ # Something to store the final results in shape = (np.int64(len(cz)), np.int64(max_layers)) n_layers = np.zeros(shape[0], dtype=np.int32) distance = np.zeros(shape=shape, dtype=FTYPE) density = np.zeros(shape=shape, dtype=FTYPE) # Loop over all CZ values for k, coszen in enumerate(cz): tot_earth_len = -2 * coszen * r_detector # To store results traverse_rhos = np.zeros(max_layers, dtype=FTYPE) traverse_dist = np.zeros(max_layers, dtype=FTYPE) traverse_electron_frac = np.zeros(max_layers, dtype=FTYPE) # Above horizon if coszen >= 0: kappa = (detector_depth + prop_height)/r_detector path_len = ( r_detector * np.sqrt(coszen**2 - 1 + (1 + kappa)**2) - r_detector * coszen ) # Path through the air: kappa = detector_depth / r_detector lam = ( coszen + np.sqrt(coszen**2 - 1 + (1 + kappa) * (1 + kappa)) ) lam *= r_detector path_thru_atm = ( prop_height * (prop_height + 2*detector_depth + 2*r_detector) / (path_len + lam) ) path_thru_outerlayer = path_len - path_thru_atm traverse_rhos[0] = 0.0 traverse_dist[0] = path_thru_atm traverse_electron_frac[0] = default_elec_frac # In that case the neutrino passes through some earth (?) layers = 1 if detector_depth > min_detector_depth: traverse_rhos[1] = rhos[0] traverse_dist[1] = path_thru_outerlayer traverse_electron_frac[1] = YeFrac[-1] layers += 1 # Below horizon else: path_len = ( np.sqrt((r_detector + prop_height + detector_depth)**2 - r_detector**2 * (1 - coszen**2)) - r_detector * coszen ) # Path through air (that's down from production height in the # atmosphere?) traverse_rhos[0] = 0 traverse_dist[0] = ( prop_height * (prop_height + detector_depth + 2*r_detector) / path_len ) # TODO: Why default here? traverse_electron_frac[0] = default_elec_frac i_trav = 1 # Path through the final layer above the detector (if necessary) # NOTE: outer top layer is assumed to be the same as the next layer # inward. if detector_depth > min_detector_depth: traverse_rhos[1] = rhos[0] traverse_dist[1] = path_len - tot_earth_len - traverse_dist[0] traverse_electron_frac[1] = YeFrac[-1] i_trav += 1 # See how many layers we will pass layers = 0 for val in coszen_limit: if coszen < val: layers += 1 # The zeroth layer is the air! # ... and the first layer is the top layer (if detector is not on # surface) for i in range(layers): # this is the density traverse_rhos[i+i_trav] = rhos[i] # TODO: Why default? is this air with density 0 and electron # fraction just doesn't matter? traverse_electron_frac[i+i_trav] = default_elec_frac for rad_i in range(len(YeOuterRadius)): # TODO: why 1.001 here? if radii[i] < (YeOuterRadius[rad_i] * 1.001): traverse_electron_frac[i+i_trav] = YeFrac[rad_i] break # Now calculate the distance travele in layer c2 = coszen**2 R2 = r_detector**2 s1 = radii[i]**2 - R2*(1 -c2) s2 = radii[i+1]**2 - R2*(1 -c2) cross_this = 2. * np.sqrt(s1) if i < layers - 1: cross_next = 2. * np.sqrt(s2) traverse_dist[i+i_trav] = 0.5 * (cross_this - cross_next) else: traverse_dist[i+i_trav] = cross_this # Assumes azimuthal symmetry if i > 0 and i < layers: index = 2 * layers - i + i_trav - 1 traverse_rhos[index] = traverse_rhos[i+i_trav-1] traverse_dist[index] = traverse_dist[i+i_trav-1] traverse_electron_frac[index] = ( traverse_electron_frac[i+i_trav-1] ) # That is now the total layers = 2 * layers + i_trav - 1 n_layers[k] = np.int32(layers) density[k] = traverse_rhos * traverse_electron_frac distance[k] = traverse_dist return n_layers, density.ravel(), distance.ravel() class Layers(object): """ Calculate the path through earth for a given layer model with densities (PREM), the electron fractions (Ye) and an array of coszen values Parameters ---------- prem_file : str path to PREM file containing layer radii and densities as white space separated txt detector_depth : float depth of detector underground in km prop_height : float the production height of the neutrinos in the atmosphere in km (?) Attributes: ---------- max_layers : int maximum number of layers (this is important for the shape of the output! if less than maximumm number of layers are crossed, it's filled up with 0s n_layers : 1d int array of length len(cz) number of layers crossed for every CZ value density : 1d float array of length (max_layers * len(cz)) containing density values and filled up with 0s otherwise distance : 1d float array of length (max_layers * len(cz)) containing distance values and filled up with 0s otherwise """ def __init__(self, prem_file, detector_depth=1., prop_height=2.): # Load earth model if prem_file is not None : self.using_earth_model = True prem = from_file(prem_file, as_array=True) self.rhos = prem[...,1][::-1].astype(FTYPE) self.radii = prem[...,0][::-1].astype(FTYPE) r_earth = prem[-1][0] self.default_elec_frac = 0.5 n_prem = len(self.radii) - 1 self.max_layers = 2 * n_prem + 1 else : self.using_earth_model = False r_earth = 6371.0 #If no Earth model provided, use a standard Earth radius value # Set some other self.r_detector = r_earth - detector_depth self.prop_height = prop_height self.detector_depth = detector_depth self.min_detector_depth = 1.0e-3 # <-- Why? // [km] so min is ~ 1 m # Some additional handling of the Earth model if self.using_earth_model: # Change outermost radius to a bit underground, where the detector if self.detector_depth >= self.min_detector_depth: self.radii[0] -= detector_depth self.max_layers += 1 # Compute coszen limit self.computeMinLengthToLayers() def setElecFrac(self, YeI, YeO, YeM): """ Parameters ---------- YeI, YeO, YeM : scalars Three electron fractions (Ye), where I=inner core, O=outer core, and M=mantle """ if not self.using_earth_model : raise ValueError("Cannot set electron fraction when not using an Earth model") self.YeFrac = np.array([YeI, YeO, YeM], dtype=FTYPE) # TODO: these numbers are just hard coded for some reason...? self.YeOuterRadius = np.array([1121.5, 3480.0, self.r_detector], dtype=FTYPE) def computeMinLengthToLayers(self): # Compute which layer is tangeted at which angle coszen_limit = [] # First element of self.radii is largest radius! for i, rad in enumerate(self.radii): # Using a cosine threshold instead! if i == 0: x = 0 else: x = - np.sqrt(1 - (rad**2 / self.r_detector**2)) coszen_limit.append(x) self.coszen_limit =
np.array(coszen_limit, dtype=FTYPE)
numpy.array
import scipy.ndimage as nd from scipy.optimize import curve_fit import numpy as np import matplotlib.pyplot as p import astropy.units as u from astropy.table import QTable from .profile import profile_line eight_conn = np.ones((3, 3)) end_structs = [np.array([[1, 0, 0], [0, 1, 0], [0, 0, 0]]), np.array([[0, 1, 0], [0, 1, 0], [0, 0, 0]]), np.array([[0, 0, 1], [0, 1, 0], [0, 0, 0]]), np.array([[0, 0, 0], [1, 1, 0], [0, 0, 0]]), np.array([[0, 0, 0], [0, 1, 1], [0, 0, 0]]), np.array([[0, 0, 0], [0, 1, 0], [1, 0, 0]]), np.array([[0, 0, 0], [0, 1, 0], [0, 1, 0]]), np.array([[0, 0, 0], [0, 1, 0], [0, 0, 1]])] four_conn_posns = [1, 3, 5, 7] eight_conn_posns = [0, 2, 6, 8] def filament_profile(skeleton, image, pixscale, max_dist=0.025 * u.pc, distance=250. * u.pc, num_avg=3, verbose=False, bright_unit="Jy km/s", noise=None, fit_profiles=True): ''' Calculate radial profiles along the main extent of a skeleton (ie. the longest path). The skeleton must contain a single branch with no intersections. Parameters ---------- skeleton : np.ndarray Boolean array containing the skeleton image : np.ndarray Image to compute the profiles from. Must match the spatial extent of the skeleton array. pixscale : `~astropy.units.Quantity` Angular size of a pixel in the image. Must have units equivalent to degrees. max_dist : astropy Quantity, optional The angular or physical (when distance is given) extent to create the profile away from the centre skeleton pixel. The entire profile will be twice this value (for each side of the profile). distance : astropy Quantity, optional Physical distance to the region in the image. If None is given, results will be in angular units based on the header. num_avg : int, optional Number of points before and after a pixel that is used when computing the normal vector. Using at least three points is recommended due to small pixel instabilities in the skeletons. verbose : bool, optional Enable plotting of the profile and the accompanying for each pixel in the skeleton. bright_unit : string or astropy Unit Brightness unit of the image. noise : np.ndarray, optional RMS array for the accompanying image. When provided, the errors are calculated along each of the profiles and used as weights in the fitting. fit_profiles : bool, optional When enabled, fits a Gaussian model to the profiles. Otherwise only the profiles are returned. Returns ------- line_distances : list Distances along the profiles. line_profiles : list Radial profiles. profile_extents : list Contains the pixel position of the start of the profile, the skeleton pixel, and the end of the profile. tab : astropy QTable Table of the fit results and errors with appropriate units. ''' deg_per_pix = pixscale.to(u.deg) / u.pixel if distance is not None: phys_per_pix = distance * (np.pi / 180.) * deg_per_pix / u.deg max_pixel = (max_dist / phys_per_pix).value else: # max_dist should then be in pixel or angular units if not isinstance(max_dist, u.Quantity): # Assume pixels max_pixel = max_dist else: try: max_pixel = max_dist.to(u.pix).value except u.UnitConversionError: # In angular units equiv = [(u.pixel, u.deg, lambda x: x / (pixscale * u.pix), lambda x: x * pixscale * u.pix)] max_pixel = max_dist.to(u.pix, equivalencies=equiv).value if bright_unit is None: bright_unit = u.dimensionless_unscaled elif isinstance(bright_unit, str): bright_unit = u.Unit(bright_unit) elif isinstance(bright_unit, u.UnitBase): pass else: raise TypeError("bright_unit must be compatible with astropy.units.") # Make sure the noise array is the same shape if noise is not None: assert noise.shape == image.shape # Get the points in the skeleton (in order) skel_pts = walk_through_skeleton(skeleton) line_profiles = [] line_distances = [] profile_extents = [] profile_fits = [] red_chisqs = [] for j, i in enumerate(range(num_avg, len(skel_pts) - num_avg)): # Calculate the normal direction from the surrounding pixels pt1 = avg_pts([skel_pts[i + j] for j in range(-num_avg, 0)]) pt2 = avg_pts([skel_pts[i + j] for j in range(1, num_avg + 1)]) vec = np.array([float(x2 - x1) for x2, x1 in zip(pt1, pt2)]) vec /= np.linalg.norm(vec) per_vec = perpendicular(vec) line_pts = find_path_ends(skel_pts[i], max_pixel, per_vec) left_profile, left_dists = \ profile_line(image, skel_pts[i], line_pts[0]) right_profile, right_dists = \ profile_line(image, skel_pts[i], line_pts[1]) total_profile = np.append(left_profile[::-1], right_profile) * \ bright_unit if noise is not None: left_profile, _ = \ profile_line(noise, skel_pts[i], line_pts[0]) right_profile, _ = \ profile_line(noise, skel_pts[i], line_pts[1]) noise_profile = np.append(left_profile[::-1], right_profile) * \ bright_unit else: noise_profile = None if distance is not None: total_dists = np.append(-left_dists[::-1], right_dists) \ * u.pix * phys_per_pix else: total_dists = np.append(-left_dists[::-1], right_dists) \ * u.pix * deg_per_pix if noise is not None: if len(total_profile) != len(noise_profile): raise ValueError("Intensity and noise profile lengths do not" " match. Have you applied the same mask to" " both?") line_profiles.append(total_profile) line_distances.append(total_dists) profile_extents.append([line_pts[0], skel_pts[i], line_pts[1]]) if fit_profiles: # Now fit! profile_fit, profile_fit_err, red_chisq = \ gauss_fit(total_dists.value, total_profile.value, sigma=noise_profile) profile_fits.append(np.hstack([profile_fit, profile_fit_err])) red_chisqs.append(red_chisq) if verbose: p.subplot(121) p.imshow(image, origin='lower') p.contour(skeleton, colors='r') p.plot(skel_pts[i][1], skel_pts[i][0], 'bD') p.plot(line_pts[0][1], line_pts[0][0], 'bD') p.plot(line_pts[1][1], line_pts[1][0], 'bD') p.subplot(122) p.plot(total_dists, total_profile, 'bD') pts = np.linspace(total_dists.min().value, total_dists.max().value, 100) if fit_profiles: p.plot(pts, gaussian(pts, *profile_fit), 'r') if distance is not None: unit = (u.pix * phys_per_pix).unit.to_string() else: unit = (u.pix * deg_per_pix).unit.to_string() p.xlabel("Distance from skeleton (" + unit + ")") p.ylabel("Surface Brightness (" + bright_unit.to_string() + ")") p.tight_layout() p.show() if fit_profiles: profile_fits = np.asarray(profile_fits) red_chisqs = np.asarray(red_chisqs) # Create an astropy table of the fit results param_names = ["Amplitude", "Std Dev", "Background"] param_errs = [par + " Error" for par in param_names] colnames = param_names + param_errs in_bright_units = [True, False, True] * 2 tab = QTable() tab["Number"] = np.arange(profile_fits.shape[0]) tab.add_index("Number") tab["Red Chisq"] = red_chisqs for i, (name, is_bright) in enumerate(zip(colnames, in_bright_units)): if is_bright: col_unit = bright_unit else: if distance is not None: col_unit = (u.pix * phys_per_pix).unit else: col_unit = (u.pix * deg_per_pix).unit tab[name] = profile_fits[:, i] * col_unit return line_distances, line_profiles, profile_extents, tab else: return line_distances, line_profiles def perpendicular(a): ''' Return the perpendicular vector to a given 2D vector. ''' b = np.empty_like(a) b[0] = -a[1] b[1] = a[0] return b def walk_through_skeleton(skeleton): ''' Starting from one end, walk through a skeleton in order. Intended for use with skeletons that contain no branches. ''' # Calculate the end points end_pts = return_ends(skeleton) if len(end_pts) != 2: raise ValueError("Skeleton must contain no intersections.") # Force the first end point to be closest to the image origin. if two_point_dist(end_pts[1], [0, 0]) < two_point_dist(end_pts[0], [0, 0]): end_pts = end_pts[::-1] all_pts = int(np.sum(skeleton)) yy, xx = np.mgrid[-1:2, -1:2] yy = yy.ravel() xx = xx.ravel() for i in range(all_pts): if i == 0: ordered_pts = [end_pts[0]] prev_pt = end_pts[0] else: # Check for neighbors y, x = prev_pt # Extract the connected region neighbors = skeleton[y - 1:y + 2, x - 1:x + 2].ravel() # Define the corresponding array indices. yy_inds = yy + y xx_inds = xx + x hits = [int(elem) for elem in np.argwhere(neighbors)] # Remove the centre point and any points already in the list for pos, (y_ind, x_ind) in enumerate(zip(yy_inds, xx_inds)): if (y_ind, x_ind) in ordered_pts: hits.remove(pos) num_hits = len(hits) if num_hits == 0: # You've reached the end. It better be the other end point if prev_pt[0] != end_pts[1][0] or prev_pt[1] != end_pts[1][1]: raise ValueError("Final point does not match expected" " end point. Check input skeleton for" " intersections.") break elif num_hits == 1: # You have found the next point posn = hits[0] next_pt = (y + yy[posn], x + xx[posn]) ordered_pts.append(next_pt) else: # There's at least a couple neighbours (for some reason) # Pick the 4-connected component since it is the closest for fours in four_conn_posns: if fours in hits: posn = hits[hits.index(fours)] break else: raise ValueError("Disconnected eight-connected pixels?") next_pt = (y + yy[posn], x + xx[posn]) ordered_pts.append(next_pt) prev_pt = next_pt return ordered_pts def return_ends(skeleton): ''' Find the endpoints of the skeleton. ''' end_points = [] for i, struct in enumerate(end_structs): hits = nd.binary_hit_or_miss(skeleton, structure1=struct) if not np.any(hits): continue for y, x in zip(*np.where(hits)): end_points.append((y, x)) return end_points def find_path_ends(posn, max_dist, vector): ''' Find ends of a path for line_profile given a vector direction. ''' vector = vector.astype(float) / np.linalg.norm(vector) max_size = np.ceil(max_dist).astype(int) yy, xx = np.mgrid[-max_size:max_size + 1, -max_size:max_size + 1] max_circle = yy**2 + xx**2 <= max_dist**2 ring = \ np.logical_xor(max_circle, nd.binary_erosion(max_circle, eight_conn)) radius_pts = [(y + posn[0], x + posn[1]) for y, x in zip(*np.where(ring))] x_step = vector[1] y_step = vector[0] y_diff = max_size * y_step x_diff = max_size * x_step neg_line_posn = (posn[0] - y_diff, posn[1] - x_diff) pos_line_posn = (posn[0] + y_diff, posn[1] + x_diff) # pos_dists = np.array([two_point_dist(pos_line_posn, pt) # for pt in radius_pts]) # neg_dists = np.array([two_point_dist(neg_line_posn, pt) # for pt in radius_pts]) # These should be the ones used to ensure # proper distance from the skeleton point. # pos_posn give weird results though... # pos_posn = radius_pts[np.argmin(pos_dists)] # neg_posn = radius_pts[np.argmin(neg_dists)] return [neg_line_posn, pos_line_posn] def two_point_dist(pt1, pt2): return np.linalg.norm([x2 - x1 for x2, x1 in zip(pt1, pt2)]) def avg_pts(pts): dims = len(pts[0]) avg_pt = [] for dim in range(dims): avg_pt.append(np.mean([pt[dim] for pt in pts]).astype(int)) return avg_pt def gaussian(x, *p): ''' Parameters ---------- x : list or numpy.ndarray 1D array of values where the model is evaluated p : tuple Components are: * p[0] Amplitude * p[1] Mean * p[2] Width * p[3] Background ''' return (p[0] - p[2]) * np.exp(-1 * np.power(x, 2) / (2 *
np.power(p[1], 2)
numpy.power
from ..initial_param.kinect_para import Kinect_para import numpy as np from math import acos from scipy.signal import argrelextrema from scipy.ndimage.filters import gaussian_filter1d as gf import inflect,pdb class Swing(object): """ Dectect if body bend to left or right. Also if arm is straight or not. """ def __init__(self): self.angle_mean = [] self.angel_le = [] self.angel_re = [] self.angle_ini = 90.0 self.bend_max = [] self.bend_min = [] self.cnvt = inflect.engine() # converting numerals into ordinals self.max_ary = np.array([[0, 0]]) self.min_ary = np.array([[0, np.inf]]) self.max_len = 1 self.min_len = 1 self.bend_th = 20 self.kpm = Kinect_para() self.bend_left = True # default parameters self.cnt = 0 self.do = False self.err = [] self.errsum = [] self.evalstr = '' self.eval = '' def vec_angle(self, vec1, vec2=
np.array([1, 0, 0])
numpy.array
from deepNets import layers from deepNets import layer_utils import numpy as np # from layers import * # from layer_utils import * class Net(object): def __init__(self): self.params = {} self.reg = 0.0 self.dtype = np.float64 self.seed = None self.layer_defs = [] self.layers_length = 0 self.layerDims = [] self.bn_params = [] def check_syntax(self,layer,inp=False,loss=False): layer_check = layer.get("layer_type",None) if inp: assert layer_check != None and layer_check == "input", "Input layer required" elif loss: assert layer_check != None and layer_check == "loss", "loss layer required" layer_check = layer.get("num_classes",None) assert layer_check != None and layer_check > 0 , "Number of classes required" else: assert layer_check != None and (layer_check == "relu" or layer_check == "batchnorm" or layer_check == "layernorm" or layer_check == "conv" or layer_check == "pool") , "Incorrect layer found" if layer_check == "relu": hidden = layer.get("hidden_layers",0) assert hidden > 0 ,"Hidden layers not specified" elif layer_check == "conv": filters = layer.get("filters",0) filter_size = layer.get("filter_size",0) padding = layer.get("padding",0) stride = layer.get("stride",1) assert filters > 0 and filter_size > 0 and padding >= 0 and stride >= 1 , "Wrong parameters for conv layer" elif layer_check == "pool": filter_size = layer.get("filter_size",0) stride = layer.get("stride",1) assert filter_size > 0 and stride >= 1 , "Wrong parameters for conv layer" else: self.layers_length -= 1 def makeLayerDims(self,layer_defs): inp_dim = layer_defs[0].get("inp",None) if(len(inp_dim[0].shape)==3): c,h,w = inp_dim[0].shape conv_flag = False for i in range(len(layer_defs)-1): if i == 0: checkConv = layer_defs[i+1].get("layer_type",None) if checkConv == "conv": conv_flag = True continue get_inp = layer_defs[i].get("inp",None) xdim = get_inp[0].shape self.layerDims.append(np.prod(xdim)) continue self.check_syntax(layer_defs[i],False,False) get_layer = layer_defs[i].get("layer_type",None) if get_layer == "relu": if conv_flag: conv_flag = False self.layerDims.append(c*h*w) get_hidden = layer_defs[i].get("hidden_layers",None) self.layerDims.append(get_hidden) elif get_layer == "conv": dims = [layer_defs[i].get("filters",0),layer_defs[i].get("filter_size",0)] assert conv_flag , "Cannot unpack " + str(self.layerDims[-1]) + " into " + str(dims[0]) + " x " + str(dims[1]) + " x " + str(dims[1]) padding = layer_defs[i].get("padding",0) stride = layer_defs[i].get("stride",1) #updating the parameters channel,height and width for flattening c = dims[0] assert (h - dims[1] + 2*padding)%stride == 0, "Conv filter height not proper" assert (w - dims[1] + 2*padding)%stride == 0, "Conv filter width not proper" h = (h - dims[1] + 2*padding)//stride + 1 w = (w - dims[1] + 2*padding)//stride + 1 self.layerDims.append(dims) elif get_layer == "pool": assert conv_flag , "Input layer cannot be pooled without conv layer on top" filter_size = layer_defs[i].get("filter_size",0) stride = layer_defs[i].get("stride",1) #Default 1 assert (h - filter_size)%stride == 0, "Pool filter height not proper" assert (w - filter_size)%stride == 0, "Pool filter width not proper" h = (h - filter_size)//stride + 1 w = (w - filter_size)//stride + 1 self.layers_length -= 1 #For loss layer if conv_flag: conv_flag = False self.layerDims.append(c*h*w) self.layerDims.append(layer_defs[-1].get("num_classes",None)) return def makeLayers(self,layer_defs,initialization="None",weight_scale=1e-3): self.layer_defs = layer_defs self.layers_length = len(layer_defs) - 1 input_layer = layer_defs[0] self.check_syntax(input_layer,True,False) loss_layer = layer_defs[-1] self.check_syntax(loss_layer,False,True) self.makeLayerDims(layer_defs) channel = 0 for i in range(self.layers_length): if type(self.layerDims[i]) is list: if channel == 0: channel = input_layer.get("inp").shape[1] # 3 channel image is preferred self.params["W"+str(i+1)] = weight_scale * np.random.randn(self.layerDims[i][0],channel,self.layerDims[i][1],self.layerDims[i][1]) self.params["b"+str(i+1)] = np.zeros(self.layerDims[i][0]) self.params["gamma"+str(i+1)] = np.ones(self.layerDims[i][0]) self.params["beta"+str(i+1)] =
np.zeros(self.layerDims[i][0])
numpy.zeros
from itertools import product import numpy as np from aif360.metrics import BinaryLabelDatasetMetric, utils from aif360.datasets import BinaryLabelDataset class ClassificationMetric(BinaryLabelDatasetMetric): """Class for computing metrics based on two BinaryLabelDatasets. The first dataset is the original one and the second is the output of the classification transformer (or similar). """ def __init__(self, dataset, classified_dataset, unprivileged_groups=None, privileged_groups=None): """ Args: dataset (BinaryLabelDataset): Dataset containing ground-truth labels. classified_dataset (BinaryLabelDataset): Dataset containing predictions. privileged_groups (list(dict)): Privileged groups. Format is a list of `dicts` where the keys are `protected_attribute_names` and the values are values in `protected_attributes`. Each `dict` element describes a single group. See examples for more details. unprivileged_groups (list(dict)): Unprivileged groups in the same format as `privileged_groups`. Raises: TypeError: `dataset` and `classified_dataset` must be :obj:`~aif360.datasets.BinaryLabelDataset` types. """ if not isinstance(dataset, BinaryLabelDataset): raise TypeError("'dataset' should be a BinaryLabelDataset") # sets self.dataset, self.unprivileged_groups, self.privileged_groups super(ClassificationMetric, self).__init__(dataset, unprivileged_groups=unprivileged_groups, privileged_groups=privileged_groups) if isinstance(classified_dataset, BinaryLabelDataset): self.classified_dataset = classified_dataset else: raise TypeError("'classified_dataset' should be a " "BinaryLabelDataset.") # Verify if everything except the predictions and metadata are the same # for the two datasets with self.dataset.temporarily_ignore('labels', 'scores'): if self.dataset != self.classified_dataset: raise ValueError("The two datasets are expected to differ only " "in 'labels' or 'scores'.") def binary_confusion_matrix(self, privileged=None): """Compute the number of true/false positives/negatives, optionally conditioned on protected attributes. Args: privileged (bool, optional): Boolean prescribing whether to condition this metric on the `privileged_groups`, if `True`, or the `unprivileged_groups`, if `False`. Defaults to `None` meaning this metric is computed over the entire dataset. Returns: dict: Number of true positives, false positives, true negatives, false negatives (optionally conditioned). """ condition = self._to_condition(privileged) return utils.compute_num_TF_PN(self.dataset.protected_attributes, self.dataset.labels, self.classified_dataset.labels, self.dataset.instance_weights, self.dataset.protected_attribute_names, self.dataset.favorable_label, self.dataset.unfavorable_label, condition=condition) def generalized_binary_confusion_matrix(self, privileged=None): """Compute the number of generalized true/false positives/negatives, optionally conditioned on protected attributes. Generalized counts are based on scores and not on the hard predictions. Args: privileged (bool, optional): Boolean prescribing whether to condition this metric on the `privileged_groups`, if `True`, or the `unprivileged_groups`, if `False`. Defaults to `None` meaning this metric is computed over the entire dataset. Returns: dict: Number of generalized true positives, generalized false positives, generalized true negatives, generalized false negatives (optionally conditioned). """ condition = self._to_condition(privileged) return utils.compute_num_gen_TF_PN(self.dataset.protected_attributes, self.dataset.labels, self.classified_dataset.scores, self.dataset.instance_weights, self.dataset.protected_attribute_names, self.dataset.favorable_label, self.dataset.unfavorable_label, condition=condition) def num_true_positives(self, privileged=None): r"""Return the number of instances in the dataset where both the predicted and true labels are 'favorable', :math:`TP = \sum_{i=1}^n \mathbb{1}[y_i = \text{favorable}]\mathbb{1}[\hat{y}_i = \text{favorable}]`, optionally conditioned on protected attributes. Args: privileged (bool, optional): Boolean prescribing whether to condition this metric on the `privileged_groups`, if `True`, or the `unprivileged_groups`, if `False`. Defaults to `None` meaning this metric is computed over the entire dataset. Raises: AttributeError: `privileged_groups` or `unprivileged_groups` must be must be provided at initialization to condition on them. """ return self.binary_confusion_matrix(privileged=privileged)['TP'] def num_false_positives(self, privileged=None): r""":math:`FP = \sum_{i=1}^n \mathbb{1}[y_i = \text{unfavorable}]\mathbb{1}[\hat{y}_i = \text{favorable}]` Args: privileged (bool, optional): Boolean prescribing whether to condition this metric on the `privileged_groups`, if `True`, or the `unprivileged_groups`, if `False`. Defaults to `None` meaning this metric is computed over the entire dataset. Raises: AttributeError: `privileged_groups` or `unprivileged_groups` must be must be provided at initialization to condition on them. """ return self.binary_confusion_matrix(privileged=privileged)['FP'] def num_false_negatives(self, privileged=None): r""":math:`FN = \sum_{i=1}^n \mathbb{1}[y_i = \text{favorable}]\mathbb{1}[\hat{y}_i = \text{unfavorable}]` Args: privileged (bool, optional): Boolean prescribing whether to condition this metric on the `privileged_groups`, if `True`, or the `unprivileged_groups`, if `False`. Defaults to `None` meaning this metric is computed over the entire dataset. Raises: AttributeError: `privileged_groups` or `unprivileged_groups` must be must be provided at initialization to condition on them. """ return self.binary_confusion_matrix(privileged=privileged)['FN'] def num_true_negatives(self, privileged=None): r""":math:`TN = \sum_{i=1}^n \mathbb{1}[y_i = \text{unfavorable}]\mathbb{1}[\hat{y}_i = \text{unfavorable}]` Args: privileged (bool, optional): Boolean prescribing whether to condition this metric on the `privileged_groups`, if `True`, or the `unprivileged_groups`, if `False`. Defaults to `None` meaning this metric is computed over the entire dataset. Raises: AttributeError: `privileged_groups` or `unprivileged_groups` must be must be provided at initialization to condition on them. """ return self.binary_confusion_matrix(privileged=privileged)['TN'] def num_generalized_true_positives(self, privileged=None): """Return the generalized number of true positives, :math:`GTP`, the weighted sum of predicted scores where true labels are 'favorable', optionally conditioned on protected attributes. Args: privileged (bool, optional): Boolean prescribing whether to condition this metric on the `privileged_groups`, if `True`, or the `unprivileged_groups`, if `False`. Defaults to `None` meaning this metric is computed over the entire dataset. Raises: AttributeError: `privileged_groups` or `unprivileged_groups` must be must be provided at initialization to condition on them. """ return self.generalized_binary_confusion_matrix( privileged=privileged)['GTP'] def num_generalized_false_positives(self, privileged=None): """Return the generalized number of false positives, :math:`GFP`, the weighted sum of predicted scores where true labels are 'favorable', optionally conditioned on protected attributes. Args: privileged (bool, optional): Boolean prescribing whether to condition this metric on the `privileged_groups`, if `True`, or the `unprivileged_groups`, if `False`. Defaults to `None` meaning this metric is computed over the entire dataset. Raises: AttributeError: `privileged_groups` or `unprivileged_groups` must be must be provided at initialization to condition on them. """ return self.generalized_binary_confusion_matrix( privileged=privileged)['GFP'] def num_generalized_false_negatives(self, privileged=None): """Return the generalized number of false negatives, :math:`GFN`, the weighted sum of predicted scores where true labels are 'favorable', optionally conditioned on protected attributes. Args: privileged (bool, optional): Boolean prescribing whether to condition this metric on the `privileged_groups`, if `True`, or the `unprivileged_groups`, if `False`. Defaults to `None` meaning this metric is computed over the entire dataset. Raises: AttributeError: `privileged_groups` or `unprivileged_groups` must be must be provided at initialization to condition on them. """ return self.generalized_binary_confusion_matrix( privileged=privileged)['GFN'] def num_generalized_true_negatives(self, privileged=None): """Return the generalized number of true negatives, :math:`GTN`, the weighted sum of predicted scores where true labels are 'favorable', optionally conditioned on protected attributes. Args: privileged (bool, optional): Boolean prescribing whether to condition this metric on the `privileged_groups`, if `True`, or the `unprivileged_groups`, if `False`. Defaults to `None` meaning this metric is computed over the entire dataset. Raises: AttributeError: `privileged_groups` or `unprivileged_groups` must be must be provided at initialization to condition on them. """ return self.generalized_binary_confusion_matrix( privileged=privileged)['GTN'] def performance_measures(self, privileged=None): """Compute various performance measures on the dataset, optionally conditioned on protected attributes. Args: privileged (bool, optional): Boolean prescribing whether to condition this metric on the `privileged_groups`, if `True`, or the `unprivileged_groups`, if `False`. Defaults to `None` meaning this metric is computed over the entire dataset. Returns: dict: True positive rate, true negative rate, false positive rate, false negative rate, positive predictive value, negative predictive value, false discover rate, false omission rate, and accuracy (optionally conditioned). """ TP = self.num_true_positives(privileged=privileged) FP = self.num_false_positives(privileged=privileged) FN = self.num_false_negatives(privileged=privileged) TN = self.num_true_negatives(privileged=privileged) GTP = self.num_generalized_true_positives(privileged=privileged) GFP = self.num_generalized_false_positives(privileged=privileged) GFN = self.num_generalized_false_negatives(privileged=privileged) GTN = self.num_generalized_true_negatives(privileged=privileged) P = self.num_positives(privileged=privileged) N = self.num_negatives(privileged=privileged) return dict( TPR=TP / P, TNR=TN / N, FPR=FP / N, FNR=FN / P, GTPR=GTP / P, GTNR=GTN / N, GFPR=GFP / N, GFNR=GFN / P, PPV=TP / (TP+FP) if (TP+FP) > 0.0 else np.float64(0.0), NPV=TN / (TN+FN) if (TN+FN) > 0.0 else np.float64(0.0), FDR=FP / (FP+TP) if (FP+TP) > 0.0 else np.float64(0.0), FOR=FN / (FN+TN) if (FN+TN) > 0.0 else np.float64(0.0), ACC=(TP+TN) / (P+N) if (P+N) > 0.0 else np.float64(0.0) ) def true_positive_rate(self, privileged=None): """Return the ratio of true positives to positive examples in the dataset, :math:`TPR = TP/P`, optionally conditioned on protected attributes. Args: privileged (bool, optional): Boolean prescribing whether to condition this metric on the `privileged_groups`, if `True`, or the `unprivileged_groups`, if `False`. Defaults to `None` meaning this metric is computed over the entire dataset. Raises: AttributeError: `privileged_groups` or `unprivileged_groups` must be must be provided at initialization to condition on them. """ return self.performance_measures(privileged=privileged)['TPR'] def false_positive_rate(self, privileged=None): """:math:`FPR = FP/N` Args: privileged (bool, optional): Boolean prescribing whether to condition this metric on the `privileged_groups`, if `True`, or the `unprivileged_groups`, if `False`. Defaults to `None` meaning this metric is computed over the entire dataset. Raises: AttributeError: `privileged_groups` or `unprivileged_groups` must be must be provided at initialization to condition on them. """ return self.performance_measures(privileged=privileged)['FPR'] def false_negative_rate(self, privileged=None): """:math:`FNR = FN/P` Args: privileged (bool, optional): Boolean prescribing whether to condition this metric on the `privileged_groups`, if `True`, or the `unprivileged_groups`, if `False`. Defaults to `None` meaning this metric is computed over the entire dataset. Raises: AttributeError: `privileged_groups` or `unprivileged_groups` must be must be provided at initialization to condition on them. """ return self.performance_measures(privileged=privileged)['FNR'] def true_negative_rate(self, privileged=None): """:math:`TNR = TN/N` Args: privileged (bool, optional): Boolean prescribing whether to condition this metric on the `privileged_groups`, if `True`, or the `unprivileged_groups`, if `False`. Defaults to `None` meaning this metric is computed over the entire dataset. Raises: AttributeError: `privileged_groups` or `unprivileged_groups` must be must be provided at initialization to condition on them. """ return self.performance_measures(privileged=privileged)['TNR'] def generalized_true_positive_rate(self, privileged=None): """Return the ratio of generalized true positives to positive examples in the dataset, :math:`GTPR = GTP/P`, optionally conditioned on protected attributes. Args: privileged (bool, optional): Boolean prescribing whether to condition this metric on the `privileged_groups`, if `True`, or the `unprivileged_groups`, if `False`. Defaults to `None` meaning this metric is computed over the entire dataset. Raises: AttributeError: `privileged_groups` or `unprivileged_groups` must be must be provided at initialization to condition on them. """ return self.performance_measures(privileged=privileged)['GTPR'] def generalized_false_positive_rate(self, privileged=None): """:math:`GFPR = GFP/N` Args: privileged (bool, optional): Boolean prescribing whether to condition this metric on the `privileged_groups`, if `True`, or the `unprivileged_groups`, if `False`. Defaults to `None` meaning this metric is computed over the entire dataset. Raises: AttributeError: `privileged_groups` or `unprivileged_groups` must be must be provided at initialization to condition on them. """ return self.performance_measures(privileged=privileged)['GFPR'] def generalized_false_negative_rate(self, privileged=None): """:math:`GFNR = GFN/P` Args: privileged (bool, optional): Boolean prescribing whether to condition this metric on the `privileged_groups`, if `True`, or the `unprivileged_groups`, if `False`. Defaults to `None` meaning this metric is computed over the entire dataset. Raises: AttributeError: `privileged_groups` or `unprivileged_groups` must be must be provided at initialization to condition on them. """ return self.performance_measures(privileged=privileged)['GFNR'] def generalized_true_negative_rate(self, privileged=None): """:math:`GTNR = GTN/N` Args: privileged (bool, optional): Boolean prescribing whether to condition this metric on the `privileged_groups`, if `True`, or the `unprivileged_groups`, if `False`. Defaults to `None` meaning this metric is computed over the entire dataset. Raises: AttributeError: `privileged_groups` or `unprivileged_groups` must be must be provided at initialization to condition on them. """ return self.performance_measures(privileged=privileged)['GTNR'] def positive_predictive_value(self, privileged=None): """:math:`PPV = TP/(TP + FP)` Args: privileged (bool, optional): Boolean prescribing whether to condition this metric on the `privileged_groups`, if `True`, or the `unprivileged_groups`, if `False`. Defaults to `None` meaning this metric is computed over the entire dataset. Raises: AttributeError: `privileged_groups` or `unprivileged_groups` must be must be provided at initialization to condition on them. """ return self.performance_measures(privileged=privileged)['PPV'] def false_discovery_rate(self, privileged=None): """:math:`FDR = FP/(TP + FP)` Args: privileged (bool, optional): Boolean prescribing whether to condition this metric on the `privileged_groups`, if `True`, or the `unprivileged_groups`, if `False`. Defaults to `None` meaning this metric is computed over the entire dataset. Raises: AttributeError: `privileged_groups` or `unprivileged_groups` must be must be provided at initialization to condition on them. """ return self.performance_measures(privileged=privileged)['FDR'] def false_omission_rate(self, privileged=None): """:math:`FOR = FN/(TN + FN)` Args: privileged (bool, optional): Boolean prescribing whether to condition this metric on the `privileged_groups`, if `True`, or the `unprivileged_groups`, if `False`. Defaults to `None` meaning this metric is computed over the entire dataset. Raises: AttributeError: `privileged_groups` or `unprivileged_groups` must be must be provided at initialization to condition on them. """ return self.performance_measures(privileged=privileged)['FOR'] def negative_predictive_value(self, privileged=None): """:math:`NPV = TN/(TN + FN)` Args: privileged (bool, optional): Boolean prescribing whether to condition this metric on the `privileged_groups`, if `True`, or the `unprivileged_groups`, if `False`. Defaults to `None` meaning this metric is computed over the entire dataset. Raises: AttributeError: `privileged_groups` or `unprivileged_groups` must be must be provided at initialization to condition on them. """ return self.performance_measures(privileged=privileged)['NPV'] def accuracy(self, privileged=None): """:math:`ACC = (TP + TN)/(P + N)`. Args: privileged (bool, optional): Boolean prescribing whether to condition this metric on the `privileged_groups`, if `True`, or the `unprivileged_groups`, if `False`. Defaults to `None` meaning this metric is computed over the entire dataset. Raises: AttributeError: `privileged_groups` or `unprivileged_groups` must be must be provided at initialization to condition on them. """ return self.performance_measures(privileged=privileged)['ACC'] def error_rate(self, privileged=None): """:math:`ERR = (FP + FN)/(P + N)` Args: privileged (bool, optional): Boolean prescribing whether to condition this metric on the `privileged_groups`, if `True`, or the `unprivileged_groups`, if `False`. Defaults to `None` meaning this metric is computed over the entire dataset. Raises: AttributeError: `privileged_groups` or `unprivileged_groups` must be must be provided at initialization to condition on them. """ return 1. - self.accuracy(privileged=privileged) def true_positive_rate_difference(self): r""":math:`TPR_{D = \text{unprivileged}} - TPR_{D = \text{privileged}}` """ return self.difference(self.true_positive_rate) def false_positive_rate_difference(self): r""":math:`FPR_{D = \text{unprivileged}} - FPR_{D = \text{privileged}}` """ return self.difference(self.false_positive_rate) def false_negative_rate_difference(self): r""":math:`FNR_{D = \text{unprivileged}} - FNR_{D = \text{privileged}}` """ return self.difference(self.false_negative_rate) def false_omission_rate_difference(self): r""":math:`FOR_{D = \text{unprivileged}} - FOR_{D = \text{privileged}}` """ return self.difference(self.false_omission_rate) def false_discovery_rate_difference(self): r""":math:`FDR_{D = \text{unprivileged}} - FDR_{D = \text{privileged}}` """ return self.difference(self.false_discovery_rate) def false_positive_rate_ratio(self): r""":math:`\frac{FPR_{D = \text{unprivileged}}}{FPR_{D = \text{privileged}}}` """ return self.ratio(self.false_positive_rate) def false_negative_rate_ratio(self): r""":math:`\frac{FNR_{D = \text{unprivileged}}}{FNR_{D = \text{privileged}}}` """ return self.ratio(self.false_negative_rate) def false_omission_rate_ratio(self): r""":math:`\frac{FOR_{D = \text{unprivileged}}}{FOR_{D = \text{privileged}}}` """ return self.ratio(self.false_omission_rate) def false_discovery_rate_ratio(self): r""":math:`\frac{FDR_{D = \text{unprivileged}}}{FDR_{D = \text{privileged}}}` """ return self.ratio(self.false_discovery_rate) def average_odds_difference(self): r"""Average of difference in FPR and TPR for unprivileged and privileged groups: .. math:: \tfrac{1}{2}\left[(FPR_{D = \text{unprivileged}} - FPR_{D = \text{privileged}}) + (TPR_{D = \text{unprivileged}} - TPR_{D = \text{privileged}}))\right] A value of 0 indicates equality of odds. """ return 0.5 * (self.difference(self.false_positive_rate) + self.difference(self.true_positive_rate)) def average_abs_odds_difference(self): r"""Average of absolute difference in FPR and TPR for unprivileged and privileged groups: .. math:: \tfrac{1}{2}\left[|FPR_{D = \text{unprivileged}} - FPR_{D = \text{privileged}}| + |TPR_{D = \text{unprivileged}} - TPR_{D = \text{privileged}}|\right] A value of 0 indicates equality of odds. """ return 0.5 * (np.abs(self.difference(self.false_positive_rate)) + np.abs(self.difference(self.true_positive_rate))) def error_rate_difference(self): r"""Difference in error rates for unprivileged and privileged groups, :math:`ERR_{D = \text{unprivileged}} - ERR_{D = \text{privileged}}`. """ return self.difference(self.error_rate) def error_rate_ratio(self): r"""Ratio of error rates for unprivileged and privileged groups, :math:`\frac{ERR_{D = \text{unprivileged}}}{ERR_{D = \text{privileged}}}`. """ return self.ratio(self.error_rate) def num_pred_positives(self, privileged=None): r""":math:`\sum_{i=1}^n \mathbb{1}[\hat{y}_i = \text{favorable}]` Args: privileged (bool, optional): Boolean prescribing whether to condition this metric on the `privileged_groups`, if `True`, or the `unprivileged_groups`, if `False`. Defaults to `None` meaning this metric is computed over the entire dataset. Raises: AttributeError: `privileged_groups` or `unprivileged_groups` must be must be provided at initialization to condition on them. """ condition = self._to_condition(privileged) return utils.compute_num_pos_neg( self.classified_dataset.protected_attributes, self.classified_dataset.labels, self.classified_dataset.instance_weights, self.classified_dataset.protected_attribute_names, self.classified_dataset.favorable_label, condition=condition) def num_pred_negatives(self, privileged=None): r""":math:`\sum_{i=1}^n \mathbb{1}[\hat{y}_i = \text{unfavorable}]` Args: privileged (bool, optional): Boolean prescribing whether to condition this metric on the `privileged_groups`, if `True`, or the `unprivileged_groups`, if `False`. Defaults to `None` meaning this metric is computed over the entire dataset. Raises: AttributeError: `privileged_groups` or `unprivileged_groups` must be must be provided at initialization to condition on them. """ condition = self._to_condition(privileged) return utils.compute_num_pos_neg( self.classified_dataset.protected_attributes, self.classified_dataset.labels, self.classified_dataset.instance_weights, self.classified_dataset.protected_attribute_names, self.classified_dataset.unfavorable_label, condition=condition) def selection_rate(self, privileged=None): r""":math:`Pr(\hat{Y} = \text{favorable})` Args: privileged (bool, optional): Boolean prescribing whether to condition this metric on the `privileged_groups`, if `True`, or the `unprivileged_groups`, if `False`. Defaults to `None` meaning this metric is computed over the entire dataset. Raises: AttributeError: `privileged_groups` or `unprivileged_groups` must be must be provided at initialization to condition on them. """ return (self.num_pred_positives(privileged=privileged) / self.num_instances(privileged=privileged)) def disparate_impact(self): r""" .. math:: \frac{Pr(\hat{Y} = 1 | D = \text{unprivileged})} {Pr(\hat{Y} = 1 | D = \text{privileged})} """ return self.ratio(self.selection_rate) def statistical_parity_difference(self): r""" .. math:: Pr(\hat{Y} = 1 | D = \text{unprivileged}) - Pr(\hat{Y} = 1 | D = \text{privileged}) """ return self.difference(self.selection_rate) def generalized_entropy_index(self, alpha=2): r"""Generalized entropy index is proposed as a unified individual and group fairness measure in [3]_. With :math:`b_i = \hat{y}_i - y_i + 1`: .. math:: \mathcal{E}(\alpha) = \begin{cases} \frac{1}{n \alpha (\alpha-1)}\sum_{i=1}^n\left[\left(\frac{b_i}{\mu}\right)^\alpha - 1\right],& \alpha \ne 0, 1,\\ \frac{1}{n}\sum_{i=1}^n\frac{b_{i}}{\mu}\ln\frac{b_{i}}{\mu},& \alpha=1,\\ -\frac{1}{n}\sum_{i=1}^n\ln\frac{b_{i}}{\mu},& \alpha=0. \end{cases} Args: alpha (int): Parameter that regulates the weight given to distances between values at different parts of the distribution. References: .. [3] <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, and <NAME>, "A Unified Approach to Quantifying Algorithmic Unfairness: Measuring Individual and Group Unfairness via Inequality Indices," ACM SIGKDD International Conference on Knowledge Discovery and Data Mining, 2018. """ y_pred = self.classified_dataset.labels.ravel() y_true = self.dataset.labels.ravel() y_pred = (y_pred == self.classified_dataset.favorable_label).astype( np.float64) y_true = (y_true == self.dataset.favorable_label).astype(np.float64) b = 1 + y_pred - y_true if alpha == 1: # moving the b inside the log allows for 0 values return np.mean(np.log((b / np.mean(b))**b) / np.mean(b)) elif alpha == 0: return -np.mean(np.log(b / np.mean(b)) / np.mean(b)) else: return np.mean((b / np.mean(b))**alpha - 1) / (alpha * (alpha - 1)) def _between_group_generalized_entropy_index(self, groups, alpha=2): r"""Between-group generalized entropy index is proposed as a group fairness measure in [2]_ and is one of two terms that the generalized entropy index decomposes to. Args: groups (list): A list of groups over which to calculate this metric. Groups should be disjoint. By default, this will use the `privileged_groups` and `unprivileged_groups` as the only two groups. alpha (int): See :meth:`generalized_entropy_index`. References: .. [2] <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, and <NAME>, "A Unified Approach to Quantifying Algorithmic Unfairness: Measuring Individual and Group Unfairness via Inequality Indices," ACM SIGKDD International Conference on Knowledge Discovery and Data Mining, 2018. """ b = np.zeros(self.dataset.labels.size, dtype=np.float64) for group in groups: classified_group = utils.compute_boolean_conditioning_vector( self.classified_dataset.protected_attributes, self.classified_dataset.protected_attribute_names, condition=group) true_group = utils.compute_boolean_conditioning_vector( self.dataset.protected_attributes, self.dataset.protected_attribute_names, condition=group) # ignore if there are no members of this group present if not np.any(true_group): continue y_pred = self.classified_dataset.labels[classified_group].ravel() y_true = self.dataset.labels[true_group].ravel() y_pred = (y_pred == self.classified_dataset.favorable_label).astype( np.float64) y_true = (y_true == self.dataset.favorable_label).astype(np.float64) b[true_group] = np.mean(1 + y_pred - y_true) if alpha == 1: return np.mean(np.log((b / np.mean(b))**b) /
np.mean(b)
numpy.mean
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Sep 20 18:42:58 2018 @author: owenmadin """ #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Sep 20 11:33:46 2018 @author: owenmadin """ """ This code performs an RJMC model selection problem over three square regions of uniform probability, defined as squares of side length 1,2 and 5 with one corner at (0,0) and another at (s,s). The uniform probability is defined as positive inside each square, and zero outside each square. """ import numpy as np import scipy as sp import matplotlib.pyplot as plt import pandas as pd import yaml from LennardJones_correlations import LennardJones from LennardJones_2Center_correlations import LennardJones_2C from scipy.stats import distributions from scipy.stats import linregress from scipy.optimize import minimize import random as rm # Define probabilities for both regions def test_pdf_1(model,x,y): if model == 0: if 0 <= x <= 1 and 0 <= y <= 1: f=5 else: f=0 if model == 1: if 0 <= x <= 2 and 0 <= y <= 2: f=5 else: f=0 if model == 2: if 0 <= x <= 5 and 0 <= y <= 5: f=5 else: f=0 return f def test_pdf_2(model,x,y): if model == 0: if 0 <= x <= 1 and 0 <= y <= 1: f=5 else: f=0 if model == 1: if 1 <= x <= 3 and 1 <= y <= 3: f=5 else: f=0 if model == 2: if 3 <= x <= 6 and 3 <= y <= 6: f=5 else: f=0 return f dnorm = distributions.norm.logpdf dgamma = distributions.gamma.logpdf duni = distributions.uniform.logpdf rnorm = np.random.normal runif = np.random.rand #Define log priors for the distributions. For now, we will use a uniform prior on (10,10), but we may want to change the prior for different models in the future def calc_posterior(model,x,y): logp = 0 logp += duni(x, 0, 10) logp += duni(y, 0, 10) #prop_density=test_pdf_1(model,x,y) prop_density=test_pdf_2(model,x,y) logp += np.log(prop_density) return logp def T_matrix_scale_one(): T_matrix_x_scale=np.ones((3,3)) T_matrix_y_scale=np.ones((3,3)) T_matrix_x_scale[0,1]=3 T_matrix_y_scale[0,1]=3 T_matrix_x_scale[1,0]=1./3 T_matrix_y_scale[1,0]=1./3 T_matrix_x_scale[0,2]=6 T_matrix_y_scale[0,2]=6 T_matrix_x_scale[2,0]=1./6 T_matrix_y_scale[2,0]=1./6 T_matrix_x_scale[1,2]=6./3 T_matrix_y_scale[1,2]=6./3 T_matrix_x_scale[2,1]=3./6 T_matrix_y_scale[2,1]=3./6 return T_matrix_x_scale, T_matrix_y_scale def T_matrix_scale_two(): T_matrix_x_scale=np.ones((3,3)) T_matrix_y_scale=np.ones((3,3)) T_matrix_x_scale[0,1]=4 T_matrix_x_scale[1,0]=1./4 T_matrix_x_scale[0,2]=9 T_matrix_x_scale[2,0]=1./9 T_matrix_x_scale[1,2]=9/4 T_matrix_x_scale[2,1]=4./9 T_matrix_y_scale[0,1]=4 T_matrix_y_scale[1,0]=1./4 T_matrix_y_scale[0,2]=9 T_matrix_y_scale[2,0]=1./9 T_matrix_y_scale[1,2]=9./4 T_matrix_y_scale[2,1]=4./9 return T_matrix_x_scale, T_matrix_y_scale def T_matrix_translation(): T_matrix_x=np.zeros((2,2)) T_matrix_y=np.zeros((2,2)) T_matrix_x[0,1]=2 T_matrix_y[0,1]=2 T_matrix_x[1,0]=-2 T_matrix_y[1,0]=-2 return T_matrix_x, T_matrix_y T_matrix_x_scale_1, T_matrix_y_scale_1 = T_matrix_scale_one() T_matrix_x_scale_2, T_matrix_y_scale_2 = T_matrix_scale_two() def RJMC_tuned(calc_posterior,n_iterations, initial_values, prop_var, tune_for=None, tune_interval=1, map_scale='False'): n_params = len(initial_values) #One column is the model number # Initial proposal standard deviations prop_sd = prop_var # Initialize trace for parameters trace = np.zeros((n_iterations+1, n_params)) #n_iterations + 1 to account for guess logp_trace = np.zeros(n_iterations+1) # Set initial values trace[0] = initial_values # Initialize acceptance counts accepted = [0]*n_params rejected = [0]*n_params model_swaps = 0 model_swap_attempts = 0 swap_freq = 1 swap_flag='False' # OCM: Currently attempting a model swap every single move, although this can be easily changed. This is something that is not of critical importance now but will be important in the future. # Calculate joint posterior for initial values current_log_prob = calc_posterior(*trace[0]) logp_trace[0] = current_log_prob #OCM: This is just the priors at this point. if tune_for is None: tune_for = n_iterations/2 for i in range(n_iterations): swap_flag='False' if not i%1000: print('Iteration '+str(i)) # Grab current parameter values current_params = trace[i].copy() trace[i+1] = current_params.copy() #Initialize the next step with the current step. Then update if MCMC move is accepted current_model = int(current_params[0]) logp_trace[i+1] = current_log_prob.copy() # Loop through model parameters for j in range(n_params): # Get current value for parameter j params = current_params.copy() # This approach updates previous param values # Propose new values if j == 0: #If proposing a new model if not i%swap_freq: mod_ran = np.random.random() if mod_ran < 1./3: #Use new models with equal probability proposed_model = 0 elif mod_ran >= 2./3: proposed_model = 1 else: proposed_model = 2 if proposed_model != current_model: model_swap_attempts += 1 params[0] = proposed_model if map_scale=='True': params[1] *= T_matrix_x_scale_1[current_model,proposed_model] params[2] *= T_matrix_y_scale_1[current_model,proposed_model] #params[1] *= T_matrix_x_scale_2[current_model,proposed_model] #params[2] *= T_matrix_y_scale_2[current_model,proposed_model] ''' else: params[1] += T_matrix_x[current_model,proposed_model] params[2] += T_matrix_y[current_model,proposed_model] # Calculate log posterior with proposed value ''' proposed_log_prob = calc_posterior(*params) # Log-acceptance rate alpha = (proposed_log_prob - current_log_prob) + np.log(T_matrix_x_scale_1[current_model,proposed_model]) + np.log(T_matrix_y_scale_1[current_model,proposed_model]) #alpha = (proposed_log_prob - current_log_prob) + np.log(T_matrix_x_scale_2[current_model,proposed_model]) + np.log(T_matrix_y_scale_2[current_model,proposed_model]) urv = runif() # Test proposed value if np.log(urv) < alpha: # Accept trace[i+1] = params logp_trace[i+1] = proposed_log_prob.copy() current_log_prob = proposed_log_prob.copy() current_params = params accepted[j] += 1 if j == 0: if proposed_model != current_model: model_swaps += 1 swap_flag = 'True' else: if swap_flag=='False': params[j] = rnorm(current_params[j], prop_sd[j]) # Calculate log posterior with proposed value proposed_log_prob = calc_posterior(*params) # Log-acceptance rate alpha = (proposed_log_prob - current_log_prob) #OCM: The two components of the acceptance ratio here are the log of the ratio of the probabilities, and the log of the jacobian determinant between the model spaces # Sample a uniform random variate (urv) urv = runif() # Test proposed value if
np.log(urv)
numpy.log
import logging import unittest import numpy as np from mne import BaseEpochs from moabb.datasets.fake import FakeDataset from moabb.paradigms import ( P300, SSVEP, BaseMotorImagery, BaseP300, BaseSSVEP, FilterBankLeftRightImagery, FilterBankMotorImagery, FilterBankSSVEP, LeftRightImagery, ) log = logging.getLogger(__name__) log.setLevel(logging.ERROR) class SimpleMotorImagery(BaseMotorImagery): # Needed to assess BaseImagery def used_events(self, dataset): return dataset.event_id class Test_MotorImagery(unittest.TestCase): def test_BaseImagery_paradigm(self): paradigm = SimpleMotorImagery() dataset = FakeDataset(paradigm="imagery") X, labels, metadata = paradigm.get_data(dataset, subjects=[1]) # we should have all the same length self.assertEqual(len(X), len(labels), len(metadata)) # X must be a 3D Array self.assertEqual(len(X.shape), 3) # labels must contain 3 values self.assertEqual(len(np.unique(labels)), 3) # metadata must have subjets, sessions, runs self.assertTrue("subject" in metadata.columns) self.assertTrue("session" in metadata.columns) self.assertTrue("run" in metadata.columns) # we should have only one subject in the metadata self.assertEqual(np.unique(metadata.subject), 1) # we should have two sessions in the metadata self.assertEqual(len(np.unique(metadata.session)), 2) # should return epochs epochs, _, _ = paradigm.get_data(dataset, subjects=[1], return_epochs=True) self.assertIsInstance(epochs, BaseEpochs) def test_BaseImagery_channel_order(self): """test if paradigm return correct channel order, see issue #227""" datasetA = FakeDataset(paradigm="imagery", channels=["C3", "Cz", "C4"]) datasetB = FakeDataset(paradigm="imagery", channels=["Cz", "C4", "C3"]) paradigm = SimpleMotorImagery(channels=["C4", "C3", "Cz"]) ep1, _, _ = paradigm.get_data(datasetA, subjects=[1], return_epochs=True) ep2, _, _ = paradigm.get_data(datasetB, subjects=[1], return_epochs=True) self.assertEqual(ep1.info["ch_names"], ep2.info["ch_names"]) def test_BaseImagery_tmintmax(self): self.assertRaises(ValueError, SimpleMotorImagery, tmin=1, tmax=0) def test_BaseImagery_filters(self): # can work with filter bank paradigm = SimpleMotorImagery(filters=[[7, 12], [12, 24]]) dataset = FakeDataset(paradigm="imagery") X, labels, metadata = paradigm.get_data(dataset, subjects=[1]) # X must be a 4D Array self.assertEqual(len(X.shape), 4) self.assertEqual(X.shape[-1], 2) # should return epochs epochs, _, _ = paradigm.get_data(dataset, subjects=[1], return_epochs=True) self.assertIsInstance(epochs, BaseEpochs) def test_baseImagery_wrongevent(self): # test process_raw return empty list if raw does not contain any # selected event. cetain runs in dataset are event specific. paradigm = SimpleMotorImagery(filters=[[7, 12], [12, 24]]) dataset = FakeDataset(paradigm="imagery") raw = dataset.get_data([1])[1]["session_0"]["run_0"] # add something on the event channel raw._data[-1] *= 10 self.assertIsNone(paradigm.process_raw(raw, dataset)) # zeros it out raw._data[-1] *= 0 self.assertIsNone(paradigm.process_raw(raw, dataset)) def test_BaseImagery_noevent(self): # Assert error if events from paradigm and dataset dont overlap paradigm = SimpleMotorImagery(events=["left_hand", "right_hand"]) dataset = FakeDataset(paradigm="imagery") self.assertRaises(AssertionError, paradigm.get_data, dataset) def test_LeftRightImagery_paradigm(self): # with a good dataset paradigm = LeftRightImagery() dataset = FakeDataset(event_list=["left_hand", "right_hand"], paradigm="imagery") X, labels, metadata = paradigm.get_data(dataset, subjects=[1]) self.assertEqual(len(np.unique(labels)), 2) self.assertEqual(list(np.unique(labels)), ["left_hand", "right_hand"]) # should return epochs epochs, _, _ = paradigm.get_data(dataset, subjects=[1], return_epochs=True) self.assertIsInstance(epochs, BaseEpochs) def test_LeftRightImagery_noevent(self): # we cant pass event to this class self.assertRaises(ValueError, LeftRightImagery, events=["a"]) def test_LeftRightImagery_badevents(self): paradigm = LeftRightImagery() # does not accept dataset with bad event dataset = FakeDataset(paradigm="imagery") self.assertRaises(AssertionError, paradigm.get_data, dataset) def test_FilterBankMotorImagery_paradigm(self): # can work with filter bank paradigm = FilterBankMotorImagery() dataset = FakeDataset(paradigm="imagery") X, labels, metadata = paradigm.get_data(dataset, subjects=[1]) # X must be a 4D Array self.assertEqual(len(X.shape), 4) self.assertEqual(X.shape[-1], 6) # should return epochs epochs, _, _ = paradigm.get_data(dataset, subjects=[1], return_epochs=True) self.assertIsInstance(epochs, BaseEpochs) def test_FilterBankMotorImagery_moreclassesthanevent(self): self.assertRaises( AssertionError, FilterBankMotorImagery, n_classes=3, events=["hands", "feet"] ) def test_FilterBankLeftRightImagery_paradigm(self): # can work with filter bank paradigm = FilterBankLeftRightImagery() dataset = FakeDataset(event_list=["left_hand", "right_hand"], paradigm="imagery") X, labels, metadata = paradigm.get_data(dataset, subjects=[1]) # X must be a 4D Array self.assertEqual(len(X.shape), 4) self.assertEqual(X.shape[-1], 6) # should return epochs epochs, _, _ = paradigm.get_data(dataset, subjects=[1], return_epochs=True) self.assertIsInstance(epochs, BaseEpochs) class SimpleP300(BaseP300): # Needed to assess BaseP300 def used_events(self, dataset): return dataset.event_id class Test_P300(unittest.TestCase): def test_BaseP300_paradigm(self): paradigm = SimpleP300() dataset = FakeDataset(paradigm="p300", event_list=["Target", "NonTarget"]) X, labels, metadata = paradigm.get_data(dataset, subjects=[1]) # we should have all the same length self.assertEqual(len(X), len(labels), len(metadata)) # X must be a 3D Array self.assertEqual(len(X.shape), 3) # labels must contain 2 values (Target/NonTarget) self.assertEqual(len(np.unique(labels)), 2) # metadata must have subjets, sessions, runs self.assertTrue("subject" in metadata.columns) self.assertTrue("session" in metadata.columns) self.assertTrue("run" in metadata.columns) # we should have only one subject in the metadata self.assertEqual(np.unique(metadata.subject), 1) # we should have two sessions in the metadata self.assertEqual(len(np.unique(metadata.session)), 2) # should return epochs epochs, _, _ = paradigm.get_data(dataset, subjects=[1], return_epochs=True) self.assertIsInstance(epochs, BaseEpochs) def test_BaseP300_channel_order(self): """test if paradigm return correct channel order, see issue #227""" datasetA = FakeDataset( paradigm="p300", channels=["C3", "Cz", "C4"], event_list=["Target", "NonTarget"], ) datasetB = FakeDataset( paradigm="p300", channels=["Cz", "C4", "C3"], event_list=["Target", "NonTarget"], ) paradigm = SimpleP300(channels=["C4", "C3", "Cz"]) ep1, _, _ = paradigm.get_data(datasetA, subjects=[1], return_epochs=True) ep2, _, _ = paradigm.get_data(datasetB, subjects=[1], return_epochs=True) self.assertEqual(ep1.info["ch_names"], ep2.info["ch_names"]) def test_BaseP300_tmintmax(self): self.assertRaises(ValueError, SimpleP300, tmin=1, tmax=0) def test_BaseP300_filters(self): # can work with filter bank paradigm = SimpleP300(filters=[[1, 12], [12, 24]]) dataset = FakeDataset(paradigm="p300", event_list=["Target", "NonTarget"]) X, labels, metadata = paradigm.get_data(dataset, subjects=[1]) # X must be a 4D Array self.assertEqual(len(X.shape), 4) self.assertEqual(X.shape[-1], 2) # should return epochs epochs, _, _ = paradigm.get_data(dataset, subjects=[1], return_epochs=True) self.assertIsInstance(epochs, BaseEpochs) def test_BaseP300_wrongevent(self): # test process_raw return empty list if raw does not contain any # selected event. cetain runs in dataset are event specific. paradigm = SimpleP300(filters=[[1, 12], [12, 24]]) dataset = FakeDataset(paradigm="p300", event_list=["Target", "NonTarget"]) raw = dataset.get_data([1])[1]["session_0"]["run_0"] # add something on the event channel raw._data[-1] *= 10 self.assertIsNone(paradigm.process_raw(raw, dataset)) # zeros it out raw._data[-1] *= 0 self.assertIsNone(paradigm.process_raw(raw, dataset)) def test_P300_specifyevent(self): # we cant pass event to this class self.assertRaises(ValueError, P300, events=["a"]) def test_P300_wrongevent(self): # does not accept dataset with bad event paradigm = P300() dataset = FakeDataset(paradigm="p300") self.assertRaises(AssertionError, paradigm.get_data, dataset) def test_P300_paradigm(self): # with a good dataset paradigm = P300() dataset = FakeDataset(event_list=["Target", "NonTarget"], paradigm="p300") X, labels, metadata = paradigm.get_data(dataset, subjects=[1]) self.assertEqual(len(np.unique(labels)), 2) self.assertEqual(list(np.unique(labels)), sorted(["Target", "NonTarget"])) # should return epochs epochs, _, _ = paradigm.get_data(dataset, subjects=[1], return_epochs=True) self.assertIsInstance(epochs, BaseEpochs) class Test_SSVEP(unittest.TestCase): def test_BaseSSVEP_paradigm(self): paradigm = BaseSSVEP(n_classes=None) dataset = FakeDataset(paradigm="ssvep") X, labels, metadata = paradigm.get_data(dataset, subjects=[1]) # Verify that they have the same length self.assertEqual(len(X), len(labels), len(metadata)) # X must be a 3D array self.assertEqual(len(X.shape), 3) # labels must contain 3 values self.assertEqual(len(np.unique(labels)), 3) # metadata must have subjets, sessions, runs self.assertTrue("subject" in metadata.columns) self.assertTrue("session" in metadata.columns) self.assertTrue("run" in metadata.columns) # Only one subject in the metadata self.assertEqual(np.unique(metadata.subject), 1) # we should have two sessions in the metadata, n_classes = 2 as default self.assertEqual(len(np.unique(metadata.session)), 2) # should return epochs epochs, _, _ = paradigm.get_data(dataset, subjects=[1], return_epochs=True) self.assertIsInstance(epochs, BaseEpochs) def test_BaseSSVEP_channel_order(self): """test if paradigm return correct channel order, see issue #227""" datasetA = FakeDataset(paradigm="ssvep", channels=["C3", "Cz", "C4"]) datasetB = FakeDataset(paradigm="ssvep", channels=["Cz", "C4", "C3"]) paradigm = BaseSSVEP(channels=["C4", "C3", "Cz"]) ep1, _, _ = paradigm.get_data(datasetA, subjects=[1], return_epochs=True) ep2, _, _ = paradigm.get_data(datasetB, subjects=[1], return_epochs=True) self.assertEqual(ep1.info["ch_names"], ep2.info["ch_names"]) def test_baseSSVEP_tmintmax(self): # Verify that tmin < tmax self.assertRaises(ValueError, BaseSSVEP, tmin=1, tmax=0) def test_BaseSSVEP_filters(self): # Accept filters paradigm = BaseSSVEP(filters=[(10.5, 11.5), (12.5, 13.5)]) dataset = FakeDataset(paradigm="ssvep") X, labels, metadata = paradigm.get_data(dataset, subjects=[1]) # X must be a 4D array self.assertEqual(len(X.shape), 4) # Last dim should be 2 as the number of filters self.assertEqual(X.shape[-1], 2) # should return epochs epochs, _, _ = paradigm.get_data(dataset, subjects=[1], return_epochs=True) self.assertIsInstance(epochs, BaseEpochs) def test_BaseSSVEP_nclasses_default(self): # Default is with 3 classes paradigm = BaseSSVEP() dataset = FakeDataset(paradigm="ssvep") X, labels, metadata = paradigm.get_data(dataset, subjects=[1]) # labels must contain all 3 classes of dataset, # as n_classes is "None" by default (taking all classes) self.assertEqual(len(
np.unique(labels)
numpy.unique
import time import numpy as np import multiprocessing as mp import ctypes from rlpyt.samplers.base import BaseSampler from rlpyt.samplers.utils import build_samples_buffer, build_step_buffer from rlpyt.samplers.parallel_worker import sampling_process from rlpyt.samplers.gpu.collectors import EvalCollector from rlpyt.utils.logging import logger from rlpyt.agents.base import AgentInputs from rlpyt.utils.collections import AttrDict EVAL_TRAJ_CHECK = 0.2 # Seconds. class AsyncGpuSampler(BaseSampler): ########################################################################### # Master runner methods. ########################################################################### def master_runner_initialize(self, agent, bootstrap_value=False, traj_info_kwargs=None): # Construct an example of each kind of data that needs to be stored. env = self.EnvCls(**self.env_kwargs) agent.initialize(env.spaces, share_memory=True) # Actual agent initialization, keep. samples_pyt, samples_np, examples = build_samples_buffer(agent, env, self.batch_spec, bootstrap_value, agent_shared=True, env_shared=True, subprocess=False) # Would like subprocess=True, but might hang? _, samples_np2, _ = build_samples_buffer(agent, env, self.batch_spec, bootstrap_value, agent_shared=True, env_shared=True, subprocess=False) env.close() del env if traj_info_kwargs: for k, v in traj_info_kwargs.items(): setattr(self.TrajInfoCls, "_" + k, v) self.double_buffer = double_buffer = (samples_np, samples_np2) self.examples = examples return double_buffer, examples ########################################################################### # Sampler runner methods (forked). ########################################################################### def sample_runner_initialize(self, affinity): n_server = len(affinity) n_worker = sum(len(aff["workers_cpus"]) for aff in affinity) n_envs_list = [self.batch_spec.B // n_worker] * n_worker if not self.batch_spec.B % n_worker == 0: logger.log("WARNING: unequal number of envs per process, from " f"batch_B {self.batch_spec.B} and n_parallel {n_worker} " "(possible suboptimal speed).") for b in range(self.batch_spec.B % n_worker): n_envs_list[b] += 1 if self.eval_n_envs > 0: eval_n_envs_per = max(1, self.eval_n_envs // len(n_envs_list)) eval_n_envs = eval_n_envs_per * n_worker logger.log(f"Total parallel evaluation envs: {eval_n_envs}.") self.eval_max_T = 1 + int(self.eval_max_steps // eval_n_envs) self.eval_n_envs_per = eval_n_envs_per else: self.eval_n_envs_per = 0 self.eval_max_T = 0 ctrl = AttrDict( quit=mp.RawValue(ctypes.c_bool, False), barrier_in=mp.Barrier(n_server + n_worker + 1), barrier_out=mp.Barrier(n_server + n_worker + 1), do_eval=mp.RawValue(ctypes.c_bool, False), itr=mp.RawValue(ctypes.c_long, 0), ) traj_infos_queue = mp.Queue() common_kwargs = dict( ctrl=ctrl, traj_infos_queue=traj_infos_queue, ) servers_kwargs = assemble_servers_kwargs(affinity, n_envs_list, self.seed, self.double_buffer) servers = [mp.Process(target=self.action_server_process, kwargs=s_kwargs.update(**common_kwargs)) for s_kwargs in servers_kwargs] for s in servers: s.start() self.servers = servers self.ctrl = ctrl self.traj_infos_queue = traj_infos_queue def obtain_samples(self, itr): self.ctrl.barrier_in.wait() # Sampling in sub-processes here. self.ctrl.barrier_out.wait() traj_infos = list() while self.traj_infos_queue.qsize(): traj_infos.append(self.traj_infos_queue.get()) return traj_infos def evaluate_agent(self, itr): self.ctrl.do_eval = True self.sync.stop_eval.value = False self.ctrl.barrier_in.wait() traj_infos = list() if self.eval_max_trajectories is not None: while True: time.sleep(EVAL_TRAJ_CHECK) while self.traj_infos_queue.qsize(): traj_infos.append(self.traj_infos_queue.get()) if len(traj_infos) >= self.eval_max_trajectories: self.sync.stop_eval.value = True logger.log("Evaluation reached max num trajectories " f"({self.eval_max_trajectories}).") break # Stop possibly before workers reach max_T. if self.ctrl.barrier_out.parties - self.ctrl.barrier_out.n_waiting == 1: logger.log("Evaluation reached max num time steps " f"({self.eval_max_T}).") break # Workers reached max_T. self.ctrl.barrier_out.wait() while self.traj_infos_queue.qsize(): traj_infos.append(self.traj_infos_queue.get()) self.ctrl.do_eval.value = False return traj_infos def shutdown(self): self.ctrl.quit.value = True self.ctrl.barrier_in.wait() for s in self.servers: s.join() ########################################################################### # Methods in forked action server process. ########################################################################### def action_server_process(self, double_buffer_slice, ctrl, traj_infos_queue, affinity, seed, n_envs_list): """Runs in forked process, inherits from original process, so can easily pass args to env worker processes, forked from here.""" self.ctrl = ctrl self.launch_workers(double_buffer_slice, traj_infos_queue, affinity, seed, n_envs_list) self.agent.initialize_cuda(cuda_idx=affinity["cuda_idx"], ddp=False) while True: self.ctrl.barrier_in.wait() if self.ctrl.quit.value: break self.agent.recv_shared_memory() if self.ctrl.do_eval.value: self.agent.eval_mode(self.ctrl.itr.value) self.serve_actions_evaluation() else: self.agent.sample_mode(self.ctrl.itr.value) self.serve_actions() self.ctrl.barrier_out.wait() self.shutdown_workers() def serve_actions(self): step_blockers, act_waiters = self.sync.step_blockers, self.sync.act_waiters step_np, step_pyt = self.step_buffer_np, self.step_buffer_pyt agent_inputs = AgentInputs(step_pyt.observation, step_pyt.action, step_pyt.reward) # Fixed buffer objects. for t in range(self.batch_spec.T): for b in step_blockers: b.acquire() # Workers written obs and rew, first prev_act. if self.mid_batch_reset and np.any(step_np.done): for b_reset in np.where(step_np.done)[0]: step_np.action[b_reset] = 0 # Null prev_action into agent. step_np.reward[b_reset] = 0 # Null prev_reward into agent. self.agent.reset_one(idx=b_reset) action, agent_info = self.agent.step(*agent_inputs) step_np.action[:] = action # Worker applies to env. step_np.agent_info[:] = agent_info # Worker sends to traj_info. for w in act_waiters: w.release() # Signal to worker. for b in step_blockers: b.acquire() if "bootstrap_value" in self.samples_np.agent: self.samples_np.agent.bootstrap_value[:] = self.agent.value( *agent_inputs) if
np.any(step_np.done)
numpy.any
import itertools import warnings from inspect import signature from timeit import default_timer from sklearn.preprocessing import normalize import dask import numpy as np try: import shap except: msg = "SHAP not found, therefore using SHAP-values for feature importance not available." warnings.warn(msg) shap = None from dask import delayed from networkx import NetworkXUnfeasible, find_cycle, topological_sort from sklearn.ensemble import ( ExtraTreesClassifier, ExtraTreesRegressor, RandomForestClassifier, RandomForestRegressor, ) from sklearn.impute import SimpleImputer from sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor from ..algo import ( evaluation, imputation, inference, inference_v3, new_inference, new_prediction, selection, vector_prediction, ) from ..algo.induction import base_induction_algorithm, expand_induction_algorithm from ..composition import CompositeModel, NewCompositeModel, o, x from ..graph import build_diagram, compose_all, get_targ, model_to_graph from ..utils import ( DESC_ENCODING, MISS_ENCODING, TARG_ENCODING, DecoratedDecisionTreeClassifier, DecoratedDecisionTreeRegressor, DecoratedRandomForestClassifier, DecoratedRandomForestRegressor, code_to_query, get_i_o, query_to_code, ) from ..visuals import save_diagram, show_diagram try: from xgboost import XGBClassifier as XGBC from xgboost import XGBRegressor as XGBR except: XGBC, XGBR = None, None try: from lightgbm import LGBMClassifier as LGBMC from lightgbm import LGBMRegressor as LGBMR except: LGBMC, LGBMR = None, None try: from catboost import CatBoostClassifier as CBC from catboost import CatBoostRegressor as CBR except: CBC, CBR = None, None try: from wekalearn import RandomForestClassifier as WLC from wekalearn import RandomForestRegressor as WLR except: WLC, WLR = None, None class Mercs(object): delimiter = "_" selection_algorithms = dict( default=selection.base_selection_algorithm, base=selection.base_selection_algorithm, random=selection.random_selection_algorithm, ) induction_algorithms = dict( base=base_induction_algorithm, default=base_induction_algorithm, expand=expand_induction_algorithm, ) classifier_algorithms = dict( DT=DecisionTreeClassifier, DDT=DecoratedDecisionTreeClassifier, RF=RandomForestClassifier, DRF=DecoratedRandomForestClassifier, XGB=XGBC, xgb=XGBC, weka=WLC, LGBM=LGBMC, lgbm=LGBMC, CB=CBC, extra=ExtraTreesClassifier, ) regressor_algorithms = dict( DT=DecisionTreeRegressor, DDT=DecoratedDecisionTreeRegressor, RF=RandomForestRegressor, DRF=DecoratedDecisionTreeRegressor, XGB=XGBR, xgb=XGBR, weka=WLR, LGBM=LGBMR, lgbm=LGBMR, CB=CBR, extra=ExtraTreesRegressor, ) prediction_algorithms = dict( mi=vector_prediction.mi, mrai=vector_prediction.mrai, it=vector_prediction.it, rw=vector_prediction.rw, ) inference_algorithms = dict( base=inference.base_inference_algorithm, dask=inference_v3.inference_algorithm, own=inference_v3.inference_algorithm, ) imputer_algorithms = dict( nan=imputation.nan_imputation, NAN=imputation.nan_imputation, NaN=imputation.nan_imputation, null=imputation.nan_imputation, NULL=imputation.nan_imputation, skl=imputation.skl_imputation, base=imputation.skl_imputation, default=imputation.skl_imputation, ) evaluation_algorithms = dict( base=evaluation.base_evaluation, default=evaluation.base_evaluation, dummy=evaluation.dummy_evaluation, ) # Used in parse kwargs to identify parameters. If this identification goes wrong, you are sending settings # somewhere you do not want them to be. So, this is a tricky part, and moreover hardcoded. In other words: # this is risky terrain, and should probably be done differently in the future. configuration_prefixes = dict( imputation={"imputation", "imp"}, induction={"induction", "ind"}, selection={"selection", "sel"}, prediction={"prediction", "pred", "prd"}, inference={"inference", "infr", "inf"}, classification={"classification", "classifier", "clf"}, regression={"regression", "regressor", "rgr"}, metadata={"metadata", "meta", "mtd"}, evaluation={"evaluation", "evl"}, ) def __init__( self, selection_algorithm="base", induction_algorithm="base", classifier_algorithm="DT", regressor_algorithm="DT", prediction_algorithm="mi", inference_algorithm="own", imputer_algorithm="default", evaluation_algorithm="default", random_state=42, **kwargs ): self.params = dict( selection_algorithm=selection_algorithm, induction_algorithm=induction_algorithm, classifier_algorithm=classifier_algorithm, regressor_algorithm=regressor_algorithm, prediction_algorithm=prediction_algorithm, inference_algorithm=inference_algorithm, imputer_algorithm=imputer_algorithm, evaluation_algorithm=evaluation_algorithm, random_state=random_state, ) self.params = {**self.params, **kwargs} self.random_state = random_state self.selection_algorithm = self.selection_algorithms[selection_algorithm] # N.b.: First try to look up the key. If the key is not found, we assume the algorithm itself was passed. self.classifier_algorithm = self.classifier_algorithms.get( classifier_algorithm, classifier_algorithm ) self.regressor_algorithm = self.regressor_algorithms.get( regressor_algorithm, regressor_algorithm ) self.prediction_algorithm = self.prediction_algorithms[prediction_algorithm] self.inference_algorithm = self.inference_algorithms[inference_algorithm] self.induction_algorithm = self.induction_algorithms[ induction_algorithm ] # For now, we only have one. self.imputer_algorithm = self.imputer_algorithms[imputer_algorithm] self.evaluation_algorithm = self.evaluation_algorithms[evaluation_algorithm] # Data-structures self.m_codes = np.array([]) self.m_list = [] self.c_list = [] self.g_list = [] self.i_list = [] self.m_fimps = np.array([]) self.m_score = np.array([]) self.FI = np.array([]) self.targ_ids = np.array([]) # Query-related things self.q_code = None self.q_desc_ids = None self.q_targ_ids = None self.q_diagram = None self.q_compose = None self.q_methods = [] # Configurations self.imp_cfg = self._default_config(self.imputer_algorithm) self.ind_cfg = self._default_config(self.induction_algorithm) self.sel_cfg = self._default_config(self.selection_algorithm) self.clf_cfg = self._default_config(self.classifier_algorithm) self.rgr_cfg = self._default_config(self.regressor_algorithm) self.prd_cfg = self._default_config(self.prediction_algorithm) self.inf_cfg = self._default_config(self.inference_algorithm) self.evl_cfg = self._default_config(self.evaluation_algorithm) self.configuration = dict( imputation=self.imp_cfg, induction=self.ind_cfg, selection=self.sel_cfg, classification=self.clf_cfg, regression=self.rgr_cfg, prediction=self.prd_cfg, inference=self.inf_cfg, ) # Collect all configs in one self._update_config(random_state=random_state, **kwargs) self.metadata = dict() self.model_data = dict() self._extra_checks_on_config() return def fit(self, X, y=None, m_codes=None, **kwargs): assert isinstance(X, np.ndarray) if y is not None: assert isinstance(y, np.ndarray) X = np.c_[X, y] tic = default_timer() self.metadata = self._default_metadata(X) self._update_metadata(**kwargs) self.i_list = self.imputer_algorithm(X, self.metadata.get("nominal_attributes")) # N.b.: `random state` parameter is in `self.sel_cfg` if m_codes is None: self.m_codes = self.selection_algorithm(self.metadata, **self.sel_cfg) else: self.m_codes = m_codes self.m_list = self.induction_algorithm( X, self.m_codes, self.metadata, self.classifier_algorithm, self.regressor_algorithm, self.clf_cfg, self.rgr_cfg, **self.ind_cfg ) self._filter_m_list_m_codes() self._consistent_datastructures() if self.imputer_algorithm == self.imputer_algorithms.get("nan"): # If you do no have imputers, you cannot use them as a baseline evaluation self.evl_cfg["consider_imputations"] = False self.m_score = self.evaluation_algorithm( X, self.m_codes, self.m_list, self.i_list, **self.evl_cfg ) toc = default_timer() self.model_data["ind_time"] = toc - tic self.metadata["n_component_models"] = len(self.m_codes) return def predict( self, X, q_code=None, inference_algorithm=None, prediction_algorithm=None, **kwargs ): # Update configuration if necessary if q_code is None: q_code = self._default_q_code() if inference_algorithm is not None: self._reconfig_inference(inference_algorithm=inference_algorithm) if prediction_algorithm is not None: self._reconfig_prediction( prediction_algorithm=prediction_algorithm, **kwargs ) # Adjust data self.q_code = q_code self.q_desc_ids, self.q_targ_ids, _ = code_to_query( self.q_code, return_list=True ) # Make query-diagram tic_prediction = default_timer() self.m_sel = self.prediction_algorithm( self.m_codes, self.m_fimps, self.m_score, q_code=self.q_code, **self.prd_cfg ) toc_prediction = default_timer() tic_diagram = default_timer() self.q_diagram = self._build_q_diagram(self.m_list, self.m_sel) toc_diagram = default_timer() tic_infalgo = default_timer() if isinstance(self.q_diagram, tuple): self.q_diagrams = self.q_diagram # for d in self.q_diagrams: # print(d.nodes) # self.c_list.append(self._build_q_model(X, d)) self.c_list = [self._build_q_model(X, d) for d in self.q_diagrams] self.c_sel = list(range(len(self.c_list))) self.c_diagram = self._build_q_diagram( self.c_list, self.c_sel, composition=True ) self.q_model = self._build_q_model(X, self.c_diagram) else: self.q_model = self._build_q_model(X, self.q_diagram) toc_infalgo = default_timer() tic_dask = default_timer() X = X[:, self.q_model.desc_ids] result = self.q_model.predict(X) toc_dask = default_timer() self.model_data["prd_time"] = toc_prediction - tic_prediction self.model_data["dia_time"] = toc_diagram - tic_diagram self.model_data["infalgo_time"] = toc_infalgo - tic_infalgo self.model_data["dsk_time"] = toc_dask - tic_dask self.model_data["inf_time"] = toc_dask - tic_prediction return result def get_params(self, deep=False): return self.params # Diagrams def _build_q_diagram(self, m_list, m_sel, composition=False): if isinstance(m_sel, tuple): diagrams = [ build_diagram( m_list, m_sel_instance, self.q_code, prune=True, composition=composition, ) for m_sel_instance in m_sel ] return tuple(diagrams) else: return build_diagram( m_list, m_sel, self.q_code, prune=True, composition=composition ) def show_q_diagram(self, kind="svg", fi=False, ortho=False, index=None, **kwargs): if isinstance(self.q_diagram, tuple) and index is None: return show_diagram(self.c_diagram, kind=kind, fi=fi, ortho=ortho, **kwargs) elif isinstance(self.q_diagram, tuple): return show_diagram( self.q_diagram[index], kind=kind, fi=fi, ortho=ortho, **kwargs ) else: return show_diagram(self.q_diagram, kind=kind, fi=fi, ortho=ortho, **kwargs) def save_diagram(self, fname=None, kind="svg", fi=False, ortho=False): return save_diagram(self.q_diagram, fname, kind=kind, fi=fi, ortho=ortho) # Inference def _build_q_model(self, X, diagram): try: self.inference_algorithm( diagram, self.m_list, self.i_list, self.c_list, X, self.metadata.get("nominal_attributes"), ) except NetworkXUnfeasible: cycle = find_cycle(self.q_diagram, orientation="original") msg = """ Topological sort failed, investigate diagram to debug. I will never be able to squeeze a prediction out of a diagram with a loop. Cycle was: {} """.format( cycle ) raise RecursionError(msg) n_component_models = self.metadata["n_component_models"] q_model = NewCompositeModel( diagram, nominal_attributes=self.metadata["nominal_attributes"], n_component_models=n_component_models, ) return q_model def _merge_q_models(self, q_models): q_diagram = build_diagram(self.c_list, self.c_sel, self.q_code, prune=True) return q_diagram def merge_models(self, q_models): types = self._get_types(self.metadata) walks = [ model_to_graph(m, types, idx=idx, composition=True) for idx, m in enumerate(q_models) ] q_diagram = compose_all(walks) filtered_nodes = self.filter_nodes(q_diagram) try: self.inference_algorithm(q_diagram, sorted_nodes=filtered_nodes) except NetworkXUnfeasible: cycle = find_cycle(q_diagram, orientation="original") msg = """ Topological sort failed, investigate diagram to debug. I will never be able to squeeze a prediction out of a diagram with a loop. Cycle was: {} """.format( cycle ) raise RecursionError(msg) q_model = CompositeModel(q_diagram) return q_diagram, q_model def _get_q_model(self, q_diagram, X): self._add_imputer_function(q_diagram) try: self.inference_algorithm(q_diagram, X=X) except NetworkXUnfeasible: cycle = find_cycle(q_diagram, orientation="original") msg = """ Topological sort failed, investigate diagram to debug. I will never be able to squeeze a prediction out of a diagram with a loop. Cycle was: {} """.format( cycle ) raise RecursionError(msg) q_model = CompositeModel(q_diagram) return q_model # Filter def _filter_m_list_m_codes(self): """Filtering out the failed models. This happens when TODO: EXPLAIN """ fail_m_idxs = [i for i, m in enumerate(self.m_list) if m is None] self.m_codes = np.delete(self.m_codes, fail_m_idxs, axis=0) self.m_list = [m for m in self.m_list if m is not None] return # Graphs def _consistent_datastructures(self, binary_scores=False): self._update_m_codes() self._update_m_fimps() return def _expand_m_list(self): self.m_list = list(itertools.chain.from_iterable(self.m_list)) return def _add_model(self, model, binary_scores=False): self.m_list.append(model) self._consistent_datastructures(binary_scores=binary_scores) return def _update_m_codes(self): self.m_codes = np.array( [ query_to_code( list(model.desc_ids), list(model.targ_ids), attributes=self.metadata["attributes"], ) for model in self.m_list ] ) return def _update_m_fimps(self): init = np.zeros(self.m_codes.shape) for m_idx, mod in enumerate(self.m_list): init[m_idx, list(mod.desc_ids)] = mod.feature_importances_ self.m_fimps = init return def _update_m_score(self, binary_scores=False): if binary_scores: self.m_score = (self.m_codes == TARG_ENCODING).astype(float) return # Imputer def _add_imputer_function(self, g): for n in g.nodes: if g.nodes[n]["kind"] == "imputation": idx = g.nodes[n]["idx"] f_1 = self._dummy_array # Artificial input f_2 = self.i_list[idx].transform # Actual imputation f_3 = np.ravel # Return a vector, not array g.nodes[n]["function"] = o(f_3, o(f_2, f_1)) return # Add ids @staticmethod def _add_ids(g, desc_ids, targ_ids): g.graph["desc_ids"] = set(desc_ids) g.graph["targ_ids"] = set(targ_ids) return g # Metadata def _default_metadata(self, X): if X.ndim != 2: X = X.reshape(-1, 1) n_rows, n_cols = X.shape types = [X[0, 0].dtype for _ in range(n_cols)] nominal_attributes = set( [att for att, typ in enumerate(types) if self._is_nominal(typ)] ) numeric_attributes = set( [att for att, typ in enumerate(types) if self._is_numeric(typ)] ) metadata = dict( attributes=set(range(n_cols)), n_attributes=n_cols, types=types, nominal_attributes=nominal_attributes, numeric_attributes=numeric_attributes, ) return metadata def _update_metadata(self, **kwargs): self._update_dictionary(self.metadata, kind="metadata", **kwargs) # Assure every attribute is `typed`: If not every attribute is here, set to numeric type (default) numeric = self.metadata["numeric_attributes"] nominal = self.metadata["nominal_attributes"] att_ids = self.metadata["attributes"] # All attributes should be accounted for and none should be double. if (len(nominal) + len(numeric) - len(att_ids)) != 0: numeric = att_ids - nominal self._update_dictionary( self.metadata, kind="metadata", numeric_attributes=numeric ) return # Configuration def _reconfig_prediction(self, prediction_algorithm="mi", **kwargs): self.prediction_algorithm = self.prediction_algorithms[prediction_algorithm] self.prd_cfg = self._default_config(self.prediction_algorithm) self.configuration["prediction"] = self.prd_cfg self._update_config(**kwargs) return def _reconfig_inference(self, inference_algorithm="own", **kwargs): self.inference_algorithm = self.inference_algorithms[inference_algorithm] self.inf_cfg = self._default_config(self.inference_algorithm) self.configuration["inference"] = self.inf_cfg self._update_config(**kwargs) return @staticmethod def _default_config(method): config = {} sgn = signature(method) for key, parameter in sgn.parameters.items(): if parameter.default is not parameter.empty: config[key] = parameter.default return config def _update_config(self, **kwargs): for kind in self.configuration: self._update_dictionary(self.configuration[kind], kind=kind, **kwargs) return def _extra_checks_on_config(self): self._check_xgb_single_target() return def _check_xgb_single_target(self): nb_targets = self.configuration["selection"]["nb_targets"] if nb_targets == 1: return None else: if ( self.classifier_algorithm is self.classifier_algorithms["XGB"] or self.regressor_algorithm is self.regressor_algorithms["XGB"] ): xgb = True else: xgb = False if xgb: msg = """ XGBoost cannot deal with multi-target outputs. Hence, the `nb_targets` parameter is automatically adapted to 1, so only single-target trees will be learned. Please take this into account. """ warnings.warn(msg) self.configuration["selection"]["nb_targets"] = 1 return def _parse_kwargs(self, kind="selection", **kwargs): prefixes = [e + self.delimiter for e in self.configuration_prefixes[kind]] parameter_map = { x.split(prefix)[1]: x for x in kwargs for prefix in prefixes if x.startswith(prefix) } return parameter_map def _update_dictionary(self, dictionary, kind=None, **kwargs): # Immediate matches overlap = set(dictionary).intersection(set(kwargs)) for k in overlap: dictionary[k] = kwargs[k] if kind is not None: # Parsed matches parameter_map = self._parse_kwargs(kind=kind, **kwargs) overlap = set(dictionary).intersection(set(parameter_map)) for k in overlap: dictionary[k] = kwargs[parameter_map[k]] return # Helpers def _filter_X(self, X): # Filter relevant input attributes if X.shape[1] != len(self.q_compose.desc_ids): indices = self._overlapping_indices( self.q_desc_ids, self.q_compose.desc_ids ) return X[:, indices] @staticmethod def _dummy_array(X): """ Return an array of np.nan, with the same number of rows as the input array. Parameters ---------- X: np.ndarray(), n_rows, n_cols = X.shape, We use the shape of X to deduce shape of our output. Returns ------- a: np.ndarray(), shape= (n_rows, 1) n_rows is the same as the number of rows as X. """ n_rows, _ = X.shape a = np.empty((n_rows, 1)) a.fill(np.nan) return a def _default_q_code(self): q_code = np.zeros(self.metadata["n_attributes"]) q_code[-1] = TARG_ENCODING return q_code @staticmethod def _is_nominal(t): condition_01 = t == np.dtype(int) return condition_01 @staticmethod def _is_numeric(t): condition_01 = t == np.dtype(float) return condition_01 @staticmethod def _get_types(metadata): nominal = {i: "nominal" for i in metadata["nominal_attributes"]} numeric = {i: "numeric" for i in metadata["numeric_attributes"]} return {**nominal, **numeric} @staticmethod def _overlapping_indices(a, b): """ Given an array a and b, return the indices (in a) of elements that occur in both a and b. Parameters ---------- a b Returns ------- Examples -------- a = [4,5,6] b = [4,6,7] overlapping_indices(a, b) = [0,2] """ return np.nonzero(np.in1d(a, b))[0] @staticmethod def filter_nodes(g): # This is not as safe as it should be sorted_nodes = list(topological_sort(g)) filtered_nodes = [] for n in reversed(sorted_nodes): if g.nodes[n]["kind"] == "model": break filtered_nodes.append(n) filtered_nodes = list(reversed(filtered_nodes)) return filtered_nodes # SYNTH def autocomplete(self, X, **kwargs): return # Legacy (delete when I am sure they can go) def predict_old( self, X, q_code=None, prediction_algorithm=None, beta=False, **kwargs ): # Update configuration if necessary if q_code is None: q_code = self._default_q_code() if prediction_algorithm is not None: reuse = False self._reconfig_prediction( prediction_algorithm=prediction_algorithm, **kwargs ) # Adjust data tic_prediction = default_timer() self.q_code = q_code self.q_desc_ids, self.q_targ_ids, _ = code_to_query( self.q_code, return_list=True ) # Make query-diagram self.q_diagram = self.prediction_algorithm( self.g_list, q_code, self.fi, self.t_codes, **self.prd_cfg ) toc_prediction = default_timer() tic_dask = default_timer() toc_dask = default_timer() tic_compute = default_timer() res = self.q_model.predict.compute() toc_compute = default_timer() # Diagnostics self.model_data["prd_time"] = toc_prediction - tic_prediction self.model_data["dsk_time"] = toc_dask - tic_dask self.model_data["cmp_time"] = toc_compute - tic_compute self.model_data["inf_time"] = toc_compute - tic_prediction self.model_data["ratios"] = ( self.model_data["prd_time"] / self.model_data["inf_time"], self.model_data["dsk_time"] / self.model_data["inf_time"], self.model_data["cmp_time"] / self.model_data["inf_time"], ) return res def _update_g_list(self): types = self._get_types(self.metadata) self.g_list = [ model_to_graph(m, types=types, idx=idx) for idx, m in enumerate(self.m_list) ] return def _update_t_codes(self): self.t_codes = (self.m_codes == TARG_ENCODING).astype(int) return # AVATAR-TOOLS def avatar( self, explainer_data, background_data=None, check_additivity=True, keep_abs_shaps=False, **explainer_kwargs ): assert shap is not None, "SHAP not found, so cannot do anything here." self._init_avatar() for m_idx in range(len(self.m_list)): # Extract tree and m_code tree = self.m_list[m_idx].model m_code = self.m_codes[m_idx] # Filter data attribute_filter = m_code == DESC_ENCODING X = explainer_data[:, attribute_filter] if background_data is not None: B = background_data[:, attribute_filter] else: B = background_data # Shap Calculation explainer = shap.TreeExplainer(tree, data=B, **explainer_kwargs) raw_shaps = explainer.shap_values(X, check_additivity=check_additivity) # Process Shap values abs_shaps = self._raw_to_abs_shaps(raw_shaps) nrm_shaps = self._abs_to_nrm_shaps(abs_shaps) if keep_abs_shaps: self.abs_shaps.append(abs_shaps) self.nrm_shaps.append(nrm_shaps) self._format_abs_shaps() self._format_nrm_shaps() return @staticmethod def _raw_to_abs_shaps(raw_shaps): # Process Shap values tsr_shaps = np.array(raw_shaps) # tensor abs_shaps = np.abs(tsr_shaps) # absolute if len(abs_shaps.shape) == 3: # In case of nominal target, sum shap values across target classes abs_shaps =
np.sum(abs_shaps, axis=0)
numpy.sum
import os import tempfile import shutil import numpy as np import unittest import unittest.mock as mock from gulpio.utils import (check_ffmpeg_exists, burst_video_into_frames, resize_by_short_edge, resize_images, get_single_video_path, temp_dir_for_bursting, DuplicateIdException, remove_entries_with_duplicate_ids, _remove_duplicates_in_metadict, ) from gulpio.fileio import GulpIngestor from fileio_tests import DummyVideosAdapter class FSBase(unittest.TestCase): def setUp(self): self.temp_dir = tempfile.mkdtemp(prefix='utils-test-') def tearDown(self): shutil.rmtree(self.temp_dir) class TestCheckFFMPEGExists(unittest.TestCase): @mock.patch('os.system', mock.Mock(return_value=0)) def test_exists(self): self.assertEqual(True, check_ffmpeg_exists()) @mock.patch('os.system', mock.Mock(return_value=1)) def test_does_not_exists(self): self.assertEqual(False, check_ffmpeg_exists()) class TestBurstVideoIntoFrames(unittest.TestCase): def test_mp4(self): video_path = os.path.join(os.path.dirname(__file__), 'test.mp4') with temp_dir_for_bursting() as temp_burst_dir: imgs = burst_video_into_frames(video_path, temp_burst_dir) # different ffmpeg versions, yield slightly different numbers self.assertIn(len(imgs), [140, 141]) def test_mp4_with_lower_frame_rate(self): video_path = os.path.join(os.path.dirname(__file__), 'test.mp4') with temp_dir_for_bursting() as temp_burst_dir: imgs = burst_video_into_frames(video_path, temp_burst_dir, frame_rate=8) self.assertEqual(39, len(imgs)) def test_webm(self): video_path = os.path.join(os.path.dirname(__file__), 'test.webm') with temp_dir_for_bursting() as temp_burst_dir: imgs = burst_video_into_frames(video_path, temp_burst_dir) # different ffmpeg versions, yield slightly different numbers self.assertIn(len(imgs), [140, 141]) def test_webm_with_lower_frame_rate(self): video_path = os.path.join(os.path.dirname(__file__), 'test.webm') with temp_dir_for_bursting() as temp_burst_dir: imgs = burst_video_into_frames(video_path, temp_burst_dir, frame_rate=8) self.assertEqual(39, len(imgs)) class TestResizeImages(unittest.TestCase): @mock.patch('cv2.imread') @mock.patch('gulpio.utils.resize_by_short_edge') def test(self, mock_resize, mock_imread): mock_imread.side_effect = ['READ_IMAGE1', 'READ_IMAGE2', 'READ_IMAGE3'] mock_resize.side_effect = ['RESIZED_IMAGE1', 'RESIZED_IMAGE2', 'RESIZED_IMAGE3'] input_ = ['ANY_IMAGE1', 'ANY_IMAGE2', 'ANY_IMAGE3'] received = list(resize_images(input_, img_size=1)) self.assertEqual(['RESIZED_IMAGE1', 'RESIZED_IMAGE2', 'RESIZED_IMAGE3'], received) class TestResizeByShortEdge(unittest.TestCase): def test_resize_first_edge_shorter(self): input_image = np.zeros((6, 10)) size = 3 correct_result = np.zeros((3, 5)) result = resize_by_short_edge(input_image, size) np.testing.assert_array_equal(correct_result, result) def test_resize_second_edge_shorter(self): input_image = np.zeros((10, 6)) size = 3 correct_result = np.zeros((5, 3)) result = resize_by_short_edge(input_image, size) np.testing.assert_array_equal(correct_result, result) class TestGetSingleVideoPath(FSBase): def test_video_exists(self): test_video_path = os.path.join(self.temp_dir, 'test.mp4') open(test_video_path, 'w').close() received = get_single_video_path(self.temp_dir) self.assertEqual(test_video_path, received) def test_video_doesnt_exists(self): self.assertRaises(AssertionError, get_single_video_path, 'ANY_PATH') class TestRemoveEntriesWithDuplicateIds(FSBase): def test_no_duplicates(self): adapter = DummyVideosAdapter(3) output_directory = os.path.join(self.temp_dir, "ANY_OUTPUT_DIR") ingestor = GulpIngestor(adapter, output_directory, 2, 1) ingestor() meta_dict = [{'meta': {'name': 'new_video'}, 'frames': [np.ones((4, 1, 3), dtype='uint8')], 'id': 3 }] new_meta = remove_entries_with_duplicate_ids( output_directory, meta_dict) self.assertEqual(meta_dict, new_meta) def test_one_out_of_one_duplicate(self): adapter = DummyVideosAdapter(3) output_directory = os.path.join(self.temp_dir, "ANY_OUTPUT_DIR") ingestor = GulpIngestor(adapter, output_directory, 2, 1) ingestor() meta_dict = [{'meta': {'name': 'new_video'}, 'frames': [np.ones((4, 1, 3), dtype='uint8')], 'id': 1 }] with self.assertRaises(DuplicateIdException): remove_entries_with_duplicate_ids(output_directory, meta_dict) def test_one_out_of_two_duplicate(self): adapter = DummyVideosAdapter(3) output_directory = os.path.join(self.temp_dir, "ANY_OUTPUT_DIR") ingestor = GulpIngestor(adapter, output_directory, 2, 1) ingestor() input1 = {'meta': {'name': 'new_video'}, 'frames': [np.ones((4, 1, 3), dtype='uint8')], 'id': 1} input2 = {'meta': {'name': 'new_videoi_2'}, 'frames': [np.ones((4, 1, 3), dtype='uint8')], 'id': 3} meta_dict = [input1, input2] new_meta = remove_entries_with_duplicate_ids( output_directory, meta_dict) self.assertEqual(new_meta, [input2]) class TestRemoveDuplicatesInMetadict(unittest.TestCase): def test_no_duplicates_in_metadict(self): input1 = {'meta': {'name': 'new_video'}, 'frames': [np.ones((4, 1, 3), dtype='uint8')], 'id': 1} input2 = {'meta': {'name': 'new_video2'}, 'frames': [
np.ones((4, 1, 3), dtype='uint8')
numpy.ones
import copy import os import sys import numpy as np from functools import partial from matplotlib import patches import matplotlib.pyplot as plt sys.path.append(os.path.join(os.path.dirname(__file__), 'pathfind/build')) import QuoridorUtils class QuoridorBoard: def __init__(self, n, board=None): assert n >= 3 self.n = n self.history = {} midpoint_red = self.n // 2 + 1 - n % 2 midpoint_blue = self.n // 2 - 1 + n % 2 lastpoint = self.n - 1 self.red_goal = lastpoint self.blue_goal = 0 self.is_flipped = False self.max_walls = (self.n + 1) ** 2 // 10 if board: self.setBoard(board) else: self.v_walls = np.zeros((self.n - 1, self.n - 1), np.int16) self.h_walls = np.zeros((self.n - 1, self.n - 1), np.int16) self.draw = False self.paths_red, self.paths_blue = QuoridorUtils.getPathMatrices(self.v_walls, self.h_walls) self.legal_vwalls = np.ones((self.n - 1, self.n - 1), np.int16) self.legal_hwalls = np.ones((self.n - 1, self.n - 1), np.int16) # red player self.red_position = (midpoint_red, 0) self.red_walls = self.max_walls # blue player self.blue_position = (midpoint_blue, lastpoint) self.blue_walls = self.max_walls self.actions = { # NORTH 0: partial(self.move, dx=+0, dy=+1), # SOUTH 1: partial(self.move, dx=+0, dy=-1), # EAST 2: partial(self.move, dx=+1, dy=+0), # WEST 3: partial(self.move, dx=-1, dy=+0), # JN 4: partial(self.move, dx=+0, dy=+2), # JS 5: partial(self.move, dx=+0, dy=-2), # JE 6: partial(self.move, dx=+2, dy=+0), # JW 7: partial(self.move, dx=-2, dy=+0), # JNE 8: partial(self.move, dx=+1, dy=+1), # JSW 9: partial(self.move, dx=-1, dy=-1), # JNW 10: partial(self.move, dx=-1, dy=+1), # JSE 11: partial(self.move, dx=+1, dy=-1), # PLACE VERTICAL WALL 'vw': self.placeVerticalWall, # PLACE HORIZONTAL WALL 'hw': self.placeHorizontalWall, } self.convert_action = [1, 0, 3, 2, 5, 4, 7, 6, 9, 8, 11, 10] + list( np.flip(np.arange(12, 12 + (self.n - 1) ** 2).reshape((self.n - 1, self.n - 1)), (0, 1)).ravel()) + list( np.flip(np.arange(12 + (self.n - 1) ** 2, 12 + 2 * (self.n - 1) ** 2).reshape((self.n - 1, self.n - 1)), (0, 1)).ravel()) def getGameEnded(self, player): # endgame_heuristic = True # if endgame_heuristic: # dist_red = self.paths_red[self.red_position[0]][self.red_position[1]] # dist_blue = self.paths_blue[self.blue_position[0]][self.blue_position[1]] # # if player == 1 and self.red_walls == 0 and self.blue_walls == 0 and dist_red < dist_blue: # return player # if player == -1 and self.red_walls == 0 and self.blue_walls == 0 and dist_blue < dist_red: # return -player if self.red_position[1] == self.red_goal: return player elif self.blue_position[1] == self.blue_goal: return -player elif self.draw: return -1e-3 return 0 def addToHistory(self): s = self.getBoardHashable() if s in self.history: self.history[s] += 1 else: self.history[s] = 1 if self.history[s] > 2: self.draw = True def getBoard(self): # Boards boards = np.zeros((2, self.n, self.n), dtype=int) # Red position red_board = np.zeros((self.n, self.n)) red_board[self.red_position[0], self.red_position[1]] = 1 boards[0] = red_board # Blue position blue_board = np.zeros((self.n, self.n)) blue_board[self.blue_position[0], self.blue_position[1]] = 1 boards[1] = blue_board # Walls walls = np.zeros((2, self.n - 1, self.n - 1), dtype=int) walls[0] = self.v_walls walls[1] = self.h_walls # Values values = np.append(self.shortestPathActions(), [self.red_walls / self.max_walls, self.blue_walls / self.max_walls, ((self.n ** 2 + 1) - self.paths_red[self.red_position[0]][self.red_position[1]]) / ( self.n ** 2 + 1), ((self.n ** 2 + 1) - self.paths_blue[self.blue_position[0]][self.blue_position[1]]) / ( self.n ** 2 + 1), float(self.draw)]) return boards, walls, values def getBoardFlippedHorizontally(self): # Boards boards = np.zeros((2, self.n, self.n), dtype=int) # Red position red_board = np.zeros((self.n, self.n)) red_board[(self.n - 1) - self.red_position[0], self.red_position[1]] = 1 boards[0] = red_board # Blue position blue_board = np.zeros((self.n, self.n)) blue_board[(self.n - 1) - self.blue_position[0], self.blue_position[1]] = 1 boards[1] = blue_board # Walls walls = np.zeros((2, self.n - 1, self.n - 1), dtype=int) walls[0] = np.flipud(self.v_walls) walls[1] =
np.flipud(self.h_walls)
numpy.flipud
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Aug 15 17:01:14 2020 create training files @author: nel """ #%% import cv2 import os import matplotlib.pyplot as plt import numpy as np import zipfile import caiman as cm from caiman.base.rois import nf_read_roi from caiman.base.rois import nf_read_roi_zip #%% img_folder = '/home/nel/Code/NEL_LAB/Mask_RCNN/data_voltage/summary_images' masks_folder = '/home/nel/Code/NEL_LAB/Mask_RCNN/labels/combination_v1.2' #save_folder = '/home/nel/Code/NEL_LAB/Mask_RCNN/datasets/voltage_v1.2_cross3' #save_folder = '/home/nel/Code/NEL_LAB/Mask_RCNN/datasets/voltage_v1.2_L1_6' #save_folder = '/home/nel/Code/NEL_LAB/Mask_RCNN/datasets/voltage_v1.2_L1_4' #save_folder = '/home/nel/Code/NEL_LAB/Mask_RCNN/datasets/voltage_v1.2_L1_2' #save_folder = '/home/nel/Code/NEL_LAB/Mask_RCNN/datasets/voltage_v1.2_L1_1' #save_folder = '/home/nel/Code/NEL_LAB/Mask_RCNN/datasets/voltage_v1.2_TEG_2' #save_folder = '/home/nel/Code/NEL_LAB/Mask_RCNN/datasets/voltage_v1.2_TEG_1' #save_folder = '/home/nel/Code/NEL_LAB/Mask_RCNN/datasets/voltage_v1.2_HPC_8' #save_folder = '/home/nel/Code/NEL_LAB/Mask_RCNN/datasets/voltage_v1.2_HPC_4' #save_folder = '/home/nel/Code/NEL_LAB/Mask_RCNN/datasets/voltage_v1.2_HPC_2' #save_folder = '/home/nel/Code/NEL_LAB/Mask_RCNN/datasets/voltage_v1.2_HPC_1' save_folder = '/home/nel/Code/NEL_LAB/Mask_RCNN/datasets/voltage_v1.2_HPC_4_2' try: os.mkdir(save_folder) os.mkdir(save_folder+'/train') os.mkdir(save_folder+'/val') except OSError: print ("already exist") else: print ("make folders" ) files = sorted(os.listdir(img_folder)) files = np.array([file for file in files if '_summary.tif' in file]) #val_set = np.array([0, 3, 8, 10, 12, 15, 18, 21]) #val_set = np.array([1, 4, 7, 9, 13, 16, 19, 22]) #val_set = np.array([2, 5, 6, 11, 14, 17, 20, 23]) #val_set = np.array([3, 8, 10]) #train_set = np.array([4]) #val_set = np.array([0]) #train_set = np.array([1]) val_set = np.array([14, 17, 20, 23]) train_set = np.arange(12, 24) train_set = np.array(list(set(train_set) - set(val_set))) #train_set = np.array([22]) train_set = np.array([12, 15, 18, 21]) for file in files: if file in files[val_set]: group = 'val' elif file in files[train_set]: group = 'train' else: group = None if group is not None: #else: # group = 'train' summary_img = cm.load(os.path.join(img_folder, file)) input_img = summary_img[[0, 0, 1], :, :] with zipfile.ZipFile(os.path.join(masks_folder, file.split('_summary')[0]+'.zip')) as zf: names = zf.namelist() coords = [nf_read_roi(zf.open(n)) for n in names] if input_img.shape[2] < 128: for idx, i in enumerate(coords): coords[idx][:, 1] = list(np.array(i[:, 1]+ int((128-input_img.shape[2])/2))) aa = coords.copy() print('hha') polygons = [{'name': 'polygon','all_points_x':i[:,1],'all_points_y':i[:,0]} for i in coords] np.savez(save_folder+'/'+group+'/'+file.split('_summary')[0]+'_mask.npz', mask = polygons) if input_img.shape[2] < 128: temp = input_img.copy() a = [] for idx, img in enumerate(temp): a.append(cv2.copyMakeBorder(img,0, 0, int((128-input_img.shape[2])/2), int((128-input_img.shape[2])/2), borderType=cv2.BORDER_CONSTANT, value=0)) input_img = np.stack(a) print(input_img.shape) plt.figure();plt.imshow(input_img[0]);plt.show() input_img = input_img.transpose([1,2,0]) np.savez(save_folder + '/' + group + '/' + file.split('_summary')[0]+'.npz', img = input_img) """ for i in aa: plt.figure();plt.plot(i[:,0], i[:,1]) import skimage mask = np.zeros((284, 128, len(polygons))) for i, p in enumerate(polygons): # Get indexes of pixels inside the polygon and set them to 1 rr, cc = skimage.draw.polygon(p['all_points_y'], p['all_points_x']) mask[rr, cc, i] = 1 """ #%% folder = '/home/nel/Code/NEL_LAB/Mask_RCNN/datasets/voltage_v1.2_L1_6/train' files = os.listdir(folder) files = [file for file in files if 'mask' in file] for file in files: m = np.load(os.path.join(folder, file), allow_pickle=True)['mask'] print(file) print(m.shape) #%% m = np.load('/home/nel/Code/NEL_LAB/Mask_RCNN/datasets/voltage_v1.2_L1_1/train/FOV1_35um.npz', allow_pickle=True)['img'] mask = np.load('/home/nel/Code/NEL_LAB/Mask_RCNN/datasets/voltage_v1.2_L1_1/train/FOV1_35um_mask.npz', allow_pickle=True)['mask'] thresh = 296 n = 0 mask_new = [] for mm in mask: #print(mm) print(sum(mm['all_points_y']>thresh)) if sum(mm['all_points_y']>thresh) > 15: n = n + 1 mm['all_points_y'] = mm['all_points_y'] - thresh mask_new.append(mm) print(f'number of masks: {n}') mask_new =
np.array(mask_new)
numpy.array
# coding=utf-8 # Copyright 2022 The Google Research Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Lint as: python2, python3 """Unit tests for layers.py.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import tensorflow.compat.v1 as tf from tunas.rematlib import layers class ScalarMultiplicationLayer(layers.Layer): def __init__(self, initial_value, regularizer=None, name=None): super(ScalarMultiplicationLayer, self).__init__() self._initial_value = initial_value self._regularizer = regularizer self._name = name self._built = False def build(self, input_shape): with tf.variable_scope(self._name, 'ScalarMultiplicationLayer') as scope: self._scope = scope if not self._built: self._create_trainable_variable( name='scalar', initializer=self._initial_value, regularizer=self._regularizer) self._built = True return input_shape def apply(self, inputs, training): del training assert self._built with tf.variable_scope(self._scope, reuse=True): return self._get_trainable_tensor('scalar') * inputs class Constant(layers.Layer): def __init__(self, value): self._value = tf.constant(value, tf.float32) def build(self, input_shape): return self._value.shape def apply(self, inputs, training): del inputs, training return self._value class LayersTest(tf.test.TestCase): def test_with_data_dependencies(self): var1 = tf.get_variable( name='var1', initializer=0, dtype=tf.int32, use_resource=True) with tf.control_dependencies([var1.assign_add(1)]): increment_var1 = var1.read_value() var2 = tf.get_variable( name='var2', initializer=[0, 0], dtype=tf.int32, use_resource=True) with tf.control_dependencies([var2.assign_add([1, 1])]): increment_var2 = var2.read_value() var3 = tf.get_variable( name='var3', initializer=[[0, 0], [0, 0], [0, 0]], dtype=tf.int32, use_resource=True) with tf.control_dependencies([var3.assign_add([[1, 1], [1, 1], [1, 1]])]): increment_var3 = var3.read_value() output1 = tf.constant(2.0) output2 = tf.constant([3.0, 4.0]) output3 = tf.constant([[5.0, 6.0, 7.0], [8.0, 9.0, 10.0]]) tensors = layers.with_data_dependencies( [increment_var1, increment_var2, increment_var3], [output1, output2, output3]) self.evaluate(tf.global_variables_initializer()) # Verify that the output values are correct. arrays = self.evaluate(tensors) self.assertAllClose(arrays, [ 2.0, [3.0, 4.0], [[5.0, 6.0, 7.0], [8.0, 9.0, 10.0]], ]) # Verify that the dependencies are evaluated. self.assertAllClose(self.evaluate(var1), 1) self.assertAllClose(self.evaluate(var2), [1, 1]) self.assertAllClose(self.evaluate(var3), [[1, 1], [1, 1], [1, 1]]) def test_with_data_dependencies_grads(self): tensor1 = tf.constant(1.0) tensor2 = tf.constant(2.0) outputs = layers.with_data_dependencies([tensor1], [5.0 * tensor2]) self.assertLen(outputs, 1) grads = tf.gradients(outputs[0], [tensor1, tensor2]) self.assertLen(grads, 2) self.assertIsNone(grads[0]) self.assertAllClose(self.evaluate(grads[1]), 5.0) def test_layer_regularization_loss(self): initial_value = 3.0 l2_weight = 5.0 layer = ScalarMultiplicationLayer( initial_value=initial_value, regularizer=tf.keras.regularizers.l2(l2_weight)) inputs = tf.constant(10.0) layer.build(inputs.shape) layer.apply(inputs, training=True) self.evaluate(tf.global_variables_initializer()) self.assertAllClose( l2_weight * initial_value**2, self.evaluate(layer.regularization_loss())) def test_regularization_loss_for_layer_without_variables(self): layer = layers.Identity() inputs = tf.constant([1.0, -2.0, 3.0]) layer.build(inputs.shape) layer.apply(inputs, training=True) self.assertAllClose(0, self.evaluate(layer.regularization_loss())) def test_merge_shapes_with_broadcast(self): self.assertEqual( layers.merge_shapes_with_broadcast(None, None), tf.TensorShape(None)) self.assertEqual( layers.merge_shapes_with_broadcast(None, [1, 3]), tf.TensorShape([1, 3])) self.assertEqual( layers.merge_shapes_with_broadcast([8, 1], None), tf.TensorShape([8, 1])) self.assertEqual( layers.merge_shapes_with_broadcast([8, 1], []), tf.TensorShape([8, 1])) self.assertEqual( layers.merge_shapes_with_broadcast([], [1, 3]), tf.TensorShape([1, 3])) self.assertEqual( layers.merge_shapes_with_broadcast([None], [1]), tf.TensorShape([1])) self.assertEqual( layers.merge_shapes_with_broadcast([1], [None]), tf.TensorShape([1])) self.assertEqual( layers.merge_shapes_with_broadcast([None], [2]), tf.TensorShape([2])) self.assertEqual( layers.merge_shapes_with_broadcast([2], [None]), tf.TensorShape([2])) self.assertEqual( layers.merge_shapes_with_broadcast([1], [1]), tf.TensorShape([1])) self.assertEqual( layers.merge_shapes_with_broadcast([1], [2]), tf.TensorShape([2])) self.assertEqual( layers.merge_shapes_with_broadcast([2], [1]), tf.TensorShape([2])) self.assertEqual( layers.merge_shapes_with_broadcast([2], [2]), tf.TensorShape([2])) self.assertEqual( layers.merge_shapes_with_broadcast( [2, None, 8, 1, 32], [None, 4, 8, 16, 32]), tf.TensorShape([2, 4, 8, 16, 32])) with self.assertRaisesRegex(ValueError, 'Tensor shapes must have the same rank'): layers.merge_shapes_with_broadcast([1, 1], [1]) with self.assertRaisesRegex(ValueError, 'Tensor shapes are not compatible'): layers.merge_shapes_with_broadcast([2], [3]) def test_identity(self): layer = layers.Identity() inputs = tf.constant([1.0, -2.0, 3.0]) output_shape = layer.build(inputs.shape) output = layer.apply(inputs, training=True) self.assertEqual(output.shape, output_shape) self.assertAllClose(self.evaluate(output), [1.0, -2.0, 3.0]) self.assertEmpty(layer.trainable_tensors()) self.assertEmpty(layer.trainable_variables()) def test_zeros(self): layer = layers.Zeros() inputs = tf.constant([1.0, -2.0, 3.0]) output_shape = layer.build(inputs.shape) output = layer.apply(inputs, training=True) self.assertEqual(output.shape, output_shape) self.assertAllClose(self.evaluate(output), [0.0, 0.0, 0.0]) self.assertEmpty(layer.trainable_tensors()) self.assertEmpty(layer.trainable_variables()) def test_zeros_with_output_shape(self): layer = layers.Zeros(output_shape=tf.TensorShape([1, 2])) inputs = tf.constant([[1.0, -2.0, 3.0]]) output_shape = layer.build(inputs.shape) output = layer.apply(inputs, training=True) self.assertEqual(output.shape, output_shape) self.assertAllClose(self.evaluate(output), [[0.0, 0.0]]) self.assertEmpty(layer.trainable_tensors()) self.assertEmpty(layer.trainable_variables()) def test_zeros_with_output_shape_and_unknown_batch_dim(self): layer = layers.Zeros(output_shape=tf.TensorShape([None, 2])) inputs = tf.constant([[1.0, -2.0, 3.0]]) output_shape = layer.build(inputs.shape) output = layer.apply(inputs, training=True) self.assertEqual(output.shape, output_shape) self.assertAllClose(self.evaluate(output), [[0.0, 0.0]]) self.assertEmpty(layer.trainable_tensors()) self.assertEmpty(layer.trainable_variables()) def test_relu(self): layer = layers.ReLU() inputs = tf.constant([1.0, -2.0, 3.0]) output_shape = layer.build(inputs.shape) output = layer.apply(inputs, training=True) self.assertEqual(output.shape, output_shape) self.assertAllClose(self.evaluate(output), [1.0, 0.0, 3.0]) self.assertEmpty(layer.trainable_tensors()) self.assertEmpty(layer.trainable_variables()) def test_relu6(self): layer = layers.ReLU6() inputs = tf.constant([1.0, -2.0, 3.0, 7.0]) output_shape = layer.build(inputs.shape) output = layer.apply(inputs, training=True) self.assertEqual(output.shape, output_shape) self.assertAllClose(self.evaluate(output), [1.0, 0.0, 3.0, 6.0]) self.assertEmpty(layer.trainable_tensors()) self.assertEmpty(layer.trainable_variables()) def test_sigmoid(self): layer = layers.Sigmoid() inputs = tf.constant([1.0, -2.0, 3.0]) output_shape = layer.build(inputs.shape) output = layer.apply(inputs, training=True) expected_output = tf.nn.sigmoid(inputs) self.assertEqual(output.shape, output_shape) self.assertAllClose(self.evaluate(output), self.evaluate(expected_output)) self.assertEmpty(layer.trainable_tensors()) self.assertEmpty(layer.trainable_variables()) def test_swish(self): layer = layers.Swish() inputs = tf.constant([1.0, -2.0, 3.0, 7.0]) output_shape = layer.build(inputs.shape) output = layer.apply(inputs, training=True) expected_output = tf.nn.swish(inputs) self.assertEqual(output.shape, output_shape) self.assertAllClose( self.evaluate(output), self.evaluate(expected_output)) self.assertEmpty(layer.trainable_tensors()) self.assertEmpty(layer.trainable_variables()) def test_swish6(self): layer = layers.Swish6() inputs = tf.constant([1.0, -2.0, 3.0, 7.0]) output_shape = layer.build(inputs.shape) output = layer.apply(inputs, training=True) # Swish6(x) = x * relu6(x + 3) / 6 relu6 = lambda x: max(0, min(x, 6)) expected_output = [ 1 * relu6(1 + 3) / 6, -2 * relu6(-2 + 3) / 6, 3 * relu6(3 + 3) / 6, 7 * relu6(7 + 3) / 6, ] self.assertEqual(output.shape, output_shape) self.assertAllClose(self.evaluate(output), expected_output) self.assertEmpty(layer.trainable_tensors()) self.assertEmpty(layer.trainable_variables()) def test_elu(self): layer = layers.ELU() inputs = tf.constant([1.0, -2.0, 3.0]) output_shape = layer.build(inputs.shape) output = layer.apply(inputs, training=True) expected_output = tf.nn.elu(inputs) self.assertEqual(output.shape, output_shape) self.assertAllClose(self.evaluate(output), self.evaluate(expected_output)) self.assertEmpty(layer.trainable_tensors()) self.assertEmpty(layer.trainable_variables()) def test_space2depth(self): layer = layers.SpaceToDepth(block_size=2) inputs = tf.fill([1, 8, 8, 2], 1.0) expected_output = tf.fill([1, 4, 4, 8], 1.0) output_shape = layer.build(inputs.shape) output = layer.apply(inputs, training=True) self.assertEqual(output.shape, output_shape) self.assertAllClose(self.evaluate(output), self.evaluate(expected_output)) self.assertEmpty(layer.trainable_tensors()) self.assertEmpty(layer.trainable_variables()) def test_space2depth_error(self): layer = layers.SpaceToDepth(block_size=2) inputs = tf.fill([1, 5, 5, 2], 1.0) with self.assertRaisesRegex(ValueError, 'Image height 5 must be a multiple of 2'): layer.build(inputs.shape) def test_depth_padding(self): layer = layers.DepthPadding(filters=4) inputs = tf.fill([2, 8, 8, 2], 1.0) expected_output = np.concatenate( (np.ones((2, 8, 8, 2)), np.zeros((2, 8, 8, 2))), axis=3) output_shape = layer.build(inputs.shape) output = layer.apply(inputs, training=True) self.assertEqual(output.shape, output_shape) self.assertAllClose(self.evaluate(output), expected_output) self.assertEmpty(layer.trainable_tensors()) self.assertEmpty(layer.trainable_variables()) def test_depth_padding_wrong_filter(self): layer = layers.DepthPadding(filters=1) inputs = tf.fill([2, 8, 8, 2], 1.0) with self.assertRaisesWithPredicateMatch( ValueError, 'Output filters is smaller than input filters.'): layer.build(inputs.shape) def test_max_pool(self): layer = layers.MaxPool(kernel_size=(2, 2), strides=2) inputs = tf.concat( [ tf.fill([2, 2, 2, 2], 1.0), tf.fill([2, 2, 2, 2], 0.5), ], axis=3) first_row = np.ones((2, 1, 1, 2)) second_row = np.empty((2, 1, 1, 2)) second_row.fill(0.5) expected_output = np.concatenate( (first_row, second_row), axis=3) output_shape = layer.build(inputs.shape) output = layer.apply(inputs, training=True) self.assertEqual(output.shape, output_shape) self.assertAllClose(self.evaluate(output), expected_output) self.assertEmpty(layer.trainable_tensors()) self.assertEmpty(layer.trainable_variables()) def test_max_pool_3x3_strides2(self): layer = layers.MaxPool(kernel_size=(3, 3), strides=2) inputs = tf.reshape(tf.range(36), [1, 6, 6, 1]) expected_output = [[[[14], [16], [17]], [[26], [28], [29]], [[32], [34], [35]]]] output_shape = layer.build(inputs.shape) output = layer.apply(inputs, training=True) self.assertEqual(output.shape, output_shape) self.assertAllClose(self.evaluate(output), expected_output) self.assertEmpty(layer.trainable_tensors()) self.assertEmpty(layer.trainable_variables()) def test_max_pool_3x3_strides2_explicit_padding(self): layer = layers.MaxPool( kernel_size=(3, 3), strides=2, use_explicit_padding=True) inputs = tf.reshape(tf.range(36), [1, 6, 6, 1]) expected_output = [[[[7], [9], [11]], [[19], [21], [23]], [[31], [33], [35]]]] output_shape = layer.build(inputs.shape) output = layer.apply(inputs, training=True) self.assertEqual(output.shape, output_shape) self.assertAllClose(self.evaluate(output), expected_output) self.assertEmpty(layer.trainable_tensors()) self.assertEmpty(layer.trainable_variables()) def test_avg_pool(self): layer = layers.AveragePool(kernel_size=(2, 2), strides=2) inputs = tf.concat( [ tf.fill([2, 2, 2, 2], 1.0), tf.fill([2, 2, 2, 2], 0.5), ], axis=3) first_row = np.ones((2, 1, 1, 2)) second_row = np.empty((2, 1, 1, 2)) second_row.fill(0.5) expected_output = np.concatenate( (first_row, second_row), axis=3) output_shape = layer.build(inputs.shape) output = layer.apply(inputs, training=True) self.assertEqual(output.shape, output_shape) self.assertAllClose(self.evaluate(output), expected_output.tolist()) self.assertEmpty(layer.trainable_tensors()) self.assertEmpty(layer.trainable_variables()) def test_global_average_pool_no_keepdims(self): layer = layers.GlobalAveragePool(keepdims=False) inputs = tf.concat( [ tf.fill([2, 8, 8, 2], 1.0), tf.fill([2, 8, 8, 2], 2.0), tf.fill([2, 8, 8, 2], 3.0), ], axis=3) expected_output = [ [1, 1, 2, 2, 3, 3], [1, 1, 2, 2, 3, 3], ] output_shape = layer.build(inputs.shape) output = layer.apply(inputs, training=True) self.assertEqual(output.shape, output_shape) self.assertAllClose(self.evaluate(output), expected_output) self.assertEmpty(layer.trainable_tensors()) self.assertEmpty(layer.trainable_variables()) def test_global_average_pool_keepdims_size_1(self): layer = layers.GlobalAveragePool(keepdims=True) inputs = tf.concat( [ tf.fill([2, 1, 1, 2], 1.0), tf.fill([2, 1, 1, 2], 2.0), tf.fill([2, 1, 1, 2], 3.0), ], axis=3) expected_output = [ [[[1, 1, 2, 2, 3, 3]]], [[[1, 1, 2, 2, 3, 3]]], ] output_shape = layer.build(inputs.shape) output = layer.apply(inputs, training=True) self.assertEqual(output.shape, output_shape) self.assertAllClose(self.evaluate(output), expected_output) self.assertEmpty(layer.trainable_tensors()) self.assertEmpty(layer.trainable_variables()) def test_global_average_pool_no_keepdims_size_1(self): layer = layers.GlobalAveragePool(keepdims=False) inputs = tf.concat( [ tf.fill([2, 1, 1, 2], 1.0), tf.fill([2, 1, 1, 2], 2.0), tf.fill([2, 1, 1, 2], 3.0), ], axis=3) expected_output = [ [1, 1, 2, 2, 3, 3], [1, 1, 2, 2, 3, 3], ] output_shape = layer.build(inputs.shape) output = layer.apply(inputs, training=True) self.assertEqual(output.shape, output_shape) self.assertAllClose(self.evaluate(output), expected_output) self.assertEmpty(layer.trainable_tensors()) self.assertEmpty(layer.trainable_variables()) def test_global_average_pool_no_keepdims_dynamic_shape(self): layer = layers.GlobalAveragePool(keepdims=False) inputs = tf.placeholder(dtype=tf.float32, shape=[2, None, None, 6]) inputs_value = np.concatenate( [
np.full([2, 8, 8, 2], 1.0)
numpy.full
# -*- coding: utf-8 -*- """Classes and functions to manage the expansion of the electric field in plane wave and spherical wave basis sets.""" import numpy as np import os import smuthi.coordinates as coord import smuthi.vector_wave_functions as vwf import smuthi.spherical_functions as sf import smuthi.cuda_sources as cu try: import pycuda.autoinit import pycuda.driver as drv from pycuda import gpuarray from pycuda.compiler import SourceModule import pycuda.cumath except: pass import copy import math class FieldExpansion: """Base class for field expansions.""" def valid(self, x, y, z): """Test if points are in definition range of the expansion. Virtual method to be overwritten in child classes. Args: x (numpy.ndarray): x-coordinates of query points y (numpy.ndarray): y-coordinates of query points z (numpy.ndarray): z-coordinates of query points Returns: numpy.ndarray of bool datatype indicating if points are inside definition domain. """ pass def diverging(self, x, y, z): """Test if points are in domain where expansion could diverge. Virtual method to be overwritten in child classes. Args: x (numpy.ndarray): x-coordinates of query points y (numpy.ndarray): y-coordinates of query points z (numpy.ndarray): z-coordinates of query points Returns: numpy.ndarray of bool datatype indicating if points are inside divergence domain. """ pass def electric_field(self, x, y, z): """Evaluate electric field. Virtual method to be overwritten in child classes. Args: x (numpy.ndarray): x-coordinates of query points y (numpy.ndarray): y-coordinates of query points z (numpy.ndarray): z-coordinates of query points Returns: Tuple of (E_x, E_y, E_z) numpy.ndarray objects with the Cartesian coordinates of complex electric field. """ pass class PiecewiseFieldExpansion(FieldExpansion): r"""Manage a field that is expanded in different ways for different domains, i.e., an expansion of the kind .. math:: \mathbf{E}(\mathbf{r}) = \sum_{i} \mathbf{E}_i(\mathbf{r}), where .. math:: \mathbf{E}_i(\mathbf{r}) = \begin{cases} \tilde{\mathbf{E}}_i(\mathbf{r}) & \text{ if }\mathbf{r}\in D_i \\ 0 & \text{ else} \end{cases} and :math:`\tilde{\mathbf{E_i}}(\mathbf{r})` is either a plane wave expansion or a spherical wave expansion, and :math:`D_i` is its domain of validity. """ def __init__(self): self.expansion_list = [] def valid(self, x, y, z): """Test if points are in definition range of the expansion. Args: x (numpy.ndarray): x-coordinates of query points y (numpy.ndarray): y-coordinates of query points z (numpy.ndarray): z-coordinates of query points Returns: numpy.ndarray of bool datatype indicating if points are inside definition domain. """ vld = np.zeros(x.shape, dtype=bool) for fex in self.expansion_list: vld = np.logical_or(vld, fex.valid(x, y, z)) return vld def diverging(self, x, y, z): """Test if points are in domain where expansion could diverge. Args: x (numpy.ndarray): x-coordinates of query points y (numpy.ndarray): y-coordinates of query points z (numpy.ndarray): z-coordinates of query points Returns: numpy.ndarray of bool datatype indicating if points are inside divergence domain. """ dvg = np.zeros(x.shape, dtype=bool) for fex in self.expansion_list: dvg = np.logical_and(dvg, fex.diverging(x, y, z)) return dvg def electric_field(self, x, y, z): """Evaluate electric field. Args: x (numpy.ndarray): x-coordinates of query points y (numpy.ndarray): y-coordinates of query points z (numpy.ndarray): z-coordinates of query points Returns: Tuple of (E_x, E_y, E_z) numpy.ndarray objects with the Cartesian coordinates of complex electric field. """ x, y, z = np.array(x), np.array(y), np.array(z) ex = np.zeros(x.shape, dtype=complex) ey = np.zeros(x.shape, dtype=complex) ez = np.zeros(x.shape, dtype=complex) for fex in self.expansion_list: dex, dey, dez = fex.electric_field(x, y, z) ex, ey, ez = ex + dex, ey + dey, ez + dez return ex, ey, ez def compatible(self, other): """Returns always true, because any field expansion can be added to a piecewise field expansion.""" return True def __add__(self, other): """Addition of expansion objects. Args: other (FieldExpansion): expansion object to add to this object Returns: PiecewiseFieldExpansion object as the sum of this expansion and the other """ # todo: testing pfe_sum = PiecewiseFieldExpansion() if type(other).__name__ == "PiecewiseFieldExpansion": added = [False for other_fex in other.expansion_list] for self_fex in self.expansion_list: fex = copy.deepcopy(self_fex) for i, other_fex in enumerate(other.expansion_list): if (not added[i]) and self_fex.compatible(other_fex): fex = fex + other_fex added[i] = True pfe_sum.expansion_list.append(fex) for i, other_fex in enumerate(other.expansion_list): if not added[i]: pfe_sum.expansion_list.append(other_fex) else: added = False for self_fex in self.expansion_list: fex = copy.deepcopy(self_fex) if (not added) and fex.compatible(other): pfe_sum.expansion_list.append(fex + other) added = True else: pfe_sum.expansion_list.append(fex) if not added: pfe_sum.expansion_list.append(other) return pfe_sum class SphericalWaveExpansion(FieldExpansion): r"""A class to manage spherical wave expansions of the form .. math:: \mathbf{E}(\mathbf{r}) = \sum_{\tau=1}^2 \sum_{l=1}^\infty \sum_{m=-l}^l a_{\tau l m} \mathbf{\Psi}^{(\nu)}_{\tau l m}(\mathbf{r} - \mathbf{r}_i) for :math:`\mathbf{r}` located in a layer defined by :math:`z\in [z_{min}, z_{max}]` and where :math:`\mathbf{\Psi}^{(\nu)}_{\tau l m}` are the SVWFs, see :meth:`smuthi.vector_wave_functions.spherical_vector_wave_function`. Internally, the expansion coefficients :math:`a_{\tau l m}` are stored as a 1-dimensional array running over a multi index :math:`n` subsumming over the SVWF indices :math:`(\tau,l,m)`. The mapping from the SVWF indices to the multi index is organized by the function :meth:`multi_to_single_index`. Args: k (float): wavenumber in layer where expansion is valid l_max (int): maximal multipole degree :math:`l_\mathrm{max}\geq 1` where to truncate the expansion. m_max (int): maximal multipole order :math:`0 \leq m_\mathrm{max} \leq l_\mathrm{max}` where to truncate the expansion. kind (str): 'regular' for :math:`\nu=1` or 'outgoing' for :math:`\nu=3` reference_point (list or tuple): [x, y, z]-coordinates of point relative to which the spherical waves are considered (e.g., particle center). lower_z (float): the expansion is valid on and above that z-coordinate upper_z (float): the expansion is valid below that z-coordinate inner_r (float): radius inside which the expansion diverges (e.g. circumscribing sphere of particle) outer_r (float): radius outside which the expansion diverges Attributes: coefficients (numpy ndarray): expansion coefficients :math:`a_{\tau l m}` ordered by multi index n """ def __init__(self, k, l_max, m_max=None, kind=None, reference_point=None, lower_z=-np.inf, upper_z=np.inf, inner_r=0, outer_r=np.inf): self.k = k self.l_max = l_max if m_max is not None: self.m_max = m_max else: self.m_max = l_max self.coefficients = np.zeros(blocksize(self.l_max, self.m_max), dtype=complex) self.kind = kind # 'regular' or 'outgoing' self.reference_point = reference_point self.lower_z = lower_z self.upper_z = upper_z self.inner_r = inner_r self.outer_r = outer_r def valid(self, x, y, z): """Test if points are in definition range of the expansion. Args: x (numpy.ndarray): x-coordinates of query points y (numpy.ndarray): y-coordinates of query points z (numpy.ndarray): z-coordinates of query points Returns: numpy.ndarray of bool datatype indicating if points are inside definition domain. """ return np.logical_and(z >= self.lower_z, z < self.upper_z) def diverging(self, x, y, z): """Test if points are in domain where expansion could diverge. Args: x (numpy.ndarray): x-coordinates of query points y (numpy.ndarray): y-coordinates of query points z (numpy.ndarray): z-coordinates of query points Returns: numpy.ndarray of bool datatype indicating if points are inside divergence domain. """ r = np.sqrt((x - self.reference_point[0])**2 + (y - self.reference_point[1])**2 + (z - self.reference_point[2])**2) if self.kind == 'regular': return r >= self.outer_r if self.kind == 'outgoing': return r <= self.inner_r else: return None def coefficients_tlm(self, tau, l, m): """SWE coefficient for given (tau, l, m) Args: tau (int): SVWF polarization (0 for spherical TE, 1 for spherical TM) l (int): SVWF degree m (int): SVWF order Returns: SWE coefficient """ n = multi_to_single_index(tau, l, m, self.l_max, self.m_max) return self.coefficients[n] def electric_field(self, x, y, z): """Evaluate electric field. Args: x (numpy.ndarray): x-coordinates of query points y (numpy.ndarray): y-coordinates of query points z (numpy.ndarray): z-coordinates of query points Returns: Tuple of (E_x, E_y, E_z) numpy.ndarray objects with the Cartesian coordinates of complex electric field. """ x = np.array(x) y = np.array(y) z = np.array(z) xr = x[self.valid(x, y, z)] - self.reference_point[0] yr = y[self.valid(x, y, z)] - self.reference_point[1] zr = z[self.valid(x, y, z)] - self.reference_point[2] ex =
np.zeros(x.shape, dtype=complex)
numpy.zeros
""" Loads spike data, bins and smoothes. @author: bartulem """ import os import sys import sparse import warnings import matplotlib.pyplot as plt from numba import njit import numpy as np from scipy.ndimage.filters import gaussian_filter1d import sessions2load import quantify_ratemaps import decode_events warnings.simplefilter('ignore') def gaussian_smoothing(array, sigma=1, axis=1): """ Parameters ---------- array : np.ndarray The input array to be smoothed. sigma : int The SD of the smoothing window; defaults to 1 (bin). axis : int The filter smooths in 1D, so you choose the axis; defaults to 1. ---------- Returns ---------- smoothed_array : np.ndarray The 1D smoothed input array. ---------- """ return gaussian_filter1d(input=array, sigma=sigma, axis=axis) @njit(parallel=False) def get_shuffling_shifts(number_of_shuffles=1000, shuffle_range=(20, 60)): """ Parameters ---------- number_of_shuffles : int How many times to shuffle; defaults to 1000. shuffle_range : tuple Minimum and maximum number of seconds to shift the spike train; defaults to (20, 60). ---------- Returns ---------- seed_value : int64 The specific seed for generating this set of random numbers. shuffle_shifts : np.ndarray The pseudorandom shifts for generating shuffled spike trains. ---------- """ # create a seed & seed the random number generator seed_value = np.random.randint(0, 2 ** 32 - 1) np.random.seed(seed_value) # get time shifts for every shuffle shuffle_shifts = np.random.uniform(shuffle_range[0], shuffle_range[1], size=(number_of_shuffles,)) return seed_value, shuffle_shifts @njit(parallel=False) def purge_spikes_beyond_tracking(spike_train, tracking_ts, full_purge=True): """ Parameters ---------- spike_train : np.ndarray Spike times in seconds. tracking_ts : np.ndarray (2, ) The start and end of tracking relative to sessions start. full_purge : bool Remove spikes before and after tracking; defaults to True. ---------- Returns ---------- purged_spike_train : np.ndarray The spike train without spikes that precede or succeed tracking, relative to tracking start. ---------- """ if full_purge: # re-calculate spike times relative to tracking start purged_spike_train = spike_train - tracking_ts[0] # remove spikes that precede or succeed tracking purged_spike_train = purged_spike_train[(purged_spike_train >= 0) & (purged_spike_train < tracking_ts[1] - tracking_ts[0])] else: # remove spikes that succeed tracking purged_spike_train = spike_train[spike_train < tracking_ts[1] - tracking_ts[0]] return purged_spike_train @njit(parallel=False) def convert_spikes_to_frame_events(purged_spike_train, frames_total, camera_framerate=120.): """ Parameters ---------- purged_spike_train : np.ndarray Spike times in seconds (relative to tracking start). frames_total : int The total number of tracking frames in the recording. camera_framerate : np.float64 The sampling frequency of the tracking system; defaults to 120. ---------- Returns ---------- spikes_frames : np.ndarray (frames_total, ) How many spikes happened in each frame of tracking. ---------- """ # initialize an array of zeros with the size of the number of frames spikes_frames = np.zeros(frames_total) # convert spike times to frames when they happened spikes_tracking = purged_spike_train * camera_framerate spikes_tracking = np.floor(spikes_tracking, np.empty_like(spikes_tracking)) # categorize spikes for frame in spikes_tracking: spikes_frames[int(frame)] += 1 return spikes_frames @njit(parallel=False) def condense_frame_arrays(frame_array, camera_framerate=120., bin_size_ms=100, arr_type=True, sound=True): """ Parameters ---------- frame_array : np.ndarray (frames_total, ) The input frame array. bin_size_ms : int The bin size of the PETH; defaults to 100 (ms). camera_framerate : np.float64 The sampling frequency of the tracking system; defaults to 120. arr_type : bool True if it's a spike array, False if it's some other array; defaults to True. sound : bool If true, it's the sound array, if false - it's a variable; defaults to True. ---------- Returns ---------- new_arr : np.ndarray The frame array with the reduced shape. ---------- """ total_frames = frame_array.shape[0] # calculate size of new frame step = int(camera_framerate * (bin_size_ms / 1000)) new_shape = total_frames // step new_arr = np.zeros(new_shape) # fill it in ls_iter = list(range(0, new_shape * step, step)) for idx, one_bin in enumerate(ls_iter): array_excerpt = frame_array[one_bin:one_bin + step] if arr_type: new_arr[idx] = array_excerpt.sum() else: if sound: new_arr[idx] = 1 if array_excerpt.sum() >= (step / 2) else 0 else: new_arr[idx] = np.nanmean(array_excerpt) return new_arr @njit(parallel=False) def shuffle_spike_train(spike_train, random_shifts): """ Parameters ---------- spike_train : np.ndarray (number_of_spikes, ) Spike times in seconds (relative to tracking start). random_shifts : np.ndarray (number_of_shuffles, ) The pseudorandom shifts for generating shuffled spike trains. ---------- Returns ---------- shuffled_spike_train : np.ndarray (number_of_shuffles, number_of_spikes) The shuffled spike trains without spikes that precede or succeed tracking, relative to tracking start. ---------- """ # create array of zeroed values to store shuffled spikes in shuffled_spike_train_sec = np.zeros((random_shifts.shape[0], spike_train.shape[0])) # get shuffled spike time values for shuffle_idx in range(random_shifts.shape[0]): shuffled_spike_train_sec[shuffle_idx, :] = spike_train + random_shifts[shuffle_idx] return shuffled_spike_train_sec @njit(parallel=False) def find_event_starts(event_array, return_all=True, camera_framerate=120., expected_event_duration=5., min_inter_event_interval=10.): """ Parameters ---------- event_array : np.ndarray (frames_total, ) The array of events (should be binary, i.e. 0/1). return_all : bool Return all event starts, irrespective of duration; defaults to True. camera_framerate : np.float64 The sampling frequency of the tracking system; defaults to 120. expected_event_duration : int/float The expected duration of the designated event; defaults to 5 (seconds). min_inter_event_interval : int/float The minimum interval between any two adjacent events; defaults to 10 (seconds). ---------- Returns ---------- event_start_frames: np.ndarray Every frame ON (1) start in the input array. ---------- """ event_change_points = np.where(np.roll(event_array, 1) != event_array)[0] event_start_frames = event_change_points[::2] if not return_all: # this returns only events that satisfy: expected_event_duration - .1 < duration < expected_event_duration + .1 event_end_frames = event_change_points[1::2] event_durations = (event_end_frames - event_start_frames) / camera_framerate inter_event_intervals = np.concatenate((np.array([min_inter_event_interval + .1]), (event_start_frames[1:] - event_start_frames[:-1]) / camera_framerate)) event_start_frames = event_start_frames[(event_durations > (expected_event_duration - .1)) & (event_durations < (expected_event_duration + .1)) & (inter_event_intervals > min_inter_event_interval)] return event_start_frames @njit(parallel=False) def calculate_peth(input_array, event_start_frames, bin_size_ms=50, window_size=10, camera_framerate=120., behavior_input=False): """ Parameters ---------- input_array : np.ndarray Arrays with spikes/behavior allocated to tracking frames. event_start_frames : np.ndarray Every frame ON (1) start in the session. bin_size_ms : int The bin size of the PETH; defaults to 50 (ms). window_size : int The unilateral window size; defaults to 10 (seconds). camera_framerate : np.float64 The sampling frequency of the tracking system; defaults to 120. behavior_input : bool Whether or not the input array is behavioral; defaults to False. ---------- Returns ---------- peth_array : np.ndarray (epoch_num, total_window) Peri-event time histogram. ---------- """ # convert bin size to seconds bin_size = bin_size_ms / 1e3 # get bin step (number of frames in each bin) bin_step = int(round(camera_framerate * bin_size)) # get total window window_one_side = int(round((window_size / bin_size))) total_window = 2 * window_one_side # calculate PETH peth_array = np.zeros((event_start_frames.shape[0], total_window)) for epoch in range(event_start_frames.shape[0]): window_start_bin = int(round(event_start_frames[epoch] - (bin_step * window_one_side))) for one_bin in range(total_window): if behavior_input: if window_start_bin < 0: peth_array[epoch, one_bin] = np.nan else: peth_array[epoch, one_bin] = np.nanmean(input_array[window_start_bin:window_start_bin + bin_step]) else: if window_start_bin < 0: peth_array[epoch, one_bin] = np.nan else: peth_array[epoch, one_bin] = np.sum(input_array[window_start_bin:window_start_bin + bin_step]) / bin_size window_start_bin += bin_step return peth_array @njit(parallel=False) def calculate_discontinuous_peth(input_array_lst, esf, event_number, bin_size_ms=50, window_size=6, camera_framerate=120.): """ Parameters ---------- input_array_lst : list List of session arrays with spikes allocated to tracking frames. esf : list List of session behavior arrays. event_number : int Number of events to consider. bin_size_ms : int The bin size of the PETH; defaults to 50 (ms). window_size : int The complete window size; defaults to 6 (seconds). camera_framerate : np.float64 The sampling frequency of the tracking system; defaults to 120. ---------- Returns ---------- peth_array : np.ndarray (event_number, total_window) Peri-event time histogram. ---------- """ # convert bin size to seconds bin_size = bin_size_ms / 1e3 # get bin step (number of frames in each bin) bin_step = int(round(camera_framerate * bin_size)) # get total window total_window = int(round((window_size / bin_size))) switch_points = np.arange(0, total_window, total_window // 3) # calculate PETH peth_array = np.zeros((event_number, total_window)) for arr_idx, arr in enumerate(input_array_lst): for epoch in range(event_number): window_start_bin = int(round(esf[arr_idx][epoch])) for one_bin in range(total_window // 3): real_bin = one_bin + switch_points[arr_idx] peth_array[epoch, real_bin] = np.sum(arr[window_start_bin:window_start_bin + bin_step]) / bin_size window_start_bin += bin_step return peth_array @njit(parallel=False) def raster_preparation(purged_spike_train, event_start_frames, camera_framerate=120., window_size=10): """ Parameters ---------- purged_spike_train : np.ndarray The spike train without spikes that precede or succeed tracking, relative to tracking start. event_start_frames : np.ndarray Every frame ON (1) start in the session. camera_framerate : np.float64 The sampling frequency of the tracking system; defaults to 120. window_size : int The unilateral window size; defaults to 10 (seconds). ---------- Returns ---------- raster_list : list List of raster events (np.ndarrays) for that spike train. ---------- """ raster_list = [] for event in event_start_frames: window_start_seconds = (event / camera_framerate) - window_size window_centered_spikes = purged_spike_train[(purged_spike_train >= window_start_seconds) & (purged_spike_train < window_start_seconds + (window_size * 2))] - window_start_seconds raster_list.append(window_centered_spikes[window_centered_spikes > 0]) return raster_list def discontinuous_raster_preparation(purged_spike_arr, event_start_arr, event_number, camera_framerate_arr, window_size=2): """ Parameters ---------- purged_spike_arr : np.ndarray An array of spike trains without spikes that precede or succeed tracking, relative to tracking start. event_start_arr : np.ndarray An array of every start frame of speed within a specified range. event_number : int Number of events to consider. camera_framerate_arr : np.ndarray An array with camera sampling frequencies for all sessions. window_size : int The unilateral window size; defaults to 2 (seconds). ---------- Returns ---------- raster_list : list List of raster events (np.ndarrays) for that spike train. ---------- """ raster_list = [] for event_idx in range(event_number): temp_raster_list = [] for session_idx, session in enumerate(event_start_arr): if len(purged_spike_arr[session_idx]) > 0: purged_spike_train = purged_spike_arr[session_idx] window_start_seconds = (session[event_idx] / camera_framerate_arr[session_idx]) window_centered_spikes = purged_spike_train[(purged_spike_train >= window_start_seconds) & (purged_spike_train < window_start_seconds + window_size)] - window_start_seconds + (session_idx * 2) for spike in window_centered_spikes: temp_raster_list.append(spike) raster_list.append(np.array(temp_raster_list)) return raster_list @njit(parallel=False) def find_variable_sequences(variable, threshold_low=0., threshold_high=5., min_seq_duration=2, camera_framerate=120.): """ Parameters ---------- variable : np.ndarray The spike train without spikes that precede or succeed tracking, relative to tracking start. threshold_low : int/float Value above which variable should be considered; defaults to 0. threshold_high : int/float Value above which variable should not be considered; defaults to 5. min_seq_duration : int/float The minimum duration for chosen sequences; defaults to 2 (seconds). camera_framerate : np.float64 The sampling frequency of the tracking system; defaults to 120. ---------- Returns ---------- seq_starts : np.ndarray An array of sequence starts for the designated variable. ---------- """ # transform sequence duration to bins min_seq_duration = int(round(min_seq_duration * camera_framerate)) indices_above_threshold = np.where((threshold_low <= variable) & (variable <= threshold_high))[0] seq_starts = [] for idx, item in enumerate(indices_above_threshold): # both idx and item need to be below array length minus min_seq_duration idx_truth = idx <= indices_above_threshold.shape[0] - min_seq_duration item_truth = item <= variable.shape[0] - min_seq_duration if idx_truth and item_truth \ and (np.arange(item, item + min_seq_duration, 1) == indices_above_threshold[idx:idx + min_seq_duration]).all(): if len(seq_starts) == 0: seq_starts.append(item) else: if item > seq_starts[-1] + (min_seq_duration * 2): seq_starts.append(item) return np.array(seq_starts).astype(np.int32) class Spikes: # get shuffling shifts shuffle_seed, shuffle_shifts = get_shuffling_shifts() print(f"The pseudorandom number generator was seeded at {shuffle_seed}.") def __init__(self, input_file='', purged_spikes_dictionary='', input_012=['', '', ''], cluster_groups_dir='/.../cluster_groups_info', sp_profiles_csv='/.../spiking_profiles.csv', pkl_files_dir='/.../data_files'): self.input_file = input_file self.purged_spikes_dictionary = purged_spikes_dictionary self.input_012 = input_012 self.cluster_groups_dir = cluster_groups_dir self.sp_profiles_csv = sp_profiles_csv self.pkl_files_dir = pkl_files_dir def get_baseline_firing_rates(self, **kwargs): """ Description ---------- This method calculates the baseline firing rates for all selected clusters, where the baseline rate is defined as the number of spikes divided by the length of the tracking period. ---------- Parameters ---------- **kwargs (dictionary) get_clusters (str / int / list) Cluster IDs to extract (if int, takes first n clusters; if 'all', takes all); defaults to 'all'. ---------- Returns ---------- file_info (str) The shortened version of the file name. baseline_activity_dictionary (dict) A dictionary with the baseline firing rates for all desired clusters. ---------- """ get_clusters = kwargs['get_clusters'] if 'get_clusters' in kwargs.keys() \ and (kwargs['get_clusters'] == 'all' or type(kwargs['get_clusters']) == int or type(kwargs['get_clusters']) == list) else 'all' # get spike data in seconds and tracking start and end time file_id, extracted_data = sessions2load.Session(session=self.input_file).data_loader(extract_clusters=get_clusters, extract_variables=['tracking_ts']) # get baseline rates baseline_activity_dictionary = {} track_ts = extracted_data['tracking_ts'] recording_len = track_ts[1] - track_ts[0] extracted_activity = extracted_data['cluster_spikes'] for cl_id, spikes in extracted_activity.items(): # eliminate spikes that happen prior to and post tracking purged_spikes_sec = purge_spikes_beyond_tracking(spike_train=spikes, tracking_ts=track_ts) baseline_activity_dictionary[cl_id] = round(purged_spikes_sec.shape[0] / recording_len, 2) return file_id, baseline_activity_dictionary def convert_activity_to_frames_with_shuffles(self, **kwargs): """ Description ---------- This method converts cluster spiking activity into trains that match the tracking resolution, as spikes are allocated to appropriate frames. It returns such spike trains both for true and shuffled data. ---------- Parameters ---------- **kwargs (dictionary) get_clusters (str / int / list) Cluster IDs to extract (if int, takes first n clusters; if 'all', takes all); defaults to 'all'. to_shuffle (bool) Yey or ney on shuffling; defaults to False. condense_arr (bool) Yey or ney on the condensing (reducing the number of bins); defaults to False. ---------- Returns ---------- file_info (str) The shortened version of the file name. activity_dictionary (dict) A dictionary with frame-converted cluster activity and shuffled data. ---------- """ get_clusters = kwargs['get_clusters'] if 'get_clusters' in kwargs.keys() \ and (kwargs['get_clusters'] == 'all' or type(kwargs['get_clusters']) == int or type(kwargs['get_clusters']) == list) else 'all' to_shuffle = kwargs['to_shuffle'] if 'to_shuffle' in kwargs.keys() and type(kwargs['to_shuffle']) == bool else False condense_arr = kwargs['condense_arr'] if 'condense_arr' in kwargs.keys() and type(kwargs['condense_arr']) == bool else False condense_bin_ms = kwargs['condense_bin_ms'] if 'condense_bin_ms' in kwargs.keys() and type(kwargs['condense_bin_ms']) == int else 100 # get spike data in seconds and tracking start and end time file_id, extracted_data = sessions2load.Session(session=self.input_file).data_loader(extract_clusters=get_clusters, extract_variables=['tracking_ts', 'framerate', 'total_frame_num']) # convert spike arrays to frame arrays activity_dictionary = {} purged_spikes_dictionary = {} track_ts = extracted_data['tracking_ts'] extracted_activity = extracted_data['cluster_spikes'] empirical_camera_fr = extracted_data['framerate'] total_frame_num = extracted_data['total_frame_num'] for cell_id, spikes in extracted_activity.items(): activity_dictionary[cell_id] = {} # eliminate spikes that happen prior to and post tracking purged_spikes_sec = purge_spikes_beyond_tracking(spike_train=spikes, tracking_ts=track_ts) purged_spikes_dictionary[cell_id] = purged_spikes_sec # covert spikes to frame arrays cell_id_activity = convert_spikes_to_frame_events(purged_spike_train=purged_spikes_sec, frames_total=total_frame_num, camera_framerate=empirical_camera_fr) if not condense_arr: activity_dictionary[cell_id]['activity'] = sparse.COO(cell_id_activity).astype(np.int16) else: activity_dictionary[cell_id]['activity'] = sparse.COO(condense_frame_arrays(frame_array=cell_id_activity, bin_size_ms=condense_bin_ms)).astype(np.int16) if to_shuffle: activity_dictionary[cell_id]['shuffled'] = {} # shuffle the purged spike train N times shuffled_spikes_sec = shuffle_spike_train(purged_spikes_sec, Spikes.shuffle_shifts) # convert shuffles to frame arrays for shuffle_idx in range(shuffled_spikes_sec.shape[0]): purged_shuffle = purge_spikes_beyond_tracking(spike_train=shuffled_spikes_sec[shuffle_idx, :], tracking_ts=track_ts, full_purge=False) shuffle_cell_id = convert_spikes_to_frame_events(purged_spike_train=purged_shuffle, frames_total=total_frame_num, camera_framerate=empirical_camera_fr) if not condense_arr: activity_dictionary[cell_id]['shuffled'][shuffle_idx] = sparse.COO(shuffle_cell_id).astype(np.int16) else: activity_dictionary[cell_id]['shuffled'][shuffle_idx] = sparse.COO(condense_frame_arrays(frame_array=shuffle_cell_id)).astype(np.int16) return file_id, activity_dictionary, purged_spikes_dictionary def get_peths(self, **kwargs): """ Description ---------- This method converts cluster spiking activity into peri-event time histograms (PETHs), where you have the option to define bin and window size. NB: As of yet, it is NOT set to do the same for shuffled spike data (but it's a simple fix). Details: Each spike train is zeroed to tracking start and purged of spikes that exceed those boundaries. The spike train is then binned to match the tracking resolution, and spike counts are allocated to the appropriate frames. These spike counts are further binned (50 ms) to encompass a window (10 s) before and after every event onset (the start of the white noise stimulation). Rates are calculated and smoothed with a 3 bin Gaussian kernel. Raster arrays are prepared by zeroing spike times to each start of the trial window. Behavioral peths bin and compute the status of any given behavioral feature around relevant events (NB: works only for speed as of yet). ---------- Parameters ---------- **kwargs (dictionary) get_clusters (str / int / list) Cluster IDs to extract (if int, takes first n clusters; if 'all', takes all); defaults to 'all'. bin_size_ms (int) The bin size of the PETH; defaults to 50 (ms). window_size (int / float) The unilateral window size; defaults to 10 (seconds). return_all (bool) Return all event starts, irrespective of duration; defaults to True. expected_event_duration (int / float) The expected duration of the designated event; defaults to 5 (seconds). min_inter_event_interval (int / float) The minimum interval between any two adjacent events; defaults to 10 (seconds). smooth (bool) Smooth PETHs; defaults to False. smooth_sd (int) The SD of the smoothing window; defaults to 1 (bin). smooth_axis (int) The smoothing axis in a 2D array; defaults to 1 (smooths within rows). raster (bool) Prepare arrays from making raster plots; defaults to False. beh_raster (str / bool) Prepare behavior arrays from making raster plots; defaults to False. ---------- Returns ---------- peth_dictionary (dict) Peri-event time histogram for all clusters (np.ndarray (epoch_num, total_window)). raster_dictionary (dict) Raster arrays for all clusters zeroed to window start. peth_beh (np.ndarray) Peri-event time histogram for the designated behavioral feature (np.ndarray (epoch_num, total_window)). ---------- """ get_clusters = kwargs['get_clusters'] if 'get_clusters' in kwargs.keys() \ and (kwargs['get_clusters'] == 'all' or type(kwargs['get_clusters']) == int or type(kwargs['get_clusters']) == list) else 'all' bin_size_ms = kwargs['bin_size_ms'] if 'bin_size_ms' in kwargs.keys() and type(kwargs['bin_size_ms']) == int else 50 window_size = kwargs['window_size'] if 'window_size' in kwargs.keys() and (type(kwargs['window_size']) == int or type(kwargs['window_size']) == float) else 10 return_all = kwargs['return_all'] if 'return_all' in kwargs.keys() and type(kwargs['return_all']) == bool else True expected_event_duration = kwargs['expected_event_duration'] if 'expected_event_duration' in kwargs.keys() \ and (type(kwargs['expected_event_duration']) == int or type(kwargs['expected_event_duration']) == float) else 5 min_inter_event_interval = kwargs['min_inter_event_interval'] if 'min_inter_event_interval' in kwargs.keys() \ and (type(kwargs['min_inter_event_interval']) == int or type(kwargs['min_inter_event_interval']) == float) else 10 smooth = kwargs['smooth'] if 'smooth' in kwargs.keys() and type(kwargs['smooth']) == bool else False smooth_sd = kwargs['smooth_sd'] if 'smooth_sd' in kwargs.keys() and type(kwargs['smooth_sd']) == int else 1 smooth_axis = kwargs['smooth_axis'] if 'smooth_axis' in kwargs.keys() and type(kwargs['smooth_axis']) == int else 1 raster = kwargs['raster'] if 'raster' in kwargs.keys() and type(kwargs['raster']) == bool else False beh_raster = kwargs['beh_raster'] if 'beh_raster' in kwargs.keys() and (type(kwargs['beh_raster']) == str or type(kwargs['beh_raster']) == bool) else False # extract relevant variables / clusters from session data get_variables = ['imu_sound', 'framerate'] if type(beh_raster) == str: get_variables.append(beh_raster) ses_name, session_vars = sessions2load.Session(session=self.input_file).data_loader(extract_variables=get_variables) # get activity converted to frames file_id, activity_dictionary, purged_spikes_dictionary = self.convert_activity_to_frames_with_shuffles(get_clusters=get_clusters) # get event start frames event_start_frames = find_event_starts(session_vars['imu_sound'], return_all=return_all, camera_framerate=session_vars['framerate'], expected_event_duration=expected_event_duration, min_inter_event_interval=min_inter_event_interval) # get raster plot if raster: raster_dictionary = {} for cell_id, purged_spikes in purged_spikes_dictionary.items(): if cell_id in get_clusters: raster_dictionary[cell_id] = raster_preparation(purged_spike_train=purged_spikes, event_start_frames=event_start_frames, camera_framerate=session_vars['framerate'], window_size=window_size) # get PETHs for each cluster and smooth if necessary peth_dictionary = {} for cell_id in activity_dictionary.keys(): peth_dictionary[cell_id] = {} peth_array = calculate_peth(input_array=activity_dictionary[cell_id]['activity'].todense().astype(np.float32), event_start_frames=event_start_frames, bin_size_ms=bin_size_ms, window_size=window_size, camera_framerate=session_vars['framerate']) if smooth: peth_dictionary[cell_id]['peth'] = gaussian_smoothing(array=peth_array, sigma=smooth_sd, axis=smooth_axis) else: peth_dictionary[cell_id]['peth'] = peth_array # get behavior for raster (nb: currently only works for speed) if type(beh_raster) == str: peth_beh = calculate_peth(input_array=session_vars[beh_raster][:, 3], event_start_frames=event_start_frames, bin_size_ms=bin_size_ms, window_size=window_size, camera_framerate=session_vars['framerate'], behavior_input=True) if smooth: peth_beh = gaussian_smoothing(array=peth_beh, sigma=smooth_sd, axis=smooth_axis) if raster and beh_raster is not False: return ses_name, peth_dictionary, raster_dictionary, peth_beh elif raster and beh_raster is False: return ses_name, peth_dictionary, raster_dictionary else: return ses_name, peth_dictionary def get_discontinuous_peths(self, **kwargs): """ Description ---------- This method converts cluster spiking activity into peri-event time histograms (PETHs), where you have the option to define bin and window size. It should be used to construct PETHs whose trial parts come from different sessions. Details: Each session spike train is zeroed to tracking start and purged of spikes that exceed those boundaries. The spike train is then binned to match the tracking resolution, and spike counts are allocated to the appropriate frames. These spike counts are further binned (50 ms) to encompass a window (2 s) after every event onset (NB: which for our purpose is a 2s window where the speed of the animal was < 5 cm/s) Rates are calculated and smoothed with a 3 bin Gaussian kernel for each session segment separately. Raster arrays are prepared by zeroing spike times to each start of the trial window. ---------- Parameters ---------- **kwargs (dictionary) get_clusters (str / int / list) Cluster IDs to extract (if int, takes first n clusters; if 'all', takes all); defaults to 'all'. decode_what (str) What are you decoding; defaults to 'luminance'. cluster_areas (list) Cluster area(s) of choice; defaults to ['A']. cluster_type (str) Cluster type of choice; defaults to True. speed_threshold_low (int/float) Value above which variable should be considered; defaults to 0. speed_threshold_high (int/float) Value below which variable should not be considered; defaults to 5. speed_min_seq_duration (int/float) The minimum duration for chosen sequences; defaults to 2 (seconds). discontinuous_raster (bool) Prepare arrays from making raster plots; defaults to False. bin_size_ms (int) The bin size of the PETH; defaults to 50 (ms). window_size (int / float) The unilateral window size; defaults to 10 (seconds). smooth (bool) Smooth PETHs; defaults to False. smooth_sd (int) The SD of the smoothing window; defaults to 1 (bin). ---------- Returns ---------- peth_dictionary (dict) Peri-event time histogram for all clusters (np.ndarray (epoch_num, total_window)). raster_dictionary (dict) Raster arrays for all clusters zeroed to window start. ---------- """ get_clusters = kwargs['get_clusters'] if 'get_clusters' in kwargs.keys() \ and (kwargs['get_clusters'] == 'all' or type(kwargs['get_clusters']) == int or type(kwargs['get_clusters']) == list) else 'all' decode_what = kwargs['decode_what'] if 'decode_what' in kwargs.keys() and type(kwargs['decode_what']) == str else 'luminance' cluster_areas = kwargs['cluster_areas'] if 'cluster_areas' in kwargs.keys() and type(kwargs['cluster_areas']) == list else ['A'] cluster_type = kwargs['cluster_type'] if 'cluster_type' in kwargs.keys() and type(kwargs['cluster_type']) == str else True speed_threshold_high = kwargs['speed_threshold_high'] if 'speed_threshold_high' in kwargs.keys() and ( type(kwargs['speed_threshold_high']) == int or type(kwargs['speed_threshold_high']) == float) else 5. speed_threshold_low = kwargs['speed_threshold_low'] if 'speed_threshold_low' in kwargs.keys() and ( type(kwargs['speed_threshold_low']) == int or type(kwargs['speed_threshold_low']) == float) else 0. speed_min_seq_duration = kwargs['speed_min_seq_duration'] if 'speed_min_seq_duration' in kwargs.keys() \ and (type(kwargs['speed_min_seq_duration']) == int or type(kwargs['speed_min_seq_duration']) == float) else 2. discontinuous_raster = kwargs['discontinuous_raster'] if 'discontinuous_raster' in kwargs.keys() and type(kwargs['discontinuous_raster']) == bool else False bin_size_ms = kwargs['bin_size_ms'] if 'bin_size_ms' in kwargs.keys() and type(kwargs['bin_size_ms']) == int else 50 window_size = kwargs['window_size'] if 'window_size' in kwargs.keys() and (type(kwargs['window_size']) == int or type(kwargs['window_size']) == float) else 6 to_smooth = kwargs['to_smooth'] if 'to_smooth' in kwargs.keys() and type(kwargs['to_smooth']) == bool else False smooth_sd = kwargs['smooth_sd'] if 'smooth_sd' in kwargs.keys() and type(kwargs['smooth_sd']) == int else 1 # choose clusters for PETHs all_clusters, chosen_clusters, extra_chosen_clusters, cluster_dict = decode_events.choose_012_clusters(the_input_012=self.input_012, cl_gr_dir=self.cluster_groups_dir, sp_prof_csv=self.sp_profiles_csv, cl_areas=cluster_areas, cl_type=cluster_type, dec_type=decode_what, desired_profiles=True) # check if cluster(s) exist in the input sessions for cluster in get_clusters: if cluster not in all_clusters: print(f"Sorry, cluster {cluster} not in the input files!") sys.exit() # get activity dictionary zero_first_second_activity = {0: {}, 1: {}, 2: {}} zero_first_second_purged_spikes = {0: {}, 1: {}, 2: {}} for cluster in get_clusters: for file_idx, one_file in enumerate(self.input_012): if cluster in cluster_dict[file_idx]: file_id, activity_dictionary, purged_spikes_dictionary = Spikes(input_file=one_file).convert_activity_to_frames_with_shuffles(get_clusters=cluster, to_shuffle=False) zero_first_second_activity[file_idx][cluster] = activity_dictionary[cluster] zero_first_second_purged_spikes[file_idx][cluster] = purged_spikes_dictionary[cluster] # get behavior onsets session_variables = {0: {}, 1: {}, 2: {}} zero_first_second_behavior = {0: [], 1: [], 2: []} for file_idx, one_file in enumerate(self.input_012): ses_name, session_vars = sessions2load.Session(session=one_file).data_loader(extract_variables=['speeds', 'framerate']) session_variables[file_idx] = session_vars zero_first_second_behavior[file_idx] = find_variable_sequences(variable=session_vars['speeds'][:, 3], threshold_low=speed_threshold_low, threshold_high=speed_threshold_high, min_seq_duration=speed_min_seq_duration, camera_framerate=session_variables[file_idx]['framerate']) # find session with least events and get that number max_event_num_all_sessions = min([len(list(value)) for value in zero_first_second_behavior.values()]) # get raster plot if discontinuous_raster: raster_dictionary = {} for cluster in get_clusters: pu_sp_tr_lst = [] es_lst = [] cam_fr = [] for session_idx in range(len(self.input_012)): cam_fr.append(session_variables[session_idx]['framerate']) es_lst.append(zero_first_second_behavior[session_idx]) if cluster in zero_first_second_purged_spikes[session_idx].keys(): pu_sp_tr_lst.append(zero_first_second_purged_spikes[session_idx][cluster]) else: pu_sp_tr_lst.append(np.empty(1)) raster_dictionary[cluster] = discontinuous_raster_preparation(purged_spike_arr=np.array(pu_sp_tr_lst), event_start_arr=np.array(es_lst), event_number=max_event_num_all_sessions, camera_framerate_arr=np.array(cam_fr), window_size=speed_min_seq_duration) # get PETHs for each cluster and smooth if necessary peth_dictionary = {} for cluster in get_clusters: peth_dictionary[cluster] = {} input_arr_ls = [] esf_lst = [] for session in zero_first_second_activity.keys(): esf_lst.append(zero_first_second_behavior[session]) if cluster in zero_first_second_activity[session].keys(): input_arr_ls.append(zero_first_second_activity[session][cluster]['activity'].todense().astype(np.float32)) else: input_arr_ls.append(np.zeros(session_variables[session]['total_frame_num']).astype(np.float32)) peth_array = calculate_discontinuous_peth(input_array_lst=input_arr_ls, esf=esf_lst, event_number=max_event_num_all_sessions, bin_size_ms=bin_size_ms, window_size=window_size) # smooth every sequence separately if to_smooth: total_window = int(round((window_size / (bin_size_ms / 1e3)))) switch_points = np.arange(0, total_window, total_window // 3) for epoch in range(max_event_num_all_sessions): for sp_idx, sp in enumerate(switch_points): peth_array[epoch, sp:sp + (total_window // 3)] = gaussian_smoothing(array=peth_array[epoch, sp:sp + (total_window // 3)], sigma=smooth_sd, axis=0) peth_dictionary[cluster]['discontinuous_peth'] = peth_array if discontinuous_raster: return peth_dictionary, raster_dictionary else: return peth_dictionary def correlate_activity(self, **kwargs): """ Description ---------- This method correlates spiking activity between different clusters within a recording condition and then compares how it differs across conditions (e.g. light/dark). ---------- Parameters ---------- **kwargs (dictionary) to_corr (bool) To correlate or use covariance; defaults to True. condense_bin_ms (int) The size of bin for spikes; defaults to 100 (ms). specific_date (dict) Selected dates for specific animals; defaults to *see below*. corr_input_dict (dict) Parameters that find appropriate clusters; defaults to *see below*. ---------- Returns ---------- activity_correlation (fig) A figure of activity correlations. ---------- """ to_corr = kwargs['to_corr'] if 'to_corr' in kwargs.keys() and type(kwargs['to_corr']) == bool else True condense_bin_ms = kwargs['condense_bin_ms'] if 'condense_bin_ms' in kwargs.keys() and type(kwargs['condense_bin_ms']) == int else 100 specific_date = kwargs['specific_date'] if 'specific_date' in kwargs.keys() and type(kwargs['specific_date']) == dict else {'bruno': ['020520', '030520'], 'roy': True, 'jacopo': True, 'crazyjoe': True, 'frank': True, 'johnjohn': ['210520', '220520'], 'kavorka': True} corr_input_dict = kwargs['corr_input_dict'] if 'corr_input_dict' in kwargs.keys() and type(kwargs['corr_input_dict']) == dict else {'light1': {'area_filter': 'V', 'animal_filter': True, 'profile_filter': True, 'session_id_filter': 's1', 'session_non_filter': True, 'session_type_filter': True, 'cluster_type_filter': 'good', 'specific_date': None}, 'dark': {'area_filter': 'V', 'animal_filter': True, 'profile_filter': True, 'session_id_filter': True, 'session_non_filter': True, 'session_type_filter': ['dark'], 'cluster_type_filter': 'good', 'specific_date': None}} cluster_dict = {} for session_type in corr_input_dict.keys(): cluster_dict[session_type] = quantify_ratemaps.RatemapCharacteristics(pkl_sessions_dir=self.pkl_files_dir, area_filter=corr_input_dict[session_type]['area_filter'], animal_filter=corr_input_dict[session_type]['animal_filter'], profile_filter=corr_input_dict[session_type]['profile_filter'], session_id_filter=corr_input_dict[session_type]['session_id_filter'], session_non_filter=corr_input_dict[session_type]['session_non_filter'], session_type_filter=corr_input_dict[session_type]['session_type_filter'], cluster_type_filter=corr_input_dict[session_type]['cluster_type_filter'], cluster_groups_dir=self.cluster_groups_dir, sp_profiles_csv=self.sp_profiles_csv, specific_date=corr_input_dict[session_type]['specific_date']).file_finder(return_clusters=True, sort_ch_num=True) # get clusters that are present in both sessions acceptable_cluster_dict = {} for st_idx, session_type in enumerate(cluster_dict.keys()): if st_idx == 0: for animal in cluster_dict[session_type].keys(): for bank in cluster_dict[session_type][animal].keys(): for cl in cluster_dict[session_type][animal][bank]: if cl in cluster_dict[list(cluster_dict.keys())[1]][animal][bank]: if session_type not in acceptable_cluster_dict.keys(): acceptable_cluster_dict[session_type] = {} if animal not in acceptable_cluster_dict[session_type].keys(): acceptable_cluster_dict[session_type][animal] = {} if bank not in acceptable_cluster_dict[session_type][animal].keys(): acceptable_cluster_dict[session_type][animal][bank] = [] acceptable_cluster_dict[session_type][animal][bank].append(cl) # get activity for each cluster activity_dict = {} for session_type in acceptable_cluster_dict.keys(): for animal in acceptable_cluster_dict[session_type].keys(): activity_dict[animal] = {} for bank in acceptable_cluster_dict[session_type][animal].keys(): activity_dict[animal][bank] = {key: {} for key in cluster_dict.keys()} for pkl_file in os.listdir(self.pkl_files_dir): first_for_loop = False if (specific_date[animal] is True or any(one_date in pkl_file for one_date in specific_date[animal])) and \ animal in pkl_file and \ bank in pkl_file and \ (corr_input_dict[session_type]['session_id_filter'] is True or corr_input_dict[session_type]['session_id_filter'] in pkl_file) and \ (corr_input_dict[session_type]['session_non_filter'] is True or corr_input_dict[session_type]['session_non_filter'] not in pkl_file) and \ (corr_input_dict[session_type]['session_type_filter'] is True or any( one_word in pkl_file for one_word in corr_input_dict[session_type]['session_type_filter']) in pkl_file): for pkl_file2 in os.listdir(self.pkl_files_dir): if (specific_date[animal] is True or any(one_date in pkl_file2 for one_date in specific_date[animal])) and \ animal in pkl_file2 and \ bank in pkl_file2 and \ (corr_input_dict[list(cluster_dict.keys())[1]]['session_id_filter'] is True or corr_input_dict[list(cluster_dict.keys())[1]][ 'session_id_filter'] in pkl_file2) and \ (corr_input_dict[list(cluster_dict.keys())[1]]['session_non_filter'] is True or corr_input_dict[list(cluster_dict.keys())[1]][ 'session_non_filter'] not in pkl_file2) and \ (corr_input_dict[list(cluster_dict.keys())[1]]['session_type_filter'] is True or any( one_word in pkl_file2 for one_word in corr_input_dict[list(cluster_dict.keys())[1]]['session_type_filter'])): print(pkl_file, pkl_file2) file_id, \ activity_dictionary, \ purged_spikes_dictionary = Spikes(input_file=f'{self.pkl_files_dir}{os.sep}{pkl_file}').convert_activity_to_frames_with_shuffles( get_clusters=acceptable_cluster_dict[session_type][animal][bank], to_shuffle=False, condense_arr=True, condense_bin_ms=condense_bin_ms) file_id2, \ activity_dictionary2, \ purged_spikes_dictionary2 = Spikes(input_file=f'{self.pkl_files_dir}{os.sep}{pkl_file2}').convert_activity_to_frames_with_shuffles( get_clusters=acceptable_cluster_dict[session_type][animal][bank], to_shuffle=False, condense_arr=True, condense_bin_ms=condense_bin_ms) activity_dict[animal][bank][session_type] = activity_dictionary activity_dict[animal][bank][list(cluster_dict.keys())[1]] = activity_dictionary2 first_for_loop = True break if first_for_loop: break # place activity in arrays rearranged_activity_dict = {} for animal in activity_dict.keys(): rearranged_activity_dict[animal] = {} for bank in activity_dict[animal].keys(): rearranged_activity_dict[animal][bank] = {} for session_type in cluster_dict.keys(): for cl_idx, cl in enumerate(activity_dict[animal][bank][session_type].keys()): if cl_idx == 0: arr_len = np.shape(activity_dict[animal][bank][session_type][cl]['activity'].todense())[0] break rearranged_activity_dict[animal][bank][session_type] = np.zeros((len(activity_dict[animal][bank][session_type].keys()), arr_len)) for cl_idx, cl in enumerate(activity_dict[animal][bank][session_type].keys()): rearranged_activity_dict[animal][bank][session_type][cl_idx, :] = activity_dict[animal][bank][session_type][cl]['activity'].todense() # calculate corr/cov and plot for animal in rearranged_activity_dict.keys(): for bank in rearranged_activity_dict[animal].keys(): results = {} for session_type in rearranged_activity_dict[animal][bank].keys(): if to_corr: results[session_type] =
np.corrcoef(x=rearranged_activity_dict[animal][bank][session_type])
numpy.corrcoef
# Copyright (c) 2017 The Khronos Group 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. from __future__ import division import sys import os import shutil import tarfile import inspect import traceback import numpy as np import tensorflow as tf if sys.version_info[0] < 3: from Queue import Queue else: from queue import Queue from tensorflow.python.ops import gen_math_ops as tf_ops from tensorflow.contrib.layers.python.layers import layers as tf_layers from tensorflow.python.layers import utils RedText = "\x1b[31m" ResetStyle = "\x1b[0m" def tf_version_greater(major, minor): str = tf.__version__ i = str.index('.') j = str.index('.', i+1) return (int(str[:i]), int(str[i+1:j])) >= (major, minor) def print_error(msg, stack): sys.stderr.write("%sError: %s%s\n" % (RedText, msg, ResetStyle)) if stack is not None: traceback.print_list(stack) def print_warning(msg): sys.stderr.write("%sWarning: %s%s\n" % (RedText, msg, ResetStyle)) def undecorate(decorated, orig_name=None): if orig_name is None: orig_name = decorated.__name__ if not hasattr(decorated, "__closure__") or not decorated.__closure__: return decorated for obj in (c.cell_contents for c in decorated.__closure__): if hasattr(obj, "__name__") and obj.__name__ == orig_name: return obj if hasattr(obj, "__closure__") and obj.__closure__: found = undecorate(obj, orig_name) if found: return found return None class InvocationTrace: def __init__(self, functions, handler): self.frame = None self.invocations = list() self.handler = handler self.func_names = set() self.qualified = {} for func in functions: undecorated = undecorate(func) self.func_names.add(undecorated.__name__) self.qualified[undecorated.__module__ + '.' + undecorated.__name__] = func def __call__(self, frame, event, result): func_name = frame.f_code.co_name if func_name == '__init__': result = frame.f_locals.get('self') if result is not None: func_name = result.__class__.__name__ if func_name not in self.func_names: return mod = inspect.getmodule(frame) if mod is None: return func_name = mod.__name__ + '.' + func_name if event == 'call': if self.frame is None: func = self.qualified.get(func_name) if func is not None: arg_values = inspect.getargvalues(frame) self.frame = frame self.func = func self.args = {key: value for (key,value) in arg_values.locals.items() if key in arg_values.args} elif event == 'return': if self.frame == frame and result is not None: if isinstance(result, (list, dict)): result = result.copy() results = result if isinstance(result, tuple) else (result, ) stack = traceback.extract_stack(frame.f_back) self.invocations.append((self.func, self.args, results, stack)) if self.handler: self.handler(self.func, self.args, results, stack) self.frame = None return self class TF2NNEFConverter: def __init__(self, producers, exporters, reader, output_path): self.producers = producers self.exporters = exporters self.reader = reader self.consumrs = {} self.tensor_names = {} self.tensor_counts = {} self.activations = [] self.output_path = output_path self.fused = set() for invocation in producers.values(): args = invocation[1] for arg in args.values(): if isinstance(arg, (tf.Tensor, tf.Variable)): self.consumrs.setdefault(arg, []).append(invocation) def producer(self, tensor): return self.producers.get(tensor) def consumers(self, tensor): return self.consumrs.get(tensor) def consumer(self, tensor): consumers = self.consumrs.get(tensor) return consumers[0] if consumers is not None and len(consumers) == 1 else None def exporter(self, func): item = self.exporters.get(func) return item[0] if isinstance(item, tuple) else item def make_fused(self, tensor): self.fused.add(tensor) def is_fused(self, tensor): return tensor in self.fused def make_constant(self, tf_tensor, nnef_value): self.tensor_names[tf_tensor] = nnef_value def make_tensor(self, tf_tensor, nnef_name, indexed=True): name = self.tensor_names.get(tf_tensor) if name is not None: return name if indexed: count = self.tensor_counts.get(nnef_name, 1) self.tensor_counts[nnef_name] = count + 1 indexed_name = nnef_name + str(count) else: indexed_name = nnef_name self.tensor_names[tf_tensor.value() if isinstance(tf_tensor, tf.Variable) else tf_tensor] = indexed_name self.activations.append((tf_tensor, indexed_name)) return indexed_name def make_passthrough_tensor(self, tf_tensor_in, tf_tensor_out): variable = isinstance(tf_tensor_out, tf.Variable) self.tensor_names[tf_tensor_out.value() if variable else tf_tensor_out] = self.nnef_tensor(tf_tensor_in) def nnef_tensor(self, tf_tensor): if isinstance(tf_tensor, (float, int)): return str(float(tf_tensor)) elif isinstance(tf_tensor, tf.Variable): return self.tensor_names[tf_tensor.value()] else: return self.tensor_names[tf_tensor] def nnef_op(self, func): item = self.exporters.get(func) return item[1] if isinstance(item, tuple) else None @staticmethod def nnef_shape(shape, stack=None, is_filter=False, is_broadcast=False): if isinstance(shape, tf.Tensor): shape = tf.contrib.util.constant_value(shape) if shape is None: print_error('cannot handle dynamic tensor shape', stack) return [] if isinstance(shape, tf.TensorShape): shape = shape.as_list() if not isinstance(shape, list): shape = list(shape) shape = [s.value if isinstance(s, tf.Dimension) else int(s) for s in shape] if len(shape) == 0: return [] elif len(shape) == 1: return [1, shape[0]] if is_broadcast else [shape[0]] elif len(shape) == 2: return shape else: if is_filter: return [shape[-1], shape[-2]] + shape[:-2] else: return [shape[0], shape[-1]] + shape[1:-1] @staticmethod def nnef_axis(axis, rank): if axis < 0: axis = rank + axis if rank == 1: return 1 elif rank == 2: return axis else: if axis == 0: return 0 elif axis == rank - 1: return 1 else: return axis + 1 @staticmethod def nnef_axes(axis, rank): if isinstance(axis, (list, tuple)): return [TF2NNEFConverter.nnef_axis(a, rank) for a in axis] else: return [TF2NNEFConverter.nnef_axis(axis, rank)] @staticmethod def nnef_bool(value): if value is None: value = False return 'true' if value else 'false' @staticmethod def nnef_array(value, rank): if isinstance(value, list): return value elif isinstance(value, tuple): return list(value) else: return [value] * rank @staticmethod def nnef_padding(padding, rank): return [] if padding.upper() == 'SAME' else [(0, 0)] * rank @staticmethod def nnef_padding_ex(padding, input_sizes, filter_sizes, strides): def same_padding(input_size, filter_size, stride): output_size = int(np.ceil(float(input_size) / float(stride))) pad_total = (output_size - 1) * stride + filter_size - input_size if pad_total >= 0: pad_front = pad_total // 2 pad_back = pad_total - pad_front return (pad_front, pad_back) else: return (0, pad_total) def valid_padding(input_size, filter_size, stride): output_size = int(np.ceil(float(input_size - filter_size + 1) / float(stride))) pad_total = (output_size - 1) * stride + filter_size - input_size return (0, pad_total) return [same_padding(input_size, filter_size, stride) if padding.upper() == 'SAME' else valid_padding(input_size, filter_size, stride) for (input_size, filter_size, stride) in zip(input_sizes, filter_sizes, strides)] @staticmethod def nnef_tensor_shuffle_dims(tensor, is_filter, is_broadcast): rank = tensor.ndim if rank == 0: return tensor elif rank == 1: return np.expand_dims(tensor, axis=0) if is_broadcast else tensor elif rank == 2: return tensor else: axes = [rank-1, rank-2] + list(range(rank-2)) if is_filter else [0, rank-1] + list(range(1,rank-1)) return np.transpose(tensor, axes) @staticmethod def nnef_ids(ids): return "[" + ", ".join(map(str, ids)) + "]" @staticmethod def dilated_size(size, dilation): return [(s - 1) * d + 1 for (s, d) in zip(size, dilation)] def propagate_padding(self, input, padding, border, spatial, stack): producer = self.producer(input) if producer is not None and producer[0] == tf.pad: if len(padding) == 0: print_error("only 'VALID' padding is accepted after an explicit 'pad' operation", stack) args = producer[1] border = args['mode'].lower() if border == 'symmetric': border = 'reflect-even' paddings = args['paddings'] paddings = paddings[1:-1] if spatial else [paddings[0], paddings[-1]] + paddings[1:-1] padding = [tuple(p) for p in paddings] return padding, border def propagate_space_to_batch(self, input, dilation, padding): producer = self.producer(input) if producer is not None and (producer[0] == tf.space_to_batch_nd or producer[0] == tf.space_to_batch): args = producer[1] input = args['input'] dilation = args['block_shape'].tolist() padding = 'SAME' if args['paddings'].any() else 'VALID' return input, dilation, padding def propagate_batch_to_space(self, output): consumer = self.consumer(output) if consumer is not None and (consumer[0] == tf.batch_to_space_nd or consumer[0] == tf.batch_to_space): results = consumer[2] return results[0] return output def is_binary_op(self, func): return self.exporter(func) == export_binary def is_broadcast(self, tensor): shape = tensor.shape if isinstance(shape, tf.TensorShape): shape = shape.dims if len(shape) != 1: return False consumers = self.consumers(tensor) if consumers is None: return False for invocation in consumers: func, args = invocation[:2] if self.is_binary_op(func): x = args['x'] other = args['y'] if tensor == x else x elif func == tf.nn.bias_add: other = args['value'] elif func == tf.nn.batch_normalization or func == tf.nn.fused_batch_norm: other = args['x'] else: return False if isinstance(other, tf.Variable): other = other.value() if not isinstance(other, tf.Tensor): return False if other.shape[-1] != tensor.shape[0]: return False return True def is_filter(self, tensor): consumers = self.consumers(tensor) if consumers is not None: for invocation in consumers: func, args = invocation[:2] if func in [tf.nn.conv1d, tf.nn.atrous_conv2d, tf.nn.atrous_conv2d_transpose] \ and args['filters'] == tensor: return True elif func in [tf.nn.conv2d, tf.nn.conv3d, tf.nn.convolution, tf.nn.conv2d_transpose, tf.nn.conv3d_transpose, tf.nn.depthwise_conv2d, tf.nn.depthwise_conv2d_native, tf.nn.depthwise_conv2d_native_backprop_input] \ and args['filter'] == tensor: return True elif func == tf.nn.separable_conv2d: if args['depthwise_filter'] == tensor or args['pointwise_filter'] == tensor: return True return False def is_depthwise(self, tensor): consumers = self.consumers(tensor) if consumers is not None: for invocation in consumers: func, args = invocation[:2] if func in [tf.nn.depthwise_conv2d, tf.nn.depthwise_conv2d_native, tf.nn.depthwise_conv2d_native_backprop_input] \ and args['filter'] == tensor: return True elif func == tf.nn.separable_conv2d: if args['depthwise_filter'] == tensor: return True return False def export_skip(func, args, results, stack, converter): return None def export_passthrough(func, args, results, stack, converter): arg = converter.exporters.get(func)[1] converter.make_passthrough_tensor(args[arg], results[0]) return None def export_placeholder(func, args, results, stack, converter): result = results[0] shape = converter.nnef_shape(args['shape'], stack=stack, is_broadcast=converter.is_broadcast(result)) name = args['name'] if name is not None: output = converter.make_tensor(result, name, indexed=False) else: output = converter.make_tensor(result, 'input') return "{} = external(shape = {})".format(output, shape) def export_variable(func, args, results, stack, converter): name = args['name'] if name is None or name == '': print_error("non-empty 'name' argument must be provided for {}". format("tf.Variable()" if func == tf.Variable else "tf.get_variable()"), stack) return None if func == tf.get_variable: initializer = args.get('initializer') if isinstance(initializer, np.ndarray): shape = initializer.shape elif isinstance(initializer, (int, float)): shape = [1,1] else: shape = args['shape'] else: shape = tf.convert_to_tensor(args['initial_value']).shape result = results[0] is_filter = converter.is_filter(result) is_depthwise = converter.is_depthwise(result) is_broadcast = converter.is_broadcast(result) shape = converter.nnef_shape(shape, stack=stack, is_filter=is_filter, is_broadcast=is_broadcast) pos = name.rfind('/') output = converter.make_tensor(result, name[pos + 1:] if pos != -1 else name) if is_filter and is_depthwise: shape[0] *= shape[1] shape[1] = 1 if converter.reader: key = result.name[:-2] if converter.reader.has_tensor(key): tensor = converter.reader.get_tensor(key) if is_filter and is_depthwise: tensor = np.reshape(tensor, newshape = tensor.shape[:-2] + (1, tensor.shape[-2] * tensor.shape[-1])) filename = converter.output_path + '/' + name + '.dat' write_nnef_tensor(filename, tensor, is_filter=is_filter, is_broadcast=is_broadcast) else: print_error("variable '{}' not found in checkpoint".format(key), stack) return "{} = variable(shape = {}, label = '{}')".format(output, shape, name) def export_constant(func, args, results, stack, converter): shape = args['shape'] value = args['value'] result = results[0] singular = True if shape is not None: for s in shape: if s != 1: singular = False if not isinstance(value, (np.ndarray, list, tuple)) and singular: converter.make_constant(results[0], float(value)) return None if not isinstance(value, np.ndarray): value = np.array(value, dtype=np.float32) if value.size == 1 and singular: converter.make_constant(results[0], value.flatten()[0]) return None if shape is None: shape = list(value.shape) is_broadcast = converter.is_broadcast(result) shape = converter.nnef_shape(shape, stack=stack, is_broadcast=is_broadcast) value = converter.nnef_tensor_shuffle_dims(value, is_filter=False, is_broadcast=is_broadcast).flatten().tolist() output = converter.make_tensor(results[0], 'const') return '{} = constant(shape = {}, value = {})'.format(output, shape, value) def export_conv(func, args, results, stack, converter): kernel = args['filter'] if isinstance(kernel, tf.Variable): kernel = kernel.value() value = args.get('input') if value is None: value = args['value'] input = converter.nnef_tensor(value) filter = converter.nnef_tensor(kernel) size = kernel.shape.as_list()[:-2] strides = list(args['strides'])[1:-1] rate = args.get('rate', args.get('dilation_rate')) rate = list(rate) if rate else [1] * len(size) filter_sizes = converter.dilated_size(size, rate) padding = args['padding'] border = 'constant' value, rate, padding = converter.propagate_space_to_batch(value, rate, padding) result = converter.propagate_batch_to_space(results[0]) bias = 0.0 consumers = converter.consumers(result) if consumers is not None and len(consumers) == 1: invocation = consumers[0] _func, _args, _res = invocation[:3] if _func == tf.nn.bias_add and _args["value"] == result: bias = converter.nnef_tensor(_args["bias"]) result = _res[0] converter.make_fused(result) elif _func in [tf.add, tf_ops.add]: if _args["x"] == result: bias = converter.nnef_tensor(_args["y"]) elif _args["y"] == result: bias = converter.nnef_tensor(_args["x"]) result = _res[0] converter.make_fused(result) output_shape = args.get('output_shape') if output_shape is not None: if isinstance(output_shape, tf.Tensor): output_shape = tf.contrib.util.constant_value(output_shape) if output_shape is None: output_shape = result.get_shape() if output_shape is not None: output_shape = output_shape.as_list() if None in output_shape: output_shape = None if output_shape is None: print_warning("dynamic 'output_shape' cannot be evaluated, reverting to default") value_shape = value.shape.as_list()[1:-1] input_shape = output_shape[1:-1] if output_shape is not None else \ [utils.deconv_output_length(value_shape[i], filter_sizes[i], padding.lower(), strides[i]) for i in range(len(value_shape))] padding = converter.nnef_padding_ex(padding, input_shape, filter_sizes, strides) else: padding = converter.nnef_padding(padding, len(size)) padding, border = converter.propagate_padding(value, padding, border, spatial=True, stack=stack) op = converter.nnef_op(func) output = converter.make_tensor(result, 'conv' if op == 'planewise_conv' else op) return "{} = {}({}, {}, {}, padding = {}, border = '{}', stride = {}, dilation = {})" \ .format(output, op, input, filter, bias, padding, border, strides, rate) def export_convolution(func, args, results, stack, converter): args['strides'] = [1] + list(args['strides']) + [1] return export_conv(func, args, results, stack, converter) def export_separable_conv(func, args, results, stack, converter): value = args['input'] depth_kernel = args['depthwise_filter'] point_kernel = args['pointwise_filter'] if isinstance(depth_kernel, tf.Variable): depth_kernel = depth_kernel.value() if isinstance(point_kernel, tf.Variable): point_kernel = point_kernel.value() input = converter.nnef_tensor(value) depth_filter = converter.nnef_tensor(depth_kernel) point_filter = converter.nnef_tensor(point_kernel) size = depth_kernel.shape.as_list()[:-2] strides = converter.nnef_array(args['strides'][1:-1], 2) rate = converter.nnef_array(args['rate'], 2) padding = converter.nnef_padding(args['padding'], len(size)) border = 'constant' padding, border = converter.propagate_padding(value, padding, border, spatial=True, stack=stack) output = converter.make_tensor(results[0], 'conv') return "{} = separable_conv({}, plane_filter = {}, point_filter = {}, padding = {}, border = '{}', stride = {}, dilation = {})" \ .format(output, input, depth_filter, point_filter, padding, border, strides, rate) def export_pool(func, args, results, stack, converter): value = args['value'] input = converter.nnef_tensor(value) size = converter.nnef_shape(args['ksize'], stack=stack) strides = converter.nnef_shape(args['strides'], stack=stack) padding = converter.nnef_padding(args['padding'], len(size)) border = 'ignore' padding, border = converter.propagate_padding(value, padding, border, spatial=False, stack=stack) op = converter.nnef_op(func) output = converter.make_tensor(results[0], 'pool') return "{} = {}({}, size = {}, padding = {}, border = '{}', stride = {})".format(output, op, input, size, padding, border, strides) def export_activation(func, args, results, stack, converter): x = converter.nnef_tensor(args['features']) op = converter.nnef_op(func) output = converter.make_tensor(results[0], op) return '{} = {}({})'.format(output, op, x) def export_unary(func, args, results, stack, converter): x = converter.nnef_tensor(args['x']) op = converter.nnef_op(func) output = converter.make_tensor(results[0], op) return '{} = {}({})'.format(output, op, x) def export_binary(func, args, results, stack, converter): x = converter.nnef_tensor(args['x']) y = converter.nnef_tensor(args['y']) op = converter.nnef_op(func) output = converter.make_tensor(results[0], op) return '{} = {}({}, {})'.format(output, op, x, y) def export_squared_diff(func, args, results, stack, converter): x = converter.nnef_tensor(args['x']) y = converter.nnef_tensor(args['y']) output = converter.make_tensor(results[0], 'diff') return '{} = sqr({} - {})'.format(output, x, y) def export_where(func, args, results, stack, converter): c = converter.nnef_tensor(args['condition']) x = converter.nnef_tensor(args['x']) y = converter.nnef_tensor(args['y']) if x is None or y is None: print_error("arguments must not be None in tf.where() operation", stack) return None output = converter.make_tensor(results[0], 'select') return '{} = select({}, {}, {})'.format(output, c, x, y) def export_reduce(func, args, results, stack, converter): tensor = args['input_tensor'] input = converter.nnef_tensor(tensor) rank = len(tensor.shape.as_list()) axis = args['axis'] axes = sorted(converter.nnef_axes(axis, rank)) if axis else list(range(rank)) op = converter.nnef_op(func) output = converter.make_tensor(results[0], 'reduce') return '{} = {}({}, axes = {})'.format(output, op, input, axes) def export_lrn(func, args, results, stack, converter): input = converter.nnef_tensor(args['input']) depth_radius = args['depth_radius'] depth_size = 2 * depth_radius + 1 bias = float(args['bias']) alpha = float(args['alpha'] * depth_size) beta = float(args['beta']) size = [1, depth_size, 1, 1] output = converter.make_tensor(results[0], 'norm') return '{} = local_response_normalization({}, size = {}, alpha = {}, beta = {}, bias = {})'\ .format(output, input, size, alpha, beta, bias) def export_batch_normalization(func, args, results, stack, converter): input = converter.nnef_tensor(args['x']) mean = converter.nnef_tensor(args['mean']) variance = converter.nnef_tensor(args['variance']) offset = converter.nnef_tensor(args['offset']) if args.get('offset') is not None else float(0) scale = converter.nnef_tensor(args['scale']) if args.get('scale') is not None else float(1) epsilon = float(args.get('variance_epsilon', args.get('epsilon'))) output = converter.make_tensor(results[0], 'norm') return '{} = batch_normalization({}, mean = {}, variance = {}, offset = {}, scale = {}, epsilon = {})'\ .format(output, input, mean, variance, offset, scale, epsilon) def export_l2_normalization(func, args, results, stack, converter): input = converter.nnef_tensor(args['x']) axes = sorted(converter.nnef_axes(args['dim'])) epsilon = float(args.get('epsilon')) output = converter.make_tensor(results[0], 'norm') return "{} = l2_normalization({}, axes = {}, bias = {})".format(output, input, axes, epsilon) def export_matmul(func, args, results, stack, converter): A = converter.nnef_tensor(args['a']) B = converter.nnef_tensor(args['b']) trA = converter.nnef_bool(args['transpose_a']) trB = converter.nnef_bool(args['transpose_b']) output = converter.make_tensor(results[0], 'matmul') return '{} = matmul({}, {}, trA = {}, trB = {})'.format(output, A, B, trA, trB) def export_assign(func, args, results, stack, converter): ref = converter.nnef_tensor(args['ref']) value = converter.nnef_tensor(args['value']) output = converter.make_tensor(results[0], 'assign') return '{} = update({}, {})'.format(output, ref, value) def export_add_n(func, args, results, stack, converter): inputs = args['inputs'] value = converter.nnef_ids([converter.nnef_tensor(input) for input in inputs]) output = converter.make_tensor(results[0], 'add') return '{} = add_n({})'.format(output, value) def export_bias_add(func, args, results, stack, converter): input = converter.nnef_tensor(args['value']) bias = converter.nnef_tensor(args['bias']) output = converter.make_tensor(results[0], 'add') return '{} = add({}, {})'.format(output, input, bias) def export_concat(func, args, results, stack, converter): values = args['values'] rank = values[0].shape.ndims axis = converter.nnef_axis(args['axis'], rank) parts = converter.nnef_ids([converter.nnef_tensor(value) for value in values]) output = converter.make_tensor(results[0], 'concat') return '{} = concat({}, axis = {})'.format(output, parts, axis) def export_split(func, args, results, stack, converter): value = args['value'] whole = converter.nnef_tensor(value) num_or_sizes = args['num_or_size_splits'] ratios = num_or_sizes if isinstance(num_or_sizes, list) else [1] * num_or_sizes rank = value.shape.ndims axis = converter.nnef_axis(args['axis'], rank) output = converter.nnef_ids([converter.make_tensor(result, 'split') for result in results[0]]) return '{} = split({}, axis = {}, ratios = {})'.format(output, whole, axis, ratios) def export_softmax(func, args, results, stack, converter): logits = args['logits'] rank = len(logits.shape.as_list()) axis = sorted(converter.nnef_axes(args.get('dim', -1), rank)) parts = converter.nnef_tensor(logits) output = converter.make_tensor(results[0], 'softmax') return '{} = softmax({}, axes = {})'.format(output, parts, axis) def export_moments(func, args, results, stack, converter): value = args['x'] input = converter.nnef_tensor(value) rank = value.shape.ndims axes = sorted(converter.nnef_axes(args['axes'], rank)) mean = converter.make_tensor(results[0], 'mean') variance = converter.make_tensor(results[1], 'variance') return "{}, {} = moments({}, axes = {})".format(mean, variance, input, axes) def export_reshape(func, args, results, stack, converter): input = converter.nnef_tensor(args['tensor']) shape = converter.nnef_shape(args['shape'], stack=stack) output = converter.make_tensor(results[0], 'reshape') return '{} = reshape({}, shape = {})'.format(output, input, shape) def export_flatten(func, args, results, stack, converter): value = args['inputs'] input = converter.nnef_tensor(value) output = converter.make_tensor(results[0], 'reshape') return '{} = reshape({}, shape = [0, -1])'.format(output, input) def export_expand_dims(func, args, results, stack, converter): value = args['input'] rank = value.shape.ndims input = converter.nnef_tensor(value) axis = args['axis'] if axis is None: axis = rank shape = value.shape.as_list() shape.insert(axis, 1) shape = converter.nnef_shape(shape) output = converter.make_tensor(results[0], 'reshape') return '{} = reshape({}, shape = {})'.format(output, input, shape) def export_squeeze(func, args, results, stack, converter): value = args['input'] input = converter.nnef_tensor(value) axis = args['axis'] if axis is not None: axis = sorted(axis) else: shape = value.shape.as_list() axis = [i for i in range(len(shape)) if shape[i] == 1] rank = value.shape.ndims if axis == list(range(rank - 1)) or axis == list(range(1,rank - 1)): converter.make_passthrough_tensor(value, results[0]) return None axes = converter.nnef_axes(axis, rank) shape = '' for a in range(0,rank): if a not in axes: if len(shape) != 0: shape += ', ' shape += 'shape_of({})[{}]'.format(input, a) output = converter.make_tensor(results[0], 'reshape') return '{} = reshape({}, shape = [{}])'.format(output, input, shape) def export_transpose(func, args, results, stack, converter): value = args['a'] input = converter.nnef_tensor(value) rank = value.shape.ndims perm = args['perm'] if perm is None: perm = list(reversed(range(rank))) perm = converter.nnef_axes(perm, rank) p = list(perm) for i in range(len(perm)): perm[converter.nnef_axis(i, rank)] = p[i] output = converter.make_tensor(results[0], 'trans') return '{} = transpose({}, perm = {})'.format(output, input, perm) def export_resize_images(func, args, results, stack, converter): value = args['images'] input = converter.nnef_tensor(value) size = args['size'] method = args['method'] aligned = args['align_corners'] if isinstance(size, tf.Tensor): print_error('cannot handle dynamic target size in tf.image.resize()', stack) return None input_size = [s.value if isinstance(s,tf.Dimension) else int(s) for s in value.shape[1:-1]] size = [s.value if isinstance(s, tf.Dimension) else int(s) for s in size] if size[0] == input_size[0] and size[1] == input_size[1]: converter.make_passthrough_tensor(value, results[0]) return None if (size[0] > input_size[0] and size[1] < input_size[1]) or (size[0] < input_size[0] and size[1] > input_size[1]): print_error("resize must be up or down-sampling", stack) return None if size[0] > input_size[0]: if size[0] % input_size[0] or size[1] % input_size[1]: print_error('only integer factor resize allowed', stack) return None factor = [size[0] // input_size[0], size[1] // input_size[1]] output = converter.make_tensor(results[0], 'upsample') if method == tf.image.ResizeMethod.BILINEAR: return "{} = multilinear_upsample({}, factor = {}, method = '{}', border = 'replicate')"\ .format(output, input, factor, 'aligned' if aligned else 'asymmetric') elif method == tf.image.ResizeMethod.NEAREST_NEIGHBOR: return "{} = nearest_upsample({}, factor = {})".format(output, input, factor) else: print_error("unsupported upsample method '{}'".format(method), stack) return None else: if input_size[0] % size[0] or input_size[1] % size[1]: print_error('only integer factor resize allowed', stack) return None factor = [input_size[0] // size[0], input_size[1] // size[1]] output = converter.make_tensor(results[0], 'downsample') if method == tf.image.ResizeMethod.AREA: return "{} = area_downsample({}, factor = {})".format(output, input, factor) elif method == tf.image.ResizeMethod.NEAREST_NEIGHBOR: return "{} = nearest_downsample({}, factor = {})".format(output, input, factor) else: print_error("unsupported downsample method '{}'".format(method), stack) return None def export_resize_bilinear(func, args, results, stack, converter): args['method'] = tf.image.ResizeMethod.BILINEAR return export_resize_images(func, args, results, stack, converter) def export_resize_bicubic(func, args, results, stack, converter): args['method'] = tf.image.ResizeMethod.BICUBIC return export_resize_images(func, args, results, stack, converter) def export_resize_nearest(func, args, results, stack, converter): args['method'] = tf.image.ResizeMethod.NEAREST_NEIGHBOR return export_resize_images(func, args, results, stack, converter) def export_resize_area(func, args, results, stack, converter): args['method'] = tf.image.ResizeMethod.AREA return export_resize_images(func, args, results, stack, converter) def export_space_to_batch(func, args, results, stack, converter): input = converter.nnef_tensor(args['input']) block_shape = args['block_shape'] paddings = args['paddings'] output = converter.make_tensor(results[0], 'space2batch') return "{} = space2batch({}, block_shape = {}, paddings = {})".format(output, input, block_shape, paddings) def export_batch_to_space(func, args, results, stack, converter): input = converter.nnef_tensor(args['input']) block_shape = args['block_shape'] output = converter.make_tensor(results[0], 'batch2space') return "{} = batch2space({}, block_shape = {})".format(output, input, block_shape) DefaultExporters =\ { tf.Variable: (export_variable, 'variable'), tf.get_variable: (export_variable, 'variable'), tf.placeholder: (export_placeholder, 'external'), tf.constant: (export_constant, 'constant'), tf.identity: (export_passthrough, 'input'), tf.concat: (export_concat, 'concat'), tf.split: (export_split, 'split'), tf.reshape: (export_reshape, 'reshape'), tf.squeeze: (export_squeeze, 'reshape'), tf.expand_dims: (export_expand_dims, 'reshape'), tf.transpose: (export_transpose, 'transpose'), tf.stop_gradient: (export_passthrough, 'input'), tf.cast: (export_passthrough, 'x'), tf.pad: (export_passthrough, 'tensor'), tf.add: (export_binary, 'add'), tf.subtract: (export_binary, 'sub'), tf.multiply: (export_binary, 'mul'), tf.divide: (export_binary, 'div'), tf.pow: (export_binary, 'pow'), tf.squared_difference: (export_squared_diff, 'sqr'), tf.logical_and: (export_binary, 'and'), tf.logical_or: (export_binary, 'or'), tf.negative: (export_unary, 'neg'), tf.logical_not: (export_unary, 'not'), tf.abs: (export_unary, 'abs'), tf.sign: (export_unary, 'sign'), tf.exp: (export_unary, 'exp'), tf.log: (export_unary, 'log'), tf.sqrt: (export_unary, 'sqrt'), tf.rsqrt: (export_unary, 'rsqrt'), tf.square: (export_unary, 'sqr'), tf.floor: (export_unary, 'floor'), tf.ceil: (export_unary, 'ceil'), tf.round: (export_unary, 'round'), tf.where: (export_where, 'select'), tf.greater: (export_binary, 'gt'), tf.greater_equal: (export_binary, 'ge'), tf.less: (export_binary, 'lt'), tf.less_equal: (export_binary, 'le'), tf.equal: (export_binary, 'eq'), tf.not_equal: (export_binary, 'ne'), tf.minimum: (export_binary, 'min'), tf.maximum: (export_binary, 'max'), tf.assign: (export_assign, 'update'), tf_ops.add: (export_binary, 'add'), tf_ops.sub: (export_binary, 'sub'), tf_ops.mul: (export_binary, 'mul'), tf_ops.div: (export_binary, 'div'), tf_ops.real_div: (export_binary, 'div'), tf_ops._pow: (export_binary, 'pow'), tf_ops.logical_and: (export_binary, 'and'), tf_ops.logical_or: (export_binary, 'or'), tf_ops.neg: (export_unary, 'neg'), tf_ops.reciprocal: (export_unary, 'rcp'), tf_ops.logical_not: (export_unary, 'not'), tf_ops._abs: (export_unary, 'abs'), tf_ops.sign: (export_unary, 'sign'), tf_ops.exp: (export_unary, 'exp'), tf_ops.log: (export_unary, 'log'), tf_ops.square: (export_unary, 'sqr'), tf_ops.floor: (export_unary, 'floor'), tf_ops.ceil: (export_unary, 'ceil'), tf_ops.round: (export_unary, 'round'), tf_ops.greater: (export_binary, 'gt'), tf_ops.greater_equal: (export_binary, 'ge'), tf_ops.less: (export_binary, 'lt'), tf_ops.less_equal: (export_binary, 'le'), tf_ops.equal: (export_binary, 'eq'), tf_ops.not_equal: (export_binary, 'ne'), tf_ops.sqrt: (export_unary, 'sqrt'), tf_ops.rsqrt: (export_unary, 'rsqrt'), tf.sigmoid: (export_unary, 'sigmoid'), tf.tanh: (export_unary, 'tanh'), tf.reduce_sum: (export_reduce, 'sum_reduce'), tf.reduce_mean: (export_reduce, 'mean_reduce'), tf.reduce_max: (export_reduce, 'max_reduce'), tf.matmul: (export_matmul, 'matmul'), tf.add_n: (export_add_n, 'add_n'), tf.nn.sigmoid: (export_unary, 'sigmoid'), tf.nn.tanh: (export_unary, 'tanh'), tf.nn.elu: (export_activation, 'elu'), tf.nn.relu: (export_activation, 'relu'), tf.nn.softsign: (export_activation, 'softsign'), tf.nn.softplus: (export_activation, 'softplus'), tf.nn.conv1d: (export_conv, 'conv'), tf.nn.conv2d: (export_conv, 'conv'), tf.nn.conv3d: (export_conv, 'conv'), tf.nn.convolution: (export_convolution, 'conv'), tf.nn.conv2d_transpose: (export_conv, 'deconv'), tf.nn.conv3d_transpose: (export_conv, 'deconv'), tf.nn.depthwise_conv2d: (export_conv, 'planewise_conv'), tf.nn.depthwise_conv2d_native: (export_conv, 'planewise_conv'), tf.nn.separable_conv2d: (export_separable_conv, 'conv'), tf.nn.max_pool: (export_pool, 'max_pool'), tf.nn.max_pool_with_argmax: (export_pool, 'max_pool_with_indices'), tf.nn.avg_pool: (export_pool, 'avg_pool'), tf.nn.dropout: (export_passthrough, 'x'), tf.nn.bias_add: (export_bias_add, 'add'), tf.nn.lrn: (export_lrn, 'local_response_normalization'), tf.nn.local_response_normalization: (export_lrn, 'local_response_normalization'), tf.nn.batch_normalization: (export_batch_normalization, 'batch_normalization'), tf.nn.fused_batch_norm: (export_batch_normalization, 'batch_normalization'), tf.nn.l2_normalize: (export_l2_normalization, 'l2_normalization'), tf.nn.softmax: (export_softmax, 'softmax'), tf.nn.moments: (export_moments, 'moments'), tf.image.resize_images: export_resize_images, tf.image.resize_bilinear: export_resize_bilinear, tf.image.resize_nearest_neighbor: export_resize_nearest, tf.image.resize_bicubic: export_resize_bicubic, tf.image.resize_area: export_resize_area, tf.space_to_batch: (export_passthrough, 'input'), tf.space_to_batch_nd: (export_passthrough, 'input'), tf.batch_to_space: export_skip, tf.batch_to_space_nd: export_skip, tf_layers.softmax: (export_softmax, 'softmax'), tf_layers.flatten: (export_flatten, 'reshape'), } if tf_version_greater(1,3): DefaultExporters.update( { tf.sinh: (export_unary, 'sinh'), tf.cosh: (export_unary, 'cosh') }) def unrolled_rnn(cell, inputs, sequence_length=None, initial_state=None, dtype=tf.float32, scope=None): if sequence_length is None: sequence_length = tf.constant(shape=[inputs.shape[0]], value=[float(inputs.shape[1])], dtype=tf.float32) split_inputs = tf.split(inputs, axis=1, num_or_size_splits=inputs.shape[1]) if initial_state is not None: c, h = initial_state else: c = tf.zeros(shape=[inputs.shape[0], inputs.shape[2]], dtype=dtype) h = tf.zeros(shape=[inputs.shape[0], inputs.shape[2]], dtype=dtype) _c = c _h = h output_list = [] with tf.variable_scope(scope or "rnn"): for index, input in enumerate(split_inputs): output, (c, h) = cell(tf.squeeze(input, axis=[1]), (c, h)) output_list.append(output) condition = tf.equal(sequence_length, index + 1) _c = tf.where(condition, c, _c) _h = tf.where(condition, h, _h) outputs = tf.concat(output_list, axis=1) return outputs, (_c, _h) def trace_invocations(func, functions, handler=None): systrace = sys.gettrace() trace = InvocationTrace(functions, handler) sys.settrace(trace) results = func() sys.settrace(systrace) if isinstance(results, (tf.Tensor, tf.Variable)): outputs = { 'output': results } elif isinstance(results, (list, tuple)): outputs = {} for i, result in enumerate(results): if isinstance(result, (tf.Tensor, tf.Variable)): outputs['output' + str(i+1)] = result elif isinstance(results, dict): outputs = {} for name, result in results.items(): if isinstance(result, (tf.Tensor, tf.Variable)): outputs[name] = result return trace.invocations, outputs def enumerate_dependencies(dependencies, targets, exclusions): q = Queue() s = set() def insert(tensor,func,stack): if tensor not in s: if isinstance(tensor, tf.Variable): tensor = tensor.value() q.put((tensor,func,stack)) s.add(tensor) for target in targets: insert(target,None,None) while not q.empty(): tensor, func, stack = q.get() invocation = dependencies.get(tensor) if invocation is None: if func: op = func.__module__ + '.' + func.__name__ print_error("tensor '{}' used by operation {} is not the result of any exported operation".format(tensor.name, op), stack) else: print_error("output tensor '{}' is not the result of any exported operation".format(tensor.name), stack) continue func, args, results, stack = invocation exc = exclusions.get(func) for key, arg in args.items(): if exc is not None and key in exc: continue if isinstance(arg, (list, tuple)): for a in arg: if isinstance(a, (tf.Tensor, tf.Variable)): insert(a, func, stack) elif isinstance(arg, (tf.Tensor, tf.Variable)): insert(arg, func, stack) return s def write_nnef_version(file, major, minor): np.asarray([0x4E, 0xEF], dtype=np.uint8).tofile(file)
np.asarray([major,minor], dtype=np.uint8)
numpy.asarray
#!/usr/bin/env python # # timeresp_test.py - test time response functions # RMM, 17 Jun 2011 (based on TestMatlab from v0.4c) # # This test suite just goes through and calls all of the MATLAB # functions using different systems and arguments to make sure that # nothing crashes. It doesn't test actual functionality; the module # specific unit tests will do that. import unittest import numpy as np from control.timeresp import * from control.statesp import * from control.xferfcn import TransferFunction, _convert_to_transfer_function from control.dtime import c2d from control.exception import slycot_check class TestTimeresp(unittest.TestCase): def setUp(self): """Set up some systems for testing out MATLAB functions""" A = np.matrix("1. -2.; 3. -4.") B = np.matrix("5.; 7.") C = np.matrix("6. 8.") D = np.matrix("9.") self.siso_ss1 = StateSpace(A, B, C, D) # Create some transfer functions self.siso_tf1 = TransferFunction([1], [1, 2, 1]) self.siso_tf2 = _convert_to_transfer_function(self.siso_ss1) # Create MIMO system, contains ``siso_ss1`` twice A = np.matrix("1. -2. 0. 0.;" "3. -4. 0. 0.;" "0. 0. 1. -2.;" "0. 0. 3. -4. ") B = np.matrix("5. 0.;" "7. 0.;" "0. 5.;" "0. 7. ") C = np.matrix("6. 8. 0. 0.;" "0. 0. 6. 8. ") D = np.matrix("9. 0.;" "0. 9. ") self.mimo_ss1 = StateSpace(A, B, C, D) # Create discrete time systems self.siso_dtf1 = TransferFunction([1], [1, 1, 0.25], True) self.siso_dtf2 = TransferFunction([1], [1, 1, 0.25], 0.2) self.siso_dss1 = tf2ss(self.siso_dtf1) self.siso_dss2 = tf2ss(self.siso_dtf2) self.mimo_dss1 = StateSpace(A, B, C, D, True) self.mimo_dss2 = c2d(self.mimo_ss1, 0.2) def test_step_response(self): # Test SISO system sys = self.siso_ss1 t = np.linspace(0, 1, 10) youttrue = np.array([9., 17.6457, 24.7072, 30.4855, 35.2234, 39.1165, 42.3227, 44.9694, 47.1599, 48.9776]) # SISO call tout, yout = step_response(sys, T=t) np.testing.assert_array_almost_equal(yout, youttrue, decimal=4) np.testing.assert_array_almost_equal(tout, t) # Play with arguments tout, yout = step_response(sys, T=t, X0=0) np.testing.assert_array_almost_equal(yout, youttrue, decimal=4) np.testing.assert_array_almost_equal(tout, t) X0 = np.array([0, 0]) tout, yout = step_response(sys, T=t, X0=X0) np.testing.assert_array_almost_equal(yout, youttrue, decimal=4) np.testing.assert_array_almost_equal(tout, t) tout, yout, xout = step_response(sys, T=t, X0=0, return_x=True) np.testing.assert_array_almost_equal(yout, youttrue, decimal=4) np.testing.assert_array_almost_equal(tout, t) # Test MIMO system, which contains ``siso_ss1`` twice sys = self.mimo_ss1 _t, y_00 = step_response(sys, T=t, input=0, output=0) _t, y_11 = step_response(sys, T=t, input=1, output=1) np.testing.assert_array_almost_equal(y_00, youttrue, decimal=4) np.testing.assert_array_almost_equal(y_11, youttrue, decimal=4) # Make sure continuous and discrete time use same return conventions sysc = self.mimo_ss1 sysd = c2d(sysc, 1) # discrete time system Tvec = np.linspace(0, 10, 11) # make sure to use integer times 0..10 Tc, youtc = step_response(sysc, Tvec, input=0) Td, youtd = step_response(sysd, Tvec, input=0) np.testing.assert_array_equal(Tc.shape, Td.shape) np.testing.assert_array_equal(youtc.shape, youtd.shape) def test_step_info(self): # From matlab docs: sys = TransferFunction([1,5,5],[1,1.65,5,6.5,2]) Strue = { 'RiseTime': 3.8456, 'SettlingTime': 27.9762, 'SettlingMin': 2.0689, 'SettlingMax': 2.6873, 'Overshoot': 7.4915, 'Undershoot': 0, 'Peak': 2.6873, 'PeakTime': 8.0530 } S = step_info(sys) # Very arbitrary tolerance because I don't know if the # response from the MATLAB is really that accurate. # maybe it is a good idea to change the Strue to match # but I didn't do it because I don't know if it is # accurate either... rtol = 2e-2 np.testing.assert_allclose( S.get('RiseTime'), Strue.get('RiseTime'), rtol=rtol) np.testing.assert_allclose( S.get('SettlingTime'), Strue.get('SettlingTime'), rtol=rtol) np.testing.assert_allclose( S.get('SettlingMin'), Strue.get('SettlingMin'), rtol=rtol) np.testing.assert_allclose( S.get('SettlingMax'), Strue.get('SettlingMax'), rtol=rtol) np.testing.assert_allclose( S.get('Overshoot'), Strue.get('Overshoot'), rtol=rtol) np.testing.assert_allclose( S.get('Undershoot'), Strue.get('Undershoot'), rtol=rtol) np.testing.assert_allclose( S.get('Peak'), Strue.get('Peak'), rtol=rtol) np.testing.assert_allclose( S.get('PeakTime'), Strue.get('PeakTime'), rtol=rtol) np.testing.assert_allclose( S.get('SteadyStateValue'), 2.50, rtol=rtol) def test_impulse_response(self): # Test SISO system sys = self.siso_ss1 t = np.linspace(0, 1, 10) youttrue = np.array([86., 70.1808, 57.3753, 46.9975, 38.5766, 31.7344, 26.1668, 21.6292, 17.9245, 14.8945]) tout, yout = impulse_response(sys, T=t) np.testing.assert_array_almost_equal(yout, youttrue, decimal=4) np.testing.assert_array_almost_equal(tout, t) # Play with arguments tout, yout = impulse_response(sys, T=t, X0=0) np.testing.assert_array_almost_equal(yout, youttrue, decimal=4) np.testing.assert_array_almost_equal(tout, t) X0 = np.array([0, 0]) tout, yout = impulse_response(sys, T=t, X0=X0) np.testing.assert_array_almost_equal(yout, youttrue, decimal=4) np.testing.assert_array_almost_equal(tout, t) tout, yout, xout = impulse_response(sys, T=t, X0=0, return_x=True) np.testing.assert_array_almost_equal(yout, youttrue, decimal=4) np.testing.assert_array_almost_equal(tout, t) # Test MIMO system, which contains ``siso_ss1`` twice sys = self.mimo_ss1 _t, y_00 = impulse_response(sys, T=t, input=0, output=0) _t, y_11 = impulse_response(sys, T=t, input=1, output=1) np.testing.assert_array_almost_equal(y_00, youttrue, decimal=4) np.testing.assert_array_almost_equal(y_11, youttrue, decimal=4) # Test MIMO system, as mimo, and don't trim outputs sys = self.mimo_ss1 _t, yy = impulse_response(sys, T=t, input=0) np.testing.assert_array_almost_equal( yy, np.vstack((youttrue, np.zeros_like(youttrue))), decimal=4) def test_initial_response(self): # Test SISO system sys = self.siso_ss1 t = np.linspace(0, 1, 10) x0 = np.array([[0.5], [1]]) youttrue = np.array([11., 8.1494, 5.9361, 4.2258, 2.9118, 1.9092, 1.1508, 0.5833, 0.1645, -0.1391]) tout, yout = initial_response(sys, T=t, X0=x0) np.testing.assert_array_almost_equal(yout, youttrue, decimal=4) np.testing.assert_array_almost_equal(tout, t) # Play with arguments tout, yout, xout = initial_response(sys, T=t, X0=x0, return_x=True) np.testing.assert_array_almost_equal(yout, youttrue, decimal=4) np.testing.assert_array_almost_equal(tout, t) # Test MIMO system, which contains ``siso_ss1`` twice sys = self.mimo_ss1 x0 = np.matrix(".5; 1.; .5; 1.") _t, y_00 = initial_response(sys, T=t, X0=x0, input=0, output=0) _t, y_11 = initial_response(sys, T=t, X0=x0, input=1, output=1) np.testing.assert_array_almost_equal(y_00, youttrue, decimal=4) np.testing.assert_array_almost_equal(y_11, youttrue, decimal=4) def test_initial_response_no_trim(self): # test MIMO system without trimming t = np.linspace(0, 1, 10) x0 = np.matrix(".5; 1.; .5; 1.") youttrue = np.array([11., 8.1494, 5.9361, 4.2258, 2.9118, 1.9092, 1.1508, 0.5833, 0.1645, -0.1391]) sys = self.mimo_ss1 _t, yy = initial_response(sys, T=t, X0=x0) np.testing.assert_array_almost_equal( yy, np.vstack((youttrue, youttrue)), decimal=4) def test_forced_response(self): t = np.linspace(0, 1, 10) # compute step response - test with state space, and transfer function # objects u = np.array([1., 1, 1, 1, 1, 1, 1, 1, 1, 1]) youttrue = np.array([9., 17.6457, 24.7072, 30.4855, 35.2234, 39.1165, 42.3227, 44.9694, 47.1599, 48.9776]) tout, yout, _xout = forced_response(self.siso_ss1, t, u) np.testing.assert_array_almost_equal(yout, youttrue, decimal=4) np.testing.assert_array_almost_equal(tout, t) _t, yout, _xout = forced_response(self.siso_tf2, t, u) np.testing.assert_array_almost_equal(yout, youttrue, decimal=4) # test with initial value and special algorithm for ``U=0`` u = 0 x0 = np.matrix(".5; 1.") youttrue = np.array([11., 8.1494, 5.9361, 4.2258, 2.9118, 1.9092, 1.1508, 0.5833, 0.1645, -0.1391]) _t, yout, _xout = forced_response(self.siso_ss1, t, u, x0) np.testing.assert_array_almost_equal(yout, youttrue, decimal=4) # Test MIMO system, which contains ``siso_ss1`` twice # first system: initial value, second system: step response u = np.array([[0., 0, 0, 0, 0, 0, 0, 0, 0, 0], [1., 1, 1, 1, 1, 1, 1, 1, 1, 1]]) x0 = np.array([[.5], [1], [0], [0]]) youttrue = np.array([[11., 8.1494, 5.9361, 4.2258, 2.9118, 1.9092, 1.1508, 0.5833, 0.1645, -0.1391], [9., 17.6457, 24.7072, 30.4855, 35.2234, 39.1165, 42.3227, 44.9694, 47.1599, 48.9776]]) _t, yout, _xout = forced_response(self.mimo_ss1, t, u, x0) np.testing.assert_array_almost_equal(yout, youttrue, decimal=4) # Test discrete MIMO system to use correct convention for input sysc = self.mimo_ss1 dt=t[1]-t[0] sysd = c2d(sysc, dt) # discrete time system Tc, youtc, _xoutc = forced_response(sysc, t, u, x0) Td, youtd, _xoutd = forced_response(sysd, t, u, x0) np.testing.assert_array_equal(Tc.shape, Td.shape) np.testing.assert_array_equal(youtc.shape, youtd.shape) np.testing.assert_array_almost_equal(youtc, youtd, decimal=4) # Test discrete MIMO system without default T argument u = np.array([[0., 0, 0, 0, 0, 0, 0, 0, 0, 0], [1., 1, 1, 1, 1, 1, 1, 1, 1, 1]]) x0 = np.array([[.5], [1], [0], [0]]) youttrue = np.array([[11., 8.1494, 5.9361, 4.2258, 2.9118, 1.9092, 1.1508, 0.5833, 0.1645, -0.1391], [9., 17.6457, 24.7072, 30.4855, 35.2234, 39.1165, 42.3227, 44.9694, 47.1599, 48.9776]]) _t, yout, _xout = forced_response(sysd, U=u, X0=x0) np.testing.assert_array_almost_equal(yout, youttrue, decimal=4) def test_lsim_double_integrator(self): # Note: scipy.signal.lsim fails if A is not invertible A = np.mat("0. 1.;0. 0.") B = np.mat("0.; 1.") C = np.mat("1. 0.") D = 0. sys = StateSpace(A, B, C, D) def check(u, x0, xtrue): _t, yout, xout = forced_response(sys, t, u, x0) np.testing.assert_array_almost_equal(xout, xtrue, decimal=6) ytrue = np.squeeze(np.asarray(C.dot(xtrue))) np.testing.assert_array_almost_equal(yout, ytrue, decimal=6) # test with zero input npts = 10 t = np.linspace(0, 1, npts) u = np.zeros_like(t) x0 = np.array([2., 3.]) xtrue = np.zeros((2, npts)) xtrue[0, :] = x0[0] + t * x0[1] xtrue[1, :] = x0[1] check(u, x0, xtrue) # test with step input u = np.ones_like(t) xtrue = np.array([0.5 * t**2, t]) x0 = np.array([0., 0.]) check(u, x0, xtrue) # test with linear input u = t xtrue = np.array([1./6. * t**3, 0.5 * t**2]) check(u, x0, xtrue) def test_discrete_initial(self): h1 = TransferFunction([1.], [1., 0.], 1.) t, yout = impulse_response(h1, np.arange(4)) np.testing.assert_array_equal(yout, [0., 1., 0., 0.]) @unittest.skipIf(not slycot_check(), "slycot not installed") def test_step_robustness(self): "Unit test: https://github.com/python-control/python-control/issues/240" # Create 2 input, 2 output system num = [ [[0], [1]], [[1], [0]] ] den1 = [ [[1], [1,1]], [[1,4], [1]] ] sys1 = TransferFunction(num, den1) den2 = [ [[1], [1e-10, 1, 1]], [[1,4], [1]] ] # slight perturbation sys2 = TransferFunction(num, den2) # Compute step response from input 1 to output 1, 2 t1, y1 = step_response(sys1, input=0) t2, y2 = step_response(sys2, input=0) np.testing.assert_array_almost_equal(y1, y2) def test_time_vector(self): "Unit test: https://github.com/python-control/python-control/issues/239" # Discrete time simulations with specified time vectors Tin1 = np.arange(0, 5, 1) # matches dtf1, dss1; multiple of 0.2 Tin2 = np.arange(0, 5, 0.2) # matches dtf2, dss2 Tin3 = np.arange(0, 5, 0.5) # incompatible with 0.2 # Initial conditions to use for the different systems siso_x0 = [1, 2] mimo_x0 = [1, 2, 3, 4] # # Easy cases: make sure that output sample time matches input # # No timebase in system => output should match input # # Initial response tout, yout = initial_response(self.siso_dtf1, Tin2, siso_x0, squeeze=False) self.assertEqual(np.shape(tout), np.shape(yout[0,:])) np.testing.assert_array_equal(tout, Tin2) # Impulse response tout, yout = impulse_response(self.siso_dtf1, Tin2, squeeze=False) self.assertEqual(np.shape(tout), np.shape(yout[0,:])) np.testing.assert_array_equal(tout, Tin2) # Step response tout, yout = step_response(self.siso_dtf1, Tin2, squeeze=False) self.assertEqual(np.shape(tout), np.shape(yout[0,:])) np.testing.assert_array_equal(tout, Tin2) # Forced response with specified time vector tout, yout, xout = forced_response(self.siso_dtf1, Tin2, np.sin(Tin2), squeeze=False) self.assertEqual(np.shape(tout), np.shape(yout[0,:])) np.testing.assert_array_equal(tout, Tin2) # Forced response with no time vector, no sample time (should use 1) tout, yout, xout = forced_response(self.siso_dtf1, None, np.sin(Tin1), squeeze=False) self.assertEqual(np.shape(tout), np.shape(yout[0,:])) np.testing.assert_array_equal(tout, Tin1) # MIMO forced response tout, yout, xout = forced_response(self.mimo_dss1, Tin1, (np.sin(Tin1), np.cos(Tin1)), mimo_x0) self.assertEqual(np.shape(tout), np.shape(yout[0,:])) self.assertEqual(np.shape(tout), np.shape(yout[1,:])) np.testing.assert_array_equal(tout, Tin1) # Matching timebase in system => output should match input # # Initial response tout, yout = initial_response(self.siso_dtf2, Tin2, siso_x0, squeeze=False) self.assertEqual(np.shape(tout), np.shape(yout[0,:])) np.testing.assert_array_equal(tout, Tin2) # Impulse response tout, yout = impulse_response(self.siso_dtf2, Tin2, squeeze=False) self.assertEqual(np.shape(tout), np.shape(yout[0,:])) np.testing.assert_array_equal(tout, Tin2) # Step response tout, yout = step_response(self.siso_dtf2, Tin2, squeeze=False) self.assertEqual(np.shape(tout), np.shape(yout[0,:])) np.testing.assert_array_equal(tout, Tin2) # Forced response tout, yout, xout = forced_response(self.siso_dtf2, Tin2, np.sin(Tin2), squeeze=False) self.assertEqual(np.shape(tout), np.shape(yout[0,:])) np.testing.assert_array_equal(tout, Tin2) # Forced response with no time vector, use sample time tout, yout, xout = forced_response(self.siso_dtf2, None, np.sin(Tin2), squeeze=False) self.assertEqual(np.shape(tout), np.shape(yout[0,:])) np.testing.assert_array_equal(tout, Tin2) # Compatible timebase in system => output should match input # # Initial response tout, yout = initial_response(self.siso_dtf2, Tin1, siso_x0, squeeze=False) self.assertEqual(np.shape(tout), np.shape(yout[0,:])) np.testing.assert_array_equal(tout, Tin1) # Impulse response tout, yout = impulse_response(self.siso_dtf2, Tin1, squeeze=False) self.assertEqual(np.shape(tout), np.shape(yout[0,:])) np.testing.assert_array_equal(tout, Tin1) # Step response tout, yout = step_response(self.siso_dtf2, Tin1, squeeze=False) self.assertEqual(np.shape(tout), np.shape(yout[0,:])) np.testing.assert_array_equal(tout, Tin1) # Forced response tout, yout, xout = forced_response(self.siso_dtf2, Tin1, np.sin(Tin1), squeeze=False) self.assertEqual(np.shape(tout), np.shape(yout[0,:])) np.testing.assert_array_equal(tout, Tin1) # # Interpolation of the input (to match scipy.signal.dlsim) # # Initial response tout, yout, xout = forced_response(self.siso_dtf2, Tin1, np.sin(Tin1), interpolate=True, squeeze=False) self.assertEqual(np.shape(tout), np.shape(yout[0,:])) self.assertTrue(np.allclose(tout[1:] - tout[:-1], self.siso_dtf2.dt)) # # Incompatible cases: make sure an error is thrown # # System timebase and given time vector are incompatible # # Initial response with self.assertRaises(Exception) as context: tout, yout = initial_response(self.siso_dtf2, Tin3, siso_x0, squeeze=False) self.assertTrue(isinstance(context.exception, ValueError)) def test_discrete_time_steps(self): """Make sure rounding errors in sample time are handled properly""" # See https://github.com/python-control/python-control/issues/332) # # These tests play around with the input time vector to make sure that # small rounding errors don't generate spurious errors. # Discrete time system to use for simulation # self.siso_dtf2 = TransferFunction([1], [1, 1, 0.25], 0.2) # Set up a time range and simulate T = np.arange(0, 100, 0.2) tout1, yout1 = step_response(self.siso_dtf2, T) # Simulate every other time step T =
np.arange(0, 100, 0.4)
numpy.arange
import numpy as np def normalize_to_range(array, R): """Returns array normalized to range R.""" array = array -
np.min(array)
numpy.min
import numpy as np from scipy.signal import filtfilt class LaneLocalizer(): def __init__(self, lane_xs, lane_ys, lane_yaws, lane_vs, s_resolution=0.5): # Make sure yaw angles are within bounds: lane_ss = self._get_cumulative_distances(lane_xs, lane_ys) lane_yaws = self._bound_angle_within_pi(lane_yaws) s_interp = np.arange(0., lane_ss[-1] + s_resolution/2., s_resolution) x_interp = np.interp(s_interp, lane_ss, lane_xs) y_interp = np.interp(s_interp, lane_ss, lane_ys) yaw_interp = np.interp(s_interp, lane_ss, np.unwrap(lane_yaws)) v_interp = np.interp(s_interp, lane_ss, lane_vs) curv_interp = self._get_curvatures(s_interp, yaw_interp) yaw_interp = self._bound_angle_within_pi(yaw_interp) self.lane_arr = np.column_stack((s_interp, x_interp, y_interp, yaw_interp, v_interp, curv_interp)) self.lane_length = s_interp[-1] @staticmethod def _bound_angle_within_pi(angle): """ Given an angle, adjusts it to lie within a +/- PI range """ return (angle + np.pi) % (2 * np.pi) - np.pi # https://stackoverflow.com/questions/15927755/opposite-of-numpy-unwrap @staticmethod def _get_cumulative_distances(xs, ys): # Arclength/progress estimation. lane_xy = np.column_stack((xs, ys)) lane_ss = np.cumsum( np.linalg.norm( np.diff(lane_xy, axis=0), axis=1 ) ) lane_ss = np.insert(lane_ss, 0, [0.0]) return lane_ss @staticmethod def _get_curvatures(ss, yaws): # Curvature estimation. curv_raw = LaneLocalizer._bound_angle_within_pi(np.diff(yaws)) / np.diff(ss) if len(curv_raw) < 10: curv_filt = curv_raw else: curv_filt = filtfilt(np.ones((3,))/3, 1, curv_raw) curv_filt = np.append(curv_filt, curv_filt[-1]) return curv_filt def get_reference_speed_and_curvature(self, s): closest_index = np.argmin( np.abs(self.lane_arr[:,0] - s) ) v_waypoint = self.lane_arr[closest_index, 4] curv_waypoint = self.lane_arr[closest_index, 5] return v_waypoint, curv_waypoint def convert_global_to_frenet_coords(self, x, y, psi, extrapolate_s = False): xy_traj = self.lane_arr[:,1:3] xy_query = np.array([x, y]) closest_index = np.argmin( np.linalg.norm(xy_traj - xy_query, axis=1) ) # Note: Can do some smarter things here, like linear interpolation. # If s_K+1 - s_k is reasonably small, we can assume s of the waypoint # and s of the query point are the same for simplicity. s_waypoint = self.lane_arr[closest_index, 0] xy_waypoint = self.lane_arr[closest_index, 1:3] psi_waypoint = self.lane_arr[closest_index, 3] rot_global_to_frenet = np.array([[ np.cos(psi_waypoint), np.sin(psi_waypoint)], \ [-np.sin(psi_waypoint), np.cos(psi_waypoint)]]) # Error_xy = xy deviation (global frame) # Error_frenet = e_s, e_y deviation (Frenet frame) error_xy = xy_query - xy_waypoint error_frenet = rot_global_to_frenet @ error_xy # e_psi error_psi = self._bound_angle_within_pi(psi - psi_waypoint) if extrapolate_s: if closest_index == 0 or closest_index == self.lane_arr.shape[0]-1: s_waypoint += error_frenet[0] # Add "e_s" at the endpoints to extrapolate the lane. return s_waypoint, error_frenet[1], error_psi # s, ey, epsi def convert_frenet_to_global_coords(self, s, ey, epsi): s_traj = self.lane_arr[:,0] # Handle "closest waypoint" differently based on s_query: if s < s_traj[0]: # NOTE: This can be problematic if s_query is really far away from the start. # Not handling this but intuitively, need to do some extrapolation. x_waypoint = self.lane_arr[0, 1] y_waypoint = self.lane_arr[0, 2] psi_waypoint = self.lane_arr[0, 3] elif s > s_traj[-1]: # NOTE: This can be problematic if s_query is really far away from the end. # Not handling this but intuitively, need to do some extrapolation. x_waypoint = self.lane_arr[-1, 1] y_waypoint = self.lane_arr[-1, 2] psi_waypoint = self.lane_arr[-1, 3] else: # NOTE: keeping this simple and using the closest waypoint, in place of more # complex and possibly error-prone interpolation strategies. closest_index = np.argmin( np.abs( s_traj - s) ) x_waypoint = self.lane_arr[closest_index, 1] y_waypoint = self.lane_arr[closest_index, 2] psi_waypoint = self.lane_arr[closest_index, 3] rot_frenet_to_global = np.array([[np.cos(psi_waypoint), -np.sin(psi_waypoint)], \ [np.sin(psi_waypoint), np.cos(psi_waypoint)]]) error_global = rot_frenet_to_global @ np.array([0, ey]) # assuming "e_s" is 0. x_global = x_waypoint + error_global[0] y_global = y_waypoint + error_global[1] psi_global = self._bound_angle_within_pi(psi_waypoint + epsi) return x_global, y_global, psi_global def get_lane_measurement(self, x, y): # Similar to conversion to Frenet coords but getting the actual waypoint / local rotation matrix. xy_traj = self.lane_arr[:,1:3] xy_query = np.array([x, y]) closest_index = np.argmin( np.linalg.norm(xy_traj - xy_query, axis=1) ) xy_waypoint = self.lane_arr[closest_index, 1:3] psi_waypoint = self.lane_arr[closest_index, 3] pose_waypoint = np.append(xy_waypoint, psi_waypoint) rot_frenet_to_global = np.array([[np.cos(psi_waypoint), -
np.sin(psi_waypoint)
numpy.sin
from typing import List import numpy as np import tensorflow as tf class AutoRegressive: """Auto regressive, it is used to generate text""" def beam_search(self, inputs: List[np.ndarray], **kwargs) -> np.ndarray: """ Beam search :param inputs: a list contain input ids or input masks or segment ids for 1 sample :return: 1 axis list, each elements is vocab id """ top_k = self.top_k output_ids = np.empty((1, 0), dtype=int) if self.start_id is None else np.array([[self.start_id]]) output_scores = np.zeros(1) for step in range(self.max_len): scores = self.next_token_scores(inputs, output_ids).numpy() if step == 0: inputs = [np.repeat(_input, top_k, axis=0) for _input in inputs] scores = output_scores.reshape((-1, 1)) + scores indices = scores.argpartition(-top_k, axis=None)[-top_k:] indices_1 = indices // scores.shape[1] indices_2 = (indices % scores.shape[1]).reshape((-1, 1)) output_ids = np.concatenate([output_ids[indices_1], indices_2], 1) output_scores = np.take_along_axis(scores, indices, axis=None) end_counts = (output_ids == self.end_id).sum(1) if output_ids.shape[1] >= self.min_len: best_one = output_scores.argmax() if end_counts[best_one] == self.min_ends: # 如果已经终止 return output_ids[best_one][:-1] else: # 否则,只保留未完成部分, 未完成部分还没有结束标志 flag = (end_counts < self.min_ends) # 标记未完成序列 if not flag.all(): # 如果有已完成的 inputs = [_input[flag] for _input in inputs] # 扔掉已完成序列 output_ids = output_ids[flag] # 扔掉已完成序列 output_scores = output_scores[flag] # 扔掉已完成序列 top_k = flag.sum() # top_k相应变化 return output_ids[output_scores.argmax()] def random_sample(self, inputs: List[np.ndarray], **kwargs) -> np.ndarray: """ Random sample :param inputs: a list contain input ids or input masks or segment ids for 1 sample :return: 2 axis list, each list contains all token ids of each sentence """ output_ids = np.empty((1, 0), dtype=int) if self.start_id is None else np.array([[self.start_id]]) results = [] for step in range(self.max_len): probas = self.next_token_prob(inputs, output_ids).numpy() p_indices = None k_indices = None probas /= probas.sum(axis=1, keepdims=True) # normalization if step == 0: probas =
np.repeat(probas, self.num_samples, axis=0)
numpy.repeat
# -*- coding: utf-8 -*- # MegEngine is Licensed under the Apache License, Version 2.0 (the "License") # # Copyright (c) 2014-2021 Megvii Inc. All rights reserved. # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. import itertools import numpy as np import megengine as mge import megengine.autodiff as ad import megengine.functional as F from megengine import Tensor from megengine.core._imperative_rt.core2 import ( _set_drop_flag, _set_swap_flag, get_option, set_option, ) from megengine.module import Linear, Module from megengine.optimizer import SGD batch_size = 64 data_shape = (batch_size, 2) label_shape = (batch_size,) def minibatch_generator(): while True: inp_data = np.zeros((batch_size, 2)) label = np.zeros(batch_size, dtype=np.int32) for i in range(batch_size): # [x0, x1], sampled from U[-1, 1] inp_data[i, :] = np.random.rand(2) * 2 - 1 label[i] = 0 if np.prod(inp_data[i]) < 0 else 1 yield inp_data.astype(np.float32), label.astype(np.int32) def calculate_precision(data: np.ndarray, pred: np.ndarray) -> float: """ Calculate precision for given data and prediction. :type data: [[x, y], ...] :param data: Input data :type pred: [[x_pred, y_pred], ...] :param pred: Network output data """ correct = 0 assert len(data) == len(pred) for inp_data, pred_output in zip(data, pred): label = 0 if np.prod(inp_data) < 0 else 1 pred_label =
np.argmax(pred_output)
numpy.argmax
import numpy ''' compute angle (in degrees) for p0p1p2 corner Inputs: p0,p1,p2 - points in the form of [x,y] ''' def calc_angle(p0, p1, p2): v0 = numpy.array(p0) -
numpy.array(p1)
numpy.array
#!/usr/bin/env python """ Portierung der Matlab-Skripts zu Python-Funktionen Matlab-Code Prof. Dr. <NAME>, <EMAIL> Portierung zu Python 8/2017 <NAME>, <EMAIL> Teil des Praktikums zur Vorlesung Quellen- und Kanalcodierung """ import numpy as np, matplotlib.pyplot as plt from ipywidgets import interact import ipywidgets as widgets def my_range(start, end, step): """ range for a loop with decimal incrementation stepsize step in range of [start, end] """ while start <= end: yield start start += step def reconprk_old(): """ Version ohne ipython-Widget """ T = 1 # T ist die Zeitkonstante der raised cosine function T_s = 0.5 * T # für alpha=0.5 beträgt die Bandbreite zwar nur 1.5/T, es wird aber trotzdem mit T_s=0.5T (über-)abgetastet. alpha = 0.499 # Roll-Off Faktor amp_si = (1 + alpha) / T * T_s # Amplitudenfaktor =2f_g*T_s t = np.linspace(-4, 4, 81) # Betrachteter Ausschnitt des Signals x = np.sinc(t / T) *
np.cos(np.pi * alpha * t / T)
numpy.cos
""" Functions that used in data preprocessing. """ import torch import numpy as np from tqdm import tqdm from collections import Counter from .dict_utils import counter2ordered_dict from common.constants import NLP, SPM from allennlp.modules.elmo import batch_to_ids def text2tokens(sentence): """ Transform text to tokens list. :param sentence: input text :return: list of token texts """ doc = NLP(sentence) return [token.text for token in doc] def get_token_char_level_spans(text, tokens): """ Get tokens' char-level [) spans in text. :param text: input text :param tokens: list of token texts :return: list of tokens' char-level [) spans in text, each span is a tuple """ current = 0 spans = [] for token in tokens: current = text.find(token, current) if current < 0: print("Token {} cannot be found".format(token)) raise Exception() spans.append((current, current + len(token))) current += len(token) return spans def spacydoc2tokens(doc): """ Transform spaCy doc to tokens list. :param doc: spaCy doc :return: list of token texts """ return [token.text for token in doc] def word2wid(word, word2id_dict, OOV="<oov>"): """ Transform single word to word index. :param word: a word :param word2id_dict: a dict map words to indexes :param OOV: a token that represents Out-of-Vocabulary words :return: int index of the word """ for each in (word, word.lower(), word.capitalize(), word.upper()): if each in word2id_dict: return word2id_dict[each] return word2id_dict[OOV] def char2cid(char, char2id_dict, OOV="<oov>"): """ Transform single character to character index. :param char: a character :param char2id_dict: a dict map characters to indexes :param OOV: a token that represents Out-of-Vocabulary characters :return: int index of the character """ if char in char2id_dict: return char2id_dict[char] return char2id_dict[OOV] def spacydoc2wids(spacy_doc, word2id_dict, sent_length, PAD="<pad>", OOV="<oov>"): """ Transform spaCy doc to padded word indexes list. :param spacy_doc: a spaCy doc :param word2id_dict: a dict map words to indexes :param sent_length: maximum length (number of words) of input text :param PAD: a token that represents pad :param OOV: a token that represents Out-of-Vocabulary words :return: list of word indexes """ word_ids = np.ones(sent_length, dtype=np.int32) * word2id_dict[PAD] words = [token.text for token in spacy_doc] for i, token in enumerate(words): if i == sent_length: break word_ids[i] = word2wid(token, word2id_dict, OOV) return word_ids def spacydoc2cids(spacy_doc, char2id_dict, sent_length, word_length, PAD="<pad>", OOV="<oov>"): """ Transform spaCy doc to padded character indexes 2D list. :param spacy_doc: a spaCy doc :param char2id_dict: a dict map characters to indexes :param sent_length: maximum length (number of words) of input text :param word_length: maximum length (number of characters) of words :param PAD: a token that represents pad :param OOV: a token that represents Out-of-Vocabulary words :return: 2D list of character indexes """ char_ids = np.ones( [sent_length, word_length], dtype=np.int32) * char2id_dict[PAD] words = [token.text for token in spacy_doc] chars = [list(token) for token in words] for i, token in enumerate(chars): if i == sent_length: break for j, char in enumerate(token): if j == word_length: break char_ids[i, j] = char2cid(char, char2id_dict, OOV) return char_ids def spacydoc2tagids(spacy_doc, tag_type, tag2id_dict, sent_length, PAD="<pad>", OOV="<oov>"): """ Transform spaCy doc to padded tag indexes list. :param spacy_doc: a spaCy doc :param tag_type: type of tag, currently support "pos", "ner", "iob", "dep" :param tag2id_dict: a dict map words to tags :param sent_length: maximum length (number of words) of input text :param PAD: a token that represents pad :param OOV: a token that represents Out-of-Vocabulary words :return: list of tag indexes """ tag_ids = np.ones(sent_length, dtype=np.int32) * tag2id_dict[PAD] if tag_type == "pos": tags = [token.tag_ for token in spacy_doc] elif tag_type == "ner": tags = [token.ent_type_ for token in spacy_doc] elif tag_type == "iob": tags = [token.ent_iob_ for token in spacy_doc] elif tag_type == "dep": tags = [token.dep_ for token in spacy_doc] else: print("tag_type must be POS, NER, IOB or DEP.") for i, token in enumerate(tags): if i == sent_length: break tag_ids[i] = char2cid(token, tag2id_dict, OOV) return tag_ids def spacydoc2features(spacy_doc, feature_type, sent_length): """ Transform spaCy doc to padded tokens feature list. :param spacy_doc: a spaCy doc :param feature_type: type of features :param sent_length: maximum length (number of words) of input text :return: list of token feature values """ features_padded =
np.zeros([sent_length], dtype=np.float32)
numpy.zeros
#!/usr/bin/env python """ Convert a svg file into 2D triangle mesh. """ import argparse import logging import pymesh import numpy as np from numpy.linalg import norm import os.path from subprocess import check_call from time import time def parse_args(): parser = argparse.ArgumentParser(__doc__); parser.add_argument("--engine", help="Triangulation engine", choices=( "triangle_conforming_delaunay", "triangle_constrained_delaunay", "cgal_constrained_delaunay", "cgal_conforming_delaunay", "geogram_delaunay", "jigsaw_frontal_delaunay", "mmg_delaunay", "triwild"), default="triangle_conforming_delaunay"); parser.add_argument("--resolve-self-intersection", "-r", action="store_true"); parser.add_argument("--with-frame", '-f', action="store_true"); parser.add_argument("--with-cell-label", "-l", action="store_true"); parser.add_argument("--with-cleanup", "-c", action="store_true"); parser.add_argument("--with-triangulation", "-t", action="store_true"); parser.add_argument("--stage", type=int, default=1); parser.add_argument("--epsilon", type=float, default=1e-3); parser.add_argument("--log", type=str, help="Logging level", choices=["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"], default="INFO"); parser.add_argument("--with-features", '-F', action="store_true", help="TriWild specific option to preserve features"); parser.add_argument("input_svg"); parser.add_argument("output_mesh"); return parser.parse_args(); def get_logger(level): numeric_level = getattr(logging, level, None); if not isinstance(numeric_level, int): raise ValueError('Invalid log level: {}'.format(level)); logging.basicConfig(level=numeric_level); return logging.getLogger("PyMesh.Triangulation"); def drop_zero_dim(wires): # Trim zero dimension. if wires.dim == 3: vertices = wires.vertices; assert(np.all(vertices[:,2] == 0)); vertices = vertices[:, [0,1]]; wires.load(vertices, wires.edges); return wires; def cleanup(wires, logger): if wires.num_vertices == 0: return wires; start_time = time(); tol = 1e-6; vertices, edges, __ = pymesh.remove_duplicated_vertices_raw( wires.vertices, wires.edges, tol); # Remove duplicated edges. ordered_edges = np.sort(edges, axis=1); __, unique_edge_ids, __ = pymesh.unique_rows(ordered_edges); edges = edges[unique_edge_ids, :]; wires.load(vertices, edges); # Remove topologically degenerate edges. is_not_topologically_degenerate = edges[:,0] != edges[:,1]; if not np.all(is_not_topologically_degenerate): wires.filter_edges(is_not_topologically_degenerate); finish_time = time(); t = finish_time - start_time; logger.info("Cleanup running time: {}".format(t)); return wires; def add_frame(wires): if wires.num_vertices == 0: return wires; vertices = wires.vertices; edges = wires.edges; bbox_min = np.amin(vertices, axis=0); bbox_max = np.amax(vertices, axis=0); bbox_center = 0.5 * (bbox_min + bbox_max); diag_len = norm(bbox_max - bbox_min); offset = np.ones(2) * diag_len / 20; bbox_min -= offset; bbox_max += offset; frame_vertices = np.array([ [bbox_min[0], bbox_min[1]], [bbox_max[0], bbox_min[1]], [bbox_max[0], bbox_max[1]], [bbox_min[0], bbox_max[1]], ]); frame_edges = np.array([ [0, 1], [1, 2], [2, 3], [3, 0], ]) + wires.num_vertices; vertices = np.vstack([vertices, frame_vertices]); edges = np.vstack([edges, frame_edges]); wires.load(vertices, edges); return wires; def resolve_self_intersection(wires, logger): if wires.num_vertices == 0: return wires; bbox_min, bbox_max = wires.bbox; tol = norm(bbox_max - bbox_min) / 1000; start_time = time(); vertices, edges = pymesh.snap_rounding(wires.vertices, wires.edges, tol); finish_time = time(); t = finish_time - start_time; logger.info("Snap rounding running time: {}".format(t)); wires.load(vertices, edges); return wires; def triangulate(wires, engine, stage, eps, logger, wire_file, json_file): if wires.num_vertices == 0: return pymesh.form_mesh(np.zeros((0, 2)), np.zeros((0,3))); basename = os.path.splitext(wire_file)[0]; if engine == "triwild": out_mesh = "{}_linear.msh".format(basename); log_file = "{}_triwild.log".format(basename); if json_file is not None: command = "TriWild --mute-log --feature-envelope-r {} --stage {} --log-file {} --feature-input {} --output-linear-mesh --skip-eps --input {} --output {}".format( eps, stage, log_file, json_file, wire_file, basename); else: command = "TriWild --mute-log --feature-envelope-r {} --stage {} --log-file {} --output-linear-mesh --skip-eps --input {} --output {}".format( eps, stage, log_file, wire_file, basename); print(command); start_time = time(); check_call(command.split()); finish_time = time(); t = finish_time - start_time; mesh = pymesh.load_mesh(out_mesh, drop_zero_dim=True); else: mesh, t = pymesh.triangulate_beta(wires.vertices, wires.edges, engine=engine, with_timing=True); logger.info("Triangulation running time: {}".format(t)); return mesh; def compute_cell_labels(wires, mesh, logger): start_time = time(); arrangement = pymesh.Arrangement2(); arrangement.points = wires.vertices; arrangement.segments = wires.edges; arrangement.run(); mesh.add_attribute("face_centroid"); centroids = mesh.get_face_attribute("face_centroid"); r = arrangement.query(centroids); finish_time = time(); t = finish_time - start_time; logger.info("Arrangement running time: {}".format(t)); cell_type =
np.array([item[0] for item in r])
numpy.array
import pickle from pathlib import Path from typing import Tuple, Union import click import numpy import rich from molesp.cli._cli import compute_surface from molesp.models import ESPMolecule, Surface from nagl.utilities.toolkits import capture_toolkit_warnings from openff.recharge.charges.bcc import BCCCollection, BCCGenerator from openff.recharge.charges.library import ( LibraryChargeCollection, LibraryChargeGenerator, LibraryChargeParameter, ) from openff.recharge.charges.qc import QCChargeGenerator, QCChargeSettings from openff.recharge.charges.vsite import VirtualSiteCollection, VirtualSiteGenerator from openff.recharge.conformers import ConformerGenerator, ConformerSettings from openff.recharge.esp import ESPSettings from openff.recharge.esp.psi4 import Psi4ESPGenerator from openff.recharge.grids import MSKGridSettings from openff.recharge.utilities.geometry import compute_inverse_distance_matrix from openff.recharge.utilities.toolkits import VdWRadiiType, compute_vdw_radii from openff.toolkit.topology import Molecule from openff.units import unit from openff.utilities import temporary_cd from openmm import unit as openmm_unit from pydantic import parse_file_as _CACHED_CHARGES = {} def compute_base_charge( molecule: Molecule, conformer_settings: ConformerSettings, charge_settings: QCChargeSettings, ): tagged_smiles = molecule.to_smiles(mapped=True) if tagged_smiles in _CACHED_CHARGES: return _CACHED_CHARGES[tagged_smiles] conformers = ConformerGenerator.generate(molecule, conformer_settings) charges = QCChargeGenerator.generate(molecule, conformers, charge_settings) charge_collection = LibraryChargeCollection( parameters=[ LibraryChargeParameter( smiles=tagged_smiles, value=[float(v) for v in charges.flatten().tolist()], ) ] ) _CACHED_CHARGES[tagged_smiles] = charge_collection return charge_collection def compute_mm_esp( molecule: Molecule, conformer: unit.Quantity, charge_collection: Union[ Tuple[ConformerSettings, QCChargeSettings], LibraryChargeCollection ], bcc_collection: BCCCollection, vsite_collection: VirtualSiteCollection, grid: unit.Quantity, ): console = rich.get_console() console.print("applying MM charges") if not isinstance(charge_collection, LibraryChargeCollection): conformer_settings, charge_settings = charge_collection charge_collection = compute_base_charge( molecule, conformer_settings, charge_settings ) atom_charges = LibraryChargeGenerator.generate(molecule, charge_collection) if len(bcc_collection.parameters) > 0: atom_charges += BCCGenerator.generate(molecule, bcc_collection) if len(vsite_collection.parameters) > 0: vsite_charges = VirtualSiteGenerator.generate_charge_increments( molecule, vsite_collection ) n_vsites = len(vsite_charges) - molecule.n_atoms full_charges = ( numpy.vstack([atom_charges, numpy.zeros((n_vsites, 1))]) + vsite_charges ) else: full_charges = atom_charges if len(vsite_collection.parameters) > 0: vsite_coordinates = VirtualSiteGenerator.generate_positions( molecule, vsite_collection, conformer ) full_coordinates =
numpy.vstack([conformer, vsite_coordinates])
numpy.vstack
import pdb import numpy as np import scipy as sp import scipy.optimize as op import util import matplotlib.pyplot as plt import time # Laplace Inference ----------------------------------------------------------- def negLogPosteriorUnNorm(xbar, ybar, C_big, d_big, K_bigInv, xdim, ydim): xbar = np.ndarray.flatten(np.asarray(xbar)) ybar = np.ndarray.flatten(np.asarray(ybar)) T = int(len(d_big)/ydim) C_big = np.asarray(C_big) d_big = np.asarray(d_big) K_bigInv = np.asarray(K_bigInv) A = np.dot(C_big.T, xbar) + d_big Aexp = np.exp(A) L1 = np.dot(Aexp, np.ones(ydim*T)) L2 = -
np.dot(ybar, A.T)
numpy.dot
import numpy as np import matplotlib.pyplot as plt from matplotlib.image import imread from mpl_toolkits.mplot3d import Axes3D # 与门 权重偏置 AND_W = np.array([0.5, 0.5]) AND_B = -0.7 # 与非门 权重偏置 NAND_W = np.array([-0.5, -0.5]) NAND_B = 0.7 # 或门 权重偏置 OR_W = np.array([0.5, 0.5]) OR_B = -0.3 # 感知机 def Perceptron(x): return np.array(x > 0, dtype=np.int) # sigmoid def Sigmoid(x): return 1 / (1 + np.exp(-x)) # Relu def Relu(x): return np.maximum(0, x) # 这个激活函数在"分类"中,比较常用 def Softmax(a): c=np.max(a) exp_a = np.exp(a-c) y = exp_a / np.sum(exp_a) return y # 异或门 def XOR(x1, x2): local_x1 = Perceptron(np.sum(np.array([x1, x2])*NAND_W)+NAND_B) local_x2 = Perceptron(np.sum(np.array([x1, x2])*OR_W)+OR_B) return Sigmoid(np.sum(np.array([local_x1, local_x2])*AND_W)+AND_B) def test1(): print(XOR(0, 0)) print(XOR(1, 0)) print(XOR(0, 1)) print(XOR(1, 1)) def test2(): x = np.arange(-10, 10, 0.1) y1 = Perceptron(x) y2 = Sigmoid(x) plt.plot(x, x,linestyle='--',label="x") plt.plot(x, y1,label="Perceptron") plt.plot(x, y2,label="Sigmoid") plt.xlabel("X") plt.ylabel("Y") plt.ylim(-0.01, 1.01) # 指定y轴的范围 plt.legend() plt.show() #第三章 def identity_function(x): return x def test3(): # 输入层 X = np.array([1.0, 0.5])#输入层 W1 = np.array([[0.1, 0.3, 0.5], [0.2, 0.4, 0.6]])#输入层权重 B1 = np.array([0.1, 0.2, 0.3])#输入层偏置 A1 = np.dot(X, W1) + B1 Z1 = Sigmoid(A1) #print(A1) # [0.3, 0.7, 1.1] #print(Z1) # [0.57444252, 0.66818777, 0.75026011] # 隐含层 W2 = np.array([[0.1, 0.4], [0.2, 0.5], [0.3, 0.6]]) B2 = np.array([0.1, 0.2]) A2 = np.dot(Z1, W2) + B2 Z2 = Sigmoid(A2) # 输出层 W3 = np.array([[0.1, 0.3], [0.2, 0.4]]) B3 = np.array([0.1, 0.2]) A3 = np.dot(Z2, W3) + B3 Y = identity_function(A3) # 或者Y = A3 print(Y) # 把test3规整下: # 网络权重和偏置 def init_network(): network = {} network['W1'] = np.array([[0.1, 0.3, 0.5], [0.2, 0.4, 0.6]]) network['b1'] = np.array([0.1, 0.2, 0.3]) network['W2'] = np.array([[0.1, 0.4], [0.2, 0.5], [0.3, 0.6]]) network['b2'] = np.array([0.1, 0.2]) network['W3'] = np.array([[0.1, 0.3], [0.2, 0.4]]) network['b3'] = np.array([0.1, 0.2]) return network # 前向运算 def forward(network, x): W1, W2, W3 = network['W1'], network['W2'], network['W3'] b1, b2, b3 = network['b1'], network['b2'], network['b3'] a1 = np.dot(x, W1) + b1 z1 = Sigmoid(a1) a2 = np.dot(z1, W2) + b2 z2 = Sigmoid(a2) a3 = np.dot(z2, W3) + b3 y = identity_function(a3) return y # 测试数据 def test4(): network = init_network() x = np.array([1.0, 0.5]) y = forward(network, x) print(y) # [ 0.31682708 0.69627909] def test5(): a=np.array([0.3,2.9,4.0]) y=Softmax(a) print(y) def APerceptron(w,b,x): y=np.sum(x*w)+b # 激活函数 if(y>=0): return 1 else: return 0 # 第一层 XOR_W1_1 = np.array([0.5, 0.5]) XOR_B1_1 = -0.7 XOR_W1_2= np.array([-0.5, -0.5]) XOR_B1_2 = 0.3 # 第二层 XOR_W2 =
np.array([-0.5,-0.5])
numpy.array
import numpy as np import modern_robotics as mr from modern_robotics.core import Adjoint, FKinBody, JacobianBody, MatrixLog6, se3ToVec, TransInv """ Code to calculate the feedforward control for the youBot """ def FeedbackControl(X, Xd, Xd_next, Kp, Ki, dt, curr_config, Xerr_integral): """ Calculates the kinematic task-space feedforward and feedback control law Makes use of the equation: V(t) = [Adx^-1xd]Vd(t) + KpXerr(t) + Ki*integral(0:t)(Xerr(t))dt Args: X : Current actual end-effector configuration Tse Xd : Current end-effector reference configuration Tse,d Xd_next : End-effector reference configuration at the next timestep in the reference trajectory Xd at Δt later Kp : The feedback proportional gain Ki : The feedback integral gain dt : Timestep Δt between reference trajectory configurations curr_config : The current configuration of the robot Xerr_integral : Initial integral of the error (zeros) Returns: V : End-effector twist expressed in end-effector frame {e} Controls : The commanded wheel and arm joint speeds (m/s) Xerr : Error in X """ # initialize kinematics variables l = 0.47/2 # forward-backward distance between the wheels (m) w = 0.3/2 # side-to-side distance between wheels (m) r = 0.0475 # radius of each wheel (m) # the fixed offset from the chassis frame {b} to the base frame of the arm {0} Tb0 = np.array([[1, 0, 0, 0.1662], [0, 1, 0, 0], [0, 0, 1, 0.0026], [0, 0, 0, 1]]) # end-effector frame {e} relative to the arm base frame {0} M0e = np.array([[1, 0, 0, 0.033], [0, 1, 0, 0], [0, 0, 1, 0.6546], [0, 0, 0, 1]]) # the screw axes for the five joints in the end-effector frame {e} Blist = np.array([[0, 0, 1, 0, 0.033, 0], [0, -1, 0, -0.5076, 0, 0], [0, -1, 0, -0.3526, 0, 0], [0, -1, 0, -0.2176, 0, 0], [0, 0, 1, 0, 0, 0]]).T # find current joint angles curr_joint_ang = curr_config[3:8] # transformation from {0} to {e} T0e = FKinBody(M0e, Blist, curr_joint_ang) # transformation from {e} to {b} Teb = TransInv(T0e)@TransInv(Tb0) # compute the reference twist Vd Log = MatrixLog6(TransInv(Xd)@Xd_next) Vel = se3ToVec(Log) Vd = 1/dt * Vel # print(f"Vd: {Vd}") # compute the Ad(x^-1xd) matrix Adx_invxd = Adjoint(TransInv(X)@Xd) Adx_invxdVd = Adx_invxd@Vd # 6x6 @ 6x1 = 6x1 # print(f"Adx_invxdVd: {Adx_invxdVd}") # compute X error Xerr = se3ToVec(MatrixLog6(TransInv(X)@Xd)) # print(f"Xerr: {Xerr}") # compute the integral of the error Xerr_integral += Xerr * dt # print(f"Integral of error: {Xerr_integral}") # compute V V = Adx_invxdVd + Kp@Xerr + Ki@Xerr_integral # print(f"V: {V}") # F6 matrix F6 = r/4 * np.array([[ 0, 0, 0, 0], [ 0, 0, 0, 0], [-1/(l+w), 1/(l+w), 1/(l+w), -1/(l+w)], [ 1, 1, 1, 1], [ -1, 1, -1, 1], [ 0, 0, 0, 0]]) # arm jacobian J = JacobianBody(Blist, curr_joint_ang) # # joint limits # J_limit = J.T # if curr_joint_ang[0] < -2.95 or curr_joint_ang[0] > 2.95: # J_limit[0] = J_limit[0]*0 # if curr_joint_ang[1] < -1 or curr_joint_ang[1] > 1: # J_limit[1] = J_limit[1] * 0 # if curr_joint_ang[2] < -2 or curr_joint_ang[2] > 2: # J_limit[2] = J_limit[2] * 0 # if curr_joint_ang[3] < -2 or curr_joint_ang[3] > 2: # J_limit[3] = J_limit[3] * 0 # if curr_joint_ang[4] < -2.92 or curr_joint_ang[4] > 2.92: # J_limit[4] = J_limit[4] * 0 # J = J_limit.T # body jacobian Jb = Adjoint(Teb) @ F6 Je = np.hstack((Jb, J)) ### make joint column zero depending on config to place joint limits # print(f"Je: \n{np.around(Je, decimals=3)}") # calculate the commanded wheel and arm joint speeds: u and thetadot # using the Moore-Penrose pseudoinverse # Je_pinv = [email protected]([email protected]) Je_pinv = np.linalg.pinv(Je, 1e-3) # Je_pinv = np.linalg.pinv(Je) controls = Je_pinv@V # print(f"Controls: {np.around(controls, decimals=1)}") return V, controls, Xerr if __name__ == "__main__": """ Main function to call FeedbackControl """ Xd = np.array([[ 0, 0, 1, 0.5], [ 0, 1, 0, 0], [-1, 0, 0, 0.5], [ 0, 0, 0, 1]]) Xd_next = np.array([[ 0, 0, 1, 0.6], [ 0, 1, 0, 0], [-1, 0, 0, 0.3], [ 0, 0, 0, 1]]) X = np.array([[ 0.170, 0, 0.985, 0.387], [ 0, 1, 0, 0], [-0.985, 0, 0.170, 0.570], [ 0, 0, 0, 1]]) # Kp = np.zeros((6,6)) Kp =
np.identity(6)
numpy.identity
import sys import numpy as np from astropy import units as u from astropy.constants import G from astropy.table import QTable from scipy.integrate import solve_ivp G = 6.7e-11 # Universal gravitational constant, SI class Bodies: def __init__(self): self.posns = np.zeros((0,3)) self.vs = np.zeros((0,3)) self.ms = np.zeros((0)) self.rs = np.zeros((0)) self.sun = None self.planets = [] self.nBodies = 0 self.time = 0 #---------------------------------------- # Some general utility methods def is_iterable(self, x): # a surprising omission from standard Python? try: iterator = iter(x) except TypeError: return False else: return True def fix_units(self, val, unit): "Convert to SI if necessary and return value as a Python scalar" if isinstance(val, u.quantity.Quantity): val = val.to(unit).value return val def veclen(self, vector): # beware, units are lost and this just returns a number return np.linalg.norm(vector) def vecperp(self, vector): "rotate 90 deg ccw, return normalised vector in x,y plane" v = np.array([-vector[1], vector[0], 0]) return v/self.veclen(v) def get_time(self): "Cumulative integration time (s)" return self.time*u.s def CoM_velocity(self): "Reruns velocity of center of mass" return np.sum(self.vs * self.ms[:, np.newaxis], axis=0) / np.sum(self.ms) def fix_CoM(self): "Ensure CoM velocity is zero" self.vs -= self.CoM_velocity() #----------------------------------------------------- # Several methods to add bodies to the collection def add_sun(self, M, R=None): """ For 1-body problems, a large mass fixed at the origin M = mass (kg or Quantity) R = radius (m or Quantity); only for collision detection """ M = self.fix_units(M, u.kg) R = self.fix_units(R, u.m) self.sun = self.ms.size # index to this new body self.posns = np.concatenate((self.posns, np.zeros((1,3)))) self.vs = np.concatenate((self.vs, np.zeros((1,3)))) self.ms = np.concatenate((self.ms, [M,])) self.rs = np.concatenate((self.rs, [R,])) self.nBodies = self.ms.size def add_bodies(self, pos, v, m, R): """ Can be one body or many single: need pos and v to be 3-item iterables many: pos and p have shape (N,3), m and R are 1-D array-like """ if not self.is_iterable(m): # just have a single body # make sure the 3-vectors are numpy arrays # (this does nothing if they are already arrays) pos = np.array(pos) v = np.array(v) # get everything to a suitable shape for concatenation pos = pos[np.newaxis,:] # converts shape (3,) to (0,3) v = v[np.newaxis,:] m = [m,] R = [R,] self.posns = np.concatenate((self.posns, pos)) self.vs = np.concatenate((self.vs, v)) self.ms = np.concatenate((self.ms, [m,])) self.rs = np.concatenate((self.rs, [R,])) self.nBodies = self.ms.size def add_planet_at_pericenter(self, a, e, i=0, phi=0, m=None, R=None): """ For setting up a 1-body Keplerian orbit. a = semimajor axis (m or Quantity) e = eccentricity i = inclination (deg) phi = orientation of perihelion (deg ccw from x-axis) m = mass (kg or Quantity); only req if an N-body calc will be run R = radius (m or Quantity); only for collision detection """ if self.sun is None: display("Error: Please run add_sun() first") return else: M_sun = self.ms[self.sun] a = self.fix_units(a, u.m) m = self.fix_units(m, u.kg) R = self.fix_units(R, u.m) P = np.sqrt(4 * np.pi**2 * a**3/(G * M_sun)) planet = {} planet['P'] = P planet['a'] = a planet['e'] = e planet['i'] = i self.planets.append(planet) # set starting position and velocity, at perihelion r_dir = np.array([np.cos(phi), np.sin(phi), np.sin(i)]) rhat = r_dir/self.veclen(r_dir) r_vec = a*(1-e) * rhat vhat = self.vecperp(rhat) v_vec = np.sqrt(G*M_sun/a*(1+e)/(1-e)) * vhat self.posns = np.concatenate((self.posns, r_vec[np.newaxis,:])) self.vs = np.concatenate((self.vs, v_vec[np.newaxis,:])) self.ms = np.concatenate((self.ms, [m,])) self.rs = np.concatenate((self.rs, [R,])) self.nBodies = self.ms.size def add_binary(self, masses, a, e, Rs=None): """ For setting up a 1-body Keplerian orbit. masses = 2-tuple (kg or Quantity) a = semimajor axis (m or Quantity) e = eccentricity m = mass (kg or Quantity); only req if an N-body calc will be run Rs = radii (m or Quantity); only for collision detection """ raise NotImplementedError def add_random(self, n, L=50*u.AU, power=1/3, masses=1*u.M_sun, vs=50*u.km/u.s, radii=5*u.R_earth): """ Add n bodies at random directions within a sphere of radius L (m) Density will fall off as `power` from the origin Masses (kg) and radii (m) can each be: - a list/array which will be converted to length n as needed - a number giving the mid-point of a distribution """ def random_direction(): ra = 2*np.pi*np.random.rand(n) dec = np.arccos(2*np.random.rand(n) - 1) - np.pi/2 return ra, dec def random_unit_vector(): theta, phi = random_direction() x = np.cos(phi) * np.sin(theta) y = np.cos(phi) * np.cos(theta) z = np.sin(phi) return np.vstack((x, y, z)).transpose() def create_distribution(x, sd, shape=None): if self.is_iterable(x): # list, may need to adjust length if len(x) < n: reps = n//len(x) + 1 x = np.tile(x, reps) x = x[:n] else: # x is a midpoint, create a Gaussian around it # but don't let the tail go negative! if shape: x = np.abs(np.random.standard_normal(shape)*sd + 1) * x else: x = np.abs(np.random.randn(n)*sd + 1) * x return x L = self.fix_units(L, u.m) masses = self.fix_units(masses, u.kg) vs = self.fix_units(vs, u.m/u.s) radii = self.fix_units(radii, u.m) distances = L * np.random.rand(n)**power posns = random_unit_vector() * distances[:,np.newaxis] masses = create_distribution(masses, 0.2) vs = create_distribution(vs, 0.3, shape=(n,3)) radii = create_distribution(radii, 0.1) self.posns = np.concatenate((self.posns, posns)) self.vs = np.concatenate((self.vs, vs)) self.ms = np.concatenate((self.ms, masses)) self.rs = np.concatenate((self.rs, radii)) self.nBodies = self.ms.size self.fix_CoM() #------------------------------------------------------------------- # Methods to integrate forward in time def integrate_1body(self, t_end=None, nOrbits=1, dt=None, points_per_orbit=200, inx=-1, resTbl=True): """ Run a 1-body (Keplerian) orbit. nOrbits = number of full periods dt = time step (s or Quantity) points_per_orbit: used to calculate dt if necessary inx = index into self.planets to get orbit data (defaults to last) """ if self.sun is None: display("Error: Please run add_sun() first") return else: M_sun = self.ms[self.sun] # Quantities are accepted as parameters but the integrator needs dimensionless values t_end = self.fix_units(t_end, u.s) dt = self.fix_units(dt, u.s) # get period and calculate (if necessary) time step P = self.planets[inx]['P'] if dt is None: dt = P/points_per_orbit # seconds if t_end is None: t_end = nOrbits*P # seconds # set the total time range, and the intermediate time points t_span = (0, t_end) # (start, end) 2-tuple t_vals =
np.arange(0, t_end, dt)
numpy.arange
# *************************************************************** # Copyright (c) 2020 Jittor. All Rights Reserved. # Authors: # <NAME> <<EMAIL>> # <NAME> <<EMAIL>> # <NAME> <<EMAIL>>. # # This file is subject to the terms and conditions defined in # file 'LICENSE.txt', which is part of this source code package. # *************************************************************** import jittor as jt import numpy as np import unittest try: import autograd.numpy as anp from autograd import jacobian has_autograd = True except: has_autograd = False @unittest.skipIf(not has_autograd, "No autograd found.") class TestCodeOp(unittest.TestCase): def test_svd(self): def check_svd(a): u,s,v = anp.linalg.svd(a, full_matrices=0) return u,s,v def check_u(a): u,s,v = anp.linalg.svd(a, full_matrices=0) return u def check_s(a): u,s,v = anp.linalg.svd(a, full_matrices=0) return s def check_v(a): u,s,v = anp.linalg.svd(a, full_matrices=0) return v for i in range(50): #not for full-matrices! a = jt.random((2,2,5,4)) c_a = anp.array(a.data) u,s,v = jt.linalg.svd(a) tu,ts,tv = check_svd(c_a) assert np.allclose(tu,u.data) assert np.allclose(ts,s.data) assert np.allclose(tv,v.data) ju = jt.grad(u,a) js = jt.grad(s,a) jv = jt.grad(v,a) grad_u = jacobian(check_u) gu = grad_u(c_a) gu = np.sum(gu, 4) gu = np.sum(gu, 4) gu = np.sum(gu, 2) gu = np.sum(gu, 2) grad_s = jacobian(check_s) gs = grad_s(c_a) gs = np.sum(gs, 4) gs = np.sum(gs, 2) gs = np.sum(gs, 2) grad_v = jacobian(check_v) gv = grad_v(c_a) gv = np.sum(gv, 4) gv = np.sum(gv, 4) gv = np.sum(gv, 2) gv = np.sum(gv, 2) try: assert np.allclose(ju.data,gu,atol=1e-5) except AssertionError: print(ju.data) print(gu) try: assert np.allclose(js.data,gs,atol=1e-5) except AssertionError: print(js.data) print(gs) try: assert np.allclose(jv.data,gv,atol=1e-5) except AssertionError: print(jv.data) print(gv) def test_eigh(self): def check_eigh(a,UPLO='L'): w, v = anp.linalg.eigh(a,UPLO) return w, v def check_w(a,UPLO='L'): w, v = anp.linalg.eigh(a,UPLO) return w def check_v(a,UPLO='L'): w, v = anp.linalg.eigh(a,UPLO) return v for i in range(50): a = jt.random((2,2,3,3)) c_a = a.data w, v = jt.linalg.eigh(a) tw, tv = check_eigh(c_a) assert np.allclose(w.data,tw) assert np.allclose(v.data,tv) jw = jt.grad(w, a) jv = jt.grad(v, a) check_gw = jacobian(check_w) check_gv = jacobian(check_v) gw = check_gw(c_a) gw = np.sum(gw,4) gw = np.sum(gw,2) gw = np.sum(gw,2) assert np.allclose(gw,jw.data,rtol = 1,atol = 5e-8) gv = check_gv(c_a) gv = np.sum(gv,4) gv = np.sum(gv,4) gv = np.sum(gv,2) gv = np.sum(gv,2) assert np.allclose(gv,jv.data,rtol = 1,atol = 5e-8) def test_pinv(self): def check_pinv(a): w = anp.linalg.pinv(a) return w for i in range(50): x = jt.random((2,2,4,4)) c_a = x.data mx = jt.linalg.pinv(x) tx = check_pinv(c_a) np.allclose(mx.data,tx) jx = jt.grad(mx,x) check_grad = jacobian(check_pinv) gx = check_grad(c_a) np.allclose(gx,jx.data) def test_inv(self): def check_inv(a): w = anp.linalg.inv(a) return w for i in range(50): tn = np.random.randn(4,4).astype('float32')*5 while np.allclose(np.linalg.det(tn),0): tn = np.random.randn((4,4)).astype('float32')*5 x = jt.array(tn) x = x.reindex([2,2,x.shape[0],x.shape[1]],["i2","i3"]) c_a = x.data mx = jt.linalg.inv(x) tx = check_inv(c_a) np.allclose(mx.data,tx) jx = jt.grad(mx,x) check_grad = jacobian(check_inv) gx = check_grad(c_a) np.allclose(gx,jx.data) def test_slogdet(self): def check_ans(a): s, w = anp.linalg.slogdet(a) return s, w def check_slogdet(a): s, w = anp.linalg.slogdet(a) return w for i in range(50): tn = np.random.randn(4,4).astype('float32')*10 while np.allclose(np.linalg.det(tn),0): tn = np.random.randn((4,4)).astype('float32')*10 x = jt.array(tn) x = x.reindex([2,2,x.shape[0],x.shape[1]],["i2","i3"]) s = list(x.shape) det_s = s[:-2] if len(det_s) == 0: det_s.append(1) sign, mx = jt.linalg.slogdet(x) ts, ta = check_ans(x.data) assert np.allclose(sign.data, ts) assert np.allclose(mx.data, ta) jx = jt.grad(mx,x) check_sgrad = jacobian(check_slogdet) gx = check_sgrad(x.data) gx = np.sum(gx,2) gx = np.sum(gx,2) assert
np.allclose(gx,jx.data)
numpy.allclose
import matplotlib.pyplot as plt from pandas import read_csv from sklearn.preprocessing import MinMaxScaler, StandardScaler import numpy as np from test_labels_loader import load_test_labels def minmax_rescale(probability): scaler = MinMaxScaler(feature_range=(0.000000001, 0.999999999)) return scaler.fit_transform(probability) def softmax_rescale(probability): norm_x = StandardScaler().fit_transform(probability) return 1.0 / (1.0 + np.exp(-norm_x)) def plot(clips, probs, labels, scale=None): x, y = [], [] for i, subject in enumerate(subjects): subject_idx = [] for j, s in enumerate(clips): if subject in s: subject_idx.append(j) subject_idx = np.array(subject_idx) subj_prob = probs[subject_idx] if scale == 'softmax': y.extend(softmax_rescale(np.expand_dims(subj_prob, axis=1))) elif scale == 'minmax': y.extend(minmax_rescale(np.expand_dims(subj_prob, axis=1))) else: y.extend(subj_prob) x.extend([i] * len(subject_idx)) x = np.array(x, dtype='float32') y =
np.array(y)
numpy.array
import numpy as np, copy, json, os from numpy import sqrt, dot, cross from numpy.linalg import norm from itertools import combinations from modules import functions as f np.set_printoptions(suppress=True) BQi = lambda x: [[x, 0, 0], [0, x, 0], [0, 0, x], [-x, 0, 0], [0, -x, 0], [0, 0, -x]] sst_dict = {0: 'H', 1: 'E', 2: 'L'} def st_or(xyz, bq, p): res = None xyz_tr = xyz - xyz[0] norm = xyz_tr[1]/np.linalg.norm(xyz_tr[1]) ortha = np.cross(bq[1], norm) a1 = f.dihedral(np.array([xyz_tr[1], bq[0], ortha, bq[1]])) if a1 == a1: xyz_r1 = f.rotate_dihedral(a1, ortha, bq[0], xyz_tr) a2 = f.dihedral(np.array([xyz_r1[2], bq[0], xyz_r1[1], bq[2]])) if a2 == a2: xyz_r2 = f.rotate_dihedral(a2, xyz_r1[1], bq[0], xyz_r1) q = trilaterate(xyz_r2, p) if q is not None: pts1 = np.vstack((xyz_r2, q[0])) pts1 = f.rotate_dihedral(-a2, pts1[1], bq[0], pts1) pts1 = f.rotate_dihedral(-a1, ortha, bq[0], pts1) + xyz[0] pts2 = np.vstack((xyz_r2, q[1])) pts2 = f.rotate_dihedral(-a2, pts2[1], bq[0], pts2) pts2 = f.rotate_dihedral(-a1, ortha, bq[0], pts2) + xyz[0] res = [pts1[-1], pts2[-1]] return res def trilaterate(pts, ds): temp1 = pts[1]-pts[0] e_x = temp1/norm(temp1) temp2 = pts[2]-pts[0] i = dot(e_x, temp2) temp3 = temp2 - i*e_x e_y = temp3/norm(temp3) e_z = cross(e_x,e_y) d = norm(pts[1]-pts[0]) j = dot(e_y,temp2) x = (ds[0]**2 - ds[1]**2 + d*d) / (2*d) y = (ds[0]**2 - ds[2]**2 - 2*i*x + i*i + j*j) / (2*j) temp4 = ds[0]**2 - x*x - y*y if temp4<0: #raise Exception("The three spheres do not intersect!"); ds[:2] *=1.01 temp1 = pts[1]-pts[0] e_x = temp1/norm(temp1) temp2 = pts[2]-pts[0] i = dot(e_x, temp2) temp3 = temp2 - i*e_x e_y = temp3/norm(temp3) e_z = cross(e_x,e_y) d = norm(pts[1]-pts[0]) j = dot(e_y,temp2) x = (ds[0]**2 - ds[1]**2 + d*d) / (2*d) y = (ds[0]**2 - ds[2]**2 - 2*i*x + i*i + j*j) / (2*j) temp4 = ds[0]**2 - x*x - y*y #if temp4<0: # raise Exception("The three spheres do not intersect!"); if temp4 >= 0: z = temp4**0.5 res = [[x, y, z], [x, y, -z]] else: res = None return res def check_side_of_plane(p, x): v1 = p[1] - p[0] v2 = p[2] - p[0] va = x - p[0] cp = np.cross(v1,v2) d = np.dot(cp, va) return d def convert_dm2xyz_48o(dm, dm_ca, xx): BQ = np.array([[0, 0, 0], [1, 0, 0], [1, 1, 0]]) dist = [] coords = [] for a in range(len(dm)): ind = np.argsort([abs(x-a) for x in range(len(dm))])[:4] ind_d = [i for i in list(range(len(dm))) if i not in ind] init_pts = [dm_ca[ix] for ix in ind] ypd = np.array([dm[a][ix] for ix in ind]) pos = [] for ip in range(len(init_pts)): p1, yp1 = init_pts[ip], ypd[ip] pr, ypr = np.delete(np.array(init_pts), ip, 0), np.delete(ypd, ip) p = st_or(pr, BQ, ypr) if p is not None: #d = [np.abs(yp1 - f.distance(p1, i)) for i in p] d = [np.abs(yp1 - f.distance(p1, i)) for i in p] #if abs(d[0] - d[1]) > 0.7: p = p[np.argsort(d)[0]].tolist() pos.append(p) if pos != []: pos = np.mean(np.array(pos),axis=0) coords.append(pos.tolist()) else: print('None') coords.append(None) return coords def convert_dm2xyz_48f(dm, x): BQ = np.array([[0, 0, 0], [1, 0, 0], [1, 1, 0]]) dist = [] init_pts1 = BQi(x) n = 0 for a in range(len(dm)-2): if a==0: ind = np.argsort(dm[a])[:4] ind_d =
np.argsort(dm[a])
numpy.argsort
# -*- coding: utf-8 -*- """ Created on Tue Nov 2 10:45:24 2021 @author: wangy79 Data association class consists of - data preprocess - timestamp & frame # interpolation - unit conversion - get direction - get lane info - object stitching - GNN: global nearest neighbor (online) - BM: bipartite matching (online) - JPDA: joint probablistic data association (online) - TSM: Time-space matching (offline) - data postprocess - iteratively remove and save valid tracks - output invalid (fragmented / wrong direction / overlapped) tracks - outlier removal - connect tracks - visualization - time-space diagrams for original data and DA'ed data - # invalid tracks removed - spacing distribution B&A """ import numpy as np import utils import pandas as pd import utils_vis as vis import matplotlib.pyplot as plt import utils_evaluation as ev import itertools import multiprocessing import torch class Data_Association(): def __init__(self, data_path, params = None): ''' params = {"method": "gnn", "start": 0, "end": 1000, "lanes": [] "plot_start": 0, # for plotting tracks in online methods "plot_end": 10, "preprocess": True } ''' self.params = params if params["preprocess"]: self.df = utils.preprocess_MC(data_path) else: self.df = utils.read_data(data_path) self.df = self.df[(self.df["Frame #"] >= params["start"]) & (self.df["Frame #"] <= params["end"])] # if len(params["lanes"]) > 0: # self.df = self.df[self.df["lane"].isin(params["lanes"])] self.original = self.df.copy() self.data = {} def dist_score(self, B, B_data, DIST_MEAS='maha', DIRECTION=True): ''' compute euclidean distance between two boxes B and B_data B: predicted bbox location ['bbr_x','bbr_y', 'fbr_x','fbr_y','fbl_x','fbl_y','bbl_x', 'bbl_y'] B_data: measurement ''' B = np.reshape(B,(-1,8)) B_data = np.reshape(B_data,(-1,8)) # check sign if DIRECTION==True: if (np.sign(B[0,[2]]-B[0,[0]])!=np.sign(B_data[0,[2]]-B_data[0,[0]])) : # if not the same x direction return 99 diff = B-B_data diff = diff[0] if DIST_MEAS == 'xy': # return np.linalg.norm(B-B_data,2) # RMSE mae_x = np.mean(np.abs(diff[[0,2,4,6]])) mae_y = np.mean(np.abs(diff[[1,3,5,7]])) return (mae_x + mae_y)/2 # weighted x,y displacement, penalize y more heavily elif DIST_MEAS == 'xyw': alpha = 0.2 mae_x = np.mean(np.abs(diff[[0,2,4,6]])) mae_y = np.mean(np.abs(diff[[1,3,5,7]])) # return alpha*np.linalg.norm(B[[0,2,4,6]]-B_data[[0,2,4,6]],2) + (1-alpha)*np.linalg.norm(B[[1,3,5,7]]-B_data[[1,3,5,7]],2) return alpha*mae_x + (1-alpha)*mae_y # mahalanobis distance elif DIST_MEAS == 'maha': alpha = (1/1)**2 beta = (1/0.27)**2 d2 = 0 for i in range(4): d2 += np.sqrt(alpha*diff[i]**2+beta*diff[2*i+1]**2) return d2/4 # euclidean distance elif DIST_MEAS == 'ed': d2 = 0 for i in range(4): d2 += np.sqrt(diff[i]**2+diff[2*i+1]**2) return d2/4 else: return def iou(self,a,b,DIRECTION=True,AREA=False): """ Description ----------- Calculates intersection over union for all sets of boxes in a and b Parameters ---------- a : tensor of size [8,3] bounding boxes in relative coords b : array of size [8,3] bounding boxes in relative coords ['bbr_x','bbr_y', 'fbr_x','fbr_y','fbl_x','fbl_y','bbl_x', 'bbl_y'] Returns ------- iou - float between [0,1] if a, b are valid boxes, -1 otherwise average iou for a and b """ a,b = np.reshape(a,(1,-1)), np.reshape(b,(1,-1)) # if has invalid measurements if np.isnan(sum(sum(a))) or np.isnan(sum(sum(b))): if AREA==True: return 0,-1,-1 else: return 0 ax = np.sort(a[0,[0,2,4,6]]) ay = np.sort(a[0,[1,3,5,7]]) bx = np.sort(b[0,[0,2,4,6]]) by = np.sort(b[0,[1,3,5,7]]) area_a = (ax[3]-ax[0]) * (ay[3]-ay[0]) area_b = (bx[3]-bx[0]) * (by[3]-by[0]) if DIRECTION==True: if (np.sign(a[0,[2]]-a[0,[0]])!=np.sign(b[0,[2]]-b[0,[0]])):# if not the same x / y direction if AREA==True: return -1,area_a,area_b else: return -1 minx = max(ax[0], bx[0]) # left maxx = min(ax[2], bx[2]) miny = max(ay[1], by[1]) maxy = min(ay[3], by[3]) intersection = max(0, maxx-minx) * max(0,maxy-miny) # union = area_a + area_b - intersection + 1e-06 union = min(area_a,area_b) iou = intersection/union if AREA==True: return iou,area_a,area_b else: return iou def predict_tracks_df(self, tracks): ''' tracks: [dictionary]. Key: car_id, value: df if a track has only 1 frame, assume 25m/s otherwise do constant-velocity one-step-forward prediction Return: x: last predicted position: array of n_car x 8 tracks: updated dictionary ''' x = [] pts = ['bbr_x','bbr_y','fbr_x','fbr_y','fbl_x','fbl_y','bbl_x', 'bbl_y'] v = 30 #m/s mpf = v/30 for car_id, track_df in tracks.items(): # # direction = track_df["direction"].iloc[0] # direction = np.sign(track_df["fbr_x"].iloc[-1]-track_df["bbr_x"].iloc[-1]) track = np.array(track_df[pts]) direction = np.sign(track[-1][2]-track[-1][0]) # if len(track)>1: # average speed # frames = np.arange(0,len(track)) # fit = np.polyfit(frames,track,1) # est_speed = np.mean(fit[0,[0,2,4,6]]) # x_pred = np.polyval(fit, len(track)) # if abs(est_speed)<mpf/2 or (np.sign(est_speed)!=direction) or (abs(x_pred[0]-x_pred[2])<1): # too slow # x_pred = track[-1,:] + direction* np.array([mpf,0,mpf,0,mpf,0,mpf,0]) # else: x_pred = track[-1,:] + direction* np.array([mpf,0,mpf,0,mpf,0,mpf,0]) x_pred = np.reshape(x_pred,(1,-1)) x.append(x_pred) # prediction next frame, dim=nx8 new_row = pd.DataFrame(x_pred, columns=pts) tracks[car_id] = pd.concat([tracks[car_id], new_row]) return x, tracks def stitch_objects_gnn(self, THRESHOLD_1, THRESHOLD_2): # define the x,y range to keep track of cars in FOV (meter) xmin, xmax = min(self.df["x"].values)-10,max(self.df["x"].values)+10 ns = int(np.amin(np.array(self.df[['Frame #']]))) # start frame nf = int(np.amax(np.array(self.df[['Frame #']]))) # end frame tracks = dict() # a dictionary to store all current objects in view. key:ID, value:dataframe pts = ['bbr_x','bbr_y','fbr_x','fbr_y','fbl_x','fbl_y','bbl_x', 'bbl_y'] # pts_img = ["fbrx","fbry","fblx","fbly", "bbrx", "bbry", "bblx", "bbly", "ftrx", "ftry", "ftlx", "ftly", "btrx", "btry", "btlx", "btly"] newdf = pd.DataFrame() for k in range(ns,nf): print("\rFrame {}/{}".format(k,nf),end = "\r",flush = True) frame = self.df.loc[(self.df['Frame #'] == k)] # TODO: use groupby frame to save time y = np.array(frame[pts]) notnan = ~np.isnan(y).any(axis=1) y = y[notnan] # remove rows with missing values (dim = mx8) frame = frame.iloc[notnan,:] frame = frame.reset_index(drop=True) m_box = len(frame) n_car = len(tracks) # invalid_tracks = set() if (n_car > 0): # delete track that are out of view for car_id in list(tracks.keys()): # delete track if total matched frames < last_frame = tracks[car_id].iloc[-1] last_frame_x = np.array(last_frame[pts])[[0,2,4,6]] x1,x2 = min(last_frame_x),max(last_frame_x) frames = tracks[car_id]["Frame #"].values matched_bool = ~np.isnan(frames) frames_matched = tracks[car_id].loc[matched_bool] if (x1<xmin) or (x2>xmax): if len(frames_matched) > 0: # TODO: this threshold could be a ratio newid = frames_matched["ID"].iloc[0] frames_matched["ID"] = newid #unify ID newdf = pd.concat([newdf,frames_matched]) del tracks[car_id] n_car -= 1 if (m_box == 0) and (n_car == 0): # simply advance to the next frame continue elif (m_box == 0) and (n_car > 0): # if no measurements in current frame, simply predict x, tracks = self.predict_tracks_df(tracks) elif (m_box > 0) and (n_car == 0): # create new tracks (initialize) for i, row in frame.iterrows(): row = frame.loc[i:i,:] tracks[row['ID'].iloc[0]] = row else: x, tracks = self.predict_tracks_df(tracks) n_car = len(tracks) curr_id = list(tracks.keys()) # should be n id's # score = np.ones([m_box,n_car])*(99) score_dist = np.zeros([m_box,n_car]) score_iou =np.zeros([m_box,n_car]) invalid_meas = set() # invalid_tracks = set() for m in range(m_box): for n in range(n_car): score_dist[m,n] = self.dist_score(x[n],y[m],'maha') score_iou[m,n], areaa, areab = self.iou(x[n],y[m],DIRECTION=False,AREA=True) # if areaa < 0.5: # invalid_tracks.add(n) if areab < 1: invalid_meas.add(m) # if (1120<k<1130): # vis.plot_track(np.array(np.vstack(x), dtype=float), np.array(y,dtype=float), curr_id, frame["ID"].values, xmin,xmax, k) # if 333 in curr_id: # print("") gate = np.logical_or(score_dist<THRESHOLD_1, score_iou>0) matched_length = [] for carid in curr_id: track = tracks[carid] matched_length.append(track["Frame #"].count()) pq = np.argsort(matched_length)[::-1] # priority queue matched_m = set() for n in pq: if not any(gate[:,n]): # no matched meas for this track continue # find the best match meas for this track tracks[curr_id[n]] = tracks[curr_id[n]].reset_index(drop=True) idx_in_gate = np.where(gate[:,n])[0] best_idx = np.argmin(score_dist[idx_in_gate,n]) m = idx_in_gate[best_idx] avg_meas = frame.loc[m:m] tracks[curr_id[n]].drop(tracks[curr_id[n]].tail(1).index,inplace=True) # drop the last row (prediction) tracks[curr_id[n]] = pd.concat([tracks[curr_id[n]], avg_meas],ignore_index=True) gate[m,:] = False # elimite m from future selection matched_m.add(m) m_unassociated = set(np.arange(m_box))-matched_m for m in m_unassociated: # !TODO: make sure that y[m] at not in the gate of each other if (m not in invalid_meas): new_id = frame['ID'].iloc[m] new_meas = frame.loc[m:m] tracks[new_id] = new_meas self.df = newdf return newdf def stitch_objects_bm(self, THRESHOLD_1, THRESHOLD_2): ''' bipartite matching based on Maha distance cost ''' xmin, xmax = min(self.df["x"].values)-10,max(self.df["x"].values)+10 ns = int(np.amin(np.array(self.df[['Frame #']]))) # start frame nf = int(np.amax(np.array(self.df[['Frame #']]))) # end frame tracks = dict() # a dictionary to store all current objects in view. key:ID, value:dataframe pts = ['bbr_x','bbr_y','fbr_x','fbr_y','fbl_x','fbl_y','bbl_x', 'bbl_y'] # pts_img = ["fbrx","fbry","fblx","fbly", "bbrx", "bbry", "bblx", "bbly", "ftrx", "ftry", "ftlx", "ftly", "btrx", "btry", "btlx", "btly"] newdf = pd.DataFrame() for k in range(ns,nf): print("\rFrame {}/{}".format(k,nf),end = "\r",flush = True) frame = self.df.loc[(self.df['Frame #'] == k)] # TODO: use groupby frame to save time y = np.array(frame[pts]) notnan = ~np.isnan(y).any(axis=1) y = y[notnan] # remove rows with missing values (dim = mx8) frame = frame.iloc[notnan,:] frame = frame.reset_index(drop=True) m_box = len(frame) n_car = len(tracks) invalid_tracks = set() if (n_car > 0): # delete track that are out of view for car_id in list(tracks.keys()): # delete track if total matched frames < last_frame = tracks[car_id].iloc[-1] last_frame_x = np.array(last_frame[pts])[[0,2,4,6]] x1,x2 = min(last_frame_x),max(last_frame_x) frames = tracks[car_id]["Frame #"].values matched_bool = ~np.isnan(frames) frames_matched = tracks[car_id].loc[matched_bool] if (x1<xmin) or (x2>xmax) or (car_id in invalid_tracks): if len(frames_matched) > 0: # TODO: this threshold could be a ratio newid = frames_matched["ID"].iloc[0] frames_matched["ID"] = newid #unify ID newdf = pd.concat([newdf,frames_matched]) del tracks[car_id] n_car -= 1 if (m_box == 0) and (n_car == 0): # simply advance to the next frame continue elif (m_box == 0) and (n_car > 0): # if no measurements in current frame, simply predict x, tracks = self.predict_tracks_df(tracks) elif (m_box > 0) and (n_car == 0): # create new tracks (initialize) for i, row in frame.iterrows(): row = frame.loc[i:i,:] tracks[row['ID'].iloc[0]] = row else: x, tracks = self.predict_tracks_df(tracks) n_car = len(tracks) curr_id = list(tracks.keys()) # should be n id's # score = np.ones([m_box,n_car])*(99) score_dist = np.zeros([m_box,n_car]) score_iou =np.zeros([m_box,n_car]) invalid_meas = set() invalid_tracks = set() for m in range(m_box): for n in range(n_car): score_dist[m,n] = self.dist_score(x[n],y[m],'maha') score_iou[m,n], areaa, areab = self.iou(x[n],y[m],DIRECTION=False,AREA=True) if areaa < 0.5: invalid_tracks.add(n) if areab < 1: invalid_meas.add(m) # if (1715<k<1760): # vis.plot_track(np.array(np.vstack(x), dtype=float), np.array(y,dtype=float), curr_id, frame["ID"].values, xmin,xmax, k) # bipartite matching # score_dist[score_dist>THRESHOLD_1]=np.inf a,b = scipy.optimize.linear_sum_assignment(score_dist) gate = np.logical_or(score_dist<THRESHOLD_1, score_iou>0) matched_m = set() for i in range(len(a)): if gate[a[i]][b[i]]: n,m = b[i], a[i] tracks[curr_id[n]] = tracks[curr_id[n]].reset_index(drop=True) avg_meas = frame.loc[m:m] tracks[curr_id[n]].drop(tracks[curr_id[n]].tail(1).index,inplace=True) # drop the last row (prediction) tracks[curr_id[n]] = pd.concat([tracks[curr_id[n]], avg_meas],ignore_index=True) matched_m.add(m) # m_unassociated = np.where(np.sum(gate, axis=1)==0)[0] m_unassociated = set(np.arange(m_box))-matched_m for m in m_unassociated: # !TODO: make sure that y[m] at not in the gate of each other if (m not in invalid_meas) and (all(gate[m,:])==False) : new_id = frame['ID'].iloc[m] new_meas = frame.loc[m:m] tracks[new_id] = new_meas print("\n") print("Before DA: {} unique IDs".format(self.df.groupby("ID").ngroups)) print("After DA: {} unique IDs".format(newdf.groupby("ID").ngroups)) self.df = newdf return def stitch_objects_jpda(self, THRESHOLD_1, THRESHOLD_2): ''' 10/20/2021 use JPDA, weighted average of all meas that fall into a gate (defined by IOU and mahalanobis distance) create new ID for meas out side of the gate ''' # define the x,y range to keep track of cars in FOV (meter) xmin, xmax = min(self.df["x"].values)-10,max(self.df["x"].values)+10 ns = int(np.amin(np.array(self.df[['Frame #']]))) # start frame nf = int(np.amax(np.array(self.df[['Frame #']]))) # end frame tracks = dict() # a dictionary to store all current objects in view. key:ID, value:dataframe pts = ['bbr_x','bbr_y','fbr_x','fbr_y','fbl_x','fbl_y','bbl_x', 'bbl_y'] pts_img = ["fbrx","fbry","fblx","fbly", "bbrx", "bbry", "bblx", "bbly", "ftrx", "ftry", "ftlx", "ftly", "btrx", "btry", "btlx", "btly"] newdf = pd.DataFrame() for k in range(ns,nf): print("\rFrame {}/{}".format(k,nf),end = "\r",flush = True) frame = self.df.loc[(self.df['Frame #'] == k)] # TODO: use groupby frame to save time y = np.array(frame[pts]) notnan = ~np.isnan(y).any(axis=1) y = y[notnan] # remove rows with missing values (dim = mx8) frame = frame.iloc[notnan,:] frame = frame.reset_index(drop=True) m_box = len(frame) n_car = len(tracks) if (n_car > 0): # delete track that are out of view for car_id in list(tracks.keys()): # delete track if total matched frames < last_frame = tracks[car_id].iloc[-1] last_frame_x = np.array(last_frame[pts])[[0,2,4,6]] x1,x2 = min(last_frame_x),max(last_frame_x) frames = tracks[car_id]["Frame #"].values matched_bool = ~np.isnan(frames) frames_matched = tracks[car_id].loc[matched_bool] if (x1<xmin) or (x2>xmax): if len(frames_matched) > 0: # TODO: this threshold could be a ratio newid = frames_matched["ID"].iloc[0] frames_matched["ID"] = newid #unify ID newdf = pd.concat([newdf,frames_matched]) del tracks[car_id] n_car -= 1 if (m_box == 0) and (n_car == 0): # simply advance to the next frame continue elif (m_box == 0) and (n_car > 0): # if no measurements in current frame, simply predict x, tracks = self.predict_tracks_df(tracks) elif (m_box > 0) and (n_car == 0): # create new tracks (initialize) for i, row in frame.iterrows(): row = frame.loc[i:i,:] tracks[row['ID'].iloc[0]] = row else: x, tracks = self.predict_tracks_df(tracks) n_car = len(tracks) curr_id = list(tracks.keys()) # should be n id's # score = np.ones([m_box,n_car])*(99) score_dist = np.zeros([m_box,n_car]) score_iou =np.zeros([m_box,n_car]) invalid_meas = [] for m in range(m_box): for n in range(n_car): score_dist[m,n] = self.dist_score(x[n],y[m],'maha') score_iou[m,n], areaa, areab = self.iou(x[n],y[m],DIRECTION=False,AREA=True) if areab < 2: # invalid measurement score_dist[m,:] = 99 score_iou[m,:] = -1 invalid_meas.append(m) if (1260<k<1300): vis.plot_track(np.array(np.vstack(x), dtype=float), np.array(y,dtype=float), curr_id, frame["ID"].values, xmin,xmax, k) # if k == 409: # print("") # matching gate = np.logical_or(score_dist<THRESHOLD_1, score_iou>0) for n in range(n_car): if any(gate[:,n]): # calculate weighted average tracks[curr_id[n]] = tracks[curr_id[n]].reset_index(drop=True) frames_in_gate = frame.iloc[gate[:,n]] if len(frames_in_gate) == 1: avg_meas = frames_in_gate else: w = 1/score_dist[gate[:,n],n] w = w / w.sum(axis=0) frame_vals = np.array(frames_in_gate[pts_img+pts]) avg_meas_vals = np.reshape(np.dot(w,frame_vals),(1,-1)) avg_meas = pd.DataFrame(data=avg_meas_vals, columns=pts_img + pts) avg_meas["Frame #"] = k tracks[curr_id[n]].drop(tracks[curr_id[n]].tail(1).index,inplace=True) # drop the last row (prediction) tracks[curr_id[n]] = pd.concat([tracks[curr_id[n]], avg_meas],ignore_index=True) m_unassociated = np.where(
np.sum(gate, axis=1)
numpy.sum
from __future__ import print_function, absolute_import, division import numpy as np from numba import unittest_support as unittest from numba import hsa, intp @hsa.jit(device=True) def device_scan_generic(tid, data): """Inclusive prefix sum within a single block Requires tid should have range [0, data.size) and data.size must be power of 2. """ n = data.size # Upsweep offset = 1 d = n // 2 while d > 0: hsa.barrier(hsa.CLK_GLOBAL_MEM_FENCE) if tid < d: ai = offset * (2 * tid + 1) - 1 bi = offset * (2 * tid + 2) - 1 data[bi] += data[ai] offset *= 2 d //= 2 hsa.barrier(hsa.CLK_GLOBAL_MEM_FENCE) prefixsum = data[n - 1] hsa.barrier(hsa.CLK_GLOBAL_MEM_FENCE) if tid == 0: data[n - 1] = 0 # Downsweep d = 1 offset = n while d < n: offset //= 2 hsa.barrier(hsa.CLK_GLOBAL_MEM_FENCE) if tid < d: ai = offset * (2 * tid + 1) - 1 bi = offset * (2 * tid + 2) - 1 tmp = data[ai] data[ai] = data[bi] data[bi] += tmp d *= 2 hsa.barrier(hsa.CLK_GLOBAL_MEM_FENCE) return prefixsum _WARPSIZE = 64 @hsa.jit(device=True) def warp_scan(tid, temp, inclusive): """Intra-warp scan Note ---- Assume all threads are in lockstep """ hsa.wavebarrier() lane = tid & (_WARPSIZE - 1) if lane >= 1: temp[tid] += temp[tid - 1] hsa.wavebarrier() if lane >= 2: temp[tid] += temp[tid - 2] hsa.wavebarrier() if lane >= 4: temp[tid] += temp[tid - 4] hsa.wavebarrier() if lane >= 8: temp[tid] += temp[tid - 8] hsa.wavebarrier() if lane >= 16: temp[tid] += temp[tid - 16] hsa.wavebarrier() if lane >= 32: temp[tid] += temp[tid - 32] hsa.wavebarrier() if inclusive: return temp[tid] else: return temp[tid - 1] if lane > 0 else 0 @hsa.jit(device=True) def device_scan(tid, data, temp, inclusive): """ Args ---- tid: thread id data: scalar input for tid temp: shared memory for temporary work """ lane = tid & (_WARPSIZE - 1) warpid = tid >> 6 # Preload temp[tid] = data hsa.barrier(hsa.CLK_GLOBAL_MEM_FENCE) # Scan warps in parallel warp_scan_res = warp_scan(tid, temp, inclusive) hsa.barrier(hsa.CLK_GLOBAL_MEM_FENCE) # Get parital result if lane == (_WARPSIZE - 1): temp[warpid] = temp[tid] hsa.barrier(hsa.CLK_GLOBAL_MEM_FENCE) # Scan the partial results if warpid == 0: warp_scan(tid, temp, True) hsa.barrier(hsa.CLK_GLOBAL_MEM_FENCE) # Accumlate scanned partial results if warpid > 0: warp_scan_res += temp[warpid - 1] hsa.barrier(hsa.CLK_GLOBAL_MEM_FENCE) # Output if tid == temp.size - 1: # Last thread computes prefix sum if inclusive: temp[0] = warp_scan_res else: temp[0] = warp_scan_res + data hsa.barrier(hsa.CLK_GLOBAL_MEM_FENCE) # Load prefixsum prefixsum = temp[0] hsa.barrier(hsa.CLK_GLOBAL_MEM_FENCE) return warp_scan_res, prefixsum @hsa.jit(device=True) def shuffle_up(val, width): tid = hsa.get_local_id(0) hsa.wavebarrier() res = hsa.activelanepermute_wavewidth(val, tid - width, 0, False) return res @hsa.jit(device=True) def shuf_wave_inclusive_scan(val): tid = hsa.get_local_id(0) lane = tid & (_WARPSIZE - 1) hsa.wavebarrier() shuf = shuffle_up(val, 1) if lane >= 1: val += shuf hsa.wavebarrier() shuf = shuffle_up(val, 2) if lane >= 2: val += shuf hsa.wavebarrier() shuf = shuffle_up(val, 4) if lane >= 4: val += shuf hsa.wavebarrier() shuf = shuffle_up(val, 8) if lane >= 8: val += shuf hsa.wavebarrier() shuf = shuffle_up(val, 16) if lane >= 16: val += shuf hsa.wavebarrier() shuf = shuffle_up(val, 32) if lane >= 32: val += shuf hsa.wavebarrier() return val @hsa.jit(device=True) def shuf_device_inclusive_scan(data, temp): """ Args ---- data: scalar input for tid temp: shared memory for temporary work, requires at least threadcount/wavesize storage """ tid = hsa.get_local_id(0) lane = tid & (_WARPSIZE - 1) warpid = tid >> 6 # Scan warps in parallel warp_scan_res = shuf_wave_inclusive_scan(data) hsa.barrier() # Store partial sum into shared memory if lane == (_WARPSIZE - 1): temp[warpid] = warp_scan_res hsa.barrier() # Scan the partial sum by first wave if warpid == 0: shuf_wave_inclusive_scan(temp[lane]) hsa.barrier() # Get block sum for each wave blocksum = 0 # first wave is 0 if warpid > 0: blocksum = temp[warpid - 1] return warp_scan_res + blocksum class TestScan(unittest.TestCase): def test_single_block(self): @hsa.jit def scan_block(data, sums): sm_data = hsa.shared.array(64, dtype=intp) tid = hsa.get_local_id(0) gid = hsa.get_global_id(0) blkid = hsa.get_group_id(0) sm_data[tid] = data[gid] prefixsum = device_scan_generic(tid, sm_data) data[gid] = sm_data[tid] if tid == 0: sums[blkid] = prefixsum data =
np.random.randint(0, 4, size=64)
numpy.random.randint
import numpy as np import datetime from time import time from .binning import Binning from .binning import Binning_Types from .helper import objectview from .preprocessors import DataSource class BundleGenerator(): def __init__(self, model, binning): self.__model = model self.__binning = binning.copy() self.__last_seed = None self.__compute_probability_matrix() pass def recommended_amount(self, real_histogram): """real_histogram: the histogram of the model's source data binned with the new binning.""" min_prob = self.probabilities[ (self.probabilities[:, -1] > 0) * (real_histogram.values.flatten() > 0), -1].min() if min_prob > 0: return int(np.ceil(1/min_prob)) else: return 0 def expected_best_quality(self, amount, real_histogram): """real_histogram: the histogram of the model's source data binned with the new binning.""" index = np.array([p * amount >= 1 or real_histogram.values.flatten()[i] == 0 for i, p in enumerate(self.probabilities[:, -1])]) return self.binning.volumes.flatten()[index].sum() / \ self.binning.total_volume def __compute_probability_matrix(self): all_edges = [ np.unique(np.concatenate((gbe, mbe))) for gbe, mbe in zip(self.binning.edges, self.model.binning.edges) ] # Create sub_edges for each bin and along each dimension. sub_edges = [] for edges, coarse in zip(all_edges, self.binning.edges): sub_edges.append( [edges[(edges >= left) * (edges <= right)] for left, right in zip(coarse[:-1], coarse[1:])] ) # sub_edges is an n-dim list of lists of arrays: # sub_edges[dim][bin_index] contains the sub edges along dimension # dim for bin with index bin_index along that dimension. # Create a 1d list of all bin indices (along all dimensions) bin_indices = [range(0, i) for i in self.binning.counts] bin_indices = np.meshgrid(*bin_indices, indexing='ij') bin_indices = list(zip(*[mg.flatten() for mg in bin_indices])) # here bin_indices equals [ (x0, y0, z0), (x0, y0, z1), (x0, y1, z0) ... ] # Probabilities is a matrix with one row per bin with the format: # c_x, c_y, c_z, ... , probability # for each bin/row, where c_i indicates the center of the bin. probabilities = np.zeros((len(bin_indices), self.binning.dimensions + 1)) for i, bin_index in enumerate(bin_indices): # Find center of current bin probabilities[i, :-1] = [cpd[idx] for idx, cpd in zip(bin_index, self.binning.centers)] # Create sub-binning to calculate probability of bin sub_binning = Binning(Binning_Types.SUBBINNING, [sub_edges[dim][idx] for dim, idx in enumerate(bin_index)]) factors = sub_binning.volumes / sub_binning.total_volume alltF = self.model.F(*sub_binning.meshgrids).flatten() alltF = [x if x > 0.0 else 0.0 for x in alltF] alltF = alltF * factors.flatten() probabilities[i, -1] = sum(alltF) probabilities[:, -1] /=
np.linalg.norm(probabilities[:, -1], ord=1)
numpy.linalg.norm
import warnings import ctypes as _ctypes # Load mkl_spblas through the libmkl_rt common interface # Check each of these library types _MKL_SO_LINUX = "libmkl_rt.so" _MKL_SO_OSX = "libmkl_rt.dylib" _MKL_SO_WINDOWS = "mkl_rt.dll" # There's probably a better way to do this _libmkl, _libmkl_loading_errors = None, [] for so_file in [_MKL_SO_LINUX, _MKL_SO_OSX, _MKL_SO_WINDOWS]: try: _libmkl = _ctypes.cdll.LoadLibrary(so_file) break except (OSError, ImportError) as err: _libmkl_loading_errors.append(err) if _libmkl is None: ierr_msg = "Unable to load the MKL libraries through libmkl_rt. Try setting $LD_LIBRARY_PATH." ierr_msg += "\n\t" + "\n\t".join(map(lambda x: str(x), _libmkl_loading_errors)) raise ImportError(ierr_msg) # Use mkl-service to check version if it's installed # Since it's not on PyPi I don't want to make this an actual package dependency # So without it just create mock functions and don't do version checking try: from mkl import get_version, get_version_string except ImportError: def get_version(): return None def get_version_string(): return None if get_version() is not None and get_version()["MajorVersion"] < 2020: msg = "Loaded version of MKL is out of date: {v}".format(v=get_version_string()) warnings.warn(msg) import numpy as np import scipy.sparse as _spsparse from numpy.ctypeslib import ndpointer, as_array NUMPY_FLOAT_DTYPES = [np.float32, np.float64] class MKL: """ This class holds shared object references to C functions with arg and returntypes that can be adjusted""" MKL_INT = None MKL_INT_NUMPY = None # Import function for creating a MKL CSR object # https://software.intel.com/en-us/mkl-developer-reference-c-mkl-sparse-create-csr _mkl_sparse_d_create_csr = _libmkl.mkl_sparse_d_create_csr # Import function for creating a MKL CSR object # https://software.intel.com/en-us/mkl-developer-reference-c-mkl-sparse-create-csr _mkl_sparse_s_create_csr = _libmkl.mkl_sparse_s_create_csr # Import function for creating a MKL CSC object # https://software.intel.com/en-us/mkl-developer-reference-c-mkl-sparse-create-csc _mkl_sparse_d_create_csc = _libmkl.mkl_sparse_d_create_csc # Import function for creating a MKL CSC object # https://software.intel.com/en-us/mkl-developer-reference-c-mkl-sparse-create-csc _mkl_sparse_s_create_csc = _libmkl.mkl_sparse_s_create_csc # Export function for exporting a MKL CSR object # https://software.intel.com/en-us/mkl-developer-reference-c-mkl-sparse-export-csr _mkl_sparse_d_export_csr = _libmkl.mkl_sparse_d_export_csr # Export function for exporting a MKL CSR object # https://software.intel.com/en-us/mkl-developer-reference-c-mkl-sparse-export-csr _mkl_sparse_s_export_csr = _libmkl.mkl_sparse_s_export_csr # Export function for exporting a MKL CSC object # https://software.intel.com/en-us/mkl-developer-reference-c-mkl-sparse-export-csc _mkl_sparse_d_export_csc = _libmkl.mkl_sparse_d_export_csc # Export function for exporting a MKL CSC object # https://software.intel.com/en-us/mkl-developer-reference-c-mkl-sparse-export-csc _mkl_sparse_s_export_csc = _libmkl.mkl_sparse_s_export_csc # Import function for matmul # https://software.intel.com/en-us/mkl-developer-reference-c-mkl-sparse-spmm _mkl_sparse_spmm = _libmkl.mkl_sparse_spmm # Import function for product of sparse matrix with its transpose # https://software.intel.com/en-us/mkl-developer-reference-c-mkl-sparse-syrk _mkl_sparse_syrk = _libmkl.mkl_sparse_syrk # Import function for cleaning up MKL objects # https://software.intel.com/en-us/mkl-developer-reference-c-mkl-sparse-destroy _mkl_sparse_destroy = _libmkl.mkl_sparse_destroy # Import function for ordering MKL objects # https://software.intel.com/en-us/mkl-developer-reference-c-mkl-sparse-order _mkl_sparse_order = _libmkl.mkl_sparse_order # Import function for coverting to CSR # https://software.intel.com/en-us/mkl-developer-reference-c-mkl-sparse-convert-csr _mkl_sparse_convert_csr = _libmkl.mkl_sparse_convert_csr # Import function for matmul single dense # https://software.intel.com/en-us/mkl-developer-reference-c-mkl-sparse-spmm _mkl_sparse_s_spmmd = _libmkl.mkl_sparse_s_spmmd # Import function for matmul double dense # https://software.intel.com/en-us/mkl-developer-reference-c-mkl-sparse-spmm _mkl_sparse_d_spmmd = _libmkl.mkl_sparse_d_spmmd # Import function for matmul single sparse*dense # https://software.intel.com/en-us/mkl-developer-reference-c-mkl-sparse-mm _mkl_sparse_s_mm = _libmkl.mkl_sparse_s_mm # Import function for matmul double sparse*dense # https://software.intel.com/en-us/mkl-developer-reference-c-mkl-sparse-mm _mkl_sparse_d_mm = _libmkl.mkl_sparse_d_mm # Import function for matmul single dense*dense # https://software.intel.com/en-us/mkl-developer-reference-c-cblas-gemm _cblas_sgemm = _libmkl.cblas_sgemm # Import function for matmul double dense*dense # https://software.intel.com/en-us/mkl-developer-reference-c-cblas-gemm _cblas_dgemm = _libmkl.cblas_dgemm # Import function for matrix * vector # https://software.intel.com/en-us/mkl-developer-reference-c-mkl-sparse-mv _mkl_sparse_s_mv = _libmkl.mkl_sparse_s_mv # Import function for matrix * vector # https://software.intel.com/en-us/mkl-developer-reference-c-mkl-sparse-mv _mkl_sparse_d_mv = _libmkl.mkl_sparse_d_mv @classmethod def _set_int_type(cls, c_type, np_type): cls.MKL_INT = c_type cls.MKL_INT_NUMPY = np_type cls._mkl_sparse_d_create_csr.argtypes = cls._mkl_sparse_create_argtypes(_ctypes.c_double) cls._mkl_sparse_d_create_csr.restypes = _ctypes.c_int cls._mkl_sparse_s_create_csr.argtypes = cls._mkl_sparse_create_argtypes(_ctypes.c_float) cls._mkl_sparse_s_create_csr.restypes = _ctypes.c_int cls._mkl_sparse_d_create_csc.argtypes = cls._mkl_sparse_create_argtypes(_ctypes.c_double) cls._mkl_sparse_d_create_csc.restypes = _ctypes.c_int cls._mkl_sparse_s_create_csc.argtypes = cls._mkl_sparse_create_argtypes(_ctypes.c_float) cls._mkl_sparse_s_create_csc.restypes = _ctypes.c_int cls._mkl_sparse_d_export_csr.argtypes = cls._mkl_export_create_argtypes(_ctypes.c_double) cls._mkl_sparse_d_export_csr.restypes = _ctypes.c_int cls._mkl_sparse_s_export_csr.argtypes = cls._mkl_export_create_argtypes(_ctypes.c_float) cls._mkl_sparse_s_export_csr.restypes = _ctypes.c_int cls._mkl_sparse_d_export_csc.argtypes = cls._mkl_export_create_argtypes(_ctypes.c_double) cls._mkl_sparse_d_export_csc.restypes = _ctypes.c_int cls._mkl_sparse_s_export_csr.argtypes = cls._mkl_export_create_argtypes(_ctypes.c_float) cls._mkl_sparse_s_export_csr.restypes = _ctypes.c_int cls._mkl_sparse_spmm.argtypes = [_ctypes.c_int, sparse_matrix_t, sparse_matrix_t, _ctypes.POINTER(sparse_matrix_t)] cls._mkl_sparse_spmm.restypes = _ctypes.c_int cls._mkl_sparse_s_spmmd.argtypes = cls._mkl_sparse_spmmd_argtypes(_ctypes.c_float) cls._mkl_sparse_s_spmmd.restypes = _ctypes.c_int cls._mkl_sparse_d_spmmd.argtypes = cls._mkl_sparse_spmmd_argtypes(_ctypes.c_double) cls._mkl_sparse_d_spmmd.restypes = _ctypes.c_int cls._mkl_sparse_s_mm.argtypes = cls._mkl_sparse_mm_argtypes(_ctypes.c_float) cls._mkl_sparse_s_mm.restypes = _ctypes.c_int cls._mkl_sparse_d_mm.argtypes = cls._mkl_sparse_mm_argtypes(_ctypes.c_double) cls._mkl_sparse_d_mm.restypes = _ctypes.c_int cls._cblas_sgemm.argtypes = cls._cblas_gemm_argtypes(_ctypes.c_float) cls._cblas_sgemm.restypes = None cls._cblas_dgemm.argtypes = cls._cblas_gemm_argtypes(_ctypes.c_double) cls._cblas_dgemm.restypes = None cls._mkl_sparse_destroy.argtypes = [sparse_matrix_t] cls._mkl_sparse_destroy.restypes = _ctypes.c_int cls._mkl_sparse_order.argtypes = [sparse_matrix_t] cls._mkl_sparse_order.restypes = _ctypes.c_int cls._mkl_sparse_s_mv.argtypes = cls._mkl_sparse_mv_argtypes(_ctypes.c_float) cls._mkl_sparse_s_mv.restypes = _ctypes.c_int cls._mkl_sparse_d_mv.argtypes = cls._mkl_sparse_mv_argtypes(_ctypes.c_double) cls._mkl_sparse_d_mv.restypes = _ctypes.c_int def __init__(self): raise NotImplementedError("This class is not intended to be instanced") """ The following methods return the argtype lists for each MKL function that has s and d variants""" @staticmethod def _mkl_sparse_create_argtypes(prec_type): return [_ctypes.POINTER(sparse_matrix_t), _ctypes.c_int, MKL.MKL_INT, MKL.MKL_INT, ndpointer(dtype=MKL.MKL_INT, ndim=1, flags='C_CONTIGUOUS'), ndpointer(dtype=MKL.MKL_INT, ndim=1, flags='C_CONTIGUOUS'), ndpointer(dtype=MKL.MKL_INT, ndim=1, flags='C_CONTIGUOUS'), ndpointer(dtype=prec_type, ndim=1, flags='C_CONTIGUOUS')] @staticmethod def _mkl_export_create_argtypes(prec_type): return [sparse_matrix_t, _ctypes.POINTER(_ctypes.c_int), _ctypes.POINTER(MKL.MKL_INT), _ctypes.POINTER(MKL.MKL_INT), _ctypes.POINTER(_ctypes.POINTER(MKL.MKL_INT)), _ctypes.POINTER(_ctypes.POINTER(MKL.MKL_INT)), _ctypes.POINTER(_ctypes.POINTER(MKL.MKL_INT)), _ctypes.POINTER(_ctypes.POINTER(prec_type))] @staticmethod def _cblas_gemm_argtypes(prec_type): return [_ctypes.c_int, _ctypes.c_int, _ctypes.c_int, MKL.MKL_INT, MKL.MKL_INT, MKL.MKL_INT, prec_type, ndpointer(dtype=prec_type, ndim=2), MKL.MKL_INT, ndpointer(dtype=prec_type, ndim=2), MKL.MKL_INT, prec_type, _ctypes.POINTER(prec_type), MKL.MKL_INT] @staticmethod def _mkl_sparse_spmmd_argtypes(prec_type): return [_ctypes.c_int, sparse_matrix_t, sparse_matrix_t, _ctypes.c_int, _ctypes.POINTER(prec_type), MKL.MKL_INT] @staticmethod def _mkl_sparse_mm_argtypes(prec_type): return [_ctypes.c_int, prec_type, sparse_matrix_t, matrix_descr, _ctypes.c_int, ndpointer(dtype=prec_type, ndim=2), MKL.MKL_INT, MKL.MKL_INT, prec_type, _ctypes.POINTER(prec_type), MKL.MKL_INT] @staticmethod def _mkl_sparse_mv_argtypes(prec_type): return [_ctypes.c_int, prec_type, sparse_matrix_t, matrix_descr, ndpointer(dtype=prec_type, ndim=1), prec_type, _ctypes.POINTER(prec_type)] # Construct opaque struct & type class _sparse_matrix(_ctypes.Structure): pass sparse_matrix_t = _ctypes.POINTER(_sparse_matrix) # Matrix description struct class matrix_descr(_ctypes.Structure): _fields_ = [("sparse_matrix_type_t", _ctypes.c_int), ("sparse_fill_mode_t", _ctypes.c_int), ("sparse_diag_type_t", _ctypes.c_int)] def __init__(self, sparse_matrix_type_t=20, sparse_fill_mode_t=0, sparse_diag_type_t=0): super(matrix_descr, self).__init__(sparse_matrix_type_t, sparse_fill_mode_t, sparse_diag_type_t) # Define standard return codes RETURN_CODES = {0: "SPARSE_STATUS_SUCCESS", 1: "SPARSE_STATUS_NOT_INITIALIZED", 2: "SPARSE_STATUS_ALLOC_FAILED", 3: "SPARSE_STATUS_INVALID_VALUE", 4: "SPARSE_STATUS_EXECUTION_FAILED", 5: "SPARSE_STATUS_INTERNAL_ERROR", 6: "SPARSE_STATUS_NOT_SUPPORTED"} # Define order codes LAYOUT_CODE_C = 101 LAYOUT_CODE_F = 102 def _check_scipy_index_typing(sparse_matrix): """ Ensure that the sparse matrix indicies are in the correct integer type :param sparse_matrix: Scipy matrix in CSC or CSR format :type sparse_matrix: scipy.sparse.spmatrix """ int_max = np.iinfo(MKL.MKL_INT_NUMPY).max if (sparse_matrix.nnz > int_max) or (max(sparse_matrix.shape) > int_max): msg = "MKL interface is {t} and cannot hold matrix {m}".format(m=repr(sparse_matrix), t=MKL.MKL_INT_NUMPY) raise ValueError(msg) # Cast indexes to MKL_INT type if sparse_matrix.indptr.dtype != MKL.MKL_INT_NUMPY: sparse_matrix.indptr = sparse_matrix.indptr.astype(MKL.MKL_INT_NUMPY) if sparse_matrix.indices.dtype != MKL.MKL_INT_NUMPY: sparse_matrix.indices = sparse_matrix.indices.astype(MKL.MKL_INT_NUMPY) def _get_numpy_layout(numpy_arr): """ Get the array layout code for a dense array in C or F order. Raises a ValueError if the array is not contiguous. :param numpy_arr: Numpy dense array :type numpy_arr: np.ndarray :return: The layout code for MKL and the leading dimension :rtype: int, int """ if numpy_arr.flags.c_contiguous: return LAYOUT_CODE_C, numpy_arr.shape[1] elif numpy_arr.flags.f_contiguous: return LAYOUT_CODE_F, numpy_arr.shape[0] elif not numpy_arr.flags.contiguous: raise ValueError("Array is not contiguous") else: raise ValueError("Array layout check has failed for unknown reason") def _create_mkl_sparse(matrix): """ Create MKL internal representation :param matrix: Sparse data in CSR or CSC format :type matrix: scipy.sparse.spmatrix :return ref, double_precision: Handle for the MKL internal representation and boolean for double precision :rtype: sparse_matrix_t, float """ # Figure out which dtype for data if matrix.dtype == np.float32: double_precision = False elif matrix.dtype == np.float64: double_precision = True else: raise ValueError("Only float32 or float64 dtypes are supported") # Figure out which matrix creation function to use if _spsparse.isspmatrix_csr(matrix): assert matrix.indptr.shape[0] == matrix.shape[0] + 1 handle_func = MKL._mkl_sparse_d_create_csr if double_precision else MKL._mkl_sparse_s_create_csr elif _spsparse.isspmatrix_csc(matrix): assert matrix.indptr.shape[0] == matrix.shape[1] + 1 handle_func = MKL._mkl_sparse_d_create_csc if double_precision else MKL._mkl_sparse_s_create_csc else: raise ValueError("Matrix is not CSC or CSR") # Make sure indices are of the correct integer type _check_scipy_index_typing(matrix) assert matrix.data.shape[0] == matrix.indices.shape[0] return _pass_mkl_handle(matrix, handle_func), double_precision def _pass_mkl_handle(data, handle_func): """ Create MKL internal representation :param data: Sparse data :type data: scipy.sparse.spmatrix :return ref: Handle for the MKL internal representation :rtype: sparse_matrix_t """ # Create a pointer for the output matrix ref = sparse_matrix_t() # Load into a MKL data structure and check return ret_val = handle_func(_ctypes.byref(ref), _ctypes.c_int(0), MKL.MKL_INT(data.shape[0]), MKL.MKL_INT(data.shape[1]), data.indptr[0:-1], data.indptr[1:], data.indices, data.data) # Check return if ret_val != 0: err_msg = "{fn} returned {v} ({e})".format(fn=handle_func.__name__, v=ret_val, e=RETURN_CODES[ret_val]) raise ValueError(err_msg) return ref def _export_mkl(csr_mkl_handle, double_precision, output_type="csr"): """ Export a MKL sparse handle :param csr_mkl_handle: Handle for the MKL internal representation :type csr_mkl_handle: sparse_matrix_t :param double_precision: Use float64 if True, float32 if False. This MUST match the underlying float type - this defines a memory view, it does not cast. :type double_precision: bool :param output_type: The structure of the MKL handle (and therefore the type of scipy sparse to create) :type output_type: str :return: Sparse matrix in scipy format :rtype: scipy.spmatrix """ # Create the pointers for the output data indptrb = _ctypes.POINTER(MKL.MKL_INT)() indptren = _ctypes.POINTER(MKL.MKL_INT)() indices = _ctypes.POINTER(MKL.MKL_INT)() ordering = _ctypes.c_int() nrows = MKL.MKL_INT() ncols = MKL.MKL_INT() output_type = output_type.lower() if output_type == "csr": out_func = MKL._mkl_sparse_d_export_csr if double_precision else MKL._mkl_sparse_s_export_csr sp_matrix_constructor = _spsparse.csr_matrix elif output_type == "csc": out_func = MKL._mkl_sparse_d_export_csc if double_precision else MKL._mkl_sparse_s_export_csc sp_matrix_constructor = _spsparse.csc_matrix else: raise ValueError("Only CSR and CSC output types are supported") if double_precision: data = _ctypes.POINTER(_ctypes.c_double)() final_dtype = np.float64 else: data = _ctypes.POINTER(_ctypes.c_float)() final_dtype = np.float32 ret_val = out_func(csr_mkl_handle, _ctypes.byref(ordering), _ctypes.byref(nrows), _ctypes.byref(ncols), _ctypes.byref(indptrb), _ctypes.byref(indptren), _ctypes.byref(indices), _ctypes.byref(data)) # Check return if ret_val != 0: err_msg = "{fn} returned {v} ({e})".format(fn=out_func.__name__, v=ret_val, e=RETURN_CODES[ret_val]) raise ValueError(err_msg) # Check ordering if ordering.value != 0: raise ValueError("1-indexing (F-style) is not supported") # Get matrix dims ncols = ncols.value nrows = nrows.value # If any axis is 0 return an empty matrix if nrows == 0 or ncols == 0: return sp_matrix_constructor((nrows, ncols), dtype=final_dtype) # Get the index dimension index_dim = nrows if output_type == "csr" else ncols # Construct a numpy array and add 0 to first position for scipy.sparse's 3-array indexing indptrb = as_array(indptrb, shape=(index_dim,)) indptren = as_array(indptren, shape=(index_dim,)) indptren = np.insert(indptren, 0, indptrb[0]) nnz = indptren[-1] - indptrb[0] # If there are no non-zeros, return an empty matrix # If the number of non-zeros is insane, raise a ValueError if nnz == 0: return sp_matrix_constructor((nrows, ncols), dtype=final_dtype) elif nnz < 0 or nnz > ncols * nrows: raise ValueError("Matrix ({m} x {n}) is attempting to index {z} elements".format(m=nrows, n=ncols, z=nnz)) # Construct numpy arrays from data pointer and from indicies pointer data = np.array(as_array(data, shape=(nnz,)), copy=True) indices = np.array(as_array(indices, shape=(nnz,)), copy=True) # Pack and return the matrix return sp_matrix_constructor((data, indices, indptren), shape=(nrows, ncols)) def _destroy_mkl_handle(ref_handle): """ Deallocate a MKL sparse handle :param ref_handle: :type ref_handle: sparse_matrix_t """ ret_val = MKL._mkl_sparse_destroy(ref_handle) if ret_val != 0: raise ValueError("mkl_sparse_destroy returned {v} ({e})".format(v=ret_val, e=RETURN_CODES[ret_val])) def _order_mkl_handle(ref_handle): """ Reorder indexes in a MKL sparse handle :param ref_handle: :type ref_handle: sparse_matrix_t """ ret_val = MKL._mkl_sparse_order(ref_handle) if ret_val != 0: raise ValueError("mkl_sparse_order returned {v} ({e})".format(v=ret_val, e=RETURN_CODES[ret_val])) def _convert_to_csr(ref_handle, destroy_original=False): """ Convert a MKL sparse handle to CSR format :param ref_handle: :type ref_handle: sparse_matrix_t :return: """ csr_ref = sparse_matrix_t() ret_val = MKL._mkl_sparse_convert_csr(ref_handle, _ctypes.c_int(10), _ctypes.byref(csr_ref)) if ret_val != 0: try: _destroy_mkl_handle(csr_ref) except ValueError: pass raise ValueError("mkl_sparse_convert_csr returned {v} ({e})".format(v=ret_val, e=RETURN_CODES[ret_val])) if destroy_original: _destroy_mkl_handle(ref_handle) return csr_ref def _sanity_check(matrix_a, matrix_b, allow_vector=False): """ Check matrix dimensions :param matrix_a: sp.sparse or numpy array :param matrix_b: sp.sparse or numpy array """ a_2d, b_2d = matrix_a.ndim == 2, matrix_b.ndim == 2 a_vec, b_vec = _is_dense_vector(matrix_a), _is_dense_vector(matrix_b) # Check to make sure that both matrices are 2-d if not allow_vector and (not a_2d or not b_2d): err_msg = "Matrices must be 2d: {m1} * {m2} is not valid".format(m1=matrix_a.shape, m2=matrix_b.shape) raise ValueError(err_msg) invalid_ndims = not (a_2d or a_vec) or not (b_2d, b_vec) invalid_align = (matrix_a.shape[1] if not matrix_a.ndim == 1 else matrix_a.shape[0]) != matrix_b.shape[0] # Check to make sure that this multiplication can work if invalid_align or invalid_ndims: err_msg = "Matrix alignment error: {m1} * {m2} is not valid".format(m1=matrix_a.shape, m2=matrix_b.shape) raise ValueError(err_msg) def _cast_to_float64(matrix): """ Make a copy of the array as double precision floats or return the reference if it already is""" return matrix.astype(np.float64) if matrix.dtype != np.float64 else matrix def _type_check(matrix_a, matrix_b, cast=False, dprint=print): """ Make sure that both matrices are single precision floats or both are double precision floats If not, convert to double precision floats if cast is True, or raise an error if cast is False """ # Check dtypes if matrix_a.dtype == np.float32 and matrix_b.dtype == np.float32: return matrix_a, matrix_b elif matrix_a.dtype == np.float64 and matrix_b.dtype == np.float64: return matrix_a, matrix_b elif (matrix_a.dtype != np.float64 or matrix_b.dtype != np.float64) and cast: dprint("Recasting matrix data types {a} and {b} to np.float64".format(a=matrix_a.dtype, b=matrix_b.dtype)) return _cast_to_float64(matrix_a), _cast_to_float64(matrix_b) elif matrix_a.dtype != np.float64 or matrix_b.dtype != np.float64: err_msg = "Matrix data types must be in concordance; {a} and {b} provided".format(a=matrix_a.dtype, b=matrix_b.dtype) raise ValueError(err_msg) def _is_dense_vector(m_or_v): return not _spsparse.issparse(m_or_v) and ((m_or_v.ndim == 1) or ((m_or_v.ndim == 2) and min(m_or_v.shape) == 1)) def _empty_output_check(matrix_a, matrix_b): """Check for trivial cases where an empty array should be produced""" # One dimension is zero if min([*matrix_a.shape, *matrix_b.shape]) == 0: return True # The sparse array is empty elif _spsparse.issparse(matrix_a) and min(matrix_a.data.shape[0], matrix_a.indices.shape[0]) == 0: return True elif _spsparse.issparse(matrix_b) and min(matrix_b.data.shape[0], matrix_b.indices.shape[0]) == 0: return True # Neither trivial condition else: return False def _validate_dtype(): """ Test to make sure that this library works by creating a random sparse array in CSC format, then converting it to CSR format and making sure is has not raised an exception. """ test_array = _spsparse.random(5, 5, density=0.5, format="csc", dtype=np.float32, random_state=50) test_comparison = test_array.A csc_ref, precision_flag = _create_mkl_sparse(test_array) try: csr_ref = _convert_to_csr(csc_ref) final_array = _export_mkl(csr_ref, precision_flag) if not
np.allclose(test_comparison, final_array.A)
numpy.allclose
# coding: utf-8 # Copyright (c) 2021 AkaiKKRteam. # Distributed under the terms of the Apache License, Version 2.0. #!/bin/env python from .Error import * from .Unit import * import sys import numpy as np from pymatgen.io.cif import CifParser from pymatgen.core import Structure, PeriodicSite from pymatgen.symmetry.analyzer import SpacegroupAnalyzer from pymatgen.core.periodic_table import Element import pandas as pd from .ElementKkr import ElementKKR _kkr_bohr = Unit().length_au2ang if False: try: from pymatgen.symmetry import kpath _use_kpath = False except ImportError: print("Warning: no kpath in pymatgen. kpath will be omitted.") _use_kpath = False class _BravaisKKR: dict = { 1: "trc", # triclinic 2: "trc", # triclinic 3: "sm", # simple monoclinic 4: "sm", # simple monoclinic 5: "bsm", # base centered monoclinic 6: "sm", # simple monoclinic 7: "sm", # simple monoclinic 8: "bsm", # base centered monoclinic 9: "bsm", # base centered monoclinic 10: "sm", # simple monoclinic 11: "sm", # simple monoclinic 12: "bsm", # base centered monoclinic 13: "sm", # simple monoclinic 14: "sm", # simple monoclinic 15: "bsm", # base centered monoclinic 16: "so", # simple orthorhombic 17: "so", # simple orthorhombic 18: "so", # simple orthorhombic 19: "so", # simple orthorhombic 20: "bso", # base centered orthorhombic 21: "bso", # base centered orthorhombic 22: "fco", # face centered orthorhombic 23: "bco", # body centered orthorhombic 24: "bco", # body centered orthorhombic 25: "so", # simple orthorhombic 26: "so", # simple orthorhombic 27: "so", # simple orthorhombic 28: "so", # simple orthorhombic 29: "so", # simple orthorhombic 30: "so", # simple orthorhombic 31: "so", # simple orthorhombic 32: "so", # simple orthorhombic 33: "so", # simple orthorhombic 34: "so", # simple orthorhombic 35: "bso", # base centered orthorhombic 36: "bso", # base centered orthorhombic 37: "bso", # base centered orthorhombic 38: "bso", # base centered orthorhombic 39: "bso", # base centered orthorhombic 40: "bso", # base centered orthorhombic 41: "bso", # base centered orthorhombic 42: "fco", # face centered orthorhombic 43: "fco", # face centered orthorhombic 44: "bco", # body centered orthorhombic 45: "bco", # body centered orthorhombic 46: "bco", # body centered orthorhombic 47: "so", # simple orthorhombic 48: "so", # simple orthorhombic 49: "so", # simple orthorhombic 50: "so", # simple orthorhombic 51: "so", # simple orthorhombic 52: "so", # simple orthorhombic 53: "so", # simple orthorhombic 54: "so", # simple orthorhombic 55: "so", # simple orthorhombic 56: "so", # simple orthorhombic 57: "so", # simple orthorhombic 58: "so", # simple orthorhombic 59: "so", # simple orthorhombic 60: "so", # simple orthorhombic 61: "so", # simple orthorhombic 62: "so", # simple orthorhombic 63: "bso", # base centered orthorhombic 64: "bso", # base centered orthorhombic 65: "bso", # base centered orthorhombic 66: "bso", # base centered orthorhombic 67: "bso", # base centered orthorhombic 68: "bso", # base centered orthorhombic 69: "fco", # face centered orthorhombic 70: "fco", # face centered orthorhombic 71: "bco", # body centered orthorhombic 72: "bco", # body centered orthorhombic 73: "bco", # body centered orthorhombic 74: "bco", # body centered orthorhombic 75: "st", # simple tetragonal 76: "st", # simple tetragonal 77: "st", # simple tetragonal 78: "st", # simple tetragonal 79: "bct", # body centered tetragonal 80: "bct", # body centered tetragonal 81: "st", # simple tetragonal 82: "bct", # body centered tetragonal 83: "st", # simple tetragonal 84: "st", # simple tetragonal 85: "st", # simple tetragonal 86: "st", # simple tetragonal 87: "bct", # body centered tetragonal 88: "bct", # body centered tetragonal 89: "st", # simple tetragonal 90: "st", # simple tetragonal 91: "st", # simple tetragonal 92: "st", # simple tetragonal 93: "st", # simple tetragonal 94: "st", # simple tetragonal 95: "st", # simple tetragonal 96: "st", # simple tetragonal 97: "bct", # body centered tetragonal 98: "bct", # body centered tetragonal 99: "st", # simple tetragonal 100: "st", # simple tetragonal 101: "st", # simple tetragonal 102: "st", # simple tetragonal 103: "st", # simple tetragonal 104: "st", # simple tetragonal 105: "st", # simple tetragonal 106: "st", # simple tetragonal 107: "bct", # body centered tetragonal 108: "bct", # body centered tetragonal 109: "bct", # body centered tetragonal 110: "bct", # body centered tetragonal 111: "st", # simple tetragonal 112: "st", # simple tetragonal 113: "st", # simple tetragonal 114: "st", # simple tetragonal 115: "st", # simple tetragonal 116: "st", # simple tetragonal 117: "st", # simple tetragonal 118: "st", # simple tetragonal 119: "bct", # body centered tetragonal 120: "bct", # body centered tetragonal 121: "bct", # body centered tetragonal 122: "bct", # body centered tetragonal 123: "st", # simple tetragonal 124: "st", # simple tetragonal 125: "st", # simple tetragonal 126: "st", # simple tetragonal 127: "st", # simple tetragonal 128: "st", # simple tetragonal 129: "st", # simple tetragonal 130: "st", # simple tetragonal 131: "st", # simple tetragonal 132: "st", # simple tetragonal 133: "st", # simple tetragonal 134: "st", # simple tetragonal 135: "st", # simple tetragonal 136: "st", # simple tetragonal 137: "st", # simple tetragonal 138: "st", # simple tetragonal 139: "bct", # body centered tetragonal 140: "bct", # body centered tetragonal 141: "bct", # body centered tetragonal 142: "bct", # body centered tetragonal 143: "hcp", # hexagonal close packed 144: "hcp", # hexagonal close packed 145: "hcp", # hexagonal close packed 146: "rhb", # rhombohedral(trigonal) 147: "hcp", # hexagonal close packed 148: "rhb", # rhombohedral(trigonal) 149: "hcp", # hexagonal close packed 150: "hcp", # hexagonal close packed 151: "hcp", # hexagonal close packed 152: "hcp", # hexagonal close packed 153: "hcp", # hexagonal close packed 154: "hcp", # hexagonal close packed 155: "rhb", # rhombohedral(trigonal) 156: "hcp", # hexagonal close packed 157: "hcp", # hexagonal close packed 158: "hcp", # hexagonal close packed 159: "hcp", # hexagonal close packed 160: "rhb", # rhombohedral(trigonal) 161: "rhb", # rhombohedral(trigonal) 162: "hcp", # hexagonal close packed 163: "hcp", # hexagonal close packed 164: "hcp", # hexagonal close packed 165: "hcp", # hexagonal close packed 166: "rhb", # rhombohedral(trigonal) 167: "rhb", # rhombohedral(trigonal) 168: "hcp", # hexagonal close packed 169: "hcp", # hexagonal close packed 170: "hcp", # hexagonal close packed 171: "hcp", # hexagonal close packed 172: "hcp", # hexagonal close packed 173: "hcp", # hexagonal close packed 174: "hcp", # hexagonal close packed 175: "hcp", # hexagonal close packed 176: "hcp", # hexagonal close packed 177: "hcp", # hexagonal close packed 178: "hcp", # hexagonal close packed 179: "hcp", # hexagonal close packed 180: "hcp", # hexagonal close packed 181: "hcp", # hexagonal close packed 182: "hcp", # hexagonal close packed 183: "hcp", # hexagonal close packed 184: "hcp", # hexagonal close packed 185: "hcp", # hexagonal close packed 186: "hcp", # hexagonal close packed 187: "hcp", # hexagonal close packed 188: "hcp", # hexagonal close packed 189: "hcp", # hexagonal close packed 190: "hcp", # hexagonal close packed 191: "hcp", # hexagonal close packed 192: "hcp", # hexagonal close packed 193: "hcp", # hexagonal close packed 194: "hcp", # hexagonal close packed 195: "sc", # simple cubic 196: "fcc", # face centered cubic 197: "bcc", # body centered cubic 198: "sc", # simple cubic 199: "bcc", # body centered cubic 200: "sc", # simple cubic 201: "sc", # simple cubic 202: "fcc", # face centered cubic 203: "fcc", # face centered cubic 204: "bcc", # body centered cubic 205: "sc", # simple cubic 206: "bcc", # body centered cubic 207: "sc", # simple cubic 208: "sc", # simple cubic 209: "fcc", # face centered cubic 210: "fcc", # face centered cubic 211: "bcc", # body centered cubic 212: "sc", # simple cubic 213: "sc", # simple cubic 214: "bcc", # body centered cubic 215: "sc", # simple cubic 216: "fcc", # face centered cubic 217: "bcc", # body centered cubic 218: "sc", # simple cubic 219: "fcc", # face centered cubic 220: "bcc", # body centered cubic 221: "sc", # simple cubic 222: "sc", # simple cubic 223: "sc", # simple cubic 224: "sc", # simple cubic 225: "fcc", # face centered cubic 226: "fcc", # face centered cubic 227: "fcc", # face centered cubic 228: "fcc", # face centered cubic 229: "bcc", # body centered cubic 230: "bcc", # body centered cubic } @staticmethod def getType(group): if group in _BravaisKKR.dict: return _BravaisKKR.dict[group] else: return "aux" class _TranslationKKR: matrix = { "sc": np.array([[+1.0, 0.0, 0.0], [0.0, +1.0, 0.0], [0.0, 0.0, +1.0]]), "fcc": np.array([[0.0, 0.5, 0.5], [0.5, 0.0, 0.5], [0.5, 0.5, 0.0]]), "bcc": np.array([[-0.5, 0.5, 0.5], [0.5, -0.5, 0.5], [0.5, 0.5, -0.5]]), "hcp": np.array([[+1.0, 0.0, 0.0], [0.0, +1.0, 0.0], [0.0, 0.0, +1.0]]), "rhb": np.array([[2.0, 1.0, 1.0], [-1.0, 1.0, 1.0], [-1.0, -2.0, 1.0]])/3.0, "st": np.array([[+1.0, 0.0, 0.0], [0.0, +1.0, 0.0], [0.0, 0.0, +1.0]]), "bct": np.array([[-0.5, 0.5, 0.5], [0.5, -0.5, 0.5], [0.5, 0.5, -0.5]]), "so": np.array([[+1.0, 0.0, 0.0], [0.0, +1.0, 0.0], [0.0, 0.0, +1.0]]), "fco": np.array([[0.0, 0.5, 0.5], [0.5, 0.0, 0.5], [0.5, 0.5, 0.0]]), "bco":
np.array([[-0.5, 0.5, 0.5], [0.5, -0.5, 0.5], [0.5, 0.5, -0.5]])
numpy.array
import numpy as np import scipy.stats import copy from astropy.tests.helper import pytest from astropy.modeling import models from scipy.special import gammaln as scipy_gammaln from stingray import Lightcurve, Powerspectrum from stingray.modeling import Posterior, PSDPosterior, \ PoissonPosterior, GaussianPosterior, LaplacePosterior from stingray.modeling import set_logprior from stingray.modeling.posterior import logmin from stingray.modeling.posterior import IncorrectParameterError from stingray.modeling.posterior import LogLikelihood np.random.seed(20150907) class TestMeta(object): def test_use_loglikelihood_class_directly(self): with pytest.raises(TypeError): a = LogLikelihood(1, 2, models.Lorentz1D) def test_inherit_loglikelihood_improperly(self): class a(LogLikelihood): def __init__(self, *args, **kwargs): LogLikelihood.__init__(self, *args, **kwargs) with pytest.raises(TypeError): a(1, 2, models.Lorentz1D) def test_inherit_loglikelihood_properly(self): class a(LogLikelihood): def __init__(self, *args, **kwargs): LogLikelihood.__init__(self, *args, **kwargs) def evaluate(self, parameters): pass a(1, 2, models.Lorentz1D) class TestSetPrior(object): @classmethod def setup_class(cls): photon_arrivals = np.sort(np.random.uniform(0,1000, size=10000)) cls.lc = Lightcurve.make_lightcurve(photon_arrivals, dt=1.0) cls.ps = Powerspectrum(cls.lc, norm="frac") pl = models.PowerLaw1D() pl.x_0.fixed = True cls.lpost = PSDPosterior(cls.ps.freq, cls.ps.power, pl, m=cls.ps.m) def test_set_prior_runs(self): p_alpha = lambda alpha: ((-1. <= alpha) & (alpha <= 5.))/6.0 p_amplitude = lambda amplitude: ((-10 <= np.log(amplitude)) & ((
np.log(amplitude)
numpy.log
""" """ import csv import datetime import gzip import os import time import numpy as np import tensorflow as tf import qdraw.dataset as dataset import qdraw.dataset_iterator as dataset_iterator def build_model(data): """ """ FLAGS = tf.app.flags.FLAGS # NOTE: choose model if FLAGS.model == 'mobilenets': import qdraw.model_mobilenets as chosen_model elif FLAGS.model == 'mobilenets_v2': import qdraw.model_mobilenets_v2 as chosen_model elif FLAGS.model == 'resnet': import qdraw.model_resnet as chosen_model elif FLAGS.model == 'blind': import qdraw.model_blind as chosen_model elif FLAGS.model == 'null': import qdraw.model_null as chosen_model # NOTE: step = tf.train.get_or_create_global_step() # NOTE: training = tf.placeholder(shape=[], dtype=tf.bool) # NOTE: learning_rate = tf.placeholder(shape=[], dtype=tf.float32) # NOTE: if FLAGS.optimizer == 'adam': optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate) elif FLAGS.optimizer == 'nesterov': optimizer = tf.train.MomentumOptimizer( learning_rate=learning_rate, momentum=0.9, use_nesterov=True) # keyids, images, strokes, lengths, recognized, labels = \ data['iterator'].get_next() model = chosen_model.build_model( images, strokes, lengths, labels, training) update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS) new_model = { 'keyids': keyids, 'images': images, 'strokes': strokes, 'lengths': lengths, 'recognized': recognized, 'labels': labels, 'step': step, 'training': training, 'learning_rate': learning_rate, 'dataset_handle': data['dataset_handle'], 'loss': model['loss'], 'logits': model['logits'], 'swa': [], } # NOTE: helper function to create a placeholder for a variable def placeholder(g): return tf.placeholder(shape=g.shape, dtype=g.dtype) with tf.control_dependencies(update_ops): gradients_and_vars = optimizer.compute_gradients(model['loss']) # NOTE: if cyclic_batch_size_multiplier_max is great than 1, we will do # gradients aggregation later # NOTE: an operator to collect computed gradients new_model['gradients_result'] = [g for g, v in gradients_and_vars] gradients_and_vars = [(placeholder(g), v) for g, v in gradients_and_vars] # NOTE: an operator to feed manipulated gradients new_model['gradients_source'] = [g for g, v in gradients_and_vars] new_model['optimizer'] = \ optimizer.apply_gradients(gradients_and_vars, global_step=step) # NOTE: Averaging Weights Leads to Wider Optima and Better # Generalization, 3.2 batch normalization # for updating training variables' running averaging if FLAGS.swa_enable: for variable in tf.trainable_variables(): ph = placeholder(variable) new_model['swa'].append({ 'variable': variable, 'placeholder': ph, 'var_op': tf.assign(variable, ph), 'amount': 0.0, 'swa_weights': 0.0, 'tmp_weights': 0.0}) return new_model def train(session, experiment): """ """ FLAGS = tf.app.flags.FLAGS model = experiment['model'] step = session.run(model['step']) # NOTE: learning rate interpolation for cyclic training lr_min = FLAGS.cyclic_learning_rate_min lr_max = FLAGS.cyclic_learning_rate_max alpha = (step % FLAGS.cyclic_num_steps) / (FLAGS.cyclic_num_steps - 1) learning_rate = lr_max + (lr_min - lr_max) * alpha # NOTE: feeds for training feeds = { model['dataset_handle']: experiment['data']['train_handle'], model['learning_rate']: learning_rate, model['training']: True, } # NOTE: if cyclic_batch_size_multiplier_max is great than 1, we want to do # gradients aggregation # NOTE: batch multiplier interpolation for cyclic training scale_min = FLAGS.cyclic_batch_size_multiplier_min scale_max = FLAGS.cyclic_batch_size_multiplier_max # NOTE: assume FLAGS.cyclic_num_steps being far freater then scale beta = FLAGS.cyclic_num_steps // (scale_max - scale_min + 1) batch_multiplier = scale_min + (step % FLAGS.cyclic_num_steps) // beta all_gradients = [] losses = 0.0 # NOTE: compute gradients on nano batches for i in range(batch_multiplier): loss, gradients = session.run( [model['loss'], model['gradients_result']], feed_dict=feeds) losses += loss all_gradients.append(gradients) # NOTE: aggregate & apply gradients feeds = { model['learning_rate']: learning_rate, } for i, gradients_source in enumerate(model['gradients_source']): gradients =
np.stack([g[i] for g in all_gradients], axis=0)
numpy.stack
""" Some handy utility functions used by the other modules. """ from copy import deepcopy import numpy as np def centres_to_edges(centres): "Assuming centres is regularly spaced, return bin edges" dx = centres[1] - centres[0] return np.linspace(centres[0] - dx / 2, centres[-1] + dx / 2, len(centres) + 1) def numerical_jac(func, args, dx=1e-5): if np.isscalar(dx): dx = np.repeat(dx, len(args)) y0 = func(args) out = [0] * len(args) args = list(args) for i in range(len(args)): args[i] += dx[i] yy = func(args) out[i] = (yy - y0) / dx[i] args[i] -= dx[i] return
np.array(out)
numpy.array
# flake8: noqa from pkg_resources import resource_filename from functools import lru_cache import warnings import numpy as np from ...matlab_funcs import besselh, besselj, gammaln, lscov, quadl from ...sci_funcs import legendrePlm from ...core import stress2legendre def boundary(costheta, a=1, epsilon=.1, nu=0): """Projected boundary of a prolate spheroid Compute the boundary according to equation (4) in :cite:`Boyde2009` with the addition of the Poisson's ratio of the object. .. math:: B(\\theta) = a (1+\\epsilon) \\left[ (1+\\epsilon)^2 - \\epsilon (1+\\nu) (2+\\epsilon (1-\\nu)) \\cos^2 \\theta \\right]^{-1/2} This boundary function was derived for a prolate spheroid under the assumption that the semi-major axis :math:`a` and the semi-minor axes :math:`b=c` are defined as .. math:: a = b \\cdot \\frac{1+ \\epsilon}{1- \\nu \\epsilon} The boundary function :math:`B(\\theta)` can be derived with the above relation using the equation for a prolate spheroid. Parameters ---------- costheta: float or np.ndarray Cosine of polar coordinates :math:`\\theta` at which to compute the boundary. a: float Equatorial radii of prolate spheroid (semi-minor axis). epsilon: float Stretch ratio; defines size of semi-major axis: :math:`a = (1+\\epsilon) b`. Note that this is not the eccentricity of the prolate spheroid. nu: float Poisson's ratio :math:`\\nu` of the material. Returns ------- B: 1d ndarray Radial object boundary in dependence of theta :math:`B(\\theta)`. Notes ----- For :math:`\\nu=0`, the above equation becomes equation (4) in :cite:`Boyde2009`. """ x = costheta B = a * (1 + epsilon) \ / ((1 + epsilon)**2 - epsilon * (1 + nu) * (2 + epsilon * (1 - nu)) * x**2)**.5 return B @lru_cache(maxsize=32) def get_hgc(): """Load hypergeometric coefficients from *hypergeomdata2.dat*. These coefficients were computed by <NAME> using Wolfram Mathematica. """ hpath = resource_filename("ggf.stress.boyde2009", "hypergeomdata2.dat") hgc = np.loadtxt(hpath) return hgc def stress(object_index=1.41, medium_index=1.3465, poisson_ratio=0.45, semi_minor=2.8466e-6, stretch_ratio=0.1, wavelength=780e-9, beam_waist=3, power_left=.6, power_right=.6, dist=100e-6, n_points=100, theta_max=np.pi, field_approx="davis", ret_legendre_decomp=False, verbose=False): """Compute the stress acting on a prolate spheroid The prolate spheroid has semi-major axis :math:`a` and semi-minor axis :math:`b=c`. Parameters ---------- object_index: float Refractive index of the spheroid medium_index: float Refractive index of the surrounding medium poisson_ratio: float Poisson's ratio of the spheroid material semi_minor: float Semi-minor axis (inner) radius of the stretched object :math:`b=c`. stretch_ratio: float Measure of the deformation, defined as :math:`(a - b) / b` wavelength: float Wavelenth of the gaussian beam [m] beam_waist: float Beam waist radius of the gaussian beam [wavelengths] power_left: float Laser power of the left beam [W] power_right: float Laser power of the right beam [W] dist: float Distance between beam waist and object center [m] n_points: int Number of points to compute stresses for theta_max: float Maximum angle to compute stressed for field_approx: str TODO ret_legendre_decomp: bool If True, return coefficients of decomposition of stress into Legendre polynomials verbose: int Increase verbosity Returns ------- theta: 1d ndarray Angles for which stresses are computed sigma_rr: 1d ndarray Radial stress corresponding to angles coeff: 1d ndarray If `ret_legendre_decomp` is True, return compositions of decomposition of stress into Legendre polynomials. Notes ----- - The angles `theta` are computed on a grid that does not include zero and `theta_max`. - This implementation was first presented in :cite:`Boyde2009`. """ if field_approx not in ["davis", "barton"]: raise ValueError("`field_approx` must be 'davis' or 'barton'") object_index = complex(object_index) medium_index = complex(medium_index) W0 = beam_waist * wavelength epsilon = stretch_ratio nu = poisson_ratio # ZRL = 0.5*medium_index*2*np.pi/wavelength*W0**2 # Rayleigh range [m] # WZ = W0*(1+(beam_pos+d)**2/ZRL**2)**0.5 # beam waist at specified # position [m] K0 = 2 * np.pi / wavelength # wave vector [m] Alpha = semi_minor * K0 # size parameter C = 3e8 # speed of light [m/s] # maximum number of orders lmax = np.int(np.round(2 + Alpha + 4 * (Alpha)**(1 / 3) + 10)) if lmax > 120: msg = 'Required number of orders for accurate expansion exceeds allowed maximum!' \ + 'Reduce size of trapped particle!' raise ValueError(msg) if epsilon == 0: # spherical object, no point-matching needed (mmax = 0) mmax = 3 else: if (epsilon > 0.15): warnings.warn('Stretching ratio is high: {}'.format(epsilon)) # spheroidal object, point-matching required (mmax has to be divisible # by 3) mmax = 6 * lmax # permittivity in surrounding medium [1] EpsilonI = medium_index**2 EpsilonII = object_index**2 # permittivity in within cell [1] MuI = 1.000 # permeability in surrounding medium [1] MuII = 1.000 # permeability within cell [1] # wave constant in Maxwell's equations (surrounding medium) [1/m] K1I = 1j * K0 * EpsilonI # wave constant in Maxwell's equations (within cell) [1/m] K1II = 1j * K0 * EpsilonII # wave constant in Maxwell's equations (surrounding medium) [1/m] K2I = 1j * K0 # wave constant in Maxwell's equations (within cell) [1/m] K2II = 1j * K0 KI = (-K1I * K2I)**0.5 # wave vector (surrounding medium) [1/m] KII = (-K1II * K2II)**0.5 # wave vector (within cell) [1/m] # dimensionless parameters k0 = 1 # wave vector a = semi_minor * K0 # internal radius of stretched cell d = dist * K0 # distance from cell centre to optical stretcher # ap = a*(1+stretch_ratio) # semi-major axis (after stretching) # bp = a*(1-poisson_ratio*stretch_ratio) # semi-minor axis (after # stretching) w0 = W0 * K0 # Gaussian width # wave constant in Maxwell's equations (surrounding medium) k1I = K1I / K0 # wave constant in Maxwell's equations (within cell) k1II = K1II / K0 # wave constant in Maxwell's equations (surrounding medium) k2I = K2I / K0 # wave constant in Maxwell's equations (within cell) k2II = K2II / K0 kI = KI / K0 # wave vector (surrounding medium) kII = KII / K0 # wave vector (within cell) beta = kI # wave vector of Gaussian beam # other definitions # amplitude of electric field of left laser [kg m/(s**2 C)] EL = np.sqrt(power_left / (medium_index * C * W0**2)) # amplitude of electric field of right laser [kg m/(s**2 C)] ER = np.sqrt(power_right / (medium_index * C * W0**2)) HL = beta / k0 * EL # left laser amplitude of magnetic field HR = beta / k0 * ER # right laser amplitude of magnetic field zR = beta * w0**2 / 2 # definition of Rayleigh range S = (1 + 1j * d / zR)**(-1) # complex amplitude for Taylor expansion s = 1 / (beta * w0) # expansion parameter for Gaussian (Barton) # Functions # object boundary function: r(th) = a*B1(x) x= cos(th) def B1(x): return boundary(costheta=x, a=1, epsilon=epsilon, nu=nu) # Riccati Bessel functions and their derivatives # Riccati Bessel function (psi) def psi(l, z): return (np.pi / 2 * z)**(1 / 2) * besselj(l + 1 / 2, z) def psi1(l, z): return (np.pi / (2. * z))**(1 / 2) * \ (z * besselj(l - 1 / 2, z) - l * besselj(l + 1 / 2, z)) # first derivative (psi') def psi2(l, z): return (np.pi / 2)**(1 / 2) * (l + l**2 - z**2) * \ besselj(l + 1 / 2, z) * z**(-3 / 2) # second derivative (psi'') # First order Taylor expansion of psi is too inaccurate for larger values of k*a*Eps. # Hence, to match 1-st and higher order terms in Eps, subtract the 0-th order terms (no angular dependence) # from the exact function psi (including angular dependence) # Riccati Bessel function excluding angular dependence in 0-th order # (psiex) def psiex(l, z, x): return psi(l, z * B1(x)) - psi(l, z) def psi1ex(l, z, x): return psi1(l, z * B1(x)) - \ psi1(l, z) # first derivative of psiex def psi2ex(l, z, x): return psi2(l, z * B1(x)) - \ psi2(l, z) # second derivative of psi # defined for abbreviation def psixx(l, z, x): return psi(l, z * B1(x)) def psi1xx(l, z, x): return psi1(l, z * B1(x)) def psi2xx(l, z, x): return psi2(l, z * B1(x)) # Hankel function and its derivative def xi(l, z): return (np.pi / 2 * z)**(1 / 2) * besselh(l + 1 / 2, z) def xi1(l, z): return (np.pi / (2 * z))**(1 / 2) * \ ((l + 1) * besselh(l + 1 / 2, z) - z * besselh(l + 3 / 2, z)) def xi2(l, z): return (np.pi / 2)**(1 / 2) / \ z**(3 / 2) * (l + l**2 - z**2) * besselh(l + 1 / 2, z) # Comments: see above for psiex def xiex(l, z, x): return xi(l, z * B1(x)) - xi(l, z) def xi1ex(l, z, x): return xi1(l, z * B1(x)) - xi1(l, z) def xi2ex(l, z, x): return xi2(l, z * B1(x)) - xi2(l, z) def xixx(l, z, x): return xi(l, z * B1(x)) def xi1xx(l, z, x): return xi1(l, z * B1(x)) def xi2xx(l, z, x): return xi2(l, z * B1(x)) #% Associated Legendre functions P(m)_l(x) and their derivatives #% select mth component of vector 'legendre' [P**(m)_l(x)] # [zeros(m,1);1;zeros(l-m,1)].'*legendre(l,x) #% legendre polynomial [P**(m)_l(x)] def legendrePl(l, x): return legendrePlm(1, l, x) #% legendre polynomial [P**(1)_l(x)] def legendrePlm1(m, l, x): return ( (l - m + 1.) * legendrePlm(m, l + 1, x) - (l + 1.) * x * legendrePlm(m, l, x)) / (x**2 - 1) #% derivative d/dx[P**(m)_l(x)] def legendrePl1(l, x): return legendrePlm1(1, l, x) # defined to avoid division by zero (which can occur for x=1 in # legendrePl1... def legendrePlmex1(m, l, x): return -((l - m + 1) * legendrePlm(m, l + 1, x) - (l + 1) * x * legendrePlm(m, l, x)) def legendrePlex1(l, x): return legendrePlmex1(1, l, x) # Hypergeometric and Gamma functions hypergeomcoeff = get_hgc() ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## # Gaussian beam (incident fields) - in Cartesian basis (either Davis first order or Barton fifth order fields) # electric and magnetic fields according to Davis (first order) if field_approx == "davis": # left def eExiL(r, th, phi): return EL * (1 + 1j * (r * np.cos(th) + d) / zR)**(-1) * np.exp(-r**2 * np.sin(th)**2 / (w0**2 * (1 + 1j * (r * np.cos(th) + d) / zR))) * np.exp(1j * beta * (r * np.cos(th) + d)) def eEyiL(r, th, phi): return 0 def eEziL(r, th, phi): return -1j * (1 + 1j * (r * np.cos(th) + d) / zR)**(-1) * r * np.sin(th) * np.cos(phi) / zR * eExiL(r, th, phi) def eHxiL(r, th, phi): return 0 def eHyiL(r, th, phi): return HL * (1 + 1j * (r * np.cos(th) + d) / zR)**(-1) * np.exp(-r**2 * np.sin(th)**2 / (w0**2 * (1 + 1j * (r * np.cos(th) + d) / zR))) * np.exp(1j * beta * (r * np.cos(th) + d)) def eHziL(r, th, phi): return -1j * (1 + 1j * (r * np.cos(th) + d) / zR)**(-1) * r * np.sin(th) * np.sin(phi) / zR * eHyiL(r, th, phi) # right def eExiR(r, th, phi): return ER * (1 - 1j * (r * np.cos(th) - d) / zR)**(-1) * np.exp(-r**2 * np.sin(th)**2 / (w0**2 * (1 - 1j * (r * np.cos(th) - d) / zR))) * np.exp(-1j * beta * (r * np.cos(th) - d)) def eEyiR(r, th, phi): return 0 def eEziR(r, th, phi): return +1j * (1 - 1j * (r * np.cos(th) - d) / zR)**(-1) * r * np.sin(th) * np.cos(phi) / zR * eExiR(r, th, phi) def eHxiR(r, th, phi): return 0 def eHyiR(r, th, phi): return -HR * (1 - 1j * (r * np.cos(th) - d) / zR)**(-1) * np.exp(-r**2 * np.sin(th)**2 / (w0**2 * (1 - 1j * (r *
np.cos(th)
numpy.cos
""" MesoNet Authors: <NAME> and <NAME>, <NAME> https://github.com/bf777/MesoNet Licensed under the Creative Commons Attribution 4.0 International License (see LICENSE for details) This file has been adapted from data.py in https://github.com/zhixuhao/unet """ from __future__ import print_function from tensorflow.keras.preprocessing.image import ImageDataGenerator import numpy as np import os import skimage.io as io import skimage.transform as trans def adjustData(img, mask, flag_multi_class, num_class): if flag_multi_class: img = img / 255 mask = mask[:, :, :, 0] if (len(mask.shape) == 4) else mask[:, :, 0] new_mask =
np.zeros(mask.shape + (num_class,))
numpy.zeros
from .COAsT import COAsT # ??? import numpy as np import xarray as xr from .logging_util import get_slug, debug, error, info import sklearn.metrics as metrics from . import general_utils, plot_util, crps_util class ALTIMETRY(COAsT): ''' An object for reading, storing and manipulating altimetry data. Currently the object contains functionality for reading altimetry netCDF data from the CMEMS database. This is the default for initialisation. Data should be stored in an xarray.Dataset, in the form: * Date Format Overview * 1. A single dimension (time). 2. Three coordinates: time, latitude, longitude. All lie on the 't_dim' dimension. 3. Observed variable DataArrays on the t_dim dimension. There are currently no naming conventions for the variables however examples from the CMEMS database include sla_filtered, sla_unfiltered and mdt (mean dynamic topography). * Methods Overview * *Initialisation and File Reading* -> __init__(): Initialises an ALTIMETRY object. -> read_cmems(): Reads data from a CMEMS netCDF file. *Plotting* -> quick_plot(): Makes a quick along-track plot of specified data. *Model Comparison* -> obs_operator(): For interpolating model data to this object. -> cprs(): Calculates the CRPS between a model and obs variable. -> difference(): Differences two specified variables -> absolute_error(): Absolute difference, two variables -> mean_absolute_error(): MAE between two variables -> root_mean_square_error(): RMSE between two variables -> time_mean(): Mean of a variable in time -> time_std(): St. Dev of a variable in time -> time_correlation(): Correlation between two variables -> time_covariance(): Covariance between two variables -> basic_stats(): Calculates multiple of the above metrics. ''' ############################################################################## ### ~ Initialisation and File Reading ~ ### ############################################################################## def __init__(self, file=None, chunks: dict=None, multiple=False): debug(f"Creating a new {get_slug(self)}") if file is not None: self.read_cmems(file, chunks, multiple) else: self.dataset = None debug(f"{get_slug(self)} initialised") return def read_cmems(self, file, chunks, multiple): ''' Reads altimetry data from a CMEMS netcdf file. Calls COAsT.init() to make use of its load methods''' super().__init__(file, chunks, multiple) self.dataset = self.dataset.rename_dims(self.dim_mapping) #self.dataset.attrs = {} def set_dimension_mapping(self): self.dim_mapping = {'time': 't_dim'} debug(f"{get_slug(self)} dim_mapping set to {self.dim_mapping}") def set_variable_mapping(self): self.var_mapping = None debug(f"{get_slug(self)} var_mapping set to {self.var_mapping}") def subset_indices_lonlat_box(self, lonbounds, latbounds): """Generates array indices for data which lies in a given lon/lat box. Keyword arguments: lon -- Longitudes, 1D or 2D. lat -- Latitudes, 1D or 2D lonbounds -- Array of form [min_longitude=-180, max_longitude=180] latbounds -- Array of form [min_latitude, max_latitude] return: Indices corresponding to datapoints inside specified box """ debug(f"Subsetting {get_slug(self)} indices in {lonbounds}, {latbounds}") lon = self.dataset.longitude.copy() lat = self.dataset.latitude lon[lon>180] = lon[lon>180] - 360 lon[lon<-180] = lon[lon<-180] + 360 ff1 = ( lon > lonbounds[0] ).astype(int) # FIXME This should fail? We can just treat bools as ints here... ff2 = ( lon < lonbounds[1] ).astype(int) ff3 = ( lat > latbounds[0] ).astype(int) ff4 = ( lat < latbounds[1] ).astype(int) indices = np.where( ff1 * ff2 * ff3 * ff4 ) return indices[0] ############################################################################## ### ~ Plotting ~ ### ############################################################################## def quick_plot(self, color_var_str: str=None): ''' ''' if color_var_str is not None: color_var = self.dataset[color_var_str] title = color_var_str else: color_var = None title = 'Altimetry observation locations' info("Drawing a quick plot...") fig, ax = plot_util.geo_scatter(self.dataset.longitude, self.dataset.latitude, c=color_var, title=title ) info("Plot ready, displaying!") return fig, ax ############################################################################## ### ~ Model Comparison ~ ### ############################################################################## def obs_operator(self, model, mod_var_name:str, time_interp = 'nearest', model_mask=None): ''' For interpolating a model dataarray onto altimetry locations and times. For ALTIMETRY, the interpolation is done independently in two steps: 1. Horizontal space 2. Time Model data is taken at the surface if necessary (0 index). Example usage: -------------- altimetry.obs_operator(nemo_obj, 'sossheig') Parameters ---------- model : model object (e.g. NEMO) mod_var: variable name string to use from model object time_interp: time interpolation method (optional, default: 'nearest') This can take any string scipy.interpolate would take. e.g. 'nearest', 'linear' or 'cubic' model_mask : Mask to apply to model data in geographical interpolation of model. For example, use to ignore land points. If None, no mask is applied. If 'bathy', model variable (bathymetry==0) is used. Custom 2D mask arrays can be supplied. Returns ------- Adds a DataArray to self.dataset, containing interpolated values. ''' debug(f"Interpolating {get_slug(model)} \"{mod_var_name}\" with time_interp \"{time_interp}\"") # Determine mask if model_mask=='bathy': model_mask = model.dataset.bathymetry.values==0 # Get data arrays mod_var_array = model.dataset[mod_var_name] # Get data arrays mod_var = model.dataset[mod_var_name] # Depth interpolation -> for now just take 0 index if 'z_dim' in mod_var.dims: mod_var = mod_var.isel(z_dim=0).squeeze() # Cast lat/lon to numpy arrays obs_lon = np.array(self.dataset.longitude).flatten() obs_lat = np.array(self.dataset.latitude).flatten() interpolated = model.interpolate_in_space(mod_var, obs_lon, obs_lat) # Interpolate in time if t_dim exists in model array if 't_dim' in mod_var.dims: interpolated = model.interpolate_in_time(interpolated, self.dataset.time, interp_method=time_interp) # Take diagonal from interpolated array (which contains too many points) diag_len = interpolated.shape[0] diag_ind = xr.DataArray(np.arange(0, diag_len)) interpolated = interpolated.isel(interp_dim=diag_ind, t_dim=diag_ind) interpolated = interpolated.swap_dims({'dim_0':'t_dim'}) # Store interpolated array in dataset new_var_name = 'interp_' + mod_var_name self.dataset[new_var_name] = interpolated def crps(self, model_object, model_var_name, obs_var_name, nh_radius: float = 20, time_interp:str='linear', create_new_object = True): ''' Comparison of observed variable to modelled using the Continuous Ranked Probability Score. This is done using this ALTIMETRY object. This method specifically performs a single-observation neighbourhood- forecast method. Parameters ---------- model_object (model) : Model object (NEMO) containing model data model_var_name (str) : Name of model variable to compare. obs_var_name (str) : Name of observed variable to compare. nh_radius (float) : Neighbourhood radius (km) time_interp (str) : Type of time interpolation to use (s) create_new_obj (bool): If True, save output to new ALTIMETRY obj. Otherwise, save to this obj. Returns ------- xarray.Dataset containing times, sealevel and quality control flags Example Useage ------- # Compare modelled 'sossheig' with 'sla_filtered' using CRPS crps = altimetry.crps(nemo, 'sossheig', 'sla_filtered') ''' mod_var = model_object.dataset[model_var_name] obs_var = self.dataset[obs_var_name] crps_list, n_model_pts, contains_land = crps_util.crps_sonf_moving( mod_var, obs_var.longitude.values, obs_var.latitude.values, obs_var.values, obs_var.time.values, nh_radius, time_interp ) if create_new_object: new_object = ALTIMETRY() new_dataset = self.dataset[['longitude','latitude','time']] new_dataset['crps'] = (('t_dim'),crps_list) new_dataset['crps_n_model_pts'] = (('t_dim'), n_model_pts) new_dataset['crps_contains_land'] = (('t_dim'), contains_land) new_object.dataset = new_dataset return new_object else: self.dataset['crps'] = (('t_dim'),crps_list) self.dataset['crps_n_model_pts'] = (('t_dim'), n_model_pts) self.dataset['crps_contains_land'] = (('t_dim'), contains_land) def difference(self, var_str0:str, var_str1:str, date0=None, date1=None): ''' Difference two variables defined by var_str0 and var_str1 between two dates date0 and date1. Returns xr.DataArray ''' var0 = self.dataset[var_str0] var1 = self.dataset[var_str1] var0 = general_utils.dataarray_time_slice(var0, date0, date1).values var1 = general_utils.dataarray_time_slice(var1, date0, date1).values diff = var0 - var1 return xr.DataArray(diff, dims='t_dim', name='error', coords={'time':self.dataset.time}) def absolute_error(self, var_str0, var_str1, date0=None, date1=None): ''' Absolute difference two variables defined by var_str0 and var_str1 between two dates date0 and date1. Return xr.DataArray ''' var0 = self.dataset[var_str0] var1 = self.dataset[var_str1] var0 = general_utils.dataarray_time_slice(var0, date0, date1).values var1 = general_utils.dataarray_time_slice(var1, date0, date1).values adiff = np.abs(var0 - var1) return xr.DataArray(adiff, dims='t_dim', name='absolute_error', coords={'time':self.dataset.time}) def mean_absolute_error(self, var_str0, var_str1, date0=None, date1=None): ''' Mean absolute difference two variables defined by var_str0 and var_str1 between two dates date0 and date1. Return xr.DataArray ''' var0 = self.dataset[var_str0] var1 = self.dataset[var_str1] var0 = general_utils.dataarray_time_slice(var0, date0, date1).values var1 = general_utils.dataarray_time_slice(var1, date0, date1).values mae = metrics.mean_absolute_error(var0, var1) return mae def root_mean_square_error(self, var_str0, var_str1, date0=None, date1=None): ''' Root mean square difference two variables defined by var_str0 and var_str1 between two dates date0 and date1. Return xr.DataArray ''' var0 = self.dataset[var_str0] var1 = self.dataset[var_str1] var0 = general_utils.dataarray_time_slice(var0, date0, date1).values var1 = general_utils.dataarray_time_slice(var1, date0, date1).values rmse = metrics.mean_squared_error(var0, var1) return np.sqrt(rmse) def time_mean(self, var_str, date0=None, date1=None): ''' Time mean of variable var_str between dates date0, date1''' var = self.dataset[var_str] var = general_utils.dataarray_time_slice(var, date0, date1) return
np.nanmean(var)
numpy.nanmean
import numpy as np import scipy.spatial.distance as spatial from numpy import linalg as LA def get_dim(edgelist): """Given an adjacency list for a graph, returns the number of nodes in the graph. """ node_dict = {} node_count = 0 for edge in edgelist: p, q = edge[ :2] if p not in node_dict: node_dict[p] = True node_count += 1 if q not in node_dict: node_dict[q] = True node_count += 1 return node_count def densify(edgelist, dim = None, directed = False): """Given an adjacency list for the graph, computes the adjacency matrix. """ if dim is None: dim = get_dim(edgelist) A = np.zeros((dim, dim), dtype = np.double) for edge in edgelist: p, q, wt = edge A[p, q] = wt if not directed: A[q, p] = wt return A def compute_pinverse_diagonal(D): D_i = D.copy() for i in range(D_i.shape[0]): D_i[i, i] = 1 / D[i, i] if D[i, i] != 0 else 0 return D_i def compute_X_normalized(A, D, t = -1, lm = 1, is_normalized = True): D_i = compute_pinverse_diagonal(D) P = np.matmul(D_i, A) Identity = np.identity(A.shape[0]) e = np.ones((A.shape[0], 1)) # Compute W scale = np.matmul(e.T, np.matmul(D, e))[0, 0] W = np.multiply(1 / scale, np.matmul(e, np.matmul(e.T, D))) up_P =
np.multiply(lm, P - W)
numpy.multiply
# An implementation of Experience Replay (ER) with reservoir sampling and without using tasks from Algorithm 4 of https://openreview.net/pdf?id=B1gTShAct7 # Copyright 2019-present, IBM Research # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import torch import torch.nn as nn import torch.optim as optim from torch.autograd import Variable import numpy as np from .common import MLP, ResNet18 import random from torch.nn.modules.loss import CrossEntropyLoss from random import shuffle import sys import warnings warnings.filterwarnings("ignore") class Net(nn.Module): def __init__(self, n_inputs, n_outputs, n_tasks, args): super(Net, self).__init__() self.args = args nl, nh = args.n_layers, args.n_hiddens self.net_o = MLP([n_inputs] + [nh] * nl + [n_outputs]) self.net_n = MLP([n_inputs] + [nh] * nl + [n_outputs]) self.bce = CrossEntropyLoss() self.mse = nn.MSELoss() self.l1 = nn.L1Loss() self.n_outputs = n_outputs self.opt = optim.SGD(self.net_n.parameters(), args.lr) self.batchSize = int(args.replay_batch_size) self.memories = args.memories # allocate buffer self.M = [] self.age = 0 # handle gpus if specified self.cuda = args.cuda if self.cuda: self.net_n = self.net_n.cuda() self.net_o = self.net_o.cuda() def forward(self, x, t): output = self.net_n(x) return output, None def getBatch(self,x,y,t): mxi = np.array(x) myi = np.array(y) bxs = [] bys = [] bxs1 = [] bys1 = [] if len(self.M) > 0: order = [i for i in range(0,len(self.M))] osize = min(self.batchSize,len(self.M)) for j in range(0,osize): shuffle(order) k = order[j] x,y,t = self.M[k] xi = np.array(x) yi = np.array(y) bxs.append(xi) bys.append(yi) bxs1.append(xi) bys1.append(yi) bxs.append(mxi) bys.append(myi) bxs = Variable(torch.from_numpy(np.array(bxs))).float().view(-1,784) bys = Variable(torch.from_numpy(np.array(bys))).long().view(-1) bxs1 = Variable(torch.from_numpy(
np.array(bxs1)
numpy.array
# Author: <NAME> <<EMAIL>> from copy import deepcopy from itertools import chain, product from math import log from operator import ( add, iadd, sub, isub, mul, imul, pow, ipow, truediv, itruediv, floordiv, ifloordiv, mod, imod) import os import pickle import shutil from string import ascii_lowercase import tempfile import warnings import mne import numpy as np from numpy.testing import ( assert_equal, assert_array_equal, assert_allclose, assert_array_almost_equal) import pytest from scipy import signal from eelbrain import ( datasets, load, Var, Factor, NDVar, Datalist, Dataset, Celltable, Case, Categorial, Scalar, Sensor, UTS, set_tmin, align, align1, choose, combine, cwt_morlet, shuffled_index) from eelbrain._data_obj import ( all_equal, asvar, assub, FULL_AXIS_SLICE, longname, SourceSpace, assert_has_no_empty_cells) from eelbrain._exceptions import DimensionMismatchError from eelbrain._stats.stats import rms from eelbrain._utils.numpy_utils import newaxis from eelbrain.testing import ( assert_dataobj_equal, assert_dataset_equal, assert_source_space_equal, requires_mne_sample_data, skip_on_windows) OPERATORS = ((add, iadd, '+'), (sub, isub, '-'), (mul, imul, '*'), (mul, imul, '*'), (pow, ipow, '**'), (truediv, itruediv, '/'), (floordiv, ifloordiv, '//'), (mod, imod, '%')) def test_aggregate(): "Test aggregation methods" ds = datasets.get_uts() drop = ('rm', 'ind', 'YBin', 'YCat') # don't handle inconsistencies silently with pytest.raises(ValueError): ds.aggregate('A%B') dsa = ds.aggregate('A%B', drop=drop) assert_array_equal(dsa['n'], [15, 15, 15, 15]) idx1 = ds.eval("logical_and(A=='a0', B=='b0')") assert dsa['Y', 0] == ds['Y', idx1].mean() # unequal cell counts ds = ds[:-3] dsa = ds.aggregate('A%B', drop=drop) assert_array_equal(dsa['n'], [15, 15, 15, 12]) idx1 = ds.eval("logical_and(A=='a0', B=='b0')") assert dsa['Y', 0] == ds['Y', idx1].mean() # equalize count dsa = ds.aggregate('A%B', drop=drop, equal_count=True) assert_array_equal(dsa['n'], [12, 12, 12, 12]) idx1_12 = np.logical_and(idx1, idx1.cumsum() <= 12) assert dsa['Y', 0] == ds['Y', idx1_12].mean() # equalize count with empty cell sds = ds.sub("logical_or(A == 'a1', B == 'b1')") dsa = sds.aggregate('A%B', drop=drop, equal_count=True) assert_array_equal(dsa['n'], [12, 12, 12]) def test_align(): "Testing align() and align1() functions" ds = datasets.get_uv() # index the dataset ds.index() ds['aindex'] = ds.eval("A.enumerate_cells()") # subset idx4 = np.arange(0, ds.n_cases, 4) idx4i = idx4[::-1] ds2 = ds.sub(np.arange(0, ds.n_cases, 2)) # shuffle the whole dataset shuffle_index = np.arange(ds.n_cases) np.random.shuffle(shuffle_index) ds_shuffled = ds[shuffle_index] # align1: align Dataset to index dsa = align1(ds2, idx4) assert_array_equal(dsa['index'], idx4, "align1() failure") dsa = align1(ds2, idx4i) assert_array_equal(dsa['index'], idx4i, "align1() failure") # d_idx as Var dsa = align1(ds2[::2], idx4, idx4i) assert_array_equal(dsa['index'], idx4i, "align1() failure") with pytest.raises(ValueError): align1(ds2, idx4, idx4i) # Factor index with pytest.raises(ValueError): align1(ds, ds['rm', ::-1], 'rm') fds = ds[:20] dsa = align1(fds, fds['rm', ::-1], 'rm') assert_array_equal(dsa['index'], np.arange(19, -1, -1), "align1 Factor") # align two datasets dsa1, dsa2 = align(ds, ds2) assert_array_equal(dsa1['index'], dsa2['index'], "align() failure") dsa1, dsa2 = align(ds, ds2[::-1]) assert_array_equal(dsa1['index'], dsa2['index'], "align() failure") dsa1, dsa2 = align(ds, ds_shuffled) assert_dataset_equal(dsa1, dsa2) # align using categorial dsa1, dsa2 = align(ds, ds_shuffled, 'A % aindex') assert_dataset_equal(dsa1, dsa2) dsa1, dsa2 = align(ds, ds_shuffled, 'aindex % A') assert_dataset_equal(dsa1, dsa2) def test_celltable(): "Test the Celltable class." ds = datasets.get_uts() ds['cat'] = Factor('abcd', repeat=15) ct = Celltable('Y', 'A', ds=ds) assert ct.n_cases == 60 assert ct.n_cells == 2 assert repr(ct) == "Celltable(Y, A)" assert repr(Celltable(ds['Y'].x, 'A', ds=ds)) == "Celltable(<ndarray>, A)" assert repr(Celltable(ds['Y'].x, ds['A'].x, ds=ds)) == "Celltable(<ndarray>, <Factor>)" ct = Celltable('Y', 'A', match='rm', ds=ds) assert ct.n_cases == 30 assert ct.n_cells == 2 # cat argument ct = Celltable('Y', 'cat', cat=('c', 'b'), ds=ds) assert ct.n_cases == 30 assert ct.x[0] == 'c' assert ct.x[-1] == 'b' with pytest.raises(ValueError): Celltable('Y', 'cat', cat=('c', 'e'), ds=ds) ct = Celltable('Y', 'A', match='rm', ds=ds) assert ct.n_cases == 30 assert np.all(ct.groups['a0'] == ct.groups['a1']) ct = Celltable('Y', 'cat', match='rm', cat=('c', 'b'), ds=ds) assert ct.n_cases == 30 assert ct.x[0] == 'c' assert ct.x[-1] == 'b' # catch unequal length with pytest.raises(ValueError): Celltable(ds['Y', :-1], 'cat', ds=ds) with pytest.raises(ValueError): Celltable(ds['Y', :-1], 'cat', match='rm', ds=ds) # coercion of numerical X X = ds.eval("A == 'a0'") ct = Celltable('Y', X, cat=(None, None), ds=ds) assert ct.cat == ('False', 'True') assert_array_equal(ct.data['True'], ds['Y', X]) ct = Celltable('Y', X, cat=('True', 'False'), ds=ds) assert ('True', 'False') == ct.cat assert_array_equal(ct.data['True'], ds['Y', X]) # test coercion of Y ct = Celltable(ds['Y'].x, 'A', ds=ds) assert isinstance(ct.y, np.ndarray) ct = Celltable(ds['Y'].x, 'A', ds=ds, coercion=asvar) assert isinstance(ct.y, Var) # test sub ds_sub = ds.sub("A == 'a0'") ct_sub = Celltable('Y', 'B', ds=ds_sub) ct = Celltable('Y', 'B', sub="A == 'a0'", ds=ds) assert_dataobj_equal(ct_sub.y, ct.y) ct_sub = Celltable('Y', 'B', sub="Var(A == 'a0')", cat=('b0', 'b1'), ds=ds) assert_dataobj_equal(ct_sub.y, ct.y) # test sub with rm ct_sub = Celltable('Y', 'B', match='rm', ds=ds_sub) ct = Celltable('Y', 'B', match='rm', sub="A == 'a0'", ds=ds) assert_dataobj_equal(ct_sub.y, ct.y) # Interaction match ct = Celltable('Y', 'A', match='B % rm', ds=ds) assert ct.all_within assert_dataobj_equal(combine((ct.data['a0'], ct.data['a1'])), ds['Y']) # test rm sorting ds = Dataset() ds['rm'] = Factor('abc', repeat=4) ds['Y'] = Var(np.arange(3.).repeat(4)) ds['X'] = Factor('ab', repeat=2, tile=3) idx = np.arange(12) np.random.shuffle(idx) ds = ds[idx] ct = Celltable('Y', 'X', 'rm', ds=ds) assert_array_equal(ct.match, Factor('abc', tile=2)) assert_array_equal(ct.y, np.tile(np.arange(3.), 2)) assert_array_equal(ct.x, Factor('ab', repeat=3)) def test_coercion(): "Test data class coercion" ds = datasets.get_uts() ds['avar'] = Var.from_dict(ds['A'], {'a0': 0, 'a1': 1}) assert_array_equal(assub("A == 'a0'", ds), ds['A'] == 'a0') assert_array_equal(assub("avar == 0", ds), ds['avar'] == 0) with warnings.catch_warnings(): # element-wise comparison warnings.simplefilter("ignore") with pytest.raises(TypeError): assub("avar == '0'", ds) def test_choose(): "Test choose()" ds = datasets.get_uts(True)[::4] utsnd = ds['utsnd'] utsnd2 = utsnd + 1. idx = ds['B'] == 'b0' idxi = np.invert(idx) y = choose(idx, (utsnd, utsnd2)) assert_array_equal(y.x[idx], utsnd2.x[idx]) assert_array_equal(y.x[idxi], utsnd.x[idxi]) with pytest.raises(DimensionMismatchError): choose(idx, (utsnd, utsnd.sub(sensor='1'))) def test_combine(): "Test combine()" ds1 = datasets.get_uts() ds2 = datasets.get_uts() n = ds1.n_cases ds = combine((ds1, ds2)) assert_array_equal(ds2['Y'].x, ds['Y'].x[n:]) # list of numbers assert_dataobj_equal(combine((1., 2., 1.)), Var((1., 2., 1.))) assert_dataobj_equal(combine(('a', 'b', 'a')), Factor('aba')) # combine Datasets with unequal keys del ds1['Y'] # raise with pytest.raises(KeyError): combine((ds1, ds2)) with pytest.raises(KeyError): combine((ds2, ds1)) # drop del ds2['YCat'] ds = combine((ds1, ds2), incomplete='drop') assert 'Y' not in ds assert 'YCat' not in ds # fill in ds = combine((ds1, ds2), incomplete='fill in') assert_array_equal(ds['Y'].x[n:], ds2['Y'].x) assert_array_equal(np.isnan(ds['Y'].x[:n]), True) assert_array_equal(ds['YCat'][:n], ds1['YCat']) assert_array_equal(ds['YCat'][n:], '') # invalid input with pytest.raises(ValueError): combine(()) with pytest.raises(TypeError): combine((ds2['A'], ds2['Y'])) # combine NDVar with unequel dimensions ds = datasets.get_uts(utsnd=True) y = ds['utsnd'] y1 = y.sub(sensor=['0', '1', '2', '3']) y2 = y.sub(sensor=['1', '2', '3', '4']) ds1 = Dataset((y1,), info={'a': np.arange(2), 'b': [np.arange(2)]}) ds2 = Dataset((y2,), info={'a': np.arange(2), 'b': [np.arange(2)]}) dsc = combine((ds1, ds2)) y = dsc['utsnd'] assert list(y.sensor.names) == ['1', '2', '3'] dims = ('case', 'sensor', 'time') ref = np.concatenate((y1.get_data(dims)[:, 1:], y2.get_data(dims)[:, :3])) assert_array_equal(y.get_data(dims), ref, "combine utsnd") # info assert_array_equal(dsc.info['a'], np.arange(2)) assert len(dsc.info['b']) == 1 assert_array_equal(dsc.info['b'][0], np.arange(2)) def test_datalist(): "Test Datalist class" dl = Datalist(range(10)) # indexing assert dl[3] == 3 x = dl[:3] assert isinstance(x, Datalist) assert_array_equal(x, list(range(3))) assert_array_equal(dl[8:], list(range(8, 10))) x = dl[np.arange(10) < 3] assert isinstance(x, Datalist) assert_array_equal(x, list(range(3))) assert_array_equal(dl[np.arange(3)], list(range(3))) # __add__ x = dl + list(range(10, 12)) assert isinstance(x, Datalist) assert_array_equal(x, list(range(12))) # aggregate x = dl.aggregate(Factor('ab', repeat=5)) assert isinstance(x, Datalist) assert_array_equal(x, [2.0, 7.0]) # repr dl = Datalist([['a', 'b'], [], ['a']]) assert str(dl) == "[['a', 'b'], [], ['a']]" dl = Datalist([['a', 'b'], [], ['a']], fmt='strlist') assert str(dl) == '[[a, b], [], [a]]' assert str(dl[:2]) == '[[a, b], []]' # eq a = Datalist([[], [1], [], [1]]) b = Datalist([[], [], [2], [1]]) assert_array_equal(a == b, [True, False, False, True]) assert_array_equal(a != b, [False, True, True, False]) # deepcopy ac = deepcopy(a) assert ac is not a assert_array_equal(ac, a) ac[0].append(1) assert_array_equal(ac == a, [False, True, True, True]) # __setitem__ ac[:2] = (1, 2) assert_array_equal(ac == [1, 2, [], [1]], True) ac[np.arange(2, 4)] = [3, 4] assert_array_equal(ac == list(range(1, 5)), True) with pytest.raises(ValueError): ac[np.arange(2)] = np.arange(3) # update a._update_listlist(b) assert_array_equal(a, [[], [1], [2], [1]]) def test_dataset(): "Basic dataset operations" ds = Dataset() # naming ds['f'] = Factor('abab') assert ds['f'].name == 'f' # ds.add() with pytest.raises(ValueError): ds.add(Factor('aabb')) # no name ds.add(Factor('aabb', name='g')) assert ds['g'].name == 'g' # ds.update() ds = Dataset() ds.update({'f': Factor('abab')}) assert ds['f'].name == 'f' # checks on assignemnt ds = Dataset() ds['a'] = Factor('abab') # key check with pytest.raises(ValueError): ds[:, '1'] = 'value' # value check with pytest.raises(ValueError): ds['b'] = Factor('abcde') # length mismatch with pytest.raises(TypeError): ds['b'] = {i: i for i in range(4)} def test_dataset_combining(): "Test Dataset combination methods" ds = datasets.get_uv() del ds['fltvar'], ds['intvar'], ds['A'] ds2 = datasets.get_uv() del ds2['fltvar'], ds2['intvar'] ds.update(ds2) assert_array_equal(ds['A'], ds2['A']) ds2 = datasets.get_uv() del ds2['fltvar'], ds2['intvar'] ds2['B'][5] = 'something_else' del ds['A'] with pytest.raises(ValueError): ds.update(ds2) def test_dataset_indexing(): """Test Dataset indexing""" ds = datasets.get_uv() ds.index('case') # indexing values assert ds['A', 1] == ds['A'][1] assert ds[1, 'A'] == ds['A'][1] # indexing variables assert_dataobj_equal(ds[:, 'A'], ds['A']) assert_dataobj_equal(ds['A', :], ds['A']) assert_dataobj_equal(ds[:10, 'A'], ds['A'][:10]) assert_dataobj_equal(ds['A', :10], ds['A'][:10]) assert_dataobj_equal(ds.sub("case < 10", 'A'), ds['A'][:10]) # new Dataset through indexing ds2 = Dataset() ds2['A'] = ds['A'] assert_dataset_equal(ds[('A',)], ds2) ds2['B'] = ds['B'] assert_dataset_equal(ds['A', 'B'], ds2) assert_dataset_equal(ds[('A', 'B'), :10], ds2[:10]) assert_dataset_equal(ds[:10, ('A', 'B')], ds2[:10]) # empty index assert_dataobj_equal(ds2[[]], Dataset([Factor([], 'A'), Factor([], 'B')])) # assigning value ds[2, 'A'] = 'hello' assert ds[2, 'A'] == 'hello' ds['A', 2] = 'not_hello' assert ds[2, 'A'] == 'not_hello' # assigning new factor ds['C', :] = 'c' assert np.all(ds.eval("C == 'c'")) # assigning new Var ds['D1', :] = 5. ds[:, 'D2'] = 5. assert_array_equal(ds['D1'], 5) assert_array_equal(ds['D2'], 5) # test illegal names f = Factor('aaabbb') with pytest.raises(ValueError): ds['%dsa'] = f with pytest.raises(ValueError): ds['432'] = f with pytest.raises(ValueError): ds['%dsa', :] = 'value' with pytest.raises(ValueError): ds[:, '%dsa'] = 'value' with pytest.raises(ValueError): ds['432', :] = 4. with pytest.raises(ValueError): ds[:, '432'] = 4. # deleting items del ds['A'] assert 'A' not in ds with pytest.raises(KeyError): _ = ds['A'] del ds['B', 'rm'] assert 'B' not in ds and 'rm' not in ds def test_dataset_repr(): "Test Dataset string representation methods" ds = datasets.get_uts() assert repr(ds) == "<Dataset n_cases=60 {'A':F, 'B':F, 'rm':F, 'ind':F, 'Y':V, 'YBin':F, 'YCat':F, 'uts':Vnd}>" assert str(ds.head()) == str(ds[:10]) assert str(ds.tail()) == str(ds[-10:]) assert str(ds.summary(50)) == """Key Type Values -------------------------------------------------- A Factor a0:30, a1:30 B Factor b0:30, b1:30 rm Factor R00:4, R01:4... (15 cells, random) ind Factor R00, R01... (60 cells, random) Y Var -3.53027 - 3.04498 YBin Factor c1:34, c2:26 YCat Factor c1:17, c2:24, c3:19 uts NDVar 100 time; -2.67343 - 4.56283 -------------------------------------------------- Dataset: 60 cases""" assert str(ds[:5].summary()) == """Key Type Values ----------------------------------------------------------- A Factor a0:5 B Factor b0:5 rm Factor R00, R01, R02, R03, R04 (random) ind Factor R00, R01, R02, R03, R04 (random) Y Var 0.77358, 1.01346, 1.89424, 2.09773, 2.55396 YBin Factor c1:4, c2 YCat Factor c1:2, c2:2, c3 uts NDVar 100 time; -0.634835 - 4.56283 ----------------------------------------------------------- Dataset: 5 cases""" def test_dataset_sorting(): "Test Dataset sorting methods" test_array = np.arange(10) ds = Dataset() ds['v'] = Var(test_array) ds['f'] = Factor(test_array) # shuffle the Dataset rand_idx = test_array.copy() np.random.shuffle(rand_idx) ds_shuffled = ds[rand_idx] # ascending, Var, copy dsa = ds_shuffled.sorted('v') assert_dataset_equal(dsa, ds) # descending, Factor, in-place ds_shuffled.sort('f', descending=True) assert_dataset_equal(ds_shuffled, ds[::-1]) def test_dim_categorial(): "Test Categorial Dimension" values = ['a', 'b', 'c', 'abc'] name = 'cat' dim = Categorial(name, values) # basic properties print(dim) assert len(dim) == len(values) # persistence s = pickle.dumps(dim, pickle.HIGHEST_PROTOCOL) dim_ = pickle.loads(s) assert dim_ == dim # indexing sub_values = values[:2] idx = dim._array_index(sub_values) assert dim[idx] == Categorial(name, sub_values) assert dim._array_index('a') == values.index('a') assert dim._array_index('abc') == values.index('abc') with pytest.raises(TypeError): dim._array_index(('a', 'b', 'c')) # intersection dim2 = Categorial(name, ['c', 'b', 'e']) dim_i = dim.intersect(dim2) assert dim_i == Categorial(name, ['b', 'c']) # connectivity dim = Categorial(name, ['c', 'b', 'e'], [('b', 'c'), ('b', 'e')]) assert_array_equal(dim.connectivity(), [[0, 1], [1, 2]]) def test_dim_scalar(): "Test Scalar Dimension" d = Scalar('scalar', [20, 30, 40, 50, 60, 70]) assert repr(d) == "Scalar('scalar', [20, ..., 70] (6))" assert d._array_index(20) == 0 assert d._array_index(30) == 1 assert d._array_index(21) == 0 with pytest.raises(IndexError): d._array_index(25) # binning edges, dim = d._bin(step=20) assert edges == [20, 40, 60, 80] assert dim == Scalar('scalar', [30, 50, 70]) edges, dim = d._bin(start=30, stop=70, step=20) assert edges == [30, 50, 70] assert dim == Scalar('scalar', [40, 60]) # range not divisible by step with pytest.raises(ValueError): d._bin(start=30, step=20) with pytest.raises(ValueError): d._bin(stop=70, step=20) # nbins edges, dim = d._bin(nbins=3) assert edges == [20, 40, 60, None] assert dim == Scalar('scalar', [30, 50, 70]) edges, dim = d._bin(nbins=2) assert edges == [20, 50, None] assert dim == Scalar('scalar', [35, 65]) # uneven bin size with pytest.raises(ValueError): d._bin(nbins=4) # approximate start/stop edges, dim = d._bin(25, 65, nbins=2) assert edges == [30, 50, 70] edges, dim = d._bin(25, 65, 20) assert edges == [30, 50, 70] def test_dim_uts(): "Test UTS Dimension" uts = UTS(-0.1, 0.005, 301) # basic indexing with pytest.raises(ValueError): uts._array_index(1.5) with pytest.raises(ValueError): uts._array_index(-.15) # make sure indexing rounds correctly for floats for i, s in enumerate(np.arange(0, 1.4, 0.05)): idx = uts._array_index((-0.1 + s, s)) assert idx.start == 10 * i assert idx.stop == 20 + 10 * i # intersection uts1 = UTS(-0.1, 0.01, 50) uts2 = UTS(0, 0.01, 20) intersection = uts1.intersect(uts2) assert intersection == uts2 idx = uts1._array_index((0, 0.2)) assert uts1[idx] == uts2 def test_effect(): "Test _Effect class" # .enumerate_cells() f1 = Factor('aabbccaabbcc') f2 = Factor('abababababab') i = f1 % f2 n1 = np.concatenate((np.tile([0, 1], 3), np.tile([2, 3], 3))) assert_array_equal(f1.enumerate_cells(), n1) assert_array_equal(f2.enumerate_cells(), np.arange(6).repeat(2)) assert_array_equal(i.enumerate_cells(), np.arange(2).repeat(6)) def test_equality(): u = Var(np.arange(5.)) v = Var(np.arange(5.)) assert all_equal(u, v) u[-1] = np.nan assert not all_equal(u, v) v[-1] = np.nan assert not all_equal(u, v) assert all_equal(u, v, True) def test_factor(): "Test basic Factor functionality" # initializing assert_array_equal(Factor('ab'), ['a', 'b']) assert_array_equal(Factor('ab', repeat=2), ['a', 'a', 'b', 'b']) assert_array_equal(Factor('ab', repeat=np.array([2, 1])), ['a', 'a', 'b']) empty_factor = Factor([]) assert len(empty_factor) == 0 assert_dataobj_equal(Factor(np.empty(0)), empty_factor) # from Factor f = Factor('aabbcc') assert_array_equal(Factor(f), f) assert_array_equal(Factor(f, labels={'a': 'b'}), Factor('bbbbcc')) # removing a cell f = Factor('aabbcc') assert f.cells == ('a', 'b', 'c') assert f.n_cells == 3 f[f == 'c'] = 'a' assert f.cells == ('a', 'b') assert f.n_cells == 2 # cell order a = np.tile(np.arange(3), 3) f = Factor(a, labels={2: 'a', 1: 'b', 0: 'c'}) assert f.cells == ('a', 'b', 'c') assert f[:2].cells == ('b', 'c') # not alphabetical f = Factor(a, labels={0: 'c', 1: 'b', 2: 'a'}) assert f.cells == ('c', 'b', 'a') assert f[:2].cells == ('c', 'b') f[f == 'b'] = 'c' assert f.cells == ('c', 'a') # initialize from factor f = Factor(a, labels={0: 'c', 1: 'b', 2: 'a'}) f2 = Factor(f, labels={'c': 'c', 'b': 'c', 'a': 'a'}) assert f2.cells == ('c', 'a') # superfluous label f2 = Factor(f, labels={'c': 'a', 'x': 'c', 'b': 'b', 'a': 'c'}) assert f2.cells == ('a', 'b', 'c') # sort f = Factor(a, labels={0: 'c', 1: 'b', 2: 'a'}) f.sort_cells(('a', 'c', 'b')) assert f.cells == ('a', 'c', 'b') # label length lens = [2, 5, 32, 2, 32, 524] f = Factor(['a' * l for l in lens], 'f') fl = f.label_length() assert_array_equal(fl, lens) assert fl.info['longname'] == 'f.label_length()' lens2 = [3, 5, 32, 2, 32, 523] f2 = Factor(['b' * l for l in lens2], 'f2') assert_array_equal(fl - f2.label_length(), [a - b for a, b in zip(lens, lens2)]) # equality f = Factor('aabbcc') assert_equal(f == Factor('aabbcc'), True) assert_equal(f == Factor('bbccaa'), False) assert_equal(f == Factor('aabxxx'), (True, True, True, False, False, False)) assert_equal(f == Var(np.ones(6)), False) # Factor.as_var() assert_array_equal(f.as_var(dict(zip('abc', range(3)))), [0, 0, 1, 1, 2, 2]) assert_array_equal(f.as_var({'a': 1}, 2), [1, 1, 2, 2, 2, 2]) with pytest.raises(KeyError): f.as_var({'a': 1}) # Factor.floodfill() f = Factor([' ', ' ', '1', '2', ' ', ' ', '3', ' ', ' ', '2', ' ', ' ', '1']) regions = [ 1, 1, 1, 2, 2, 2, 3, 3, 3, 2, 2, 1, 1] regions2 = [ 1, 1, 1, 2, 2, 3, 3, 2, 2, 2, 2, 1, 1] regions3 = [ 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2] target3 = ['1', '1', '1', '2', '2', '2', '3', '3', '2', '2', '2', '2', '1'] target_p = [' ', ' ', '1', '2', '2', '2', '3', '3', '3', '2', '2', '2', '1'] assert_array_equal(f.floodfill(regions, ' '), Var(regions).as_factor()) assert_array_equal(f.floodfill(regions2, ' '), Var(regions2).as_factor()) assert_array_equal(f.floodfill(regions3, ' '), target3) assert_array_equal(f.floodfill('previous', ' '), target_p) f = Factor(['', '', 'a', '', 'e', 'r', '']) assert_array_equal(f.floodfill([1, 1, 1, 11, 11, 11, 11]), Factor('aaaeerr')) def test_factor_relabel(): "Test Factor.relabel() method" f = Factor('aaabbbccc') f.update_labels({'a': 'd'}) assert_array_equal(f, Factor('dddbbbccc')) f.update_labels({'d': 'c', 'c': 'd'}) assert_array_equal(f, Factor('cccbbbddd')) f.update_labels({'d': 'c'}) assert_array_equal(f, Factor('cccbbbccc')) with pytest.raises(KeyError): f.update_labels({'a': 'c'}) def test_interaction(): "Test Interaction" ds = datasets.get_uv() A = ds['A'] B = ds['B'] i = A % B # eq for sequence assert_array_equal(i == A % B, True) assert_array_equal(i == B % A, False) assert_array_equal(i == A, False) assert_array_equal(i == ds['fltvar'], False) assert_array_equal(ds.eval("A%B") == Factor(ds['A']) % B, True) # eq for element for a, b in product(A.cells, B.cells): assert_array_equal(i == (a, b), np.logical_and(A == a, B == b)) # Interaction.as_factor() a = Factor('aabb') i = a % Factor('cdcd') assert_dataobj_equal(i.as_factor(), Factor(['a c', 'a d', 'b c', 'b d'])) i = a % Factor(['c', '', 'c', '']) assert_dataobj_equal(i.as_factor(), Factor(['a c', 'a', 'b c', 'b'])) # pickling ip = pickle.loads(pickle.dumps(i)) assert_dataobj_equal(ip, i) def test_isin(): "Test .isin() methods" values = np.array([ 6, -6, 6, -2, -1, 0, -10, -5, -10, -6]) v = values[0] v2 = values[:2] labels = {i: c for i, c in enumerate(ascii_lowercase, -10)} vl = labels[v] v2l = [labels[v_] for v_ in v2] target = np.logical_or(values == v2[0], values == v2[1]) inv_target = np.invert(target) index_target = np.flatnonzero(values == v) empty = np.array([]) var = Var(values) assert_array_equal(var.index(v), index_target) assert_array_equal(var.isin(v2), target) assert_array_equal(var.isany(*v2), target) assert_array_equal(var.isnot(*v2), inv_target) assert_array_equal(var.isnotin(v2), inv_target) var0 = Var([]) assert_array_equal(var0.isin(v2), empty) assert_array_equal(var0.isany(*v2), empty) assert_array_equal(var0.isnot(*v2), empty) assert_array_equal(var0.isnotin(v2), empty) f = Factor(values, labels=labels) assert_array_equal(f.index(vl), index_target) assert_array_equal(f.isin(v2l), target) assert_array_equal(f.isany(*v2l), target) assert_array_equal(f.isnot(*v2l), inv_target) assert_array_equal(f.isnotin(v2l), inv_target) f0 = Factor([]) assert_array_equal(f0.isin(v2l), empty) assert_array_equal(f0.isany(*v2l), empty) assert_array_equal(f0.isnot(*v2l), empty) assert_array_equal(f0.isnotin(v2l), empty) def test_longname(): "Test info['longname'] entry" ds = Dataset() u = Var([2], 'u') v = Var([1], 'v') # simple operations, also tested in test_var() assert longname(v.abs()) == 'abs(v)' assert longname(u * v) == "u * v" assert longname(u * v.abs()) == "u * abs(v)" # Dataset assigning ds['abs_v'] = v.abs() assert longname(ds['abs_v']) == 'abs(v)' def test_model(): "Test Model class" a = Factor('ab', repeat=3, name='a') b = Factor('ab', tile=3, name='b') u = Var([1, 1, 1, -1, -1, -1], 'u') v = Var([1., 2., 3., 4., 5., 6.], 'v') w = Var([1., 0., 0., 1., 1., 0.], 'w') # model repr m = a * b + v assert repr(m) == "a + b + a % b + v" lines = ("intercept a b a x b v", "-----------------------------", "1 1 1 1 1", "1 1 0 0 2", "1 1 1 1 3", "1 0 0 0 4", "1 0 1 0 5", "1 0 0 0 6") assert str(m) == '\n'.join(lines) assert str(m.head(2)) == '\n'.join(lines[:4]) assert str(m.tail(2)) == '\n'.join(lines[:2] + lines[-2:]) str(m.info()) # model without explicit names x1 = Factor('ab', repeat=2) x2 = Factor('ab', tile=2) m = x1 * x2 assert repr(m) == "<?> + <?> + <?> % <?>" # catch explicit intercept intercept = Factor('i', repeat=4, name='intercept') with pytest.raises(ValueError): _ = a * intercept # different var/factor combinations assert a * b == a + b + a % b assert a * v == a + v + a % v assert a * (v + w) == a + v + w + a % v + a % w # parametrization m = v + w + v * w p = m._parametrize('dummy') assert p.column_names == ['intercept', 'v', 'w', 'v * w'] assert_array_equal(p.x[:, p.terms['intercept']], 1) assert_array_equal(p.x[:, p.terms['v']], v.x[:, None]) assert_array_equal(p.x[:, p.terms['w']], w.x[:, None]) assert_array_equal(p.x[:, p.terms['v * w']], (v * w).x[:, None]) # persistence mp = pickle.loads(pickle.dumps(m, pickle.HIGHEST_PROTOCOL)) mpp = mp._parametrize('dummy') assert_array_equal(mpp.x, p.x) # nested Vars m = (v + w) * u assert_dataobj_equal(m.effects[2], u) assert_dataobj_equal(m.effects[3], v * u) assert_dataobj_equal(m.effects[4], w * u) m = u * (v + w) assert_dataobj_equal(m.effects[0], u) assert_dataobj_equal(m.effects[3], u * v) assert_dataobj_equal(m.effects[4], u * w) m = (v + w) % u assert_dataobj_equal(m.effects[0], v * u) assert_dataobj_equal(m.effects[1], w * u) m = u % (v + w) assert_dataobj_equal(m.effects[0], u * v) assert_dataobj_equal(m.effects[1], u * w) def test_ndvar(): "Test the NDVar class" ds = datasets.get_uts(utsnd=True) x = ds['utsnd'] # meaningful slicing with pytest.raises(KeyError): x.sub(sensor='5') assert_equal(x.sub(sensor='4'), x.x[:, 4]) assert_equal(x.sub(sensor=['4', '3', '2']), x.x[:, [4, 3, 2]]) assert_equal(x.sub(sensor=['4']), x.x[:, [4]]) assert_equal(x.sub(case=1, sensor='4'), x.x[1, 4]) # setup indices s_case = slice(10, 13) s_sensor = slice('2', '4') s_time = slice(0.1, 0.2) b_case = np.bincount([10, 11, 12], minlength=len(x)).astype(bool) b_sensor = np.array([False, False, True, True, False]) b_time = np.bincount(range(30, 40), minlength=len(x.time)).astype(bool) a_case = np.arange(10, 13) a_sensor = ['2', '3'] a_time = np.arange(0.1, 0.2, 0.01) # slicing with different index kinds tgt = x.x[s_case, 2:4, 30:40] assert tgt.shape == (3, 2, 10) # single assert_equal(x.sub(case=s_case, sensor=s_sensor, time=s_time), tgt) assert_equal(x.sub(case=a_case, sensor=a_sensor, time=a_time), tgt) assert_equal(x.sub(case=b_case, sensor=b_sensor, time=b_time), tgt) # bool & slice assert_equal(x.sub(case=b_case, sensor=s_sensor, time=s_time), tgt) assert_equal(x.sub(case=s_case, sensor=b_sensor, time=s_time), tgt) assert_equal(x.sub(case=s_case, sensor=s_sensor, time=b_time), tgt) assert_equal(x.sub(case=b_case, sensor=b_sensor, time=s_time), tgt) assert_equal(x.sub(case=s_case, sensor=b_sensor, time=b_time), tgt) assert_equal(x.sub(case=b_case, sensor=s_sensor, time=b_time), tgt) # bool & array assert_equal(x.sub(case=b_case, sensor=a_sensor, time=a_time), tgt) assert_equal(x.sub(case=a_case, sensor=b_sensor, time=a_time), tgt) assert_equal(x.sub(case=a_case, sensor=a_sensor, time=b_time), tgt) assert_equal(x.sub(case=b_case, sensor=b_sensor, time=a_time), tgt) assert_equal(x.sub(case=a_case, sensor=b_sensor, time=b_time), tgt) assert_equal(x.sub(case=b_case, sensor=a_sensor, time=b_time), tgt) # slice & array assert_equal(x.sub(case=s_case, sensor=a_sensor, time=a_time), tgt) assert_equal(x.sub(case=a_case, sensor=s_sensor, time=a_time), tgt) assert_equal(x.sub(case=a_case, sensor=a_sensor, time=s_time), tgt) assert_equal(x.sub(case=s_case, sensor=s_sensor, time=a_time), tgt) assert_equal(x.sub(case=a_case, sensor=s_sensor, time=s_time), tgt) assert_equal(x.sub(case=s_case, sensor=a_sensor, time=s_time), tgt) # all three assert_equal(x.sub(case=a_case, sensor=b_sensor, time=s_time), tgt) assert_equal(x.sub(case=a_case, sensor=s_sensor, time=b_time), tgt) assert_equal(x.sub(case=b_case, sensor=a_sensor, time=s_time), tgt) assert_equal(x.sub(case=b_case, sensor=s_sensor, time=a_time), tgt) assert_equal(x.sub(case=s_case, sensor=a_sensor, time=b_time), tgt) assert_equal(x.sub(case=s_case, sensor=b_sensor, time=a_time), tgt) # norm y = x / x.norm('sensor') assert_allclose(y.norm('sensor'), 1.) y = ds['uts'].mean('case').norm('time') assert isinstance(y, float) # dot m = NDVar([1, 0, -1, 0, 0], x.sensor) # -> time y = m.dot(x[0]) assert_array_equal(y.x, x.x[0, 0] - x.x[0, 2]) # -> case x time y_all = m.dot(x) assert len(y_all) == len(x) assert_dataobj_equal(y_all[0], y) # -> scalar y = m.dot(x[0, :, 0.200]) assert y == x.x[0, 0, 40] - x.x[0, 2, 40] # Var v_case = Var(b_case) assert_equal(x.sub(case=v_case, sensor=b_sensor, time=a_time), tgt) # univariate result assert_dataobj_equal(x.sub(sensor='2', time=0.1), Var(x.x[:, 2, 30], x.name)) assert x.sub(case=0, sensor='2', time=0.1) == x.x[0, 2, 30] # baseline correction x_bl = x - x.summary(time=(None, 0)) # assert that the baseline is 0 bl = x_bl.summary('case', 'sensor', time=(None, 0)) assert abs(bl) < 1e-10 # iteration for i, xi in enumerate(x): assert_dataobj_equal(xi, x[i]) if i > 4: break def test_ndvar_binning(): "Test NDVar.bin()" x = np.arange(10) time = UTS(-0.1, 0.1, 10) x_dst = x.reshape((5, 2)).mean(1) time_dst = np.arange(0., 0.9, 0.2) # 1-d ndvar = NDVar(x, (time,)) b = ndvar.bin(0.2) assert_array_equal(b.x, x_dst, "Binned data") assert_array_equal(b.time, time_dst, "Bin times") b = ndvar.sub(time=(0, 0.8)).bin(0.4) assert b.shape == (2,) # 2-d ndvar = NDVar(np.vstack((x, x, x)), ('case', time)) b = ndvar.bin(0.2) assert_array_equal(b.x, np.vstack((x_dst, x_dst, x_dst)), "Binned data") assert_array_equal(b.time, time_dst, "Bin times") # time: x = np.ones((5, 70)) ndvar = NDVar(x, ('case', UTS(0.45000000000000007, 0.005, 70))) binned_ndvar = ndvar.bin(0.05) assert_array_equal(binned_ndvar.x, 1.) assert binned_ndvar.shape == (5, 7) # n_bins x = np.ones((2, 601)) ndvar = NDVar(x, ('case', UTS(-0.1, 0.001, 601))) binned_ndvar = ndvar.bin(0.1, 0.1, 0.4) assert binned_ndvar.shape == (2, 3) def test_ndvar_connectivity(): "Test NDVar dimensions with conectvity graph" ds = datasets.get_uts(utsnd=True) x = ds['utsnd'] # non-monotonic index sub_mono = x.sub(sensor=['2', '3', '4']) sub_nonmono = x.sub(sensor=['4', '3', '2']) argsort = np.array([2,1,0]) conn = argsort[sub_mono.sensor.connectivity().ravel()].reshape((-1, 2)) assert_equal(sub_nonmono.sensor.connectivity(), conn) # date for labeling x1 = ds.eval("utsnd[logical_and(A=='a0', B=='b0')].mean('case')") x2 = ds.eval("utsnd[A=='a1'].mean('case')") x = x1 + x2 # insert point that is connected by sensors but not by grid x.x[0, 50:55] = 4 # custom connectivity on first axis l = x.label_clusters(3) assert len(l.info['cids']) == 5 assert_array_equal(np.unique(l.x), np.append([0], l.info['cids'])) # custom connectivity second sensor, time = x.dims x = NDVar(x.x.T, (time, sensor)) l = x.label_clusters(3) assert len(l.info['cids']) == 5 # disconnected cat = Categorial('categorial', ('a', 'b', 'c', 'd', 'e')) x = NDVar(x.x, (time, cat)) l = x.label_clusters(3) assert len(l.info['cids']) == 13 # ordered scalar = Scalar('ordered', range(5)) x = NDVar(x.x, (time, scalar)) l = x.label_clusters(3) assert len(l.info['cids']) == 6 def ndvar_index(x, dimname, index, a_index, index_repr=True): "Helper function for test_ndvar_indexing" ax = x.get_axis(dimname) index_prefix = FULL_AXIS_SLICE * ax if dimname != 'case': dim = x.get_dim(dimname) assert_equal(dim._array_index(index), a_index) if index_repr is not False: if index_repr is True: index_repr = index assert dim._dim_index(a_index) == index_repr x_array = x.x[index_prefix + (a_index,)] x1 = x.sub(**{dimname: index}) x2 = x[index_prefix + (index,)] assert_array_equal(x1.x, x_array) assert_dataobj_equal(x2, x1) def test_ndvar_indexing(): ds = datasets.get_uts(utsnd=True) x = ds['utsnd'] # case ndvar_index(x, 'case', 1, 1) ndvar_index(x, 'case', [0, 3], [0, 3]) ndvar_index(x, 'case', slice(0, 10, 2), slice(0, 10, 2)) # Sensor ndvar_index(x, 'sensor', '0', 0) ndvar_index(x, 'sensor', ['0', '2'], [0, 2]) ndvar_index(x, 'sensor', slice('0', '2'), slice(0, 2)) ndvar_index(x, 'sensor', 0, 0, False) ndvar_index(x, 'sensor', [0, 2], [0, 2], False) ndvar_index(x, 'sensor', slice(0, 2), slice(0, 2), False) # UTS ndvar_index(x, 'time', 0, 20) ndvar_index(x, 'time', 0.1, 30) ndvar_index(x, 'time', 0.102, 30, False) ndvar_index(x, 'time', [0, 0.1, 0.2], [20, 30, 40]) ndvar_index(x, 'time', slice(0.1, None), slice(30, None)) ndvar_index(x, 'time', slice(0.2), slice(40)) ndvar_index(x, 'time', slice(0.202), slice(41), False) ndvar_index(x, 'time', slice(0.1, 0.2), slice(30, 40)) ndvar_index(x, 'time', slice(0.102, 0.2), slice(31, 40), False) ndvar_index(x, 'time', slice(0.1, None, 0.1), slice(30, None, 10)) ndvar_index(x, 'time', slice(0.1, None, 1), slice(30, None, 100)) # NDVar as index sens_mean = x.mean(('case', 'time')) idx = sens_mean > 0 pos = sens_mean[idx] assert_array_equal(pos.x > 0, True) # NDVar as index along one dimension x_tc = x.sub(sensor='1') x_time = NDVar(x_tc.time.times >= 0.3, dims=(x_tc.time,)) assert_dataobj_equal(x_tc[x_time], x_tc.sub(time=(0.3, None))) # NDVar whose dimension is smaller x_time_sub = x_time.sub(time=(0.2, None)) assert_dataobj_equal(x_tc[x_time_sub], x_tc.sub(time=(0.3, None))) # out of range index with pytest.raises(ValueError): x.sub(time=(0.1, 0.81)) with pytest.raises(IndexError): x.sub(time=(-0.25, 0.1)) # newaxis with pytest.raises(IndexError): _ = x[newaxis] x0 = x[0] assert not x0.has_case assert x0[newaxis].has_case # Scalar x = cwt_morlet(ds['uts'], [8, 10, 13, 17]) with pytest.raises(IndexError): _ = x[:, 9] with pytest.raises(IndexError): _ = x[:, 6] ndvar_index(x, 'frequency', 10, 1) ndvar_index(x, 'frequency', 10.1, 1, False) ndvar_index(x, 'frequency', 9.9, 1, False) ndvar_index(x, 'frequency', [8.1, 10.1], [0, 1], False) ndvar_index(x, 'frequency', slice(8, 13), slice(0, 2)) ndvar_index(x, 'frequency', slice(8, 13.1), slice(0, 3), False) ndvar_index(x, 'frequency', slice(8, 13.1, 2), slice(0, 3, 2), False) # Categorial x = NDVar(x.x, ('case', Categorial('cat', ['8', '10', '13', '17']), x.time)) with pytest.raises(TypeError): _ = x[:, 9] with pytest.raises(IndexError): _ = x[:, '9'] ndvar_index(x, 'cat', '13', 2) ndvar_index(x, 'cat', ['8', '13'], [0, 2]) ndvar_index(x, 'cat', slice('8', '13'), slice(0, 2)) ndvar_index(x, 'cat', slice('8', None, 2), slice(0, None, 2)) # SourceSpace x = datasets.get_mne_stc(True, subject='fsaverage') with pytest.raises(TypeError): _ = x[:'insula-rh'] with pytest.raises(TypeError): _ = x['insula-lh':'insula-rh'] with pytest.raises(TypeError): _ = x['insula-lh', 'insula-rh'] ndvar_index(x, 'source', 'L90', 90) ndvar_index(x, 'source', 'R90', 642 + 90) ndvar_index(x, 'source', ['L90', 'R90'], [90, 642 + 90]) ndvar_index(x, 'source', slice('L90', 'R90'), slice(90, 642 + 90)) ndvar_index(x, 'source', 90, 90, False) ndvar_index(x, 'source', [90, 95], [90, 95], False) ndvar_index(x, 'source', slice(90, 95), slice(90, 95), False) ndvar_index(x, 'source', 'insula-lh', x.source.parc == 'insula-lh', False) ndvar_index(x, 'source', ('insula-lh', 'insula-rh'), x.source.parc.isin(('insula-lh', 'insula-rh')), False) n_lh = x.source.parc.endswith('lh').sum() ndvar_index(x, 'source', 'lh', slice(n_lh), False) ndvar_index(x, 'source', 'rh', slice(n_lh, None), False) # index dim != dim source_rh = x.source[x.source.lh_n:] index = NDVar(np.arange(len(source_rh)) > 100, (source_rh,)) assert_dataobj_equal(x.sub(source=index), x.sub(source='rh').sub(source=index)) with pytest.raises(IndexError): x.sub(source='lh').sub(index) # multiple arguments y = ds['utsnd'].sub(sensor=[1, 2], time=[0, 0.1]) assert y.shape == (60, 2, 2) assert_array_equal(y.x, ds['utsnd'].x[:, 1:3, [20, 30]]) # argmax x.x[10, 10] = 20 assert x.argmax() == ('L10', 0.1) assert x[('L10', 0.1)] == 20 assert x.sub(source='L10').argmax() == 0.1 assert x.sub(time=0.1).argmax() == 'L10' # broadcasting u = ds[0, 'uts'] dim = Categorial('test_dim', ['a', 'b']) v = NDVar([5, 1], dim) for op, _, desc in OPERATORS: y = op(v, u) assert_array_equal(y['a'], op(5, u.x)) assert_array_equal(y['b'], op(1, u.x)) # with Case from Var case = Var([4, 1]) for op, iop, desc in OPERATORS: y = op(case, u) assert_array_equal(y[0], op(4, u.x)) assert_array_equal(y[1], op(1, u.x)) # set NDVar elements x = ds['uts'].copy() x[:3, :.0] = 0 assert_array_equal(x.x[:3, :20], 0.) assert_array_equal(x.x[3:, 20:], ds['uts'].x[3:, 20:]) # set with index NDVar x = ds['uts'].copy() index = x.mean('case') < 0 x[index] = -1 assert x.sum(index).sum() == -index.sum() i_index = ~index assert x.sum(i_index).sum() == ds['uts'].sum(i_index).sum() with pytest.raises(DimensionMismatchError): index[x != 0] = 0. # set to NDVar x = ds['utsnd'].copy() x[0] = x[1] assert_array_equal(x[0].x, x[1].x) x3 = NDVar(x[3].x.swapaxes(0, 1), x.dims[:0:-1]) x[2] = x3 assert_array_equal(x[2].x, x[3].x) x[:, '1'] = x[0, '2'] assert_array_equal(x.x[30, 1], x.x[0, 2]) with pytest.raises(ValueError): x[:, '1'] = x[6] def test_ndvar_summary_methods(): "Test NDVar methods for summarizing data over axes" ds = datasets.get_uts(utsnd=True) x = ds['utsnd'] x.info['test_item'] = 1 dim = 'sensor' axis = x.get_axis(dim) dims = ('case', 'sensor') axes = tuple(x.get_axis(d) for d in dims) idx = x > 0 x0 = x[0] idx0 = idx[0] xsub = x.sub(time=(0, 0.5)) idxsub = xsub > 0 idx1d = x.mean(('case', 'time')) > 0 # info inheritance assert x.mean(('sensor', 'time')).info == x.info # info update for booleans assert x.any(('sensor', 'time')).info == {'test_item': 1} # numpy functions assert x.any() == x.x.any() assert_array_equal(x.any(dim), x.x.any(axis)) assert_array_equal(x.any(dims), x.x.any(axes)) assert_array_equal(x.any(idx0), [x_[idx0.x].any() for x_ in x.x]) assert_array_equal(x.any(idx), [x_[i].any() for x_, i in zip(x.x, idx.x)]) assert_array_equal(x0.any(idx0), x0.x[idx0.x].any()) assert_array_equal(x.any(idxsub), xsub.any(idxsub)) assert_array_equal(x.any(idx1d), x.x[:, idx1d.x].any(1)) assert x.max() == x.x.max() assert_array_equal(x.max(dim), x.x.max(axis)) assert_array_equal(x.max(dims), x.x.max(axes)) assert_array_equal(x.max(idx0), [x_[idx0.x].max() for x_ in x.x]) assert_array_equal(x.max(idx), x.x[idx.x].max()) assert_array_equal(x0.max(idx0), x0.x[idx0.x].max()) assert_array_equal(x.max(idxsub), xsub.max(idxsub)) assert_array_equal(x.max(idx1d), x.x[:, idx1d.x].max(1)) assert x.mean() == x.x.mean() assert_array_equal(x.mean(dim), x.x.mean(axis)) assert_array_equal(x.mean(dims), x.x.mean(axes)) assert_array_almost_equal(x.mean(idx0), [x_[idx0.x].mean() for x_ in x.x]) assert_array_equal(x.mean(idx), x.x[idx.x].mean()) assert_array_equal(x0.mean(idx0), x0.x[idx0.x].mean()) assert_array_equal(x.mean(idxsub), xsub.mean(idxsub)) assert_array_equal(x.mean(idx1d), x.x[:, idx1d.x].mean(1)) assert x.min() == x.x.min() assert_array_equal(x.min(dim), x.x.min(axis)) assert_array_equal(x.min(dims), x.x.min(axes)) assert_array_equal(x.min(idx0), [x_[idx0.x].min() for x_ in x.x]) assert_array_equal(x.min(idx), x.x[idx.x].min()) assert_array_equal(x0.min(idx0), x0.x[idx0.x].min()) assert_array_equal(x.min(idxsub), xsub.min(idxsub)) assert_array_equal(x.min(idx1d), x.x[:, idx1d.x].min(1)) assert x.var() == x.x.var() assert x.var(ddof=1) == x.x.var(ddof=1) assert_array_equal(x.var(dim), x.x.var(axis)) assert_array_equal(x.var(dims, ddof=1), x.x.var(axes, ddof=1)) assert_array_almost_equal(x.var(idx0), [x_[idx0.x].var() for x_ in x.x]) assert_array_equal(x.var(idx), x.x[idx.x].var()) assert_array_equal(x0.var(idx0), x0.x[idx0.x].var()) assert_array_equal(x.var(idxsub), xsub.var(idxsub)) assert_array_equal(x.var(idx1d), x.x[:, idx1d.x].var(1)) assert x.std() == x.x.std() assert_array_equal(x.std(dim), x.x.std(axis)) assert_array_equal(x.std(dims), x.x.std(axes)) assert_array_almost_equal(x.std(idx0), [x_[idx0.x].std() for x_ in x.x]) assert_array_equal(x.std(idx), x.x[idx.x].std()) assert_array_equal(x0.std(idx0), x0.x[idx0.x].std()) assert_array_equal(x.std(idxsub), xsub.std(idxsub)) assert_array_equal(x.std(idx1d), x.x[:, idx1d.x].std(1)) # non-numpy assert x.rms() == rms(x.x) assert_array_equal(x.rms(dim), rms(x.x, axis)) assert_array_equal(x.rms(dims), rms(x.x, axes)) assert_array_almost_equal(x.rms(idx0), [rms(x_[idx0.x]) for x_ in x.x]) assert_array_equal(x.rms(idx), rms(x.x[idx.x])) assert_array_equal(x0.rms(idx0), rms(x0.x[idx0.x])) assert_array_equal(x.rms(idxsub), xsub.rms(idxsub)) assert_array_equal(x.rms(idx1d), rms(x.x[:, idx1d.x], 1)) assert x.extrema() == max(abs(x.min()), abs(x.max())) def test_ndvar_timeseries_methods(): "Test NDVar time-series methods" ds = datasets.get_uts(True) x = ds['utsnd'] case, sensor, time = x.dims xs = NDVar(x.x.swapaxes(1, 2), (case, time, sensor), x.info.copy(), x.name) # envelope env = x.envelope() assert_array_equal(env.x >= 0, True) envs = xs.envelope() assert_array_equal(env.x, envs.x.swapaxes(1,2)) # indexing assert len(ds[0, 'uts'][0.01:0.1].time) == 9 # smoothing ma = x.smooth('time', 0.2, 'blackman') assert_dataobj_equal(x.smooth('time', window='blackman', window_samples=20), ma) with pytest.raises(TypeError): x.smooth('time') with pytest.raises(TypeError): x.smooth('time', 0.2, 'blackman', window_samples=20) mas = xs.smooth('time', 0.2, 'blackman') assert_allclose(ma.x, mas.x.swapaxes(1, 2), 1e-10) ma_mean = x.mean('case').smooth('time', 0.2, 'blackman') assert_allclose(ma.mean('case').x, ma_mean.x) # against raw scipy.signal window = signal.get_window('blackman', 20, False) window /= window.sum() window.shape = (1, 1, 20) assert_array_equal(ma.x, signal.convolve(x.x, window, 'same')) # mode parameter full = signal.convolve(x.x, window, 'full') ma = x.smooth('time', 0.2, 'blackman', mode='left') assert_array_equal(ma.x, full[:, :, :ma.shape[2]]) ma = x.smooth('time', 0.2, 'blackman', mode='right') assert_array_equal(ma.x, full[:, :, -ma.shape[2]:]) # FFT x = ds['uts'].mean('case') np.sin(2 * np.pi * x.time.times, x.x) f = x.fft() assert_array_almost_equal(f.x, (f.frequency.values == 1) * (len(f) - 1)) np.sin(4 * np.pi * x.time.times, x.x) f = x.fft() assert_array_almost_equal(f.x, (f.frequency.values == 2) * (len(f) - 1)) # update tmin assert x.time.times[0] == -0.2 x = set_tmin(x, 3.2) assert x.time.times[0] == 3.2 def test_nested_effects(): """Test nested effects""" ds = datasets.get_uv(nrm=True) nested = ds.eval("nrm(B)") assert nested.cells == ds['nrm'].cells # interaction i = ds.eval("A % nrm(B)") assert i.cells == tuple(product(*(ds[f].cells for f in ['A', 'nrm']))) i = ds.eval("nrm(B) % A") assert i.cells == tuple(product(*(ds[f].cells for f in ['nrm', 'A']))) assert_has_no_empty_cells(ds.eval('A * B + nrm(B) + A % nrm(B)')) @skip_on_windows # uses R def test_ols(): "Test NDVar.ols() method" from rpy2.robjects import r # data-type assert_array_equal(NDVar([1, 2, 3], Case).ols(Var([1, 2, 3])).x, [1.]) # simulate data ds = datasets.get_uts(True) n_times = len(ds['uts'].time) x = np.zeros(n_times) x[20:40] = np.hanning(20) utsc = ds.eval("uts.copy()") utsc.x += ds['Y'].x[:, None] * x[None, :] ds_ = Dataset() ds_['x'] = Var(ds['Y'].x) ds_['x2'] = ds_['x'] + np.random.normal(0, 1, ds.n_cases) # ols regression m1 = ds_['x'] b1 = utsc.ols(m1) res1 = utsc.residuals(m1) t1 = utsc.ols_t(m1) m2 = ds_.eval("x + x2") b2 = utsc.ols(m2) res2 = utsc.residuals(m2) t2 = utsc.ols_t(m2) # compare with R for i in range(n_times): ds_['y'] = Var(utsc.x[:, i]) ds_.to_r('ds') # 1 predictor r('lm1 <- lm(y ~ x, ds)') beta = r('coef(lm1)')[1] assert b1.x[0, i] == pytest.approx(beta) res = r('residuals(lm1)') assert_array_almost_equal(res1.x[:, i], res) t = r('coef(summary(lm1))')[5] assert t1.x[0, i] == pytest.approx(t) # 2 predictors r('lm2 <- lm(y ~ x + x2, ds)') beta = r('coef(lm2)')[1:] assert_array_almost_equal(b2.x[:, i], beta) res = r('residuals(lm2)') assert_array_almost_equal(res2.x[:, i], res) lm2_coefs = r('coef(summary(lm2))') t = [lm2_coefs[7], lm2_coefs[8]] assert_array_almost_equal(t2.x[:, i], t) # 3d utsnd = ds['utsnd'] ds_['utsnd'] = utsnd b1 = ds_.eval("utsnd.ols(x)") res1 = ds_.eval("utsnd.residuals(x)") t1 = ds_.eval("utsnd.ols_t(x)") for i in range(len(b1.time)): ds_['y'] = Var(utsnd.x[:, 1, i]) ds_.to_r('ds') # 1 predictor r('lm1 <- lm(y ~ x, ds)') beta = r('coef(lm1)')[1] assert b1.x[0, 1, i] == pytest.approx(beta) res = r('residuals(lm1)') assert_array_almost_equal(res1.x[:, 1, i], res) t = r('coef(summary(lm1))')[5] assert t1.x[0, 1, i] == pytest.approx(t) def test_io_pickle(): "Test io by pickling" ds = datasets.get_uts() ds.info['info'] = "Some very useful information about the Dataset" tempdir = tempfile.mkdtemp() try: dest = os.path.join(tempdir, 'test.pickled') with open(dest, 'wb') as fid: pickle.dump(ds, fid, protocol=pickle.HIGHEST_PROTOCOL) with open(dest, 'rb') as fid: ds2 = pickle.load(fid) finally: shutil.rmtree(tempdir) assert_dataset_equal(ds, ds2) def test_io_txt(): "Test Dataset io as text" ds = datasets.get_uv() # Var that has integer values as float ds['intflt'] = ds.eval('intvar * 1.') ds['intflt'].name = 'intflt' # io test tempdir = tempfile.mkdtemp() try: dest = os.path.join(tempdir, 'test.txt') ds.save_txt(dest) ds2 = load.tsv(dest) finally: shutil.rmtree(tempdir) assert_dataset_equal(ds, ds2, decimal=6) @skip_on_windows # uses R def test_r(): "Test interaction with R through rpy2" from rpy2.robjects import r r("data(sleep)") ds = Dataset.from_r("sleep") assert ds.name == 'sleep' extra = (0.7, -1.6, -0.2, -1.2, -0.1, 3.4, 3.7, 0.8, 0.0, 2.0, 1.9, 0.8, 1.1, 0.1, -0.1, 4.4, 5.5, 1.6, 4.6, 3.4) assert_array_equal(ds.eval('extra'), extra) assert_array_equal(ds.eval('ID'), list(map(str, range(1, 11))) * 2) assert_array_equal(ds.eval('group'), ['1'] * 10 + ['2'] * 10) # test putting ds.to_r('sleep_copy') ds_copy = Dataset.from_r('sleep_copy') assert_dataset_equal(ds_copy, ds) def test_sensor(): "Test Sensor dimension" locs = np.array([[1., 0., 0.], [0., 1., 0.], [0., 0., 1.]]) names = ['1', '2', '3'] sensor = Sensor(locs, names, 'test') s1 = sensor[[0, 1]] s2 = sensor[[1, 2]] assert tuple(s1.names) == ('1', '2') assert tuple(s2.names) == ('2', '3') assert s1 == sensor[[0, 1]] assert s1 != s2 assert s1.intersect(s2) == sensor[[1]] assert sensor._dim_index(np.array([0, 1, 1], bool)) == ['2', '3'] def test_shuffle(): x = Factor('aabbaa') for _ in range(3): i = shuffled_index(6, x) assert sorted(i[2:4]) == [2, 3] assert sorted(i) == list(range(6)) @requires_mne_sample_data def test_source_space(): "Test SourceSpace Dimension" subject = 'fsaverage' data_path = mne.datasets.sample.data_path() mri_sdir = os.path.join(data_path, 'subjects') mri_dir = os.path.join(mri_sdir, subject) label_dir = os.path.join(mri_dir, 'label') label_ba1 = mne.read_label(os.path.join(label_dir, 'lh.BA1.label')) label_v1 = mne.read_label(os.path.join(label_dir, 'lh.V1.label')) label_mt = mne.read_label(os.path.join(label_dir, 'lh.MT.label')) label_ba1_v1 = label_ba1 + label_v1 label_v1_mt = label_v1 + label_mt src = datasets._mne_source_space(subject, 'ico-5', mri_sdir) source = SourceSpace.from_mne_source_spaces(src, 'ico-5', mri_sdir) source_v1 = source[source._array_index(label_v1)] assert source_v1 == SourceSpace.from_mne_source_spaces(src, 'ico-5', mri_sdir, label=label_v1) source_ba1_v1 = source[source._array_index(label_ba1_v1)] source_v1_mt = source[source._array_index(label_v1_mt)] source_v1_intersection = source_ba1_v1.intersect(source_v1_mt) assert_source_space_equal(source_v1, source_v1_intersection) # persistence assert pickle.loads(pickle.dumps(source, pickle.HIGHEST_PROTOCOL)) == source assert pickle.loads(pickle.dumps(source_v1, pickle.HIGHEST_PROTOCOL)) == source_v1 # index from label index = source.index_for_label(label_v1) assert_array_equal(index.source[index.x].vertices[0], np.intersect1d(source.lh_vertices, label_v1.vertices, 1)) # parcellation and cluster localization parc = mne.read_labels_from_annot(subject, parc='aparc', subjects_dir=mri_sdir) indexes = [source.index_for_label(label) for label in parc if len(label) > 10] x = np.vstack([index.x for index in indexes]) ds = source._cluster_properties(x) for i in range(ds.n_cases): assert ds[i, 'location'] == parc[i].name # multiple labels lingual_index = source._array_index('lingual-lh') cuneus_index = source._array_index('cuneus-lh') assert_array_equal(source._array_index(('cuneus-lh', 'lingual-lh')), np.logical_or(cuneus_index, lingual_index)) lingual_source = source[lingual_index] cuneus_source = source[cuneus_index] with pytest.raises(IndexError): _ = lingual_source._array_index(cuneus_source) sub_source = source[source._array_index(('cuneus-lh', 'lingual-lh'))] assert sub_source[sub_source._array_index('lingual-lh')] == lingual_source assert sub_source[sub_source._array_index('cuneus-lh')] == cuneus_source assert len(sub_source) == len(lingual_source) + len(cuneus_source) # indexing tgt = ['L%i' % i for i in chain(*sub_source.vertices)] assert_array_equal([i for i in sub_source], tgt) assert_array_equal([sub_source[i] for i in range(len(sub_source))], tgt) # hemisphere indexing lh = source._array_index('lh') source_lh = source[lh] assert source_lh._array_index('rh') == slice(0, 0) assert source_lh._array_index('lh') == slice(len(source_lh)) def test_var(): "Test Var objects" base = Factor('aabbcde') # initialization x = np.arange(4) y = Var(x) assert_array_equal(y, x) y = Var(x, repeat=2) assert_array_equal(y, x.repeat(2)) y = Var(x, repeat=x) assert_array_equal(y, x.repeat(x)) y = Var.from_dict(base, {'a': 5, 'e': 8}, default=0) assert_array_equal(y.x, [5, 5, 0, 0, 0, 0, 8]) with pytest.raises(TypeError): Var(x, info=1) # invalid dtypes with pytest.raises(TypeError): Var(np.array(['a', 'b', 'c'])) with pytest.raises(TypeError): Var(np.array([None, 1, 2])) # basic operations info = {'a': 1} v = Var([1., 2., 3., -4.], 'v', info=info) c = 2 v2 = Var([2., 2., 3., 3.], 'w', info=info) assert v.info == info for op, iop, desc in OPERATORS: target = op(v.x, c) vtarget = op(v.x, v2.x) # op if desc == '+': w = v.copy() w.x = iop(w.x, c) else: w = op(v, c) assert w.info == {'a': 1, 'longname': 'v %s %s' % (desc, c)} assert_array_equal(w, target) # with Var w = op(v, v2) assert w.info == {'a': 1, 'longname': 'v %s w' % desc} assert_array_equal(w, vtarget) # i-op w = v.copy() w = iop(w, c) assert_array_equal(w, target) # i-op with Var w = v.copy() w = iop(w, v2) assert_array_equal(w, vtarget) # methods w = v.abs() assert w.info == {'a': 1, 'longname': 'abs(v)'} assert_array_equal(w, np.abs(v.x)) # log x = w.log() assert x.info == {'a': 1, 'longname': 'log(abs(v))'} assert_array_equal(x,
np.log(w.x)
numpy.log
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Nov 15 10:43:11 2018 @author: kyungdoehan """ #%% Required packages import os import numpy as np #import multiprocessing as mp from t2hlib import READDATA, LAKE, PACKAGES, PROPERTIES, GRID, PLOT, RCHRG from os.path import expanduser #%% Setting up directories home = expanduser('~') flopypth = os.path.join(home+'/anaconda3/lib/python3.6/site-packages') #%% Initial variables Ma = 12.5 nz = 40 nz_fixed = 10 inz = 30 dx = 1000 dy = 1000 dat = -10000 dat_var = -3000 idat = dat - dat_var rech = 0.4 # background runoff target = 75 Kconst = 100 perm_sed = Kconst * 2 hratio = 1.0 hydchr = Kconst / 10 # 100 m, thickness iskip = 4 ivtk = 2 h_tol = 1E-4 Rflag = 1 CXrain = 0 CYrain = 0 Krain = 1 lakeK = 100 lakeb = 10.0 lamb = 1E-8 # sediment and rock density (arbitrary) rho_sed = 1700 rho_rock1 = 3000 #%% Reading data file by specified Mas class __main__: def __init__(self, Ma, nz, nz_fixed, inz, dx, dy, dat, dat_var, idat\ , rech, perm_sed, target_row, Kconst, hratio, hydchr,\ iskip, ivtk, h_tol, Rflag, CXrain, CYrain, Krain,\ lakeK, lakeb, lamb, rho_rock1, rho_sed): """ data checker """ datdef = READDATA.data(Ma) self.topoT = datdef.topo self.bdtopoT = datdef.bdtopo self.sedT = datdef.sed self.lakeT = datdef.lake self.faultT = datdef.fault print("console> data checker complete") """ Reading topography """ topo = READDATA.topo_read(Ma) self.x = topo.x self.y = topo.y self.z = topo.z # Discretization variables (hydro. model specified) grid = int(np.sqrt(len(self.x))) self.nx = grid self.ny = grid griddata = GRID.XYZ(grid, self.x, self.y, self.z) self.X = griddata.X self.Y = griddata.Y self.top = griddata.Z self.top_l = self.top.copy() self.top2 = self.top.copy() self.top3 = self.top.copy() """ Check optional files whether they are there or not there """ if self.sedT == True: print("console> reading sed data") sed = READDATA.sed_read(Ma) self.sed_x = sed.x self.sed_y = sed.y self.sed_b = sed.z elif self.sedT == False: print("console> sed data is missing for this period") self.sed_x = [] self.sed_y = [] self.sed_b = [] if self.faultT == True: print("console> reading fault data") fault = READDATA.fault_read(Ma) self.fault_x = fault.x self.fault_y = fault.y self.fault_z = fault.z fault_rearr = READDATA.fault_rearrange(Ma) self.fault_x1 = fault_rearr.x self.fault_y1 = fault_rearr.y self.fault_z1 = fault_rearr.z elif self.faultT == False: print("console> fault data is missing for this period") if self.faultT == True and self.sedT == True: self.imodel = 1 elif self.faultT == True and self.sedT == False: self.imodel = 2 elif self.faultT == False and self.sedT == True: self.imodel = 3 elif self.faultT == False and self.sedT == False: self.imodel = 4 # Exponentially increasing dz values dzr = GRID.dzratio(inz) self.dzratio = dzr.dzratio bot = GRID.bot(inz, nz_fixed, grid, self.top, dat_var, idat, self.dzratio).bot self.bot_l = bot.copy() self.bot1 = bot.copy() self.bot2 = bot.copy() dzs = GRID.dzs(self.top, bot, nz, self.ny, self.nx).dzs self.dzs_cumsum = np.cumsum(dzs, axis = 0) node = GRID.node(bot, dzs, nz, self.ny, self.nx).node self.nod = node.copy() # * .9 # Initial value of water table according to the topo. if self.lakeT == True: lake = LAKE.lake(Ma, nz, self.ny, self.nx, grid, rech,\ dx, dy, lakeK, self.top_l, self.bot_l, lakeb) self.lake_x = lake.x self.lake_y = lake.y self.lakarr = lake.lakarr self.lake_level = lake.level self.ilak = 1 self.nlakes = lake.nlakes self.ghb = lake.ghb #print(self.ghb) elif self.lakeT == False: self.ilak = 0 print("console> lake data is missing for this period \n") conductivity = PROPERTIES.cond(nz, self.ny, self.nx, Kconst, hratio,\ node, self.top, lamb, rho_rock1) self.h_ini = conductivity.h_ini self.hk = conductivity.hk self.dens = conductivity.dens self.dens1 = self.dens.copy() self.sediment = PROPERTIES.sed(self.dzs_cumsum, self.sed_b,\ self.sed_y, self.sed_x, grid,\ self.hk, nz, perm_sed, self.imodel,\ self.nod, self.top, self.ny, self.nx,\ Kconst, lamb, rho_rock1,\ self.dens1, rho_sed, self.bot1, dy, dx, dzs) #print(self.hk[:, 85, 105]) if self.faultT == True: fault = PROPERTIES.hfb(hydchr, grid, nz, self.ny, self.nx,\ self.fault_z,\ self.fault_y, self.fault_x,\ self.fault_x1, self.fault_y1,\ self.fault_z1, node, dat) self.hfb_pair = fault.hfb_pair self.hfb_info = fault.hfb_info vfb = PROPERTIES.vfb(nz, self.ny, self.nx, self.fault_x1,\ self.fault_y1, self.fault_z1,\ node, grid, hydchr, self.dzratio) self.vkcb_data = vfb.vkcb_data self.vkcb_layers = vfb.layer elif self.faultT == False: self.hfb_pair = [] self.vkcb_data = [] self.hfb_info = [] switch = 2 laytyp = PROPERTIES.laytyp(switch, nz, inz).laytyp self.xx = (0.5*(grid-1))*dx self.xn = -(0.5*(grid-1))*dx self.yx = (0.5*(grid-1))*dy self.yn = -(0.5*(grid-1))*dy self.topo = self.top.copy() if self.lakeT == True: prec = RCHRG.preci1(rech, Rflag, self.topo, self.nx, self.ny,\ self.lake_x, self.lake_y, CXrain, CYrain,\ self.lake_level, grid, self.xx,\ self.xn, self.yx, self.yn, dx, dy,\ Krain, self.ilak) self.rchrg = prec.rchrg self.prcp_t = prec.prcp_t elif self.lakeT == False: self.lake_x = [] self.lake_y = [] self.lake_level = [] prec = RCHRG.preci1(rech, Rflag, self.topo, self.nx, self.ny,\ self.lake_x, self.lake_y, CXrain, CYrain,\ self.lake_level, grid, self.xx,\ self.xn, self.yx, self.yn, dx, dy,\ Krain, self.ilak) self.rchrg = prec.rchrg self.prcp_t = prec.prcp_t self.nlakes = 0 self.ghb = [] self.ibound = PROPERTIES.boundary(bot, nz, self.ny, self.nx, grid).ibound self.conductance = PROPERTIES.cd(self.top3,\ self.bot2, dy, dx,\ self.ny, self.nx,\ self.hk, self.x, self.y,\ self.ibound, grid).conductance self.condarr = PROPERTIES.cd(self.top3,\ self.bot2, dy, dx,\ self.ny, self.nx,\ self.hk, self.x, self.y,\ self.ibound, grid).condarr # Model paths from external subroutine self.path_info = PACKAGES.paths() self.fdirmodel = self.path_info.fdirmodel self.fnmmodel = self.path_info.fnmmodel # Model packages from external subroutine modelpackage = PACKAGES.packages(nz, self.ny, self.nx, dy, dx,\ self.top, bot, self.ibound,\ self.h_ini, self.hfb_pair,\ self.conductance, laytyp, self.hk,\ self.vkcb_data, self.rchrg, self.fdirmodel,\ self.fnmmodel, self.nlakes, self.ilak\ , self.ghb, self.imodel) self.mf = modelpackage.mf self.mfdis = modelpackage.mfdis self.mfbas = modelpackage.mfbas if self.faultT == True: self.mfhfb = modelpackage.mfhfb self.mfdrn = modelpackage.mfdrn self.mfupw = modelpackage.mfupw self.mfrch = modelpackage.mfrch self.mfnwt = modelpackage.mfnwt if self.lakeT == True: self.mfghb = modelpackage.mfghb self.output = modelpackage.output def main(Ma, nz, nz_fixed, inz, dx, dy, dat, dat_var, idat\ , rech, perm_sed, target_row, Kconst, hratio, hydchr,\ iskip, ivtk, h_tol, Rflag, CXrain, CYrain, Krain,\ lakeK, lakeb, lamb, rho_rock1, rho_sed): return __main__(Ma, nz, nz_fixed, inz, dx, dy, dat, dat_var, idat\ , rech, perm_sed, target_row, Kconst, hratio, hydchr,\ iskip, ivtk, h_tol, Rflag, CXrain, CYrain, Krain,\ lakeK, lakeb, lamb, rho_rock1, rho_sed) #%% Model execution model = main(Ma, nz, nz_fixed, inz, dx, dy, dat, dat_var, idat\ , rech, perm_sed, target, Kconst, hratio, hydchr,\ iskip, ivtk, h_tol, Rflag, CXrain, CYrain, Krain,\ lakeK, lakeb, lamb, rho_rock1, rho_sed) #%% Model input checker mf = model.mf mf.dis.check() mf.drn.check() if model.lakeT == True: mf.ghb.check() mf.rch.check() mf.upw.check() mf.write_input() mf.run_model() #%% print("model recharge average: ", np.mean(model.rchrg)) print("model topography average: ", np.mean(model.top)) print("model N/K: ", np.mean(model.rchrg)/np.mean(model.hk)) #%% # Plot the grid, head contour, and discharge vector on a cross-section target = 75 import matplotlib.pyplot as plt import flopy figheadxsect, axheadxsect = plt.subplots(figsize=(40,5)) mfxsect = PLOT.fmfxsect(mf, model.mfdis, target, axheadxsect).mfxsect a = PLOT.head(mf, model.fdirmodel).a headc = PLOT.headc(mfxsect, a) if model.imodel > 4: p = PLOT.pat(mfxsect, model.hk, Kconst, model.vkcb_data,\ model.hfb_info, nz, model.ny, model.nx, model.imodel) #p1 = PLOT.wtable(mfxsect, model.top, a, nz, model.ny, model.nx) #patch1 = p1.plarr #patch1 = p.bcarray # Plotting the grid mesh #gdplot = mfxsect.plot_grid(color='r', linewidths=0.2) # Plotting the BC (blue = const. head; noflow = black) BCplot = mfxsect.plot_ibound(model.ibound, color_noflow = 'black',\ color_ch = 'blue', head = a) wtable = PLOT.wt_f(nz, model.ny, model.nx, a, model.top) wtf = wtable.wtf wtplot = mfxsect.plot_surface(wtf[0,:,:]) topplot = mfxsect.plot_surface(model.top) cellbudget = PLOT.cbc(model.fdirmodel, mf) times = cellbudget.times # Plot flux vector qx = cellbudget.qx # right face qy = cellbudget.qy # front face qz = cellbudget.qz # lower face # Average flows to cell centers avgq = PLOT.qavg(qz, qy, qx, nz, model.ny, model.nx) qx_avg = avgq.qx_avg qy_avg = avgq.qy_avg qz_avg = avgq.qz_avg y, x, z = model.mfdis.get_node_coordinates() #diagonal # [0,0] [1, 1], [2,2] cross-section # x = 1000*sqrt(2)/2 increment # z = zdiag = np.zeros((nz, model.nx), dtype=np.float32) xdiag = np.zeros((nz, model.nx), dtype=np.float32) hdiag = np.zeros((nz, model.nx), dtype=np.float32) qxdiag = np.zeros((nz, model.nx), dtype=np.float32) qydiag =
np.zeros((nz, model.nx), dtype=np.float32)
numpy.zeros
''' CONFIDENTIAL Copyright (c) 2021 <NAME>, Department of Remote Sensing and Photogrammetry, Finnish Geospatial Research Institute (FGI), National Land Survey of Finland (NLS) PERMISSION IS HEREBY LIMITED TO FGI'S INTERNAL USE ONLY. THE CODE MAY BE RE-LICENSED, SHARED, OR TAKEN INTO OTHER USE ONLY WITH A WRITTEN CONSENT FROM THE HEAD OF THE DEPARTMENT. 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 math import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from matplotlib.widgets import Slider, Button, RadioButtons, CheckButtons try: import pcl from pyquaternion import Quaternion except: print('cannot import pcl -> change python version') import matplotlib.cm as cmx from scipy.spatial import distance_matrix from scipy.optimize import leastsq import matplotlib import matplotlib.animation as animation import open3d as o3d import glob import cv2 import cv2.aruco as aruco import os from mpl_toolkits.mplot3d.proj3d import proj_transform from matplotlib.text import Annotation import pickle from matplotlib.lines import Line2D import pandas as pd import random from scipy.spatial import ConvexHull from math import sqrt from math import atan2, cos, sin, pi from collections import namedtuple from matplotlib.patches import Circle import mpl_toolkits.mplot3d.art3d as art3d from pyquaternion import Quaternion np.set_printoptions(suppress=True) def eulerAnglesToRotationMatrix2(theta): R_x = np.array([[1, 0, 0], [0, math.cos(theta[0]), -math.sin(theta[0])], [0, math.sin(theta[0]), math.cos(theta[0])] ]) R_y = np.array([[math.cos(theta[1]), 0, math.sin(theta[1])], [0, 1, 0], [-math.sin(theta[1]), 0, math.cos(theta[1])] ]) R_z = np.array([[math.cos(theta[2]), -math.sin(theta[2]), 0], [math.sin(theta[2]), math.cos(theta[2]), 0], [0, 0, 1] ]) R = np.dot(R_z, np.dot(R_y, R_x)) return R Rot_matrix = eulerAnglesToRotationMatrix2([0, 0, np.deg2rad(-90)]) InitLidar = True InitLidar = False global globalTrigger globalTrigger = True stereoRectify = False# True #stereoRectify = True class Annotation3D(Annotation): def __init__(self, s, xyz, *args, **kwargs): Annotation.__init__(self, s, xy=(0, 0), *args, **kwargs) self._verts3d = xyz def draw(self, renderer): xs3d, ys3d, zs3d = self._verts3d xs, ys, zs = proj_transform(xs3d, ys3d, zs3d, renderer.M) self.xy = (xs, ys) Annotation.draw(self, renderer) def save_obj(obj, name): with open('/home/eugeniu/catkin_ws/src/testNode/CAMERA_CALIBRATION/data/' + name + '.pkl', 'wb') as f: pickle.dump(obj, f, protocol=2) print('{}.pkl Object saved'.format(name)) def load_obj(name): with open('/home/eugeniu/Desktop/my_data/CameraCalibration/data/saved_files/' + name + '.pkl', 'rb') as f: return pickle.load(f) def showErros(_3DErros, IMageNames): print('len(_3DErros)->{}'.format(np.shape(_3DErros))) if len(_3DErros)>1: _3DErros = np.array(_3DErros).squeeze() # norm_total = np.array(_3DErros[:,0]).squeeze() norm_axis = np.array(_3DErros).squeeze() * 1000 index, bar_width = np.arange(len(IMageNames)), 0.24 fig, ax = plt.subplots() X = ax.bar(index, norm_axis[:, 0], bar_width, label="X") Y = ax.bar(index + bar_width, norm_axis[:, 1], bar_width, label="Y") Z = ax.bar(index + bar_width + bar_width, norm_axis[:, 2], bar_width, label="Z") ax.set_xlabel('images') ax.set_ylabel('errors in mm') ax.set_title('3D error') ax.set_xticks(index + bar_width / 3) ax.set_xticklabels(IMageNames) ax.legend() plt.show() def triangulation(kp1, kp2, T_1w, T_2w): """Triangulation to get 3D points Args: kp1 (Nx2): keypoint in view 1 (normalized) kp2 (Nx2): keypoints in view 2 (normalized) T_1w (4x4): pose of view 1 w.r.t i.e. T_1w (from w to 1) T_2w (4x4): pose of view 2 w.r.t world, i.e. T_2w (from w to 2) Returns: X (3xN): 3D coordinates of the keypoints w.r.t world coordinate X1 (3xN): 3D coordinates of the keypoints w.r.t view1 coordinate X2 (3xN): 3D coordinates of the keypoints w.r.t view2 coordinate """ kp1_3D = np.ones((3, kp1.shape[0])) kp2_3D = np.ones((3, kp2.shape[0])) kp1_3D[0], kp1_3D[1] = kp1[:, 0].copy(), kp1[:, 1].copy() kp2_3D[0], kp2_3D[1] = kp2[:, 0].copy(), kp2[:, 1].copy() X = cv2.triangulatePoints(T_1w[:3], T_2w[:3], kp1_3D[:2], kp2_3D[:2]) X /= X[3] X1 = T_1w[:3].dot(X) X2 = T_2w[:3].dot(X) return X[:3].T, X1.T, X2.T def triangulate(R1,R2,t1,t2,K1,K2,D1,D2, pts1, pts2): P1 = np.hstack([R1.T, -R1.T.dot(t1)]) P2 = np.hstack([R2.T, -R2.T.dot(t2)]) P1 = K1.dot(P1) P2 = K2.dot(P2) # Triangulate _3d_points = [] for i,point in enumerate(pts1): point3D = cv2.triangulatePoints(P1, P2, pts1[i], pts2[i]).T point3D = point3D[:, :3] / point3D[:, 3:4] _3d_points.append(point3D) print('Triangulate _3d_points -> {}'.format(np.shape(_3d_points))) return np.array(_3d_points).squeeze() def mai(R1,R2,t1,t2,imagePoint1,imagePoint2, K2=None,K1=None, D2=None,D1=None): # Set up two cameras near each other if K1 is None: K = np.array([ [718.856, 0., 607.1928], [0., 718.856, 185.2157], [0., 0., 1.], ]) R1 = np.array([ [1., 0., 0.], [0., 1., 0.], [0., 0., 1.] ]) R2 = np.array([ [0.99999183, -0.00280829, -0.00290702], [0.0028008, 0.99999276, -0.00257697], [0.00291424, 0.00256881, 0.99999245] ]) t1 = np.array([[0.], [0.], [0.]]) t2 = np.array([[-0.02182627], [0.00733316], [0.99973488]]) # Corresponding image points imagePoint1 = np.array([371.91915894, 221.53485107]) imagePoint2 = np.array([368.26071167, 224.86262512]) P1 = np.hstack([R1.T, -R1.T.dot(t1)]) P2 = np.hstack([R2.T, -R2.T.dot(t2)]) P1 = K1.dot(P1) P2 = K2.dot(P2) # Triangulate point3D = cv2.triangulatePoints(P1, P2, imagePoint1, imagePoint2).T point3D = point3D[:, :3] / point3D[:, 3:4] print('Triangulate point3D -> {}'.format(point3D)) # Reproject back into the two cameras rvec1, _ = cv2.Rodrigues(R1.T) # Change rvec2, _ = cv2.Rodrigues(R2.T) # Change p1, _ = cv2.projectPoints(point3D, rvec1, -t1, K1, distCoeffs=D1) # Change p2, _ = cv2.projectPoints(point3D, rvec2, -t2, K2, distCoeffs=D2) # Change # measure difference between original image point and reporjected image point reprojection_error1 = np.linalg.norm(imagePoint1 - p1[0, :]) reprojection_error2 = np.linalg.norm(imagePoint2 - p2[0, :]) print('difference between original image point and reporjected image point') print(reprojection_error1, reprojection_error2) return p1,p2 class PointCloud_filter(object): def __init__(self, file, img_file=None, img_file2=None, debug=True): self.debug = debug self.img_file = img_file self.img_file2 = img_file2 self.name = os.path.basename(file).split('.')[0] self.file = file self.useVoxel, self.voxel_size = False, 0.15 self.lowerTemplate, self.showImage = False, True self.showError = False self.points_correspondences = None self.OK = False self.useInitialPointCloud = False #user all point to fit or only margins self.chessBoard = False self.applyICP_directly = False self.s = .1 # scale self.plotInit, self.axis_on, self.colour, self.Annotate = False, True, False, False self.chess, self.corn, self.p1, self.p2, self.p3, self.ICP_finetune_plot = None, None, None, None, None, None if self.showImage: b = 1 self.pts = np.float32([[0, b, 0], [b, b, 0], [b, 0, 0], [-0.03, -0.03, 0]]) self.ImageNames = [] self._3DErros = [] self.criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 100, 0.0001) self.axis = np.float32([[1, 0, 0], [0, 1, 0], [0, 0, -1]]).reshape(-1, 3) self.objp = np.zeros((7 * 10, 3), np.float32) self.objp[:, :2] = np.mgrid[0:10, 0:7].T.reshape(-1, 2) * self.s self.fig = plt.figure(figsize=plt.figaspect(0.5)) self.fig.suptitle('Data collection', fontsize=16) self.ax = self.fig.add_subplot(1, 2, 1, projection='3d') #self.ax = self.fig.add_subplot(1, 2, 2, projection='3d') self.readCameraIntrin() self.QueryImg = cv2.imread(img_file) self.ImageNames.append(os.path.basename(img_file)) if self.img_file2: # use stereo case self.QueryImg2 = cv2.imread(img_file2) if stereoRectify: self.QueryImg = cv2.remap(src=self.QueryImg, map1=self.leftMapX, map2=self.leftMapY, interpolation=cv2.INTER_LINEAR, dst=None, borderMode=cv2.BORDER_CONSTANT) self.QueryImg2 = cv2.remap(src=self.QueryImg2, map1=self.rightMapX, map2=self.rightMapY, interpolation=cv2.INTER_LINEAR, dst=None, borderMode=cv2.BORDER_CONSTANT) gray_left = cv2.cvtColor(self.QueryImg, cv2.COLOR_BGR2GRAY) ret_left, corners_left = cv2.findChessboardCorners(gray_left, (10, 7), None) gray_right = cv2.cvtColor(self.QueryImg2, cv2.COLOR_BGR2GRAY) ret_right, corners_right = cv2.findChessboardCorners(gray_right, (10, 7), None) if ret_right and ret_left: print('Found chessboard in both images') self.chessBoard = True corners2_left = cv2.cornerSubPix(gray_left, corners_left, (11, 11), (-1, -1), self.criteria) self.corners2 = corners2_left cv2.drawChessboardCorners(self.QueryImg, (10, 7), self.corners2, ret_left) ret, self.rvecs, self.tvecs = cv2.solvePnP(self.objp, self.corners2, self.K_left, self.D_left) imgpts, jac = cv2.projectPoints(self.axis, self.rvecs, self.tvecs, self.K_left, self.D_left) self.QueryImg = self.draw(self.QueryImg, corners=corners2_left, imgpts=imgpts) self.pixelsPoints = np.asarray(corners2_left).squeeze() self.pixels_left = np.asarray(corners2_left).squeeze() corners2_right = cv2.cornerSubPix(gray_right, corners_right, (11, 11), (-1, -1), self.criteria) cv2.drawChessboardCorners(self.QueryImg2, (10, 7), corners2_right, ret_right) self.pixels_right = np.asarray(corners2_right).squeeze() self.T = np.array([-0.977, 0.004, 0.215])[:, np.newaxis] angles = np.array([np.deg2rad(1.044), np.deg2rad(22.632), np.deg2rad(-.95)]) self.R = euler_matrix(angles) #self.baseline = self.T = np.array([-1.07, 0.004, 0.215])[:, np.newaxis] self.baseline = abs(self.T[0]) print('baseline:{} m'.format(self.baseline)) self.focal_length, self.cx, self.cy = self.K[0, 0], self.K[0, 2], self.K[1, 2] self.x_left, self.x_right = self.pixels_left, self.pixels_right disparity = np.sum(np.sqrt((self.x_left - self.x_right) ** 2), axis=1) # depth = baseline (meter) * focal length (pixel) / disparity-value (pixel) -> meter self.depth = (self.baseline * self.focal_length / disparity) print('depth:{}'.format(np.shape(self.depth))) self.fxypxy = [self.K[0, 0], self.K[1, 1], self.cx, self.cy] '''print('TRIANGULATE HERE==========================================') P_1 = np.vstack((np.hstack((np.eye(3), np.zeros(3)[:, np.newaxis])), [0, 0, 0, 1])) # left camera P_2 = np.vstack((np.hstack((self.R, self.T)), [0, 0, 0, 1])) # right camera print('P1_{}, P_2{}, x_left:{}, x_right:{}'.format(np.shape(P_1), np.shape(P_2), np.shape(self.x_left), np.shape(self.x_right))) X_w, X1, X2 = triangulation(self.x_left,self.x_right,P_1,P_2) print('X_w:{}, X1:{}, X2:{}, '.format(np.shape(X_w), np.shape(X1), np.shape(X2))) print(X_w[0]) print(X1[0]) print(X2[0])''' '''R1 = np.eye(3) R2 = self.R t1 = np.array([[0.], [0.], [0.]]) t2 = self.T # Corresponding image points imagePoint1 = np.array([371.91915894, 221.53485107]) imagePoint2 = np.array([368.26071167, 224.86262512]) imagePoint1 = self.x_left[0] imagePoint2 = self.x_right[0] print('imagePoint1:{}, imagePoint2:{}'.format(np.shape(imagePoint1), np.shape(imagePoint2))) print('self.K_left ') print(self.K_left) print('self.K_right ') print(self.K_right) p1,p2 = test(R1,R2,t1,t2,imagePoint1,imagePoint2,K1=self.K_left,K2=self.K_right, D1=self.D_left,D2=self.D_right) p1 = np.array(p1).squeeze().astype(int) p2 = np.array(p2).squeeze().astype(int) print('p1:{}, p2:{}'.format(np.shape(p1), np.shape(p2))) #d2 = distance_matrix(X_w, X_w) #print('d2:{}'.format(d2)) cv2.circle(self.QueryImg, (p1[0],p1[1]), 7, (255, 0, 0), 7) cv2.circle(self.QueryImg2, (p2[0], p2[1]), 7, (255, 0, 0), 7) cv2.imshow('QueryImg', cv2.resize(self.QueryImg,None,fx=.5,fy=.5)) cv2.imshow('QueryImg2', cv2.resize(self.QueryImg2, None, fx=.5, fy=.5)) cv2.waitKey(0) cv2.destroyAllWindows()''' else: self.chessBoard = False self.useVoxel = False print('No chessboard ') corners2_left, ids_left, rejectedImgPoints = aruco.detectMarkers(gray_left, self.ARUCO_DICT) corners2_left, ids_left, _, _ = aruco.refineDetectedMarkers(image=gray_left, board=self.calibation_board, detectedCorners=corners2_left, detectedIds=ids_left, rejectedCorners=rejectedImgPoints, cameraMatrix=self.K_left, distCoeffs=self.D_left) corners2_right, ids_right, rejectedImgPoints = aruco.detectMarkers(gray_right, self.ARUCO_DICT) corners2_right, ids_right, _, _ = aruco.refineDetectedMarkers(image=gray_right, board=self.calibation_board, detectedCorners=corners2_right, detectedIds=ids_right, rejectedCorners=rejectedImgPoints, cameraMatrix=self.K_right, distCoeffs=self.D_right) if np.all(ids_left != None) and np.all(ids_right != None): print('found charuco board, in both images') retval_left, self.rvecs, self.tvecs = aruco.estimatePoseBoard(corners2_left, ids_left, self.calibation_board, self.K_left, self.D_left, None, None) retval_right, self.rvecs_right, self.tvecs_right = aruco.estimatePoseBoard(corners2_right, ids_right, self.calibation_board, self.K_right, self.D_right, None, None) if retval_left and retval_right: self.QueryImg = aruco.drawAxis(self.QueryImg, self.K_left, self.D_left, self.rvecs, self.tvecs, 0.3) self.QueryImg = aruco.drawDetectedMarkers(self.QueryImg, corners2_left, ids_left, borderColor=(0, 0, 255)) b = 1 imgpts, _ = cv2.projectPoints(self.pts, self.rvecs_right, self.tvecs_right, self.K_right, self.D_right) self.corners2_right = np.append(imgpts, np.mean(imgpts, axis=0)).reshape(-1, 2) self.dst, jacobian = cv2.Rodrigues(self.rvecs) a, circle_tvec, b = .49, [], 1 circle_tvec.append( np.asarray(self.tvecs).squeeze() + np.dot(self.dst, np.asarray([a, a, 0]))) circle_tvec = np.mean(circle_tvec, axis=0) self.QueryImg = aruco.drawAxis(self.QueryImg, self.K_left, self.D_left, self.rvecs, circle_tvec, 0.2) imgpts, _ = cv2.projectPoints(self.pts, self.rvecs, self.tvecs, self.K_left, self.D_left) self.corners2 = np.append(imgpts, np.mean(imgpts, axis=0)).reshape(-1, 2) self.pt_dict = {} for i in range(len(self.pts)): self.pt_dict[tuple(self.pts[i])] = tuple(imgpts[i].ravel()) top_right = self.pt_dict[tuple(self.pts[0])] bot_right = self.pt_dict[tuple(self.pts[1])] bot_left = self.pt_dict[tuple(self.pts[2])] top_left = self.pt_dict[tuple(self.pts[3])] cv2.circle(self.QueryImg, top_right, 4, (0, 0, 255), 5) cv2.circle(self.QueryImg, bot_right, 4, (0, 0, 255), 5) cv2.circle(self.QueryImg, bot_left, 4, (0, 0, 255), 5) cv2.circle(self.QueryImg, top_left, 4, (0, 0, 255), 5) self.QueryImg = cv2.line(self.QueryImg, top_right, bot_right, (0, 255, 0), 4) self.QueryImg = cv2.line(self.QueryImg, bot_right, bot_left, (0, 255, 0), 4) self.QueryImg = cv2.line(self.QueryImg, bot_left, top_left, (0, 255, 0), 4) self.QueryImg = cv2.line(self.QueryImg, top_left, top_right, (0, 255, 0), 4) else: print('Cannot estimate board position for both charuco') self.pixelsPoints = self.corners2.squeeze() self.pixels_left = self.pixelsPoints self.pixels_right = self.corners2_right.squeeze() self.T = np.array([-0.977, 0.004, 0.215])[:, np.newaxis] angles = np.array([np.deg2rad(1.044), np.deg2rad(22.632), np.deg2rad(-.95)]) self.R = euler_matrix(angles) # self.baseline = self.T = np.array([-1.07, 0.004, 0.215])[:, np.newaxis] self.baseline = abs(self.T[0]) print('baseline:{} m'.format(self.baseline)) self.focal_length, self.cx, self.cy = self.K[0, 0], self.K[0, 2], self.K[1, 2] self.x_left, self.x_right = self.pixels_left, self.pixels_right disparity = np.sum(np.sqrt((self.x_left - self.x_right) ** 2), axis=1) print('disparity:{}'.format(np.shape(disparity))) # depth = baseline (meter) * focal length (pixel) / disparity-value (pixel) -> meter self.depth = (self.baseline * self.focal_length / disparity) print('depth:{}'.format(np.shape(self.depth))) self.fxypxy = [self.K[0, 0], self.K[1, 1], self.cx, self.cy] else: print('No any board found!!!') else: # Undistortion h, w = self.QueryImg.shape[:2] newcameramtx, roi = cv2.getOptimalNewCameraMatrix(self.K, self.D, (w, h), 1, (w, h)) dst = cv2.undistort(self.QueryImg, self.K, self.D, None, newcameramtx) x, y, w, h = roi self.QueryImg = dst[y:y + h, x:x + w] gray = cv2.cvtColor(self.QueryImg, cv2.COLOR_BGR2GRAY) ret, corners = cv2.findChessboardCorners(gray, (10, 7), None) if ret: # found chessboard print('Found chessboard') self.chessBoard = True self.corners2 = cv2.cornerSubPix(gray, corners, (11, 11), (-1, -1), self.criteria) cv2.drawChessboardCorners(self.QueryImg, (10, 7), corners, ret) ret, self.rvecs, self.tvecs = cv2.solvePnP(self.objp, self.corners2, self.K, self.D) # ret, self.rvecs, self.tvecs, inliers = cv2.solvePnPRansac(self.objp, self.corners2, self.K, self.D) self.imgpts, jac = cv2.projectPoints(self.axis, self.rvecs, self.tvecs, self.K, self.D) self.QueryImg = self.draw(self.QueryImg, self.corners2, self.imgpts) self.pixelsPoints = np.asarray(self.corners2).squeeze() else: # check for charuco self.chessBoard = False self.useVoxel = False corners, ids, rejectedImgPoints = aruco.detectMarkers(gray, self.ARUCO_DICT) corners, ids, rejectedImgPoints, recoveredIds = aruco.refineDetectedMarkers( image=gray, board=self.calibation_board, detectedCorners=corners, detectedIds=ids, rejectedCorners=rejectedImgPoints, cameraMatrix=self.K, distCoeffs=self.D) if np.all(ids != None): print('found charuco board, ids:{}'.format(np.shape(ids))) self.chessBoard = False if len(ids) > 0: retval, self.rvecs, self.tvecs = aruco.estimatePoseBoard(corners, ids, self.calibation_board, self.K, self.D, None, None) if retval: self.QueryImg = aruco.drawAxis(self.QueryImg, self.K, self.D, self.rvecs, self.tvecs, 0.3) self.QueryImg = aruco.drawDetectedMarkers(self.QueryImg, corners, ids, borderColor=(0, 0, 255)) self.dst, jacobian = cv2.Rodrigues(self.rvecs) a, circle_tvec, b = .49, [], 1 circle_tvec.append( np.asarray(self.tvecs).squeeze() + np.dot(self.dst, np.asarray([a, a, 0]))) circle_tvec = np.mean(circle_tvec, axis=0) self.QueryImg = aruco.drawAxis(self.QueryImg, self.K, self.D, self.rvecs, circle_tvec, 0.2) imgpts, _ = cv2.projectPoints(self.pts, self.rvecs, self.tvecs, self.K, self.D) self.corners2 = np.append(imgpts, np.mean(imgpts, axis=0)).reshape(-1, 2) self.pt_dict = {} for i in range(len(self.pts)): self.pt_dict[tuple(self.pts[i])] = tuple(imgpts[i].ravel()) top_right = self.pt_dict[tuple(self.pts[0])] bot_right = self.pt_dict[tuple(self.pts[1])] bot_left = self.pt_dict[tuple(self.pts[2])] top_left = self.pt_dict[tuple(self.pts[3])] cv2.circle(self.QueryImg, top_right, 4, (0, 0, 255), 5) cv2.circle(self.QueryImg, bot_right, 4, (0, 0, 255), 5) cv2.circle(self.QueryImg, bot_left, 4, (0, 0, 255), 5) cv2.circle(self.QueryImg, top_left, 4, (0, 0, 255), 5) self.QueryImg = cv2.line(self.QueryImg, top_right, bot_right, (0, 255, 0), 4) self.QueryImg = cv2.line(self.QueryImg, bot_right, bot_left, (0, 255, 0), 4) self.QueryImg = cv2.line(self.QueryImg, bot_left, top_left, (0, 255, 0), 4) self.QueryImg = cv2.line(self.QueryImg, top_left, top_right, (0, 255, 0), 4) else: print('No board Found') self.image_ax = self.fig.add_subplot(1, 2, 2) #self.image_ax = self.fig.add_subplot(1, 2, 1) self.image_ax.imshow(self.QueryImg) self.image_ax.set_axis_off() self.image_ax.set_xlabel('Y') self.image_ax.set_ylabel('Z') else: self.fig = plt.figure() self.ax = self.fig.add_subplot(111, projection="3d") self.ax.set_xlabel('X', fontsize=10) self.ax.set_ylabel('Y', fontsize=10) self.ax.set_zlabel('Z', fontsize=10) self.fig.tight_layout() plt.subplots_adjust(left=.15, bottom=0.2) #plt.subplots_adjust( bottom=0.2) self.Rx, self.Ry, self.Rz = [np.deg2rad(-90), 0, np.deg2rad(-40)] if self.chessBoard else [0, 0, 0] self.Tx, self.Ty, self.Tz = 0, 0, 0 self.board_origin = [self.Tx, self.Ty, self.Tz] self.savePoints = Button(plt.axes([0.03, 0.45, 0.15, 0.04], ), 'filter points', color='white') self.savePoints.on_clicked(self.getClosestPoints) self.resetBtn = Button(plt.axes([0.03, 0.25, 0.15, 0.04], ), 'reset', color='white') self.resetBtn.on_clicked(self.reset) self.X_btn = Button(plt.axes([0.03, 0.9, 0.024, 0.04], ), 'X', color='red') self.X_btn.on_clicked(self.Close) self.OK_btn = Button(plt.axes([0.03, 0.83, 0.074, 0.04], ), 'OK', color='green') self.OK_btn.on_clicked(self.OK_btnClick) self.not_OK_btn = Button(plt.axes([0.105, 0.83, 0.074, 0.04], ), 'not OK', color='red') self.not_OK_btn.on_clicked(self.not_OK_btnClick) self.saveCorrespondences = Button(plt.axes([0.03, 0.76, 0.15, 0.04], ), 'Save points', color='white') self.saveCorrespondences.on_clicked(self.savePointsCorrespondences) self.fitChessboard = Button(plt.axes([0.03, 0.66, 0.15, 0.04], ), 'auto fit', color='white') self.fitChessboard.on_clicked(self.auto_fitBoard) # set up sliders self.Rx_Slider = Slider(plt.axes([0.25, 0.15, 0.65, 0.03]), 'Rx', -180, 180.0, valinit=np.degrees(self.Rx)) self.Ry_Slider = Slider(plt.axes([0.25, 0.1, 0.65, 0.03]), 'Ry', -180, 180.0, valinit=np.degrees(self.Ry)) self.Rz_Slider = Slider(plt.axes([0.25, 0.05, 0.65, 0.03]), 'Rz', -180, 180.0, valinit=np.degrees(self.Rz)) self.Rx_Slider.on_changed(self.update_R) self.Ry_Slider.on_changed(self.update_R) self.Rz_Slider.on_changed(self.update_R) self.check = CheckButtons(plt.axes([0.03, 0.3, 0.15, 0.12]), ('Axes', 'Black', 'Annotate'), (self.axis_on, self.colour, self.Annotate)) self.check.on_clicked(self.func_CheckButtons) # set up translation buttons self.step = .1 # m self.trigger = True self.Tx_btn_plus = Button(plt.axes([0.05, 0.15, 0.04, 0.045]), '+Tx', color='white') self.Tx_btn_plus.on_clicked(self.Tx_plus) self.Tx_btn_minus = Button(plt.axes([0.12, 0.15, 0.04, 0.045]), '-Tx', color='white') self.Tx_btn_minus.on_clicked(self.Tx_minus) self.Ty_btn_plus = Button(plt.axes([0.05, 0.1, 0.04, 0.045]), '+Ty', color='white') self.Ty_btn_plus.on_clicked(self.Ty_plus) self.Ty_btn_minus = Button(plt.axes([0.12, 0.1, 0.04, 0.045]), '-Ty', color='white') self.Ty_btn_minus.on_clicked(self.Ty_minus) self.Tz_btn_plus = Button(plt.axes([0.05, 0.05, 0.04, 0.045]), '+Tz', color='white') self.Tz_btn_plus.on_clicked(self.Tz_plus) self.Tz_btn_minus = Button(plt.axes([0.12, 0.05, 0.04, 0.045]), '-Tz', color='white') self.Tz_btn_minus.on_clicked(self.Tz_minus) self.Tx_flip = Button(plt.axes([0.17, 0.15, 0.04, 0.045]), 'FlipX', color='white') self.Tx_flip.on_clicked(self.flipX) self.Ty_flip = Button(plt.axes([0.17, 0.1, 0.04, 0.045]), 'FlipY', color='white') self.Ty_flip.on_clicked(self.flipY) self.Tz_flip = Button(plt.axes([0.17, 0.05, 0.04, 0.045]), 'FlipZ', color='white') self.Tz_flip.on_clicked(self.flipZ) self.radio = RadioButtons(plt.axes([0.03, 0.5, 0.15, 0.15], ), ('Final', 'Init'), active=0) self.radio.on_clicked(self.colorfunc) self.tag = None self.circle_center = None self.errors = {0: "Improper input parameters were entered.", 1: "The solution converged.", 2: "The number of calls to function has " "reached maxfev = %d.", 3: "xtol=%f is too small, no further improvement " "in the approximate\n solution " "is possible.", 4: "The iteration is not making good progress, as measured " "by the \n improvement from the last five " "Jacobian evaluations.", 5: "The iteration is not making good progress, " "as measured by the \n improvement from the last " "ten iterations.", 'unknown': "An error occurred."} self.legend_elements = [ Line2D([0], [0], marker='o', color='w', label='Original pointcloud', markerfacecolor='g', markersize=4), Line2D([0], [0], marker='o', color='w', label='Corners', markerfacecolor='k', markersize=4), Line2D([0], [0], marker='o', color='w', label='Margins', markerfacecolor='r', markersize=4), ] def setUp(self): self.getPointCoud() self.axisEqual3D(centers=np.mean(self.point_cloud, axis=0)) self.board() self.ax.legend(handles=self.legend_elements, loc='best') if self.showImage: self.getDepth_Inside_Outside() self.fitNewPlan() def auto_fitBoard(self, args): # estimate 3D-R and 3D-t between chess and PointCloud # Inital guess of the transformation x0 = np.array([np.degrees(self.Rx), np.degrees(self.Ry), np.degrees(self.Rz), self.Tx, self.Ty, self.Tz]) report = {"error": [], "template": []} def f_min(x): self.Rx, self.Ry, self.Rz = np.deg2rad(x[0]), np.deg2rad(x[1]), np.deg2rad(x[2]) self.Tx, self.Ty, self.Tz = x[3], x[4], x[5] template = self.board(plot=False) if self.useInitialPointCloud: dist_mat = distance_matrix(template, self.point_cloud) else: dist_mat = distance_matrix(template, self.corners_) err_func = dist_mat.sum(axis=1) # N x 1 # err_func = dist_mat.sum(axis=0) # N x 1 if self.debug: print('errors = {}, dist_mat:{}, err_func:{}'.format(round(np.sum(err_func), 2), np.shape(dist_mat), np.shape(err_func))) report["error"].append(np.sum(err_func)) report["template"].append(template) return err_func maxIters = 700 sol, status = leastsq(f_min, x0, ftol=1.49012e-07, xtol=1.49012e-07, maxfev=maxIters) print('sol:{}, status:{}'.format(sol, status)) print(self.errors[status]) if self.chess: self.chess.remove() if self.corn: self.corn.remove() if self.ICP_finetune_plot: self.ICP_finetune_plot.remove() self.lowerTemplate = False self.board() point_cloud = np.asarray(self.point_cloud, dtype=np.float32) template = np.asarray(report["template"][0], dtype=np.float32) if self.applyICP_directly else np.asarray( self.template_cloud, dtype=np.float32) converged, self.transf, estimate, fitness = self.ICP_finetune(template, point_cloud) # converged, self.transf, estimate, fitness = self.ICP_finetune(point_cloud,template) self.estimate = np.array(estimate) if self.chessBoard: self.ICP_finetune_plot = self.ax.scatter(self.estimate[:, 0], self.estimate[:, 1], self.estimate[:, 2], c='k', marker='o', alpha=0.8, s=4) else: idx = np.arange(start=0, stop=100, step=1) idx = np.delete(idx, [44, 45, 54, 55]) cornersToPLot = self.estimate[idx, :] self.ICP_finetune_plot = self.ax.scatter(cornersToPLot[:, 0], cornersToPLot[:, 1], cornersToPLot[:, 2], c='k', marker='o', alpha=0.8, s=4) self.trigger = False # set values of sol to Sliders self.Rx_Slider.set_val(np.rad2deg(self.Rx)) self.Ry_Slider.set_val(np.rad2deg(self.Ry)) self.Rz_Slider.set_val(np.rad2deg(self.Rz)) if self.chess: self.chess.remove() if self.corn: self.corn.remove() self.trigger = True self.board() self.AnnotateEdges() self.fig.canvas.draw_idle() if self.showError: print('min error:{} , at index:{}'.format(np.min(report["error"]), np.argmin(report["error"]))) rep = plt.figure(figsize=(15, 8)) plt.xlim(0, len(report["error"]) + 1) plt.xlabel('Iteration') plt.ylabel('RMSE') plt.yticks(color='w') plt.plot(np.arange(len(report["error"])) + 1, report["error"]) print('Start animation gif') def update_graph(num): data = np.asarray(report["template"][num]) graph._offsets3d = (data[:, 0], data[:, 1], data[:, 2]) title.set_text('Iteration {}'.format(num)) fig = plt.figure() ax = fig.add_subplot(111, projection='3d') title = ax.set_title('3D Test') data = report["template"][0] graph = ax.scatter(data[:, 0], data[:, 1], data[:, 2]) ax.scatter(self.point_cloud[:, 0], self.point_cloud[:, 1], self.point_cloud[:, 2]) ani = animation.FuncAnimation(fig, update_graph, 101, interval=2, blit=False, repeat=False) ani.save('myAnimation.gif', writer='imagemagick', fps=30) print('Animation done') plt.show() def flipX(self, event): self.Rx_Slider.set_val(np.rad2deg(self.Rx + np.pi)) self.update_R(0) def flipY(self, event): self.Ry_Slider.set_val(np.rad2deg(self.Ry + np.pi)) self.update_R(0) def flipZ(self, event): self.Rz_Slider.set_val(np.rad2deg(self.Rz + np.pi)) self.update_R(0) def update_R(self, val): if self.trigger: if self.chess: self.chess.remove() if self.corn: self.corn.remove() self.Rx = np.deg2rad(self.Rx_Slider.val) self.Ry = np.deg2rad(self.Ry_Slider.val) self.Rz = np.deg2rad(self.Rz_Slider.val) self.board() self.fig.canvas.draw_idle() def board(self, plot=True, given_origin=None, angle=None): self.board_origin = [self.Tx, self.Ty, self.Tz] if given_origin is None else given_origin if self.chessBoard: self.nCols, self.nRows, org = 7 + 2, 10 + 2, np.asarray(self.board_origin) #org[0] -= self.nCols / 2 #org[1] -= self.nRows / 2 org[0] -= 4 org[1] -= 6 #org = np.zeros(3) if self.lowerTemplate: nrCols, nrRows = 2, 3 else: nrCols, nrRows = self.nCols, self.nRows #nrCols, nrRows = self.nCols+1, self.nRows+1 #remove later print('org:{}, self.nCols - >{}, nrCols:{}'.format(org,self.nCols,nrCols)) X, Y = np.linspace(org[0], org[0] + self.nCols, num=nrCols), np.linspace(org[1], org[1] + self.nRows,num=nrRows) X, Y = np.linspace(org[0], org[0] + self.nCols-1, num=nrCols), np.linspace(org[1], org[1] + self.nRows-1, num=nrRows) print('X:{}'.format(X)) X, Y = np.meshgrid(X, Y) Z = np.full(np.shape(X), org[2]) colors, colortuple = np.empty(X.shape, dtype=str), ('k', 'w') for y in range(nrCols): for x in range(nrRows): colors[x, y] = colortuple[(x + y) % len(colortuple)] colors[0, 0] = 'r' alpha = 0.65 else: self.nCols, self.nRows, org = 10, 10, np.asarray(self.board_origin) org[0] -= self.nCols / 2 org[1] -= self.nRows / 2 # nrCols, nrRows = 4,4z nrCols, nrRows = self.nCols, self.nRows # nrCols, nrRows = 20, 20 X, Y = np.linspace(org[0], org[0] + self.nCols, num=nrCols), np.linspace(org[1], org[1] + self.nRows, num=nrRows) X, Y = np.meshgrid(X, Y) Z = np.full(np.shape(X), org[2]) alpha = 0.25 angles = np.array([self.Rx, self.Ry, self.Rz]) if angle is None else np.array(angle) Rot_matrix = self.eulerAnglesToRotationMatrix(angles) X, Y, Z = X * self.s, Y * self.s, Z * self.s corners = np.transpose(np.array([X, Y, Z]), (1, 2, 0)) init = corners.reshape(-1, 3) print('corners-----------------------------------------------------') #print(init) print('corners -> {}'.format(np.shape(init))) dist_Lidar = distance_matrix(init, init) print('dist_Lidar corners---------------------------------------------------------') print(dist_Lidar[0, :11]) translation = np.mean(init, axis=0) # get the mean point corners = np.subtract(corners, translation) # substract it from all the other points X, Y, Z = np.transpose(np.add(np.dot(corners, Rot_matrix), translation), (2, 0, 1)) # corners = np.transpose(np.array([X, Y, Z]), (1, 2, 0)).reshape(-1, 3) corners = np.transpose(np.array([X, Y, Z]), (2, 1, 0)).reshape(-1, 3) if plot: if self.chessBoard: self.chess = self.ax.plot_surface(X, Y, Z, facecolors=colors, linewidth=0.2, cmap='gray', alpha=alpha) else: self.chess = self.ax.plot_surface(X, Y, Z, linewidth=0.2, cmap='gray', alpha=alpha) idx = np.arange(start=0, stop=100, step=1) idx = np.delete(idx, [44, 45, 54, 55]) cornersToPLot = corners[idx, :] self.corn = self.ax.scatter(cornersToPLot[:, 0], cornersToPLot[:, 1], cornersToPLot[:, 2], c='tab:blue', marker='o', s=5) self.template_cloud = corners return np.array(corners) def getPointCoud(self, colorsMap='jet', skip=1, useRing = True): # X, Y, Z, intensity, ring if useRing: originalCloud = np.array(np.load(self.file, mmap_mode='r'))[:,:5] if InitLidar: xyz = originalCloud[:, 0:3] new_xyz = np.dot(xyz, Rot_matrix) originalCloud[:, 0:3] = new_xyz #mean_x = np.mean(originalCloud[:, 0]) #originalCloud[:, 0] = mean_x df = pd.DataFrame(data=originalCloud, columns=["X", "Y", "Z","intens","ring"]) gp = df.groupby('ring') keys = gp.groups.keys() #groups = gp.groups coolPoints, circlePoints = [],[] for i in keys: line = np.array(gp.get_group(i), dtype=np.float) first,last = np.array(line[0], dtype=np.float)[:3],np.array(line[-1], dtype=np.float)[:3] coolPoints.append(first) coolPoints.append(last) if self.chessBoard == False: if len(line) > 50: l = line[:,:3] for i in range(2,len(l)-2,1): d = np.linalg.norm(l[i]-l[i+1]) if d > 0.08: #half of the circle circlePoints.append(l[i]) circlePoints.append(l[i+1]) self.coolPoints = np.array(coolPoints).squeeze() self.ax.scatter(*self.coolPoints.T, color='r', marker='o', alpha=1, s=2) print('coolPoints:{}, circlePoints:{}'.format(np.shape(self.coolPoints), np.shape(circlePoints))) circlePoints = np.array(circlePoints) if len(circlePoints)>0: self.ax.scatter(*circlePoints.T, color='r', marker='o', alpha=1, s=5) self.fitCircle(circlePoints) #self.point_cloud = np.array(self.coolPoints, dtype=np.float32) self.point_cloud = np.array(np.load(self.file, mmap_mode='r')[::skip, :3], dtype=np.float32) if InitLidar: xyz = self.point_cloud[:, 0:3] new_xyz = np.dot(xyz, Rot_matrix) self.point_cloud[:, 0:3] = new_xyz # center the point_cloud #mean_x = np.mean(self.point_cloud[:, 0]) #self.point_cloud[:, 0] = mean_x self.point_cloud_mean = np.mean(self.point_cloud, axis=0) self.Tx, self.Ty, self.Tz = self.point_cloud_mean # self.point_cloud = self.point_cloud - self.point_cloud_mean self.point_cloud_colors = np.array(np.load(self.file, mmap_mode='r'))[::skip, 3] if self.plotInit: cm = plt.get_cmap(colorsMap) cNorm = matplotlib.colors.Normalize(vmin=min(self.point_cloud_colors), vmax=max(self.point_cloud_colors)) scalarMap = cmx.ScalarMappable(norm=cNorm, cmap=cm) self.p1 = self.ax.scatter(self.point_cloud[:, 0], self.point_cloud[:, 1], self.point_cloud[:, 2], color=scalarMap.to_rgba(self.point_cloud_colors), s=0.2) else: self.p = pcl.PointCloud(self.point_cloud) inlier, outliner, coefficients = self.do_ransac_plane_segmentation(self.p, pcl.SACMODEL_PLANE, pcl.SAC_RANSAC, 0.01) #self.planeEquation(coef=np.array(coefficients).squeeze()) self.point_cloud_init = self.point_cloud.copy() if self.useVoxel: pcd = o3d.geometry.PointCloud() pcd.points = o3d.utility.Vector3dVector(self.point_cloud) self.point_cloud = np.array(pcd.voxel_down_sample(voxel_size=self.voxel_size).points) # self.p1 = self.ax.scatter(outliner[:, 0], outliner[:, 1], outliner[:, 2], c='y', s=0.2) self.p2 = self.ax.scatter(inlier[:, 0], inlier[:, 1], inlier[:, 2], c='g', s=0.2) w, v = self.PCA(inlier) point = np.mean(inlier, axis=0) if self.chessBoard == False and self.circle_center: #point[1:] = self.circle_center point[[0,2]]= self.circle_center w *= 2 if self.chessBoard==False and self.circle_center: p = Circle(self.circle_center, self.circle_radius, alpha = .3, color='tab:blue') self.ax.add_patch(p) art3d.pathpatch_2d_to_3d(p, z=point[1], zdir="y") self.p3 = self.ax.quiver([point[0]], [point[1]], [point[2]], [v[0, :] * np.sqrt(w[0])], [v[1, :] * np.sqrt(w[0])], [v[2, :] * np.sqrt(w[0])], linewidths=(1.8,)) def axisEqual3D(self, centers=None): extents = np.array([getattr(self.ax, 'get_{}lim'.format(dim))() for dim in 'xyz']) sz = extents[:, 1] - extents[:, 0] # centers = np.mean(extents, axis=1) if centers is None maxsize = max(abs(sz)) r = maxsize / 2 for ctr, dim in zip(centers, 'xyz'): getattr(self.ax, 'set_{}lim'.format(dim))(ctr - r, ctr + r) def planeEquation(self, coef): a, b, c, d = coef mean = np.mean(self.point_cloud, axis=0) normal = [a, b, c] d2 = -mean.dot(normal) # print('d2:{}'.format(d2)) # print('mean:{}'.format(mean)) # print('The equation is {0}x + {1}y + {2}z = {3}'.format(a, b, c, d)) # plot the normal vector startX, startY, startZ = mean[0], mean[1], mean[2] startZ = (-normal[0] * startX - normal[1] * startY - d) * 1. / normal[2] self.ax.quiver([startX], [startY], [startZ], [normal[0]], [normal[1]], [normal[2]], linewidths=(3,),edgecolor="red") def PCA(self, data, correlation=False, sort=True): # data = nx3 mean = np.mean(data, axis=0) data_adjust = data - mean #: the data is transposed due to np.cov/corrcoef syntax if correlation: matrix = np.corrcoef(data_adjust.T) else: matrix = np.cov(data_adjust.T) eigenvalues, eigenvectors = np.linalg.eig(matrix) if sort: #: sort eigenvalues and eigenvectors sort = eigenvalues.argsort()[::-1] eigenvalues = eigenvalues[sort] eigenvectors = eigenvectors[:, sort] return eigenvalues, eigenvectors def eulerAnglesToRotationMatrix(self, theta): R_x = np.array([[1, 0, 0], [0, math.cos(theta[0]), -math.sin(theta[0])], [0, math.sin(theta[0]), math.cos(theta[0])] ]) R_y = np.array([[math.cos(theta[1]), 0, math.sin(theta[1])], [0, 1, 0], [-math.sin(theta[1]), 0, math.cos(theta[1])] ]) R_z = np.array([[math.cos(theta[2]), -math.sin(theta[2]), 0], [math.sin(theta[2]), math.cos(theta[2]), 0], [0, 0, 1] ]) R = np.dot(R_z, np.dot(R_y, R_x)) return R def do_ransac_plane_segmentation(self, pcl_data, pcl_sac_model_plane, pcl_sac_ransac, max_distance): """ Create the segmentation object :param pcl_data: point could data subscriber :param pcl_sac_model_plane: use to determine plane models :param pcl_sac_ransac: RANdom SAmple Consensus :param max_distance: Max distance for apoint to be considered fitting the model :return: segmentation object """ seg = pcl_data.make_segmenter() seg.set_model_type(pcl_sac_model_plane) seg.set_method_type(pcl_sac_ransac) seg.set_distance_threshold(max_distance) inliers, coefficients = seg.segment() inlier_object = pcl_data.extract(inliers, negative=False) outlier_object = pcl_data.extract(inliers, negative=True) if len(inliers) <= 1: outlier_object = [0, 0, 0] inlier_object, outlier_object = np.array(inlier_object), np.array(outlier_object) return inlier_object, outlier_object, coefficients def func_CheckButtons(self, label): if label == 'Axes': if self.axis_on: self.ax.set_axis_off() self.axis_on = False else: self.ax.set_axis_on() self.axis_on = True elif label == 'Black': if self.colour: self.colour = False self.ax.set_facecolor((1, 1, 1)) else: self.colour = True self.ax.set_facecolor((0, 0, 0)) elif label == 'Annotate': self.Annotate = not self.Annotate self.AnnotateEdges() self.fig.canvas.draw_idle() def ICP_finetune(self, points_in, points_out): cloud_in = pcl.PointCloud() cloud_out = pcl.PointCloud() cloud_in.from_array(points_in) cloud_out.from_array(points_out) # icp = cloud_in.make_IterativeClosestPoint() icp = cloud_out.make_IterativeClosestPoint() converged, transf, estimate, fitness = icp.icp(cloud_in, cloud_out) print('fitness:{}, converged:{}, transf:{}, estimate:{}'.format(fitness, converged, np.shape(transf), np.shape(estimate))) return converged, transf, estimate, fitness def colorfunc(self, label): if label == 'Init': self.plotInit = True else: self.plotInit = False self.reset(0) def OK_btnClick(self, args): self.OK = True plt.close() def not_OK_btnClick(self, args): self.OK = False plt.close() def Close(self, args): global globalTrigger globalTrigger = False plt.close() def reset(self, args): self.ax.cla() self.getPointCoud() self.axisEqual3D(centers=np.mean(self.point_cloud, axis=0)) self.Rx, self.Ry, self.Rz = 0, 0, 0 self.Tx, self.Ty, self.Tz = 0, 0, 0 self.board_origin = [self.Tx, self.Ty, self.Tz] self.board() self.fig.canvas.draw_idle() def getClosestPoints(self, arg): dist_mat = distance_matrix(self.template_cloud, self.point_cloud_init) self.neighbours = np.argsort(dist_mat, axis=1)[:, 0] self.finaPoints = np.asarray(self.point_cloud_init[self.neighbours, :]).squeeze() if self.chess: self.chess.remove() if self.corn: self.corn.remove() if self.p3: self.p3.remove() if self.p2: self.p2.remove() if self.p1: self.p1.remove() self.scatter_finalPoints = self.ax.scatter(self.finaPoints[:, 0], self.finaPoints[:, 1], self.finaPoints[:, 2], c='k', marker='x', s=1) self.corn = self.ax.scatter(self.template_cloud[:, 0], self.template_cloud[:, 1], self.template_cloud[:, 2], c='blue', marker='o', s=5) self.fig.canvas.draw_idle() def Tz_plus(self, event): self.Tz += self.step self.update_R(0) def Tz_minus(self, event): self.Tz -= self.step self.update_R(0) def Ty_plus(self, event): self.Ty += self.step self.update_R(0) def Ty_minus(self, event): self.Ty -= self.step self.update_R(0) def Tx_plus(self, event): self.Tx += self.step self.update_R(0) def Tx_minus(self, event): self.Tx -= self.step self.update_R(0) def readCameraIntrin(self): name = 'inside' name = 'outside' self.camera_model = load_obj('{}_combined_camera_model'.format(name)) self.camera_model_rectify = load_obj('{}_combined_camera_model_rectify'.format(name)) self.K_left = self.camera_model['K_left'] self.K_right = self.camera_model['K_right'] self.D_left = self.camera_model['D_left'] self.D_right = self.camera_model['D_right'] # self.K_left = self.camera_model['K_right'] # self.K_right = self.camera_model['K_left'] # self.D_left = self.camera_model['D_right'] # self.D_right = self.camera_model['D_left'] # print('K_left') # print(self.K_left) # print('K_right') # print(self.K_right) self.R = self.camera_model['R'] self.T = self.camera_model['T'] self.T = np.array([-0.977, 0.004, 0.215])[:, np.newaxis] angles = np.array([np.deg2rad(1.044), np.deg2rad(22.632), np.deg2rad(-.95)]) self.R = euler_matrix(angles) #self.T = np.array([-0.98, 0., 0.12])[:, np.newaxis] #self.T = np.array([-.75, 0., 0.])[:, np.newaxis] #print('self T after {}'.format(np.shape(self.T))) #angles = np.array([np.deg2rad(0.68), np.deg2rad(22.66), np.deg2rad(-1.05)]) #self.R = euler_matrix(angles) #Q = self.camera_model_rectify['Q'] #roi_left, roi_right = self.camera_model_rectify['roi_left'], self.camera_model_rectify['roi_right'] self.leftMapX, self.leftMapY = self.camera_model_rectify['leftMapX'], self.camera_model_rectify['leftMapY'] self.rightMapX, self.rightMapY = self.camera_model_rectify['rightMapX'], self.camera_model_rectify['rightMapY'] img_shape = (1936, 1216) print('img_shape:{}'.format(img_shape)) R1, R2, P1, P2, Q, roi_left, roi_right = cv2.stereoRectify(self.K_left, self.D_left, self.K_right, self.D_right, imageSize=img_shape, R=self.camera_model['R'], T=self.camera_model['T'], flags=cv2.CALIB_ZERO_DISPARITY, alpha=-1 #alpha=0 ) self.leftMapX, self.leftMapY = cv2.initUndistortRectifyMap( self.K_left, self.D_left, R1, P1, img_shape, cv2.CV_32FC1) self.rightMapX, self.rightMapY = cv2.initUndistortRectifyMap( self.K_right, self.D_right, R2, P2, img_shape, cv2.CV_32FC1) self.K = self.K_right self.D = self.D_right try: N = 5 aruco_dict = aruco.custom_dictionary(0, N, 1) aruco_dict.bytesList = np.empty(shape=(4, N - 1, N - 1), dtype=np.uint8) A = np.array([[0, 0, 1, 0, 0], [0, 1, 0, 1, 0], [0, 1, 0, 1, 0], [0, 1, 1, 1, 0], [0, 1, 0, 1, 0]], dtype=np.uint8) aruco_dict.bytesList[0] = aruco.Dictionary_getByteListFromBits(A) R = np.array([[1, 1, 1, 1, 0], [1, 0, 0, 1, 0], [1, 1, 1, 0, 0], [1, 0, 0, 1, 0], [1, 0, 0, 0, 1]], dtype=np.uint8) aruco_dict.bytesList[1] = aruco.Dictionary_getByteListFromBits(R) V = np.array([[1, 0, 0, 0, 1], [1, 0, 0, 0, 1], [1, 0, 0, 0, 1], [0, 1, 0, 1, 0], [0, 0, 1, 0, 0]], dtype=np.uint8) O = np.array([[0, 1, 1, 1, 0], [1, 0, 0, 0, 1], [1, 0, 0, 0, 1], [1, 0, 0, 0, 1], [0, 1, 1, 1, 0]], dtype=np.uint8) aruco_dict.bytesList[2] = aruco.Dictionary_getByteListFromBits(O) aruco_dict.bytesList[3] = aruco.Dictionary_getByteListFromBits(V) self.ARUCO_DICT = aruco_dict self.calibation_board = aruco.GridBoard_create( markersX=2, markersY=2, markerLength=0.126, markerSeparation=0.74, dictionary=self.ARUCO_DICT) except: print('Install Aruco') def draw(self, img, corners, imgpts): corner = tuple(corners[0].ravel()) cv2.line(img, corner, tuple(imgpts[0].ravel()), (255, 0, 0), 5) cv2.line(img, corner, tuple(imgpts[1].ravel()), (0, 255, 0), 5) cv2.line(img, corner, tuple(imgpts[2].ravel()), (0, 0, 255), 5) return img def annotate3D(self, ax, s, *args, **kwargs): self.tag = Annotation3D(s, *args, **kwargs) ax.add_artist(self.tag) def AnnotateEdges(self, giveAX=None, givenPoints=None): if self.Annotate: # add vertices annotation. if giveAX is None: if self.lowerTemplate or self.chessBoard == False: if self.chessBoard == False: pts = np.asarray(self.template_cloud.copy()).reshape(self.nCols, self.nRows, 3) idx = np.array([44, 45, 54, 55]) center = np.mean(self.template_cloud[idx], axis=0) self.templatePoints = [pts[0, -1, :], pts[-1, -1, :], pts[-1, 0, :], pts[0, 0, :], center] self.templatePoints = np.array(self.templatePoints).reshape(-1, 3) cornersToPLot = self.estimate[idx, :] for j, xyz_ in enumerate(self.templatePoints): self.annotate3D(self.ax, s=str(j), xyz=xyz_, fontsize=12, xytext=(-1, 1), textcoords='offset points', ha='right', va='bottom') else: for j, xyz_ in enumerate(self.template_cloud): self.annotate3D(self.ax, s=str(j), xyz=xyz_, fontsize=8, xytext=(-1, 1), textcoords='offset points', ha='right', va='bottom') else: try: templatePoints = np.asarray(self.template_cloud.copy()).reshape(self.nCols, self.nRows, 3)[ 1:self.nCols - 1, 1:self.nRows - 1, :] except: templatePoints = np.asarray(self.template_cloud.copy()).reshape(self.nCols+1, self.nRows+1, 3)[ 1:self.nCols - 1, 1:self.nRows - 1, :] # templatePoints = np.asarray(self.template_cloud.copy()).reshape(self.nRows,self.nCols, 3)[1:self.nRows-1,1:self.nCols-1,:] self.templatePoints = np.array(templatePoints).reshape(-1, 3) for j, xyz_ in enumerate(self.templatePoints): self.annotate3D(self.ax, s=str(j), xyz=xyz_, fontsize=8, xytext=(-3, 3), textcoords='offset points', ha='right', va='bottom') else: for j, xyz_ in enumerate(givenPoints): self.annotate3D(giveAX, s=str(j), xyz=xyz_, fontsize=10, xytext=(-3, 3), textcoords='offset points', ha='right', va='bottom') if self.showImage: # annotate image points = np.asarray(self.corners2).squeeze() font, lineType = cv2.FONT_HERSHEY_SIMPLEX, 2 if self.chessBoard else 10 for i, point in enumerate(points): point = tuple(point.ravel()) cv2.putText(self.QueryImg, '{}'.format(i), point, font, 1 if self.chessBoard else 3, (0, 0, 0) if self.chessBoard else (255, 0, 0), lineType) self.image_ax.imshow(self.QueryImg) def getCamera_XYZ_Stereo(self): #cam_rot, jac = cv2.Rodrigues(self.rvecs) #mR = np.matrix(cam_rot) #mT = np.matrix(self.tvecs) #cam_trans = -mR * mT _3DPoints = [] for i, pixel in enumerate(self.x_left): u, v = pixel.ravel() u, v = int(u), int(v) distance = self.depth[i] pt = np.array([u, v, distance]) pt[0] = pt[2] * (pt[0] - self.fxypxy[2]) / self.fxypxy[0] pt[1] = pt[2] * (pt[1] - self.fxypxy[3]) / self.fxypxy[1] # pt = pt.dot(cam_rot.T) + self.tvecs _3DPoints.append(pt) print('_3DPoints {}'.format(np.shape(_3DPoints))) print('tvec : {}'.format(np.asarray(self.tvecs).squeeze())) print('Camera_XYZ_Stereo mean {}'.format(np.mean(_3DPoints, axis=0))) _3DPoints = np.array(_3DPoints).squeeze() print('from disparity getCamera_XYZ_Stereo ') d = distance_matrix(_3DPoints,_3DPoints) print(d) return _3DPoints def getCamera_XYZ(self): R_mtx, jac = cv2.Rodrigues(self.rvecs) inv_R_mtx = np.linalg.inv(R_mtx) inv_K = np.linalg.inv(self.K) def compute_XYZ(u, v): # from 2D pixels to 3D world uv_ = np.array([[u, v, 1]], dtype=np.float32).T suv_ = uv_ xyz_ = inv_K.dot(suv_) - self.tvecs XYZ = inv_R_mtx.dot(xyz_) pred = XYZ.T[0] return pred Camera_XYZ = [] for i, point in enumerate(self.pixelsPoints): xyz = compute_XYZ(u=point[0], v=point[1]) # print 'xyz:{}'.format(xyz) Camera_XYZ.append(xyz) Camera_XYZ = np.array(Camera_XYZ) print('init tvec : {}'.format(np.asarray(self.tvecs).squeeze())) print('Camera_XYZ mean {}'.format(np.mean(Camera_XYZ, axis=0))) if self.img_file2 is None: for i, point in enumerate(Camera_XYZ): imgpts, jac = cv2.projectPoints(point, self.rvecs, self.tvecs, self.K, self.D) imgpts = np.asarray(imgpts).squeeze() cv2.circle(self.QueryImg, (int(imgpts[0]), int(imgpts[1])), 7, (255, 0, 0), 7) self.image_ax.imshow(self.QueryImg) return Camera_XYZ def getImagePixels(self): img = cv2.imread(self.img_file) #left image img2 = cv2.imread(self.img_file2) # left image gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) gray2 = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY) pixelsPoints,pixelsPoints2, _3DreconstructedBoard = [],[],[] if self.chessBoard: ret, corners = cv2.findChessboardCorners(gray, (10, 7), None) ret2, corners2 = cv2.findChessboardCorners(gray2, (10, 7), None) if ret and ret2: # found chessboard print('Found chessboard') corners_2 = cv2.cornerSubPix(gray, corners, (11, 11), (-1, -1), self.criteria) corners2_2 = cv2.cornerSubPix(gray2, corners2, (11, 11), (-1, -1), self.criteria) pixelsPoints = np.asarray(corners_2).squeeze() pixelsPoints2 = np.asarray(corners2_2).squeeze() cv2.drawChessboardCorners(img, (10, 7), corners_2, ret) cv2.drawChessboardCorners(img2, (10, 7), corners2_2, ret) # Find the rotation and translation vectors. success, rvecs, tvecs, inliers = cv2.solvePnPRansac(self.objp, corners_2, self.K, self.D) rvecs, _ = cv2.Rodrigues(rvecs) _3Dpoints = self.objp # project 3D points to image plane _2Dpoints, jac = cv2.projectPoints(_3Dpoints, rvecs, tvecs, self.K, self.D) _2Dpoints = np.array(_2Dpoints, dtype=np.float32).squeeze() print('_2Dpoints -> {}'.format(np.shape(_2Dpoints))) for i in range(len(_2Dpoints)): cv2.circle(img, tuple(_2Dpoints[i]), 5, (0, 255, 0), 3) _3Dpoints = rvecs.dot(_3Dpoints.T) + tvecs _3Dpoints = _3Dpoints.T print('_3Dpoints->{}'.format(np.shape(_3Dpoints))) dist_mat = distance_matrix(_3Dpoints, _3Dpoints) print('dist_mat for OpencvReconstructed') print(dist_mat[0, :11]) _3DreconstructedBoard = _3Dpoints else: return None,None else: corners, ids, rejectedImgPoints = aruco.detectMarkers(gray, self.ARUCO_DICT) corners, ids, rejectedImgPoints, recoveredIds = aruco.refineDetectedMarkers( image=gray, board=self.calibation_board, detectedCorners=corners, detectedIds=ids, rejectedCorners=rejectedImgPoints, cameraMatrix=self.K, distCoeffs=self.D) corners2, ids2, rejectedImgPoints2 = aruco.detectMarkers(gray2, self.ARUCO_DICT) corners2, ids2, rejectedImgPoints2, recoveredIds2 = aruco.refineDetectedMarkers( image=gray2, board=self.calibation_board, detectedCorners=corners2, detectedIds=ids2, rejectedCorners=rejectedImgPoints2, cameraMatrix=self.K, distCoeffs=self.D) if np.all(ids != None) and np.all(ids2 != None): print('found charuco board, ids:{}'.format(np.shape(ids))) if len(ids) and len(ids2) > 0: retval, self.rvecs, self.tvecs = aruco.estimatePoseBoard(corners, ids, self.calibation_board, self.K, self.D, None, None) retval2, self.rvecs2, self.tvecs2 = aruco.estimatePoseBoard(corners2, ids2, self.calibation_board, self.K, self.D, None, None) img = aruco.drawDetectedMarkers(img, corners, ids,borderColor=(0, 0, 255)) img2 = aruco.drawDetectedMarkers(img2, corners2, ids2, borderColor=(0, 0, 255)) if retval and retval2: self.dst, jacobian = cv2.Rodrigues(self.rvecs) self.dst2, jacobian = cv2.Rodrigues(self.rvecs2) #self.pts = np.float32([[0, b, 0], [b, b, 0], [b, 0, 0], [-0.03, -0.03, 0]]) b = 1 self.pts = np.float32([[0, b, 0], [b, b, 0], [b, 0, 0], [-0.03, -0.03, 0],[.5,.5,0]]) _3Dpoints = self.dst.T.dot(np.array(self.pts).squeeze().T) + self.tvecs _3Dpoints = _3Dpoints.T print('_3Dpoints->{}'.format(np.shape(_3Dpoints))) dist_mat = distance_matrix(_3Dpoints, _3Dpoints) print('dist_mat for OpencvReconstructed') print(dist_mat) _3DreconstructedBoard = _3Dpoints imgpts, _ = cv2.projectPoints(self.pts, self.rvecs, self.tvecs, self.K, self.D) #corners2 = np.append(imgpts, np.mean(imgpts, axis=0)).reshape(-1, 2) corners2 = np.array(imgpts).squeeze() self.pt_dict = {} for i in range(len(self.pts)): self.pt_dict[tuple(self.pts[i])] = tuple(imgpts[i].ravel()) top_right = self.pt_dict[tuple(self.pts[0])] bot_right = self.pt_dict[tuple(self.pts[1])] bot_left = self.pt_dict[tuple(self.pts[2])] top_left = self.pt_dict[tuple(self.pts[3])] img = cv2.line(img, top_right, bot_right, (0, 255, 0), 4) img = cv2.line(img, bot_right, bot_left, (0, 255, 0), 4) img = cv2.line(img, bot_left, top_left, (0, 255, 0), 4) img = cv2.line(img, top_left, top_right, (0, 255, 0), 4) cv2.circle(img, tuple(corners2[-1]), 5, (0, 255, 0), 3) cv2.circle(img, tuple(corners2[-2]), 5, (0, 0, 255), 3) pixelsPoints = np.asarray(corners2).squeeze() imgpts, _ = cv2.projectPoints(self.pts, self.rvecs2, self.tvecs2, self.K, self.D) #corners2 = np.append(imgpts, np.mean(imgpts, axis=0)).reshape(-1, 2) corners2 = np.array(imgpts).squeeze() self.pt_dict = {} for i in range(len(self.pts)): self.pt_dict[tuple(self.pts[i])] = tuple(imgpts[i].ravel()) top_right = self.pt_dict[tuple(self.pts[0])] bot_right = self.pt_dict[tuple(self.pts[1])] bot_left = self.pt_dict[tuple(self.pts[2])] top_left = self.pt_dict[tuple(self.pts[3])] img2 = cv2.line(img2, top_right, bot_right, (0, 255, 0), 4) img2 = cv2.line(img2, bot_right, bot_left, (0, 255, 0), 4) img2 = cv2.line(img2, bot_left, top_left, (0, 255, 0), 4) img2 = cv2.line(img2, top_left, top_right, (0, 255, 0), 4) cv2.circle(img2, tuple(corners2[-1]), 5, (0, 255, 0), 3) #cv2.circle(img2, tuple(corners2[-2]), 5, (0, 0, 255), 3) pixelsPoints2 = np.asarray(corners2).squeeze() else: return None,None else: return None,None else: return None,None scale = .4 _horizontal = np.hstack( (cv2.resize(img, None, fx=scale, fy=scale), cv2.resize(img2, None, fx=scale, fy=scale))) cv2.imshow('_horizontal', _horizontal) cv2.waitKey(0) cv2.destroyAllWindows() return pixelsPoints,pixelsPoints2, _3DreconstructedBoard def savePointsCorrespondences(self, args): display = True fig = plt.figure(figsize=plt.figaspect(1)) ax = plt.axes(projection='3d') ax.set_xlabel('X') ax.set_ylabel('Y') ax.set_zlabel('Z') if self.chessBoard: legend_elements = [ Line2D([0], [0], marker='o', label='board template', markerfacecolor='tab:blue', markersize=6), Line2D([0], [0], marker='o', label='ICP finetuned', markerfacecolor='green', markersize=6), Line2D([0], [0], marker='o', label='closest lidar points', markerfacecolor='k', markersize=6), Line2D([0], [0], marker='o', label='Camera_XYZ', markerfacecolor='red', markersize=6), ] board_template = self.template_cloud board_template_ICP_finetuned = self.estimate closest_lidar_points = self.finaPoints try: icp_finetuned_inside = np.asarray(self.estimate).reshape(self.nCols, self.nRows, 3)[1:self.nCols - 1, 1:self.nRows - 1, :] board_template_inside = board_template.reshape(self.nCols, self.nRows, 3)[1:self.nCols - 1, 1:self.nRows - 1, :] closest_lidar_points_inside = closest_lidar_points.reshape(self.nCols, self.nRows, 3)[1:self.nCols - 1, 1:self.nRows - 1, :] except: print('Second-----------------------------') icp_finetuned_inside = np.asarray(self.estimate).reshape(self.nCols+1, self.nRows+1, 3)[1:self.nCols - 1, 1:self.nRows - 1, :] board_template_inside = board_template.reshape(self.nCols+1, self.nRows+1, 3)[1:self.nCols - 1, 1:self.nRows - 1, :] closest_lidar_points_inside = closest_lidar_points.reshape(self.nCols+1, self.nRows+1, 3)[1:self.nCols - 1, 1:self.nRows - 1, :] icp_finetuned_inside = np.array(icp_finetuned_inside).reshape(-1, 3) board_template_inside = np.array(board_template_inside).reshape(-1, 3) print('board_template_inside-----------------------------------------------------') print(board_template_inside) print('board_template_inside -> {}'.format(np.shape(board_template_inside))) dist_Lidar = distance_matrix(board_template_inside, board_template_inside) print('dist_Lidar---------------------------------------------------------') print(dist_Lidar[0, :11]) closest_lidar_points_inside = np.array(closest_lidar_points_inside).reshape(-1, 3) Camera_XYZ = self.getCamera_XYZ() if self.img_file2: Camera_XYZ_Stereo = self.getCamera_XYZ_Stereo() else: Camera_XYZ_Stereo = np.array([[0, 0, 0]]) display = True if display: print('board_template:{}'.format(np.shape(board_template))) print('board_template_ICP_finetuned:{}'.format(np.shape(board_template_ICP_finetuned))) print('icp_finetuned_inside:{}'.format(np.shape(icp_finetuned_inside))) print('board_template_inside:{}'.format(np.shape(board_template_inside))) print('closest_lidar_points:{}'.format(np.shape(closest_lidar_points))) print('closest_lidar_points_inside:{}'.format(np.shape(closest_lidar_points_inside))) print('Camera_XYZ:{}'.format(np.shape(Camera_XYZ))) print('Camera_XYZ_Stereo:{}'.format(np.shape(Camera_XYZ_Stereo))) #dist = distance_matrix(Camera_XYZ_Stereo, Camera_XYZ_Stereo) #print('distance matrix Camera_XYZ_Stereo:{}'.format(dist)) ax.scatter(*board_template.T, color='b', marker='o', alpha=.5, s=8) ax.scatter(*board_template_ICP_finetuned.T, color='r', marker='o', alpha=.5, s=8) ax.scatter(*board_template_inside.T, color='tab:blue', marker='x', alpha=1, s=10) ax.scatter(*icp_finetuned_inside.T, color='g', marker='x', alpha=1, s=10) ax.scatter(*closest_lidar_points.T, color='r', marker='x', alpha=.8, s=10) ax.scatter(*closest_lidar_points_inside.T, color='k', marker='x', alpha=1, s=20) ax.scatter(*Camera_XYZ.T, color='k', marker='x', alpha=1, s=30) ax.scatter(*Camera_XYZ_Stereo.T, color='r', marker='o', alpha=1, s=3) self.AnnotateEdges(giveAX=ax, givenPoints=board_template_inside) extents = np.array([getattr(ax, 'get_{}lim'.format(dim))() for dim in 'xyz']) sz = extents[:, 1] - extents[:, 0] centers = np.mean(board_template, axis=0) # centers = np.mean(Camera_XYZ_Stereo, axis=0) if self.img_file2 is not None else np.mean(board_template,axis=0) maxsize = max(abs(sz)) r = maxsize / 2 for ctr, dim in zip(centers, 'xyz'): getattr(ax, 'set_{}lim'.format(dim))(ctr - r, ctr + r) self.pixelsPointsLeft, self.pixelsPointsRight, _3DreconstructedBoard = self.getImagePixels() print('_3DreconstructedBoard -> {}'.format(np.shape(_3DreconstructedBoard))) if len(self.pixelsPointsLeft)<=0: print('Cannot get pixels points !!! ') self.points_correspondences = dict([ ('board_template', board_template), ('board_template_ICP_finetuned', board_template_ICP_finetuned), ('board_template_inside', board_template_inside), ('icp_finetuned_inside', icp_finetuned_inside), ('closest_lidar_points', closest_lidar_points), ('closest_lidar_points_inside', closest_lidar_points_inside), ('pixelsPointsLeft', self.pixelsPointsLeft), ('pixelsPointsRight', self.pixelsPointsRight), ('Camera_XYZ_Stereo', Camera_XYZ_Stereo), ('_3DreconstructedBoard',_3DreconstructedBoard), ('Camera_XYZ', Camera_XYZ)]) # save_obj(self.points_correspondences, self.name) else: legend_elements = [ Line2D([0], [0], marker='o', label='board template all', markerfacecolor='b', markersize=6), Line2D([0], [0], marker='o', label='ICP finetuned', markerfacecolor='red', markersize=6), Line2D([0], [0], marker='o', label='board template inside', markerfacecolor='tab:blue', markersize=6), Line2D([0], [0], marker='o', label='closest lidar points', markerfacecolor='red', markersize=6), ] pts = np.asarray(self.template_cloud.copy()).reshape(self.nCols, self.nRows, 3) idx = np.array([44, 45, 54, 55]) center = np.mean(self.template_cloud[idx], axis=0) board_template = np.array([pts[0, -1, :], pts[-1, -1, :], pts[-1, 0, :], pts[0, 0, :], center]).reshape(-1, 3) board_template = board_template pts = np.asarray(self.estimate.copy()).reshape(self.nCols, self.nRows, 3) center = np.mean(self.estimate[idx], axis=0) board_template_ICP_finetuned = np.array( [pts[0, -1, :], pts[-1, -1, :], pts[-1, 0, :], pts[0, 0, :], center]).reshape(-1, 3) board_template_inside = self.templatePoints pts = np.asarray(self.finaPoints.copy()).reshape(self.nCols, self.nRows, 3) center = np.mean(self.finaPoints[idx], axis=0) closest_lidar_points = np.array( [pts[0, -1, :], pts[-1, -1, :], pts[-1, 0, :], pts[0, 0, :], center]).reshape(-1, 3) if self.img_file2: Camera_XYZ_Stereo = self.getCamera_XYZ_Stereo() else: Camera_XYZ_Stereo = np.array([[0, 0, 0]]) if display: print('board_template:{}'.format(np.shape(board_template))) print('board_template_ICP_finetuned:{}'.format(np.shape(board_template_ICP_finetuned))) print('board_template_inside:{}'.format(np.shape(board_template_inside))) print('closest_lidar_points:{}'.format(np.shape(closest_lidar_points))) print('Camera_XYZ_Stereo:{}'.format(np.shape(Camera_XYZ_Stereo))) ax.scatter(*board_template.T, color='b', marker='o', alpha=.5, s=8) ax.scatter(*board_template_ICP_finetuned.T, color='r', marker='o', alpha=.5, s=8) ax.scatter(*board_template_inside.T, color='tab:blue', marker='x', alpha=1, s=10) ax.scatter(*closest_lidar_points.T, color='r', marker='x', alpha=.8, s=10) ax.scatter(*Camera_XYZ_Stereo.T, color='r', marker='o', alpha=.8, s=20) self.AnnotateEdges(giveAX=ax, givenPoints=board_template_inside) extents = np.array([getattr(ax, 'get_{}lim'.format(dim))() for dim in 'xyz']) sz = extents[:, 1] - extents[:, 0] centers = np.mean(board_template, axis=0) # centers = np.mean(Camera_XYZ, axis=0) if self.img_file2 is not None else np.mean(board_template, axis=0) maxsize = max(abs(sz)) r = maxsize / 2 for ctr, dim in zip(centers, 'xyz'): getattr(ax, 'set_{}lim'.format(dim))(ctr - r, ctr + r) self.pixelsPointsLeft, self.pixelsPointsRight, _3DreconstructedBoard = self.getImagePixels() _3DreconstructedBoard = np.array(_3DreconstructedBoard).squeeze() print('_3DreconstructedBoard -> {}'.format(np.shape(_3DreconstructedBoard))) if len(self.pixelsPointsLeft) <= 0: print('Cannot get pixels points !!! ') ax.scatter(*_3DreconstructedBoard.T, color='b', marker='x', alpha=1, s=20) print('pixelsPointsLeft:{}'.format(np.shape(self.pixelsPointsLeft))) print('pixelsPointsRight:{}'.format(np.shape(self.pixelsPointsRight))) print('_3DreconstructedBoard:{}'.format(np.shape(_3DreconstructedBoard))) self.points_correspondences = dict([ ('board_template', board_template), ('board_template_ICP_finetuned', board_template_ICP_finetuned), ('board_template_inside', board_template_inside), ('pixelsPointsLeft', self.pixelsPointsLeft), ('pixelsPointsRight', self.pixelsPointsRight), ('_3DreconstructedBoard',_3DreconstructedBoard), ('Camera_XYZ_Stereo', Camera_XYZ_Stereo), ('closest_lidar_points', closest_lidar_points)]) # save_obj(self.points_correspondences, self.name) ax.legend(handles=legend_elements, loc='best') plt.show() def getDepth_Inside_Outside(self): calibrations = ['inside', 'outside'] output = [] for calib in calibrations: camera_model = load_obj('{}_combined_camera_model'.format(calib)) camera_model_rectify = load_obj('{}_combined_camera_model_rectify'.format(calib)) K_left = camera_model['K_right'] D_left = camera_model['D_right'] T = camera_model['T'] leftMapX, leftMapY = camera_model_rectify['leftMapX'], camera_model_rectify['leftMapY'] rightMapX, rightMapY = camera_model_rectify['rightMapX'], camera_model_rectify['rightMapY'] imgleft = cv2.imread(self.img_file) imgright = cv2.imread(self.img_file2) if stereoRectify: imgleft = cv2.remap(src=imgleft, map1=leftMapX, map2=leftMapY, interpolation=cv2.INTER_LINEAR, dst=None,borderMode=cv2.BORDER_CONSTANT) imgright = cv2.remap(src=imgright, map1=rightMapX, map2=rightMapY, interpolation=cv2.INTER_LINEAR, dst=None,borderMode=cv2.BORDER_CONSTANT) gray_left = cv2.cvtColor(imgleft, cv2.COLOR_BGR2GRAY) ret_left, corners_left = cv2.findChessboardCorners(gray_left, (10, 7), None) gray_right = cv2.cvtColor(imgright, cv2.COLOR_BGR2GRAY) ret_right, corners_right = cv2.findChessboardCorners(gray_right, (10, 7), None) if ret_left and ret_right: # found chessboard corners2_left = cv2.cornerSubPix(gray_left, corners_left, (11, 11), (-1, -1), self.criteria) x_left = np.asarray(corners2_left).squeeze() corners2_right = cv2.cornerSubPix(gray_right, corners_right, (11, 11), (-1, -1), self.criteria) x_right = np.asarray(corners2_right).squeeze() baseline = abs(T[0]) focal_length, cx, cy = K_left[0, 0], K_left[0, 2], K_left[1, 2] disparity = np.sum(np.sqrt((x_left - x_right) ** 2), axis=1) # depth = baseline (meter) * focal length (pixel) / disparity-value (pixel) -> meter depth = (baseline * focal_length / disparity) # .reshape(10,7) fxypxy = [K_left[0, 0], K_left[1, 1], cx, cy] print('{} fx:{}, fy:{}'.format(calib, round(K_left[0, 0],2), round(K_left[1, 1],2))) _3DPoints = [] for i, pixel in enumerate(x_left): u, v = pixel.ravel() u, v = int(u), int(v) distance = depth[i] # print('u:{},v:{},distance:{}'.format(u,v, distance)) pt = np.array([u, v, distance]) pt[0] = pt[2] * (pt[0] - fxypxy[2]) / fxypxy[0] pt[1] = pt[2] * (pt[1] - fxypxy[3]) / fxypxy[1] _3DPoints.append(pt) _3DPoints = np.array(_3DPoints) output.append(_3DPoints) else: print('cannot detect board in both images') if len(output)>1: inside_3D = np.array(output[0]).squeeze() outisde_3D = np.array(output[1]).squeeze() #get the error for each point a_min_b = inside_3D - outisde_3D norm_total = np.linalg.norm(a_min_b)/70 norm_axis = np.linalg.norm(a_min_b, axis=0)/70 print('norm_total:{}, norm_axis:{}'.format(norm_total,norm_axis)) self._3DErros.append(norm_axis) def fitNewPlan(self): coolPoints = self.coolPoints def minimum_bounding_rectangle(points): pi2 = np.pi / 2. # get the convex hull for the points hull = ConvexHull(points) hull_points = points[hull.vertices] y_saved = [] for simplex in hull.simplices: y = coolPoints[simplex,1] x = points[simplex, 0] z = points[simplex, 1] self.ax.plot(x, y, z, 'k-', alpha = .5) y_saved.append(y) y_saved = np.array(y_saved) # calculate edge angles edges = hull_points[1:] - hull_points[:-1] angles = np.arctan2(edges[:, 1], edges[:, 0]) angles = np.abs(np.mod(angles, pi2)) angles = np.unique(angles) rotations = np.vstack([ np.cos(angles),np.cos(angles - pi2), np.cos(angles + pi2),np.cos(angles)]).T rotations = rotations.reshape((-1, 2, 2)) # apply rotations to the hull rot_points = np.dot(rotations, hull_points.T) # find the bounding points min_x = np.nanmin(rot_points[:, 0], axis=1) max_x = np.nanmax(rot_points[:, 0], axis=1) min_y = np.nanmin(rot_points[:, 1], axis=1) max_y = np.nanmax(rot_points[:, 1], axis=1) # find the box with the best area areas = (max_x - min_x) * (max_y - min_y) best_idx = np.argmin(areas) # return the best box x1 = max_x[best_idx] x2 = min_x[best_idx] y1 = max_y[best_idx] y2 = min_y[best_idx] r = rotations[best_idx] rval = np.zeros((4, 2)) rval[0] = np.dot([x1, y2], r) rval[1] = np.dot([x2, y2], r) rval[2] = np.dot([x2, y1], r) rval[3] = np.dot([x1, y1], r) rval = np.array(rval) d_matrix = distance_matrix(rval, points) neighbours = np.argsort(d_matrix, axis=1)[:, 0] rval2 = np.asarray(coolPoints[neighbours, 1]).squeeze() return rval, rval2 points = list(self.coolPoints[:, [0, -1]]) y = np.mean(self.coolPoints[:, 1]) c, c2 = minimum_bounding_rectangle(np.array(points)) self.corners_ = [] for i,point in enumerate(c): #self.corners_.append([point[0],y, point[1]]) self.corners_.append([point[0],c2[i], point[1]]) if self.chessBoard==False and self.circle_center: self.corners_.append([self.circle_center[0],y,self.circle_center[1]]) self.corners_ = np.array(self.corners_) self.ax.scatter(*self.corners_.T, color='k', marker='x', alpha=1, s=50) def fitCircle(self, points): if len(points)>0: def calc_R(x, y, xc, yc): """calculate the distance of each 2D points from the center (xc, yc)""" return np.sqrt((x - xc) ** 2 + (y - yc) ** 2) def f(c, x, y): """calculate the algebraic distance between the data points and the mean circle centered at c=(xc, yc)""" Ri = calc_R(x, y, *c) return Ri - Ri.mean() def sigma(coords, x, y, r): """Computes Sigma for circle fit.""" dx, dy, sum_ = 0., 0., 0. for i in range(len(coords)): dx = coords[i][1] - x dy = coords[i][0] - y sum_ += (sqrt(dx * dx + dy * dy) - r) ** 2 return sqrt(sum_ / len(coords)) def hyper_fit(coords, IterMax=99, verbose=False): """ Fits coords to circle using hyperfit algorithm. Inputs: - coords, list or numpy array with len>2 of the form: [ [x_coord, y_coord], ..., [x_coord, y_coord] ] or numpy array of shape (n, 2) Outputs: - xc : x-coordinate of solution center (float) - yc : y-coordinate of solution center (float) - R : Radius of solution (float) - residu : s, sigma - variance of data wrt solution (float) """ X, Y = None, None if isinstance(coords, np.ndarray): X = coords[:, 0] Y = coords[:, 1] elif isinstance(coords, list): X = np.array([x[0] for x in coords]) Y = np.array([x[1] for x in coords]) else: raise Exception("Parameter 'coords' is an unsupported type: " + str(type(coords))) n = X.shape[0] Xi = X - X.mean() Yi = Y - Y.mean() Zi = Xi * Xi + Yi * Yi # compute moments Mxy = (Xi * Yi).sum() / n Mxx = (Xi * Xi).sum() / n Myy = (Yi * Yi).sum() / n Mxz = (Xi * Zi).sum() / n Myz = (Yi * Zi).sum() / n Mzz = (Zi * Zi).sum() / n # computing the coefficients of characteristic polynomial Mz = Mxx + Myy Cov_xy = Mxx * Myy - Mxy * Mxy Var_z = Mzz - Mz * Mz A2 = 4 * Cov_xy - 3 * Mz * Mz - Mzz A1 = Var_z * Mz + 4. * Cov_xy * Mz - Mxz * Mxz - Myz * Myz A0 = Mxz * (Mxz * Myy - Myz * Mxy) + Myz * (Myz * Mxx - Mxz * Mxy) - Var_z * Cov_xy A22 = A2 + A2 # finding the root of the characteristic polynomial y = A0 x = 0. for i in range(IterMax): Dy = A1 + x * (A22 + 16. * x * x) xnew = x - y / Dy if xnew == x or not np.isfinite(xnew): break ynew = A0 + xnew * (A1 + xnew * (A2 + 4. * xnew * xnew)) if abs(ynew) >= abs(y): break x, y = xnew, ynew det = x * x - x * Mz + Cov_xy Xcenter = (Mxz * (Myy - x) - Myz * Mxy) / det / 2. Ycenter = (Myz * (Mxx - x) - Mxz * Mxy) / det / 2. x = Xcenter + X.mean() y = Ycenter + Y.mean() r = sqrt(abs(Xcenter ** 2 + Ycenter ** 2 + Mz)) s = sigma(coords, x, y, r) iter_ = i if verbose: print('Regression complete in {} iterations.'.format(iter_)) print('Sigma computed: ', s) return x, y, r, s def least_squares_circle(coords): """Circle fit using least-squares solver. Inputs: - coords, list or numpy array with len>2 of the form: [ [x_coord, y_coord], ..., [x_coord, y_coord] ] or numpy array of shape (n, 2) Outputs: - xc : x-coordinate of solution center (float) - yc : y-coordinate of solution center (float) - R : Radius of solution (float) - residu : MSE of solution against training data (float) """ x, y = None, None if isinstance(coords, np.ndarray): x = coords[:, 0] y = coords[:, 1] elif isinstance(coords, list): x = np.array([point[0] for point in coords]) y = np.array([point[1] for point in coords]) else: raise Exception("Parameter 'coords' is an unsupported type: " + str(type(coords))) # coordinates of the barycenter x_m = np.mean(x) y_m = np.mean(y) center_estimate = x_m, y_m center, _ = leastsq(f, center_estimate, args=(x, y)) xc, yc = center Ri = calc_R(x, y, *center) R = Ri.mean() residu = np.sum((Ri - R) ** 2) return xc, yc, R, residu def plot_data_circle(x, y, xc, yc, R): """ Plot data and a fitted circle. Inputs: x : data, x values (array) y : data, y values (array) xc : fit circle center (x-value) (float) yc : fit circle center (y-value) (float) R : fir circle radius (float) Output: None (generates matplotlib plot). """ f = plt.figure(facecolor='white') plt.axis('equal') theta_fit = np.linspace(-pi, pi, 180) x_fit = xc + R * np.cos(theta_fit) y_fit = yc + R * np.sin(theta_fit) plt.plot(x_fit, y_fit, 'b-', label="fitted circle", lw=2) plt.plot([xc], [yc], 'bD', mec='y', mew=1) plt.xlabel('x') plt.ylabel('y') # plot data plt.scatter(x, y, c='red', label='data') plt.legend(loc='best', labelspacing=0.1) plt.grid() plt.title('Fit Circle') x1, y1, r1, resid1 = hyper_fit(points[:,[0,2]]) x2, y2, r2, resid2 = least_squares_circle(points[:,[0,2]]) #plot_data_circle(points[:,1], points[:,2],x,y,r) if resid1>resid2: x, y, r = x2, y2, r2 else: x, y, r = x1, y1, r1 self.circle_center = (x, y) self.circle_radius = r def getData(chess=True): pcl_files = glob.glob('/home/eugeniu/catkin_ws/src/testNode/CAMERA_CALIBRATION/data/{}/*.npy'.format('chess' if chess else 'charuco')) imgleft_files = glob.glob('/home/eugeniu/catkin_ws/src/testNode/CAMERA_CALIBRATION/data/{}/left/*.png'.format('chess' if chess else 'charuco')) imgright_files = glob.glob('/home/eugeniu/catkin_ws/src/testNode/CAMERA_CALIBRATION/data/{}/right/*.png'.format('chess' if chess else 'charuco')) pcl_files.sort() imgleft_files.sort() imgright_files.sort() GoodPoints,_3DErros, IMageNames = [],[],[] for i, file in enumerate(pcl_files): if globalTrigger: print('work with {}'.format(file)) image_left = imgleft_files[i] image_right = imgright_files[i] filt = PointCloud_filter(file=file, img_file=image_left, img_file2=image_right, debug=False) filt.setUp() plt.show() plt.close() print('\n OK:{}, Save points_correspondences : {}'.format(filt.OK, np.shape(filt.points_correspondences))) if filt.OK: GoodPoints.append(filt.points_correspondences) print('save data {} '.format(np.shape(GoodPoints))) _3DErros.append(filt._3DErros) IMageNames.append(os.path.basename(image_left)) else: print('Close') break #save_obj(GoodPoints, 'GoodPoints2_{}'.format('chess' if chess else 'charuco')) print('Data saved in GoodPoints') showErros(_3DErros, IMageNames) def euler_from_matrix(R): beta = -np.arcsin(R[2, 0]) alpha = np.arctan2(R[2, 1] / np.cos(beta), R[2, 2] / np.cos(beta)) gamma = np.arctan2(R[1, 0] / np.cos(beta), R[0, 0] / np.cos(beta)) return np.array((alpha, beta, gamma)) def euler_matrix(theta): R = np.array([[np.cos(theta[1]) * np.cos(theta[2]), np.sin(theta[0]) * np.sin(theta[1]) * np.cos(theta[2]) - np.sin(theta[2]) * np.cos(theta[0]), np.sin(theta[1]) * np.cos(theta[0]) * np.cos(theta[2]) + np.sin(theta[0]) * np.sin( theta[2])], [np.sin(theta[2]) * np.cos(theta[1]), np.sin(theta[0]) * np.sin(theta[1]) * np.sin(theta[2]) + np.cos(theta[0]) * np.cos(theta[2]), np.sin(theta[1]) * np.sin(theta[2]) * np.cos(theta[0]) - np.sin(theta[0]) * np.cos( theta[2])], [-np.sin(theta[1]), np.sin(theta[0]) * np.cos(theta[1]), np.cos(theta[0]) * np.cos(theta[1])]]) return R class LiDAR_Camera_Calibration(object): def __init__(self, file, chess = True, debug=True): self.criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 100, 0.0001) self.objp = np.zeros((7 * 10, 3), np.float32) self.objp[:, :2] = np.mgrid[0:10, 0:7].T.reshape(-1, 2) * .1 self.debug = debug self.file = file self.chess = chess if chess: self.data_key = ['board_template','board_template_ICP_finetuned','board_template_inside', 'icp_finetuned_inside','closest_lidar_points','closest_lidar_points_inside', 'pixelsPoints','Camera_XYZ_Stereo','Camera_XYZ'] else: self.data_key = ['board_template','board_template_ICP_finetuned','board_template_inside','pixelsPoints', 'Camera_XYZ_Stereo','closest_lidar_points'] self.readIntrinsics() try: self.load_points() except: print('cannot load data points') '''self.Rotation = np.array([[ 0.94901505, 0.01681284, 0.3147821 ], [-0.01003801, 0.99968204, -0.02313113], [-0.31507091, 0.018792, 0.94888207]]).squeeze() self.Translation = np.array([[-0.98078971], [ 0.00600202], [ 0.19497569]]).squeeze() #self.Translation[0] = -.64 euler = euler_from_matrix(self.Rotation) # print('euler1->{}'.format(euler)) angles = euler_from_matrix(self.Rotation) print('rotation1: ', [(180.0 / math.pi) * i for i in angles]) euler[1] = np.deg2rad(22.598) self.Rotation = euler_matrix(euler)''' def rmse(self, objp, imgp, K, D, rvec, tvec): print('objp:{}, imgp:{}'.format(np.shape(objp), np.shape(imgp))) predicted, _ = cv2.projectPoints(objp, rvec, tvec, K, D) print('rmse=====================================================') print('predicted -> {}, type - >{}'.format(np.shape(predicted), type(predicted))) predicted = cv2.undistortPoints(predicted, K, D, P=K) predicted = predicted.squeeze() pix_serr = [] for i in range(len(predicted)): xp = predicted[i, 0] yp = predicted[i, 1] xo = imgp[i, 0] yo = imgp[i, 1] pix_serr.append((xp - xo) ** 2 + (yp - yo) ** 2) ssum = sum(pix_serr) return math.sqrt(ssum / len(pix_serr)) def readIntrinsics(self): name = 'inside' name = 'outside' self.camera_model = load_obj('{}_combined_camera_model'.format(name)) self.camera_model_rectify = load_obj('{}_combined_camera_model_rectify'.format(name)) self.K_right = self.camera_model['K_left'] self.K_left = self.camera_model['K_right'] self.D_right = self.camera_model['D_left'] self.D_left = self.camera_model['D_right'] print(' self.K_right') print( self.K_right) print(' self.K_left') print(self.K_left) self.R = self.camera_model['R'] self.T = self.camera_model['T'] self.K = self.K_right self.D = self.D_right print('self T before {}'.format(np.shape(self.T))) self.T = np.array([-0.96, 0., 0.12])[:, np.newaxis] print('self T after {}'.format(np.shape(self.T))) angles = np.array([np.deg2rad(0.68), np.deg2rad(22.66), np.deg2rad(-1.05)]) self.R = euler_matrix(angles) #----------------------------------------------------- self.T = np.array([-0.977, 0.004, 0.215])[:, np.newaxis] angles = np.array([np.deg2rad(1.044), np.deg2rad(22.632), np.deg2rad(-.95)]) self.R = euler_matrix(angles) #print(self.R) print('translation is {}-----------------------------'.format(self.T)) img_shape = (1936, 1216) print('img_shape:{}'.format(img_shape)) R1, R2, P1, P2, Q, roi_left, roi_right = cv2.stereoRectify(self.K_left, self.D_left, self.K_right, self.D_right, imageSize=img_shape, R=self.camera_model['R'], T=self.camera_model['T'], flags=cv2.CALIB_ZERO_DISPARITY, alpha=-1 #alpha=0 ) #print('R1:{}'.format(R1)) #print('R2:{}'.format(R2)) # print('euler1->{}'.format(euler)) angles = euler_from_matrix(self.R) print('self.R: ', [(180.0 / math.pi) * i for i in angles]) euler = euler_from_matrix(R1) #print('euler1->{}'.format(euler)) angles = euler_from_matrix(R1) #print('rotation1: ', [(180.0 / math.pi) * i for i in angles]) euler = euler_from_matrix(R2) #print('euler2->{}'.format(euler)) angles = euler_from_matrix(R2) #print('rotation2: ', [(180.0 / math.pi) * i for i in angles]) self.R1 = R1 self.R2 = R2 self.P1 = P1 self.leftMapX, self.leftMapY = cv2.initUndistortRectifyMap( self.K_left, self.D_left, R1, P1, img_shape, cv2.CV_32FC1) self.rightMapX, self.rightMapY = cv2.initUndistortRectifyMap( self.K_right, self.D_right, R2, P2, img_shape, cv2.CV_32FC1) print('Got camera intrinsic') print('Got camera-lidar extrinsics') def load_points(self): self.Lidar_3D, self.Image_2D,self.Image_2D2, self.Image_3D,self.Camera_XYZ = [],[],[],[],[] with open(self.file, 'rb') as f: self.dataPoinst = pickle.load(f, encoding='latin1') #with open(self.file,'rb') as f: #self.dataPoinst = pickle.load(f) self.N = len(self.dataPoinst) print('Got {} data views'.format(self.N)) #self.N = 1 for i in range(self.N): try: dictionary_data = self.dataPoinst[i] LiDAR_3D_points = dictionary_data['board_template_inside'] #N x 3 #pixelsPoints = dictionary_data['pixelsPoints'] #N x 2 #StereoCam_3D_points = dictionary_data['Camera_XYZ_Stereo'] #N x 3 pixelsPointsLeft = dictionary_data['pixelsPointsLeft'] pixelsPointsRight = dictionary_data['pixelsPointsRight'] StereoCam_3D_points = dictionary_data['_3DreconstructedBoard'] #N x 3 self.Lidar_3D.append(LiDAR_3D_points) self.Image_2D.append(pixelsPointsLeft) self.Image_2D2.append(pixelsPointsRight) self.Image_3D.append(StereoCam_3D_points) if self.chess: self.Camera_XYZ.append(dictionary_data['Camera_XYZ']) except: #print('Cannot read data') pass #self.Lidar_3D = np.array(self.Lidar_3D).reshape(-1,3) #self.Image_2D = np.array(self.Image_2D).reshape(-1,2) #self.Image_3D = np.array( self.Image_3D).reshape(-1,3) print('Lidar_3D:{}, Image_2D:{}, Image_2D2:{}, Image_3D:{}'.format(np.shape(self.Lidar_3D), np.shape(self.Image_2D),np.shape(self.Image_2D2), np.shape(self.Image_3D))) def plotData(self): self.fig = plt.figure(figsize=plt.figaspect(0.33)) self.fig.tight_layout() for i in range(self.N): print('{}/{}'.format(i+1,self.N)) ax1 = self.fig.add_subplot(1, 3, 1, projection='3d') #ax1.set_title('3D LiDAR') ax1.set_xlabel('X', fontsize=8) ax1.set_ylabel('Y', fontsize=8) ax1.set_zlabel('Z', fontsize=8) ax2 = self.fig.add_subplot(1, 3, 2, projection='3d') ax2.set_title('3D Stereo cameras') ax2.set_xlabel('X', fontsize=8) ax2.set_ylabel('Y', fontsize=8) ax2.set_zlabel('Z', fontsize=8) ax3 = self.fig.add_subplot(1, 3, 3, projection='3d') ax3.set_title('2D pixels') ax3.set_xlabel('X', fontsize=8) ax3.set_ylabel('Y', fontsize=8) ax3.set_zlabel('Z', fontsize=8) _3d_LIDAR = np.array(self.Lidar_3D[i]) ax1.scatter(*_3d_LIDAR.T) self.axisEqual3D(ax1, _3d_LIDAR) _3d_cam = np.array(self.Image_3D[i]) ax2.scatter(*_3d_cam.T, c='r') self.axisEqual3D(ax2,_3d_cam) _2d_cam = np.array(self.Image_2D[i]) ax3.scatter(*_2d_cam.T, c='g') self.axisEqual3D(ax3, _2d_cam) plt.show() def axisEqual3D(self,ax,data): extents = np.array([getattr(ax, 'get_{}lim'.format(dim))() for dim in 'xyz']) sz = extents[:, 1] - extents[:, 0] centers = np.mean(data, axis=0) maxsize = max(abs(sz)) r = maxsize / 2 for ctr, dim in zip(centers, 'xyz'): getattr(ax, 'set_{}lim'.format(dim))(ctr - r, ctr + r) def get3D_3D_homography(self, src, dst): #both or Nx3 matrices src_mean = np.mean(src, axis=0) dst_mean = np.mean(dst, axis=0) # Compute covariance """try: H = reduce(lambda s, (a, b): s + np.outer(a, b), zip(src - src_mean, dst - dst_mean), np.zeros((3, 3))) u, s, v = np.linalg.svd(H) R = v.T.dot(u.T) # Rotation T = - R.dot(src_mean) + dst_mean # Translation H = np.hstack((R, T[:, np.newaxis])) return H,R.T,T except: print('switch to python 2')""" def calibrate_3D_3D_old(self): print('3D-3D ========================================================================================') file = '/home/eugeniu/catkin_ws/src/testNode/CAMERA_CALIBRATION/data/GoodPoints_3D3D_{}.pkl'.format('chess') file = '/home/eugeniu/catkin_ws/src/testNode/CAMERA_CALIBRATION/data/GoodPoints_{}.pkl'.format('chess') self.Lidar_3D, self.Image_2D, self.Image_3D, self.Camera_XYZ = [], [], [], [] with open(file, 'rb') as f: self.dataPoinst = pickle.load(f) self.N = len(self.dataPoinst) print('Got {} data views'.format(self.N)) for i in range(self.N): try: dictionary_data = self.dataPoinst[i] LiDAR_3D_points = dictionary_data['board_template_inside'] # N x 3 pixelsPoints = dictionary_data['pixelsPoints'] # N x 2 StereoCam_3D_points = dictionary_data['Camera_XYZ_Stereo'] # N x 3 #StereoCam_3D_points = dictionary_data['point3D_trianguate'] self.Lidar_3D.append(LiDAR_3D_points) self.Image_2D.append(pixelsPoints) self.Image_3D.append(StereoCam_3D_points) if self.chess: self.Camera_XYZ.append(dictionary_data['Camera_XYZ']) except: print('Cannot read data===================================================') break print('Lidar_3D:{}, Image_2D:{}, Image_3D:{}'.format(np.shape(self.Lidar_3D), np.shape(self.Image_2D), np.shape(self.Image_3D))) Lidar_3D = np.array(self.Lidar_3D).reshape(-1, 3) Image_3D = np.array( self.Image_3D).reshape(-1,3) print('Lidar_3D:{}, Image_3D:{}'.format(np.shape(Lidar_3D),np.shape(Image_3D))) #-------------------------------------#------------------------------------- c_, R_, t_ = self.estimate(Lidar_3D,Image_3D) #import superpose3d as super #(RMSD, R_, t_, c_) = super.Superpose3D(Lidar_3D, Image_3D) #print('RMSD -> {}, t_{}, c_->{}'.format(RMSD, t_, c_)) # -------------------------------------#------------------------------------- def similarity_transform(from_points, to_points): assert len(from_points.shape) == 2, \ "from_points must be a m x n array" assert from_points.shape == to_points.shape, \ "from_points and to_points must have the same shape" N, m = from_points.shape mean_from = from_points.mean(axis=0) mean_to = to_points.mean(axis=0) delta_from = from_points - mean_from # N x m delta_to = to_points - mean_to # N x m sigma_from = (delta_from * delta_from).sum(axis=1).mean() sigma_to = (delta_to * delta_to).sum(axis=1).mean() cov_matrix = delta_to.T.dot(delta_from) / N U, d, V_t = np.linalg.svd(cov_matrix, full_matrices=True) cov_rank = np.linalg.matrix_rank(cov_matrix) S = np.eye(m) if cov_rank >= m - 1 and np.linalg.det(cov_matrix) < 0: S[m - 1, m - 1] = -1 elif cov_rank < m - 1: raise ValueError("colinearility detected in covariance matrix:\n{}".format(cov_matrix)) R = U.dot(S).dot(V_t) c = (d * S.diagonal()).sum() / sigma_from t = mean_to - c * R.dot(mean_from) print('R:{},t:{},c:{}'.format(R,t,c)) return c * R, t print('similarity_transform===============================') from_points = Lidar_3D to_points = Image_3D M_ans, t_ans = similarity_transform(from_points, to_points) H, R, T = self.get3D_3D_homography(src = Lidar_3D, dst=Image_3D) print('H:{}, R:{}, T:{}'.format(np.shape(H), np.shape(R), np.shape(T))) print(H) self.fig = plt.figure(figsize=plt.figaspect(1.)) ax1 = self.fig.add_subplot(1, 1, 1, projection='3d') #ax1.set_title('3D LiDAR') ax1.set_xlabel('X', fontsize=8) ax1.set_ylabel('Y', fontsize=8) ax1.set_zlabel('Z', fontsize=8) ax1.set_axis_off() _3d_LIDAR = self.Lidar_3D[0] ax1.scatter(*_3d_LIDAR.T, label = 'LiDAR') _3d_Image = self.Image_3D[0] ax1.scatter(*_3d_Image.T, s=25, label = 'Stereo Cam') T = _3d_LIDAR.dot(c_ * R_) + t_ print('T -> {}'.format(np.shape(T))) ax1.scatter(*T.T, marker='x', label='T') d2 = distance_matrix(_3d_Image,_3d_Image) print('d2:{}'.format(d2)) print('d2 shape :{}'.format(np.shape(d2))) ones = np.ones(len(_3d_LIDAR))[:, np.newaxis] transformed_ = np.hstack((_3d_LIDAR,ones)) transformed = np.dot(H, transformed_.T).T #transformation estimated with SVD print(np.shape(transformed)) ax1.scatter(*transformed.T, s=25, label = 'ICP sol') #ax1.set_axis_off() primary = Lidar_3D# _3d_LIDAR secondary = Image_3D# _3d_Image pad = lambda x: np.hstack([x, np.ones((x.shape[0], 1))]) unpad = lambda x: x[:, :-1] X = pad(primary) Y = pad(secondary) # Solve the least squares problem X * A = Y # to find our transformation matrix A A, res, rank, s = np.linalg.lstsq(X, Y) transform = lambda x: unpad(np.dot(pad(x), A)) #print transform(primary) print("Max error:", np.abs(secondary - transform(primary)).max()) trns2 = transform(_3d_LIDAR) #transformation estimated with LS ax1.scatter(*trns2.T, label = 'least square sol') to_points = M_ans.dot(_3d_LIDAR.T).T + t_ans print('to_points ->{}'.format(np.shape(to_points))) ax1.scatter(*to_points.T, label = 'to_points') self.axisEqual3D(ax1, transformed) ax1.legend() plt.show() #---------------------------------- if True: img = cv2.imread('/home/eugeniu/catkin_ws/src/testNode/CAMERA_CALIBRATION/data/chess/left/left_4.png') img2 = cv2.imread('/home/eugeniu/catkin_ws/src/testNode/CAMERA_CALIBRATION/data/chess/right/right_4.png') cloud_file = '/home/eugeniu/catkin_ws/src/testNode/CAMERA_CALIBRATION/data/chess/cloud_4.npy' else: img = cv2.imread('/home/eugeniu/catkin_ws/src/testNode/CAMERA_CALIBRATION/data/charuco/left/left_4.png') img2 = cv2.imread('/home/eugeniu/catkin_ws/src/testNode/CAMERA_CALIBRATION/data/charuco/right/right_4.png') cloud_file = '/home/eugeniu/catkin_ws/src/testNode/CAMERA_CALIBRATION/data/charuco/cloud_4.npy' i = 12 l = '/home/eugeniu/catkin_ws/src/testNode/CAMERA_CALIBRATION/cool/left_{}.png'.format(i) r = '/home/eugeniu/catkin_ws/src/testNode/CAMERA_CALIBRATION/cool/right_{}.png'.format(i) #img, img2 = cv2.imread(l), cv2.imread(r) #cloud_file = '/home/eugeniu/catkin_ws/src/testNode/CAMERA_CALIBRATION/cool/cloud_{}.npy'.format(i) if stereoRectify and True: img = cv2.remap(src=img, map1=self.leftMapX, map2=self.leftMapY, interpolation=cv2.INTER_LINEAR, dst=None, borderMode=cv2.BORDER_CONSTANT) img2 = cv2.remap(src=img2, map1=self.rightMapX, map2=self.rightMapY, interpolation=cv2.INTER_LINEAR, dst=None, borderMode=cv2.BORDER_CONSTANT) #Points in LiDAR frame LiDAR_points3D = np.array(np.load(cloud_file, mmap_mode='r'), dtype=np.float32)[:, :3] # print('LiDAR_points3D:{}'.format(np.shape(LiDAR_points3D))) #converted in camera frame ones = np.ones(len(LiDAR_points3D))[:, np.newaxis] transformed_ = np.hstack((LiDAR_points3D, ones)) Camera_points3D = np.dot(H, transformed_.T).T #Camera_points3D = transform(LiDAR_points3D) #print('Camera_points3D:{}'.format(np.shape(Camera_points3D))) #Camera_points3D = LiDAR_points3D.dot(c_ * R_) + t_ #Camera_points3D = LiDAR_points3D.dot(R_) + t_ #Camera_points3D = transform(LiDAR_points3D) #transformation estimated with LS print('Camera_points3D -> {}'.format(Camera_points3D)) rvec, _ = cv2.Rodrigues(np.eye(3)) tvec = np.zeros(3) #Camera_points3D = LiDAR_points3D#.dot(R_) + t_ #rvec = R_ #tran = t_ #tran[0] = -0.02 #tran[1] = -0.03 print('rvec -> {}, tvec->{}'.format(np.shape(rvec),np.shape(tvec))) print('Camera_points3D -> {}'.format(np.shape(Camera_points3D))) # Reproject back into the two cameras rvec1, _ = cv2.Rodrigues(np.eye(3).T) # Change rvec2, _ = cv2.Rodrigues(self.R.T) # Change t1 = np.array([[0.], [0.], [0.]]) t2 = self.T p1, _ = cv2.projectPoints(Camera_points3D[:, :3], rvec1, -t1, self.K, distCoeffs=self.D) # Change p2, _ = cv2.projectPoints(Camera_points3D[:, :3], rvec2, -t2, self.K, distCoeffs=self.D) # Change #points2D = [cv2.projectPoints(point, rvec, tvec, self.K, self.D)[0] for point in Camera_points3D[:, :3]] points2D, _ = cv2.projectPoints(Camera_points3D[:, :3], np.identity(3), np.array([0., 0., 0.]), self.K, self.D) points2D = np.asarray(points2D).squeeze() points2D = np.asarray(p1).squeeze() print('points2D:{}, img.shape[1]:{}'.format(np.shape(points2D), img.shape[1])) inrange = np.where( (points2D[:, 0] >= 0) & (points2D[:, 1] >= 0) & (points2D[:, 0] < img.shape[1]) & (points2D[:, 1] < img.shape[0]) ) points2D = points2D[inrange[0]].round().astype('int') # Draw the projected 2D points for i in range(len(points2D)): cv2.circle(img, tuple(points2D[i]), 2, (0, 255, 0), -1) #cv2.circle(img2, tuple(points2D[i]), 2, (0, 255, 0), -1) print('rvec -> {}, tvec->{}'.format(np.shape(rvec),np.shape(tvec))) T_01 = np.vstack((np.hstack((np.eye(3), tvec[:,np.newaxis])), [0, 0, 0, 1])) # from lidar to right camera T_12 = np.vstack((np.hstack((self.R, self.T)), [0, 0, 0, 1])) # between cameras T_final = np.dot(T_01,T_12) rotation, translation = T_final[:3, :3], T_final[:3, -1] points2D = [cv2.projectPoints(point, rotation, translation, self.K, self.D)[0] for point in Camera_points3D[:, :3]] points2D = np.asarray(points2D).squeeze() points2D = np.asarray(p2).squeeze() print('points2D:{}, img.shape[1]:{}'.format(np.shape(points2D), img.shape[1])) inrange = np.where( (points2D[:, 0] >= 0) & (points2D[:, 1] >= 0) & (points2D[:, 0] < img.shape[1]) & (points2D[:, 1] < img.shape[0]) ) points2D = points2D[inrange[0]].round().astype('int') # Draw the projected 2D points for i in range(len(points2D)): cv2.circle(img2, tuple(points2D[i]), 2, (0, 255, 0), -1) cv2.imshow('left', cv2.resize(img,None, fx=.4, fy=.4)) cv2.imshow('right', cv2.resize(img2, None, fx=.4, fy=.4)) cv2.waitKey() cv2.destroyAllWindows() def drawCharuco(self, QueryImg): points2D = np.array(self.Image_2D[0]).reshape(-1, 2) for p in points2D: cv2.circle(QueryImg, tuple(p), 4, (0, 0, 255), 5) return QueryImg def calibrate_3D_2D(self, userRansac = False): points3D = np.array(self.Lidar_3D).reshape(-1, 3) points2D = np.array(self.Image_2D).reshape(-1,2) print('points3D:{}, points2D:{}'.format(np.shape(points3D),np.shape(points2D))) # Estimate extrinsics if userRansac: success, rotation_vector, translation_vector, inliers = cv2.solvePnPRansac(points3D, points2D, self.K, self.D, flags=cv2.SOLVEPNP_ITERATIVE) print('success:{},rotation_vector:{},translation_vector:{},inliers:{}'.format(success, np.shape(rotation_vector), np.shape(translation_vector), np.shape(inliers))) # Compute re-projection error. points2D_reproj = cv2.projectPoints(points3D, rotation_vector, translation_vector, self.K, self.D)[0].squeeze(1) error = (points2D_reproj - points2D)[inliers] # Compute error only over inliers. error = np.asarray(error).squeeze() print('points2D_reproj:{}, points2D:{},error:{}'.format(np.shape(points2D_reproj), np.shape(points2D), np.shape(error))) rmse = np.sqrt(np.mean(error[:, 0] ** 2 + error[:, 1] ** 2)) print('Re-projection error before LM refinement (RMSE) in px: ' + str(rmse)) # Refine estimate using LM if not success: print('Initial estimation unsuccessful, skipping refinement') elif not hasattr(cv2, 'solvePnPRefineLM'): print('solvePnPRefineLM requires OpenCV >= 4.1.1, skipping refinement') else: assert len(inliers) >= 3, 'LM refinement requires at least 3 inlier points' rotation_vector, translation_vector = cv2.solvePnPRefineLM(points3D[inliers], points2D[inliers], self.K, self.D, rotation_vector, translation_vector) # Compute re-projection error. points2D_reproj = cv2.projectPoints(points3D, rotation_vector, translation_vector, self.K, self.D)[0].squeeze(1) assert (points2D_reproj.shape == points2D.shape) error = (points2D_reproj - points2D)[inliers] # Compute error only over inliers. error = np.array(error).squeeze() rmse = np.sqrt(np.mean(error[:, 0] ** 2 + error[:, 1] ** 2)) print('Re-projection error after LM refinement (RMSE) in px: ' + str(rmse)) # Convert rotation vector #from tf.transformations import euler_from_matrix rotation_matrix = cv2.Rodrigues(rotation_vector)[0] euler = euler_from_matrix(rotation_matrix) # Save extrinsics np.savez('extrinsics{}.npz'.format('chess' if self.chess else 'charuco'),euler=euler,Rodrigues=rotation_matrix, R=rotation_vector, T=translation_vector) # Display results print('Euler angles (RPY):', euler) print('Rotation Matrix Rodrigues :', rotation_matrix) print('rotation_vector:', rotation_vector) print('Translation Offsets:', translation_vector) points2D = cv2.projectPoints(points3D, rotation_vector, translation_vector, self.K, self.D)[0].squeeze(1) print('========points3D:{}, points2D:{}=================================================='.format(np.shape(points3D),np.shape(points2D))) else: #------------------------------------------------------------------------------------------------- imgp = np.array([points2D], dtype=np.float32).squeeze() objp = np.array([points3D], dtype=np.float32).squeeze() retval, rvec, tvec = cv2.solvePnP(objp, imgp, self.K, self.D, flags=cv2.SOLVEPNP_ITERATIVE) rmat, jac = cv2.Rodrigues(rvec) q = Quaternion(matrix=rmat) print("Transform from camera to laser") print("T = ") print(tvec) print("R = ") print(rmat) print("Quaternion = ") print(q) print("RMSE in pixel = %f" % self.rmse(objp, imgp, self.K, self.D, rvec, tvec)) result_file = 'solvePnP_extrinsics{}.npz'.format('chess' if self.chess else 'charuco') with open(result_file, 'w') as f: f.write("%f %f %f %f %f %f %f" % (q.x, q.y, q.z, q.w, tvec[0], tvec[1], tvec[2])) print("Result output format: qx qy qz qw tx ty tz") #refine results print('refine results------------------------------------>') rvec, tvec = cv2.solvePnPRefineLM(objp,imgp, self.K, self.D, rvec, tvec) rmat, jac = cv2.Rodrigues(rvec) q = Quaternion(matrix=rmat) print("Transform from camera to laser") print("T = ") print(tvec) print("R = ") print(rmat) print("Quaternion = ") print(q) print('Euler angles') angles = euler_from_matrix(rmat) print(angles) print('euler angles ', [(180.0 / math.pi) * i for i in angles]) print("RMSE in pixel = %f" % self.rmse(objp, imgp, self.K, self.D, rvec, tvec)) result_file = 'refined_solvePnP_extrinsics{}.npz'.format('chess' if self.chess else 'charuco') with open(result_file, 'w') as f: f.write("%f %f %f %f %f %f %f" % (q.x, q.y, q.z, q.w, tvec[0], tvec[1], tvec[2])) def get_z(self, T_cam_world, T_world_pc, K): R = T_cam_world[:3, :3] t = T_cam_world[:3, 3] proj_mat = np.dot(K, np.hstack((R, t[:, np.newaxis]))) xyz_hom = np.hstack((T_world_pc, np.ones((T_world_pc.shape[0], 1)))) xy_hom = np.dot(proj_mat, xyz_hom.T).T z = xy_hom[:, -1] z = np.asarray(z).squeeze() return z def callback_solvePnP(self, img, cloud_file): #init calibraiton calib_file = '/home/eugeniu/catkin_ws/src/testNode/CAMERA_CALIBRATION/solvePnP_extrinsics{}.npz'.format( 'chess' if self.chess else 'charuco') calib_file_ = '/home/eugeniu/catkin_ws/src/testNode/CAMERA_CALIBRATION/combined_extrinsics{}.npz' with open(calib_file, 'r') as f: data = f.read().split() #print('data:{}'.format(data)) qx = float(data[0]) qy = float(data[1]) qz = float(data[2]) qw = float(data[3]) tx = float(data[4]) ty = float(data[5]) tz = float(data[6]) q = Quaternion(qw, qx, qy, qz).transformation_matrix q[0, 3] = tx q[1, 3] = ty q[2, 3] = tz print("Extrinsic parameter - camera to laser") print(q) tvec = q[:3, 3] rot_mat = q[:3, :3] rvec, _ = cv2.Rodrigues(rot_mat) try: objPoints = np.array(np.load(cloud_file, mmap_mode='r'), dtype=np.float32)[:, :3] print('objPoints:{}'.format(np.shape(objPoints))) Z = self.get_z(q, objPoints, self.K) objPoints = objPoints[Z > 0] #print('objPoints:{}'.format(objPoints)) img_points, _ = cv2.projectPoints(objPoints, rvec, tvec, self.K, self.D) img_points = np.squeeze(img_points) for i in range(len(img_points)): try: cv2.circle(img, (int(round(img_points[i][0])), int(round(img_points[i][1]))), 3, (0, 255, 0), 1) except OverflowError: continue if self.chess: cv2.drawChessboardCorners(img, (10, 7), np.array(self.Image_2D).reshape(-1,2), True) else: self.drawCharuco(img) except: print('callback_solvePnP - error') image = cv2.resize(img, None, fx=.6, fy=.6) return image def callback_solvePnP_Ransac(self, img, cloud_file): points3D = np.array(np.load(cloud_file, mmap_mode='r'), dtype=np.float32)[:, :3] print('points3D:{}'.format(np.shape(points3D))) file = np.load('extrinsics{}.npz'.format('chess' if self.chess else 'charuco')) euler = np.array(file["euler"]) rotation_matrix = np.array(file["Rodrigues"]) rotation_vector = np.array(file["R"]) translation_vector = np.array(file["T"]) print('Euler angles (RPY):', euler) print('Rotation Matrix Rodrigues :', rotation_matrix) print('rotation_vector:', rotation_vector) print('Translation Offsets:', translation_vector) rvec = rotation_matrix #rvec, _ = cv2.Rodrigues(rotation_matrix) print('========points3D:{}=================================================='.format( np.shape(points3D))) #points2D = cv2.projectPoints(points3D, rotation_vector, translation_vector, self.K, self.D)[0].squeeze(1) #print('points2D:{}'.format(np.shape(points2D))) points2D = [cv2.projectPoints(point, rvec, translation_vector, self.K, self.D)[0] for point in points3D[:, :3]] points2D = np.asarray(points2D).squeeze() print('points2D:{}, img.shape[1]:{}'.format(np.shape(points2D),img.shape[1])) inrange = np.where( (points2D[:, 0] >= 0) & (points2D[:, 1] >= 0) & (points2D[:, 0] < img.shape[1]) & (points2D[:, 1] < img.shape[0]) ) points2D = points2D[inrange[0]].round().astype('int') # Draw the projected 2D points for i in range(len(points2D)): cv2.circle(img, tuple(points2D[i]), 2, (0, 255, 0), -1) if self.chess: cv2.drawChessboardCorners(img, (10, 7), np.array(self.Image_2D).reshape(-1,2), True) else: self.drawCharuco(img) image = cv2.resize(img, None, fx=.6, fy=.6) return image def callback(self): if self.chess: img = cv2.imread('/home/eugeniu/catkin_ws/src/testNode/CAMERA_CALIBRATION/data/chess/left/left_0.png') cloud_file = '/home/eugeniu/catkin_ws/src/testNode/CAMERA_CALIBRATION/data/chess/cloud_0.npy' else: img = cv2.imread('/home/eugeniu/catkin_ws/src/testNode/CAMERA_CALIBRATION/data/charuco/left/left_0.png') cloud_file = '/home/eugeniu/catkin_ws/src/testNode/CAMERA_CALIBRATION/data/charuco/cloud_0.npy' #img = cv2.imread('/home/eugeniu/catkin_ws/src/testNode/CAMERA_CALIBRATION/data/charuco/left/left_0.png') #cloud_file = '/home/eugeniu/catkin_ws/src/testNode/CAMERA_CALIBRATION/data/charuco/cloud_0.npy' #img = cv2.imread('/home/eugeniu/catkin_ws/src/testNode/CAMERA_CALIBRATION/data/chess/left/left_0.png') #cloud_file = '/home/eugeniu/catkin_ws/src/testNode/CAMERA_CALIBRATION/data/chess/cloud_0.npy' #solvePnP_Ransac_image = self.callback_solvePnP_Ransac(img=img.copy(),cloud_file=cloud_file) cv2.imshow('solvePnP_Ransac', cv2.resize(img,None,fx=.4,fy=.4)) cv2.waitKey() solvePnP_image = self.callback_solvePnP(img=img.copy(),cloud_file=cloud_file) cv2.imshow('solvePnP', solvePnP_image) cv2.waitKey() cv2.destroyAllWindows() def combine_both_boards_and_train(self): #get data from chessboard name = 'chess' self.file = '/home/eugeniu/catkin_ws/src/testNode/CAMERA_CALIBRATION/data/GoodPoints_{}.pkl'.format(name) self.load_points() Lidar_3D, Image_2D, Image_3D = np.array(self.Lidar_3D).reshape(-1,3), np.array(self.Image_2D).reshape(-1,2), np.array(self.Image_3D).reshape(-1,3) #get data from charuco name = 'charuco' self.file = '/home/eugeniu/catkin_ws/src/testNode/CAMERA_CALIBRATION/data/GoodPoints_{}.pkl'.format(name) self.load_points() Lidar_3D, Image_2D = np.vstack((Lidar_3D, np.array(self.Lidar_3D).reshape(-1,3))), np.vstack((Image_2D, np.array(self.Image_2D).reshape(-1,2))) print('Lidar_3D:->{}, Image_2D:->{}'.format(np.shape(Lidar_3D), np.shape(Image_2D))) imgp = np.array([Image_2D], dtype=np.float32).squeeze() objp = np.array([Lidar_3D], dtype=np.float32).squeeze() retval, rvec, tvec = cv2.solvePnP(objp, imgp, self.K, self.D, flags=cv2.SOLVEPNP_ITERATIVE) print('tvec -> {}'.format(tvec.ravel())) rmat, jac = cv2.Rodrigues(rvec) q = Quaternion(matrix=rmat) angles = euler_from_matrix(rmat) print(angles) print('euler angles ', [(180.0 / math.pi) * i for i in angles]) print("RMSE in pixel = %f" % self.rmse(objp, imgp, self.K, self.D, rvec, tvec)) result_file = 'combined_extrinsics{}.npz' with open(result_file, 'w') as f: f.write("%f %f %f %f %f %f %f" % (q.x, q.y, q.z, q.w, tvec[0], tvec[1], tvec[2])) print('Combined calibration done!!!') def computeTransformation(self): i = 5 l = '/home/eugeniu/catkin_ws/src/testNode/CAMERA_CALIBRATION/cool/left_{}.png'.format(i) r = '/home/eugeniu/catkin_ws/src/testNode/CAMERA_CALIBRATION/cool/right_{}.png'.format(i) img1 = cv2.imread(l) img2 = cv2.imread(r) #sift = cv2.SIFT_create() sift = cv2.xfeatures2d.SIFT_create() # find the keypoints and descriptors with SIFT kp1, des1 = sift.detectAndCompute(img1, None) kp2, des2 = sift.detectAndCompute(img2, None) # FLANN parameters FLANN_INDEX_KDTREE = 1 index_params = dict(algorithm=FLANN_INDEX_KDTREE, trees=5) search_params = dict(checks=50) flann = cv2.FlannBasedMatcher(index_params, search_params) matches = flann.knnMatch(des1, des2, k=2) pts1 = [] pts2 = [] # ratio test as per Lowe's paper for i, (m, n) in enumerate(matches): if m.distance < 0.8 * n.distance: pts2.append(kp2[m.trainIdx].pt) pts1.append(kp1[m.queryIdx].pt) pts1 = np.int32(pts1) pts2 = np.int32(pts2) #F, mask = cv2.findFundamentalMat(pts1, pts2, cv2.FM_LMEDS) E, mask = cv2.findEssentialMat(pts1, pts2, self.K, cv2.RANSAC, 0.999, 1.0, None) print(E) points, R, t, mask = cv2.recoverPose(E, pts1, pts2, self.K) print('R') print(R) angles = euler_from_matrix(R) print('rotation angles: ', [(180.0 / math.pi) * i for i in angles]) print('t') print(t) for pt1, pt2 in zip(pts1, pts2): color = tuple(np.random.randint(0, 255, 3).tolist()) img1 = cv2.circle(img1, tuple(pt1), 5, color, -1) img2 = cv2.circle(img2, tuple(pt2), 5, color, -1) cv2.imshow('imgL', cv2.resize(img1, None, fx=.4, fy=.4)) cv2.imshow('imgR', cv2.resize(img2, None, fx=.4, fy=.4)) cv2.waitKey(0) cv2.destroyAllWindows() def write_ply(self, fn, verts, colors): ply_header = '''ply format ascii 1.0 element vertex %(vert_num)d property float x property float y property float z property uchar red property uchar green property uchar blue end_header ''' out_colors = colors.copy() verts = verts.reshape(-1, 3) verts = np.hstack([verts, out_colors]) with open(fn, 'wb') as f: f.write((ply_header % dict(vert_num=len(verts))).encode('utf-8')) np.savetxt(f, verts, fmt='%f %f %f %d %d %d ') def view(self): import glob import open3d file = glob.glob('/home/eugeniu/catkin_ws/src/testNode/CAMERA_CALIBRATION/*.ply') pcda = [] for i, file_path in enumerate(file): print("{} Load a ply point cloud, print it, and render it".format(file_path)) pcd = open3d.io.read_point_cloud(file_path) pcda.append(pcd) open3d.visualization.draw_geometries([pcd]) #o3d.visualization.draw_geometries([pcda[1], pcda[-1]]) def reproject_on_3D(self, useUnique = True): def readCalibrationExtrinsic(): calib_file = '/home/eugeniu/catkin_ws/src/testNode/CAMERA_CALIBRATION/solvePnP_extrinsics{}.npz'.format( 'chess' if self.chess else 'charuco') calib_file = '/home/eugeniu/catkin_ws/src/testNode/CAMERA_CALIBRATION/combined_extrinsics{}.npz' with open(calib_file, 'r') as f: data = f.read().split() #print('data:{}'.format(data)) qx = float(data[0]) qy = float(data[1]) qz = float(data[2]) qw = float(data[3]) tx = float(data[4]) ty = float(data[5]) tz = float(data[6]) q = Quaternion(qw, qx, qy, qz).transformation_matrix q[0, 3],q[1, 3],q[2, 3] = tx,ty,tz tvec = q[:3, 3] rot_mat = q[:3, :3] #rvec, _ = cv2.Rodrigues(rot_mat) rvec = rot_mat print('tvec -> {}'.format(tvec)) return rvec, tvec, q rvec, tvec, q = readCalibrationExtrinsic() print(self.K) print(self.D) print(rvec) print(tvec) i=1 i=11 l = '/home/eugeniu/catkin_ws/src/testNode/CAMERA_CALIBRATION/cool/left_{}.png'.format(i) r = '/home/eugeniu/catkin_ws/src/testNode/CAMERA_CALIBRATION/cool/right_{}.png'.format(i) imgLeft, imgRight = cv2.imread(l),cv2.imread(r) cloud_file = '/home/eugeniu/catkin_ws/src/testNode/CAMERA_CALIBRATION/cool/cloud_{}.npy'.format(i) _3DPoints = np.array(np.load(cloud_file, mmap_mode='r'), dtype=np.float32)[:, :3] #Left image-------------------------------------------------------------------------------------------- objPoints_left = _3DPoints.copy() Z = self.get_z(q, objPoints_left, self.K) objPoints_left = objPoints_left[Z > 0] print('objPoints_left:{}'.format(np.shape(objPoints_left))) points2D_left, _ = cv2.projectPoints(objPoints_left, rvec, tvec, self.K, self.D) points2D_left = np.squeeze(points2D_left) print('objPoints_left -> {}, points2D_left -> {}, '.format(np.shape(objPoints_left), np.shape(points2D_left))) inrange_left = np.where((points2D_left[:, 0] > 0) & (points2D_left[:, 1] > 0) & (points2D_left[:, 0] < imgLeft.shape[1]-1) & (points2D_left[:, 1] < imgLeft.shape[0]-1)) print('inrange_left : {}'.format(np.shape(inrange_left))) points2D_left = points2D_left[inrange_left[0]].round().astype('int') print('points2D_left:{}, '.format(np.shape(points2D_left))) #Right image ---------------------------------------------------------------------------------------- objPoints_right = _3DPoints.copy() Z = self.get_z(q, objPoints_right, self.K_left) objPoints_right = objPoints_right[Z > 0] T_01 = np.vstack((np.hstack((rvec, tvec[:, np.newaxis])), [0,0,0,1])) #from lidar to right camera T_12 = np.vstack((np.hstack((self.R, self.T)), [0,0,0,1])) #between cameras T_final = np.dot(T_12, T_01) rotation, translation = T_final[:3,:3], T_final[:3,-1] points2D_right, _ = cv2.projectPoints(objPoints_right, rotation, translation, self.K_left, self.D_left) points2D_right = np.squeeze(points2D_right) inrange_right = np.where((points2D_right[:, 0] >= 0) &(points2D_right[:, 1] >= 0) & (points2D_right[:, 0] < imgRight.shape[1]-1) &(points2D_right[:, 1] < imgRight.shape[0]-1)) print('points2D_right init ->{}'.format(np.shape(points2D_right))) points2D_right = points2D_right[inrange_right[0]].round().astype('int') print('points2D_right now ->{}'.format(np.shape(points2D_right))) #columns=["X", "Y", "Z","intens","ring"] colors = np.array(np.load(cloud_file, mmap_mode='r'))[:, 3] # # Color map for the points colors = colors[inrange_left[0]] cmap = matplotlib.cm.get_cmap('hsv') colors = cmap(colors / np.max(colors)) print('colors -> {}, min:{}, max:{}'.format(np.shape(colors), np.min(colors), np.max(colors))) colorImageLeft,colorImageRight = imgLeft.copy(),imgRight.copy() fig, axs = plt.subplots(1, 2) fig.set_size_inches(20, 10.5, forward=True) axs[0].imshow(imgLeft) #axs[0].scatter(points2D_left[:,0],points2D_left[:,1], s=.1, c='green') axs[0].scatter(points2D_left[:,0],points2D_left[:,1], s=.3, c=colors) axs[0].set_title("Left image") axs[1].set_title("Right image") axs[1].imshow(imgRight) #axs[1].scatter(points2D_right[:,0],points2D_right[:,1], s=.1, c='red') # Color map for the points colors = np.array(np.load(cloud_file, mmap_mode='r'))[:, 3] # colors = colors[inrange_right[0]] colors = cmap(colors / np.max(colors)) print('points2D_right->{}, colors->{}'.format(np.shape(points2D_right), np.shape(colors))) axs[1].scatter(points2D_right[:,0],points2D_right[:,1], s=.1, c=colors) fig.tight_layout() plt.show() points_left = objPoints_left[inrange_left[0]] points_right = objPoints_right[inrange_right[0]] print('points_left -> {}, colorImageLeft->{}'.format(np.shape(points_left), np.shape(colorImageLeft))) print('points_right -> {}, colorImageRight->{}'.format(np.shape(points_right), np.shape(colorImageRight))) colors_left = colorImageLeft[points2D_left[:, 1], points2D_left[:, 0], :] colors_right = colorImageRight[points2D_right[:, 1], points2D_right[:, 0], :] print('colors_left -> {}'.format(np.shape(colors_left))) print('colors_right -> {}'.format(np.shape(colors_right))) points = np.vstack((points_left,points_right)) color = np.vstack((colors_left,colors_right)) print('points->{}, color->{}'.format(np.shape(points), np.shape(color))) #plt.show() #self.write_ply('Lidar_cam.ply', points, color) #self.view() #plt.show() def hsv_to_rgb(h, s, v): if s == 0.0: return v, v, v i = int(h * 6.0) f = (h * 6.0) - i p = v * (1.0 - s) q = v * (1.0 - s * f) t = v * (1.0 - s * (1.0 - f)) i = i % 6 if i == 0: return v, t, p if i == 1: return q, v, p if i == 2: return p, v, t if i == 3: return p, q, v if i == 4: return t, p, v if i == 5: return v, p, q def filterOcclusion(data): print('data -> {}'.format(np.shape(data))) # ---create a pandas Dataframe with X,Y,Z print('Create a DataFrame') df = pd.DataFrame(data, columns=['X','Y','Z','X3D','Y3X','Z3D','R','G','B']) # ---sort it ascend by Z print('Sort by Z') df = df.sort_values(by=['Z'],kind='quicksort') print('Data point after sorting------------------------------') #---For each point create rectangle centered in current point xGap,yGap = 20, 50 xOffset, yOffset = int(xGap / 2), int(yGap / 2) def create_rectange(x,y,depth): bl = [x-xOffset, y+yOffset] #bottom left tr = [x+xOffset, y-yOffset] #top right return [bl,tr,depth] print('Adding rectangles') #Rectangles = np.array([create_rectange(x=row['X'],y=row['Y'], depth = row['Z']) for index, row in df.iterrows()]) vfunc = np.vectorize(create_rectange) Rectangles = vfunc(df['X'].values, df['Y'].values, df['Z'].values) df['Rectangles'] = Rectangles #Rectangles = np.asarray(Rectangles.tolist()) #print('Rectangles -> {}'.format(np.shape(Rectangles))) #bl,tr = np.asarray(Rectangles[:,0].tolist()),np.asarray(Rectangles[:,0].tolist()) # 'bl0 -> {}'.format(np.shape(bl), np.shape(tr)) #df['bl0'] = bl[:,0] #df['bl1'] = bl[:, 1] #df['tr0'] = tr[:, 0] #df['tr1'] = tr[:, 1] # For each point, project it if it does not belong in prev 5 points t = .5 def lies_inside(bl, tr, p, dist): #bottom_left, top_right, poin, distance_left, distance_right if (p[0] > bl[0] and p[0] < tr[0] and p[1] < bl[1] and p[1] > tr[1]): if abs(p[-1]-dist)>t: return True else: return False else: return False def lies_inside_(bl0,bl1, tr0,tr1, p0,p1,p2, dist): #bottom_left, top_right, poin, distance_left, distance_right if (p0 > bl0 and p0 < tr0 and p1 < bl1 and p1 > tr1): if abs(p2-dist)>t: return True else: return False else: return False lies_inside_ = np.vectorize(lies_inside_) occluded = np.zeros_like(Z, dtype=bool) projected = np.zeros_like(Z, dtype=bool) df['occluded'] = occluded df['projected'] = projected idx = range(len(df)) df['idx'] = idx df = df.set_index(['idx']) # for each point check if the prev 5 points belongs to its rectangle -> if yes-> discard it print('Compute neighbors') from sklearn.neighbors import NearestNeighbors X = np.array(df.iloc[:,0:2]) k=10 print('X -> {}'.format(np.shape(X))) nbrs = NearestNeighbors(n_neighbors=k, algorithm='ball_tree').fit(X) distances, indices = nbrs.kneighbors(X) print('distances -> {}, indices->{}, df->{}'.format(np.shape(distances), np.shape(indices), np.shape(df))) df['nbrs_indices'] = indices[:,1:].tolist() print(df.head()) import time start = time.time() print('Start projection') def soc_iter(i): print(i) # take the neighbours that are already projected and not occluded nbrs = df.iloc[i, -1] prev_points = df.iloc[nbrs] # .query('projected == 1 & occluded == 0') #5.82813405991 s condition = (prev_points.projected == True) & (prev_points.occluded == False) prev_points = prev_points[condition] # time = 156.481780052 s # print('nbrs -> {}, prev_points->{}, condition1->{}'.format(np.shape(nbrs), np.shape(prev_points), np.shape(condition))) if len(prev_points) > 0: p = np.array(df.iloc[i, 0:3]) # current_point # time = 156.481780052 s Rectangles = prev_points['Rectangles'] occlusion = [lies_inside(bl=point[0], tr=point[1], p=p, dist=point[-1]) for point in Rectangles] # time = 156.481780052 s #occlusion = lies_inside_(prev_points['bl0'].values, prev_points['bl1'].values, prev_points['tr0'].values, prev_points['tr1'].values, p[0], p[1], p[-1], prev_points['Z'].values) if np.any(occlusion): # print('point {} is occluded'.format(p)) df.loc[i, 'occluded'] = True df.loc[i, 'projected'] = True soc_iter_vect = np.vectorize(soc_iter) N = len(df) m = np.linspace(start=1, stop=N-1, num=N-1, dtype=int) print('m->{}, N:{}'.format(np.shape(m),N)) soc_iter_vect(m) # uncomment this '''for i in range(1,2): #len(df) print i # take the neighbours that are already projected and not occluded nbrs = df.iloc[i, -1] prev_points = df.iloc[nbrs]#.query('projected == 1 & occluded == 0') #5.82813405991 s condition = (prev_points.projected == True) & (prev_points.occluded == False) prev_points = prev_points[condition] #time = 156.481780052 s #print('nbrs -> {}, prev_points->{}, condition1->{}'.format(np.shape(nbrs), np.shape(prev_points), np.shape(condition))) if len(prev_points)>0: p = np.array(df.iloc[i, 0:3]) #current_point # time = 303.82229900 #occlusion = (p[0] > (prev_points.X-xOffset)) & (p[0] < (prev_points.X+xOffset)) & (p[1] < (prev_points.Y+yOffset)) & (p[1] > (prev_points.Y-yOffset)) & (abs(p[-1] - prev_points.Z) > .3) #time = 156.481780052 s Rectangles = prev_points['Rectangles'] occlusion = np.array([lies_inside(bl=point[0], tr=point[1], p=p, dist=point[-1]) for point in Rectangles]) if np.any(occlusion): #print('point {} is occluded'.format(p)) df.loc[i,'occluded'] = True df.loc[i, 'projected'] = True''' #soc_iter_vect(1) end = time.time() print('the publish took {}'.format(end - start)) print(df.head()) Points = np.array(df[df['occluded']==False]).squeeze() good_points = Points[:,0:2].astype('int') distance = Points[:,2] _3Dpoint = Points[:,3:6] _3Dcolor = Points[:, 6:9] MIN_DISTANCE, MAX_DISTANCE = np.min(distance), np.max(distance) colours = (distance - MIN_DISTANCE) / (MAX_DISTANCE - MIN_DISTANCE) colours = np.asarray([np.asarray(hsv_to_rgb( c, np.sqrt(1), 1.0)) for c in colours]) cols = 255 * colours return good_points, cols,_3Dpoint, _3Dcolor def filterOcclusion_(data): print('data -> {}'.format(np.shape(data))) # ---create a pandas Dataframe with X,Y,Z print('Create a DataFrame') df = pd.DataFrame(data, columns=['X','Y','Z','X3D','Y3X','Z3D','R','G','B']) # ---sort it ascend by Z print('Sort by Z') df = df.sort_values(by=['Z'],kind='quicksort') print('Data point after sorting------------------------------') #---For each point create rectangle centered in current point xGap,yGap = 20, 50 xOffset, yOffset = int(xGap / 2), int(yGap / 2) def create_rectange(x,y,depth): bl = [x-xOffset, y+yOffset] #bottom left tr = [x+xOffset, y-yOffset] #top right return [bl,tr,depth] print('Adding rectangles') #Rectangles = np.array([create_rectange(x=row['X'],y=row['Y'], depth = row['Z']) for index, row in df.iterrows()]) vfunc = np.vectorize(create_rectange) Rectangles = vfunc(df['X'].values, df['Y'].values, df['Z'].values) df['Rectangles'] = Rectangles t = .5 def lies_inside(bl, tr, p, dist): #bottom_left, top_right, poin, distance_left, distance_right if (p[0] > bl[0] and p[0] < tr[0] and p[1] < bl[1] and p[1] > tr[1]): if abs(p[-1]-dist)>t: return True else: return False else: return False def lies_inside_(bl0,bl1, tr0,tr1, p0,p1,p2, dist): #bottom_left, top_right, poin, distance_left, distance_right if (p0 > bl0 and p0 < tr0 and p1 < bl1 and p1 > tr1): if abs(p2-dist)>t: return True else: return False else: return False lies_inside_ = np.vectorize(lies_inside_) occluded = np.zeros_like(Z, dtype=bool) projected = np.zeros_like(Z, dtype=bool) df['occluded'] = occluded df['projected'] = projected idx = range(len(df)) df['idx'] = idx df = df.set_index(['idx']) # for each point check if the prev 5 points belongs to its rectangle -> if yes-> discard it print('Compute neighbors') from sklearn.neighbors import NearestNeighbors #X = np.array(df.iloc[:,0:2]) X = np.array(df.iloc[:, 1]) nbrs = NearestNeighbors(n_neighbors=3, algorithm='ball_tree').fit(X) distances, indices = nbrs.kneighbors(X) print('distances -> {}, indices->{}, df->{}'.format(np.shape(distances), np.shape(indices), np.shape(df))) df['nbrs_indices'] = indices[:,1:].tolist() print(df.head()) import time start = time.time() print('Start projection') def soc_iter(i): print(i) # take the neighbours that are already projected and not occluded nbrs = df.iloc[i, -1] prev_points = df.iloc[nbrs] # .query('projected == 1 & occluded == 0') #5.82813405991 s condition = (prev_points.projected == True) & (prev_points.occluded == False) prev_points = prev_points[condition] # time = 156.481780052 s # print('nbrs -> {}, prev_points->{}, condition1->{}'.format(np.shape(nbrs), np.shape(prev_points), np.shape(condition))) if len(prev_points) > 0: p = np.array(df.iloc[i, 0:3]) # current_point # time = 156.481780052 s Rectangles = prev_points['Rectangles'] occlusion = [lies_inside(bl=point[0], tr=point[1], p=p, dist=point[-1]) for point in Rectangles] # time = 156.481780052 s #occlusion = lies_inside_(prev_points['bl0'].values, prev_points['bl1'].values, prev_points['tr0'].values, prev_points['tr1'].values, p[0], p[1], p[-1], prev_points['Z'].values) if np.any(occlusion): # print('point {} is occluded'.format(p)) df.loc[i, 'occluded'] = True df.loc[i, 'projected'] = True soc_iter_vect = np.vectorize(soc_iter) N = len(df) m = np.linspace(start=1, stop=N-1, num=N-1, dtype=int) print('m->{}, N:{}'.format(np.shape(m),N)) soc_iter_vect(m) # uncomment this '''for i in range(1,2): #len(df) print i # take the neighbours that are already projected and not occluded nbrs = df.iloc[i, -1] prev_points = df.iloc[nbrs]#.query('projected == 1 & occluded == 0') #5.82813405991 s condition = (prev_points.projected == True) & (prev_points.occluded == False) prev_points = prev_points[condition] #time = 156.481780052 s #print('nbrs -> {}, prev_points->{}, condition1->{}'.format(np.shape(nbrs), np.shape(prev_points), np.shape(condition))) if len(prev_points)>0: p = np.array(df.iloc[i, 0:3]) #current_point # time = 303.82229900 #occlusion = (p[0] > (prev_points.X-xOffset)) & (p[0] < (prev_points.X+xOffset)) & (p[1] < (prev_points.Y+yOffset)) & (p[1] > (prev_points.Y-yOffset)) & (abs(p[-1] - prev_points.Z) > .3) #time = 156.481780052 s Rectangles = prev_points['Rectangles'] occlusion = np.array([lies_inside(bl=point[0], tr=point[1], p=p, dist=point[-1]) for point in Rectangles]) if np.any(occlusion): #print('point {} is occluded'.format(p)) df.loc[i,'occluded'] = True df.loc[i, 'projected'] = True''' #soc_iter_vect(1) end = time.time() print('the publish took {}'.format(end - start)) print(df.head()) Points = np.array(df[df['occluded']==False]).squeeze() good_points = Points[:,0:2].astype('int') distance = Points[:,2] _3Dpoint = Points[:,3:6] _3Dcolor = Points[:, 6:9] MIN_DISTANCE, MAX_DISTANCE = np.min(distance), np.max(distance) colours = (distance - MIN_DISTANCE) / (MAX_DISTANCE - MIN_DISTANCE) colours = np.asarray([np.asarray(hsv_to_rgb( c, np.sqrt(1), 1.0)) for c in colours]) cols = 255 * colours return good_points, cols,_3Dpoint, _3Dcolor #points left """Z = np.linalg.norm(points_left, axis=1)[:, np.newaxis] data = np.hstack((points2D_left, Z)) # N x 3 (x,y,distance) data = np.hstack((data,points_left)) # N x 6 data = np.hstack((data,colors_left)) # N x 9 (x,y,distance, X,Y,Z,R,G,B) good_points, cols,_3Dpoint, _3Dcolor = filterOcclusion(data = data) print('good_points->{}, cols->{}, _3Dpoint->{}, _3Dcolor->{}'.format( np.shape(good_points), np.shape(cols), np.shape(_3Dpoint), np.shape(_3Dcolor))) for i in range(len(good_points)): cv2.circle(imgLeft, tuple(good_points[i]), 2, cols[i], -1) '''Z = np.linalg.norm(points_right, axis=1)[:, np.newaxis] data = np.hstack((points2D_right, Z)) # N x 3 (x,y,distance) data = np.hstack((data,points_right)) # N x 6 (x,y,distance) data = np.hstack((data,colors_right)) # N x 9 (x,y,distance, X,Y,Z,R,G,B) _good_points, _cols,_3Dpoint_, _3Dcolor_ = filterOcclusion(data=data) print('good_points->{}, cols->{}, _3Dpoint->{}'.format(np.shape(good_points), np.shape(cols), np.shape(_3Dpoint))) for i in range(len(_good_points)): cv2.circle(imgRight, tuple(_good_points[i]), 2, _cols[i], -1)''' cv2.imshow('imgLeft', cv2.resize(imgLeft,None, fx=.4,fy=.4)) cv2.imshow('imgRight', cv2.resize(imgRight,None, fx=.4,fy=.4)) cv2.waitKey(0) cv2.destroyAllWindows()""" #create a combined pointcloud #print('_3Dpoint->{}, _3Dpoint_->{}'.format(np.shape(_3Dpoint), np.shape(_3Dpoint_))) #print('_3Dcolor->{}, _3Dcolor_->{}'.format(np.shape(_3Dcolor), np.shape(_3Dcolor_))) #points = np.vstack((_3Dpoint, _3Dpoint_)) #color = np.vstack((_3Dcolor, _3Dcolor_)) #points = np.vstack((_3Dpoint_, _3Dpoint)) #color = np.vstack((_3Dcolor_, _3Dcolor)) #points = _3Dpoint #np.vstack((_3Dpoint, _3Dpoint_)) #color = _3Dcolor #np.vstack((_3Dcolor, _3Dcolor_)) #print('points->{}, color->{}'.format(np.shape(points), np.shape(color))) #self.write_ply('Lidar_cam_filtered.ply', points, color) #self.view() plt.show() print('----------------------------------------------------------------------------------------') def occlus(t=.3): # columns=["X", "Y", "Z","intens","ring", time] _3DPoints = np.array(np.load(cloud_file, mmap_mode='r'), dtype=np.float32) #[:,6] # N x 6 print('_3DPoints -> {}'.format(np.shape(_3DPoints))) # Left image-------------------------------------------------------------------------------------------- objPoints_left = _3DPoints.copy() Z = self.get_z(q, objPoints_left[:,:3], self.K) objPoints_left = objPoints_left[Z > 0] print('objPoints_left:{}'.format(np.shape(objPoints_left))) points2D_left, _ = cv2.projectPoints(np.array(objPoints_left[:,:3]).squeeze(), rvec, tvec, self.K, self.D) points2D_left = np.squeeze(points2D_left) print('objPoints_left -> {}, points2D_left -> {}, '.format(np.shape(objPoints_left), np.shape(points2D_left))) inrange_left = np.where((points2D_left[:, 0] > 0) & (points2D_left[:, 1] > 0) & (points2D_left[:, 0] < imgLeft.shape[1] - 1) & (points2D_left[:, 1] < imgLeft.shape[0] - 1)) points2D_left = points2D_left[inrange_left[0]].round().astype('int') print('points2D_left:{}, '.format(np.shape(points2D_left))) points_left = objPoints_left[inrange_left[0]] colors_left = colorImageLeft[points2D_left[:, 1], points2D_left[:, 0], :] print('points->{}, color->{}'.format(np.shape(points_left), np.shape(colors_left))) distance = np.linalg.norm(points_left[:,:3], axis=1)[:, np.newaxis] MIN_DISTANCE, MAX_DISTANCE = np.min(distance), np.max(distance) colours = np.asarray((distance - MIN_DISTANCE) / (MAX_DISTANCE - MIN_DISTANCE)).squeeze() colours = np.asarray([hsv_to_rgb(0.75 * c, np.sqrt(1), 1.0) for c in colours]) cols = 255 * colours df = pd.DataFrame(data=points_left, columns=["X", "Y", "Z", "intens", "ring", "time"]) df['RGB'] = colors_left.tolist() df['pixels'] = points2D_left.tolist() df['distance'] = distance #.round() df['color'] = cols.tolist() print(df.head()) gp = df.groupby('ring') keys = gp.groups.keys() print('keys -> {}'.format(np.shape(keys))) _3Dcolor,_3Dpoint = [],[] k=0 for i in keys: group = gp.get_group(i).to_numpy() # X,Y,Z,intens,ring,time,RGB,pixels,distance,color #group = gp.get_group(i+b).to_numpy() N = len(group) print('Ring ->{}, {}'.format(i, np.shape(group))) #take x pixels pixels = np.concatenate(group[:,7]).reshape(-1,2) sorted_idx = pixels[:, 0].argsort(kind='mergesort') #sort by x pixel #sorted_idx = np.linspace(start = 0, stop = N-1, num = N, dtype = int) pixels = pixels[sorted_idx] distance = group[sorted_idx,8] points, colors = np.asarray(group[:, :3]), np.asarray(group[:, 6]) k+=1 collours = [] for j in range(1, N): d = distance[j] - distance[j - 1] s = np.sign(d) if abs(d) > t: if s < 0: col, col_ = 'b', (255, 0, 0) _3Dcolor.append(colors[j]) _3Dpoint.append(points[j]) size = 3 l=2 else: col, col_ = 'r', (0, 0, 255) #col, col_ = 'g', (0, 255, 0) size = 2 l=-1 else: col, col_ = 'g', (0, 255, 0) _3Dcolor.append(colors[j]) _3Dpoint.append(points[j]) size = 2 l = -1 collours.append(col) #cv2.circle(imgLeft, tuple(pixels[j]), size, col_, l) cv2.circle(imgLeft, tuple(pixels[j]), size, (0,255,0), l) #plt.scatter(pixels[j,0], distance[j], c=col, s=2) #plt.plot(pixels[:, 0], distance, c='blue', alpha=0.2) plt.scatter(pixels[:, 0], distance, c=collours, s=.5) #if k%3==0: #plt.grid() #plt.show() #distance = group[:,8] #unsorted #m = np.linspace(start = 0, stop = N-1, num = N, dtype = int) #plt.scatter(m, distance,s=2) #plt.grid() #plt.show() cv2.imshow('imgLeft', cv2.resize(imgLeft, None, fx=.5, fy=.5)) cv2.waitKey(0) cv2.imshow('imgLeft', cv2.resize(imgLeft, None, fx=.5, fy=.5)) plt.grid() plt.show() cv2.waitKey(0) print('_3Dpoint -> {}, _3Dcolor->{}'.format(np.shape(_3Dpoint), np.shape(_3Dcolor))) #self.write_ply('0Lidar_cam_filter2.ply', np.array(_3Dpoint), np.array(_3Dcolor)) #self.view() cv2.waitKey(0) cv2.destroyAllWindows() #occlus() #self.view() def DLT(self): def vgg_rq(S): S = S.T Q, U = np.linalg.qr(np.fliplr(np.flipud(S))) Q = np.fliplr(np.flipud(Q.T)) U = np.fliplr(np.flipud(U.T)) return U, Q def vgg_KR_from_P(P, noscale=False): N = P.shape[0] H = P[:, :N] K, R = vgg_rq(H) if not noscale: K = K / K[N - 1, N - 1] if K[0, 0] < 0: D = np.diag(np.hstack((np.array([-1, -1]), np.ones(N - 2)))) K = np.dot(K, D) R = np.dot(D, R) t = np.linalg.lstsq(-P[:, 0:N], P[:, -1])[0] return K, R, t def camcalibDLT(Xworld, Xim): # Xworld - (8, 4) # Xim - (8, 3) n, d = np.shape(Xworld) zeros_1x4 = np.zeros((1, 4)) saved_data = [] for j in range(n): world_point = np.array(Xworld[j]).reshape(1, -1) image_point = np.array(Xim[j]).reshape(-1, 1) image2world = image_point.dot(world_point) # (3, 4) minus_row1 = -(image2world[0]).reshape(1, -1) # (1, 4) minus_row2 = -(image2world[1]).reshape(1, -1) # (1, 4) row3 = image2world[2].reshape(1, -1) # (1, 4) stack = np.stack((zeros_1x4, row3, minus_row2)).reshape(1, -1) # (1, 12) saved_data.append(stack[0]) stack = np.stack((row3, zeros_1x4, minus_row1)).reshape(1, -1) # (1, 12) saved_data.append(stack[0]) saved_data = np.array(saved_data) print('saved_data ', np.shape(saved_data)) _, Sigma, V = np.linalg.svd(saved_data) P = V[np.argmin(Sigma)].reshape((3, 4)) return P def GET_DATA(): # get data from chessboard '''name = 'chess' self.file = '/home/eugeniu/catkin_ws/src/testNode/CAMERA_CALIBRATION/data/GoodPoints_{}.pkl'.format(name) self.load_points() Lidar_3D, Image_2D, Image_3D = np.array(self.Lidar_3D).reshape(-1, 3), np.array(self.Image_2D).reshape(-1, 2), np.array( self.Image_3D).reshape(-1, 3) # get data from charuco''' name = 'charuco' self.file = '/home/eugeniu/catkin_ws/src/testNode/CAMERA_CALIBRATION/data/GoodPoints_{}.pkl'.format(name) self.load_points() #Lidar_3D, Image_2D = np.vstack((Lidar_3D, np.array(self.Lidar_3D).reshape(-1, 3))), np.vstack( # (Image_2D, np.array(self.Image_2D).reshape(-1, 2))) #print('Lidar_3D:->{}, Image_2D:->{}'.format(np.shape(Lidar_3D), np.shape(Image_2D))) Lidar_3D, Image_2D, Image_3D = np.array(self.Lidar_3D).reshape(-1, 3), np.array(self.Image_2D).reshape(-1, 2), np.array( self.Image_3D).reshape(-1, 3) imgp = np.array([Image_2D], dtype=np.float32).squeeze() objp = np.array([Lidar_3D], dtype=np.float32).squeeze() return objp, imgp _3D_points, _2D_points = GET_DATA() print('_3D_points->{}, _2D_points->{}'.format(np.shape(_3D_points), np.shape(_2D_points))) P1 = camcalibDLT(np.hstack((_3D_points, np.ones((len(_3D_points), 1)))), np.hstack((_2D_points, np.ones((len(_3D_points), 1))))) print('P1 -> {}'.format(P1)) # Check the results by projecting the world points with the estimated P. # The projected points should overlap with manually localized points fig, axes = plt.subplots(nrows=1, ncols=1, figsize=(15, 15)) # plot manually localized axes.plot(_2D_points[:,0], _2D_points[:,1], 'c+', markersize=10) # plot projected pproj1 = np.dot(P1, np.hstack((_3D_points, np.ones((len(_3D_points), 1)))).T) for i in range(len(_3D_points)): axes.plot(pproj1[0, i] / pproj1[2, i], pproj1[1, i] / pproj1[2, i], 'rx', markersize=12) plt.show() print('intrinsic camera calibration matrices') K1, R1, t1 = vgg_KR_from_P(P1) print('K1') print(K1) def estimate(self, a1=None,a2=None): import numpy as np import numpy.linalg # Relevant links: # - http://stackoverflow.com/a/32244818/263061 (solution with scale) # - "Least-Squares Rigid Motion Using SVD" (no scale but easy proofs and explains how weights could be added) # Rigidly (+scale) aligns two point clouds with know point-to-point correspondences # with least-squares error. # Returns (scale factor c, rotation matrix R, translation vector t) such that # Q = P*cR + t # if they align perfectly, or such that # SUM over point i ( | P_i*cR + t - Q_i |^2 ) # is minimised if they don't align perfectly. def umeyama(P, Q): assert P.shape == Q.shape n, dim = P.shape centeredP = P - P.mean(axis=0) centeredQ = Q - Q.mean(axis=0) C = np.dot(np.transpose(centeredP), centeredQ) / n V, S, W = np.linalg.svd(C) d = (np.linalg.det(V) * np.linalg.det(W)) < 0.0 if d: S[-1] = -S[-1] V[:, -1] = -V[:, -1] R = np.dot(V, W) varP = np.var(a1, axis=0).sum() c = 1 / varP * np.sum(S) # scale factor t = Q.mean(axis=0) - P.mean(axis=0).dot(c * R) return c, R, t # Testing np.set_printoptions(precision=3) if a1 is None and a2 is None: a1 = np.array([ [0, 0, -1], [0, 0, 0], [0, 0, 1], [0, 1, 0], [1, 0, 0], ]) a2 = np.array([ [0, 0, 1], [0, 0, 0], [0, 0, -1], [0, 1, 0], [-1, 0, 0], ]) a2 *= 2 # for testing the scale calculation a2 += 3 # for testing the translation calculation c, R, t = umeyama(a1, a2) print ("R =\n", R) print ("c =", c) print ("t =\n", t) print ("Check: a1*cR + t = a2 is", np.allclose(a1.dot(c * R) + t, a2)) err = ((a1.dot(c * R) + t - a2) ** 2).sum() print ("Residual error", err) return c, R, t def project3D_2D_onImage(self, imgLeft, _3DPoints): def readCalibrationExtrinsic(): calib_file = '/home/eugeniu/catkin_ws/src/testNode/CAMERA_CALIBRATION/solvePnP_extrinsics{}.npz'.format( 'chess' if self.chess else 'charuco') calib_file = '/home/eugeniu/catkin_ws/src/testNode/CAMERA_CALIBRATION/combined_extrinsics{}.npz' with open(calib_file, 'r') as f: data = f.read().split() #print('data:{}'.format(data)) qx = float(data[0]) qy = float(data[1]) qz = float(data[2]) qw = float(data[3]) tx = float(data[4]) ty = float(data[5]) tz = float(data[6]) q = Quaternion(qw, qx, qy, qz).transformation_matrix q[0, 3],q[1, 3],q[2, 3] = tx,ty,tz tvec = q[:3, 3] rot_mat = q[:3, :3] #rvec, _ = cv2.Rodrigues(rot_mat) rvec = rot_mat print('tvec -> {}'.format(tvec)) return rvec, tvec, q rvec, tvec, q = readCalibrationExtrinsic() #Left image-------------------------------------------------------------------------------------------- objPoints_left = _3DPoints.copy() Z = self.get_z(q, objPoints_left, self.K) objPoints_left = objPoints_left[Z > 0] points2D_left, _ = cv2.projectPoints(objPoints_left, rvec, tvec, self.K, self.D) points2D_left = np.squeeze(points2D_left) inrange_left = np.where((points2D_left[:, 0] > 0) & (points2D_left[:, 1] > 0) & (points2D_left[:, 0] < imgLeft.shape[1]-1) & (points2D_left[:, 1] < imgLeft.shape[0]-1)) points2D_left = points2D_left[inrange_left[0]].round().astype('int') for i in range(len(points2D_left)): cv2.circle(imgLeft, tuple(points2D_left[i]), 2, (0, 255, 0), -1) return imgLeft def calibrate_3D_3D(self): def rot2eul(R): beta = -np.arcsin(R[2, 0]) alpha = np.arctan2(R[2, 1] / np.cos(beta), R[2, 2] / np.cos(beta)) gamma = np.arctan2(R[1, 0] / np.cos(beta), R[0, 0] / np.cos(beta)) return np.array((np.rad2deg(alpha), np.rad2deg(beta), np.rad2deg(gamma))) print('3D-3D ========================================================================================') Lidar_3D = np.array(self.Lidar_3D).reshape(-1, 3) Image_3D = np.array(self.Image_3D).reshape(-1, 3) print('Lidar_3D:{}, Image_3D:{}'.format(np.shape(Lidar_3D), np.shape(Image_3D))) self.fig = plt.figure(figsize=plt.figaspect(1.)) ax1 = self.fig.add_subplot(1, 1, 1, projection='3d') ax1.set_xlabel('X', fontsize=8) ax1.set_ylabel('Y', fontsize=8) ax1.set_zlabel('Z', fontsize=8) ax1.set_xlim([-3, 3]) ax1.set_ylim([-3, 3]) ax1.set_zlim([-5, 10]) #ax1.set_axis_off() #plot all data #ax1.scatter(*Lidar_3D.T, c='blue', label = 'LiDAR points') #ax1.scatter(*Image_3D.T, s=25, c='red', label = 'Stereo Cam points') ax1.scatter(*self.Lidar_3D[0].T, c='blue', label='LiDAR points') ax1.scatter(*self.Image_3D[0].T, s=25, c='red', label='Stereo Cam points') dist_mat = distance_matrix(self.Image_3D[0],self.Image_3D[0]) print('distance_matrix cam') print(dist_mat) dist_mat = distance_matrix(self.Lidar_3D[0], self.Lidar_3D[0]) print('distance_matrix LiDAR') print(dist_mat) #ax1.legend() #plt.show() #estimate transformation ==================================================== c, R, t = self.estimate(Lidar_3D,Image_3D) print('t:{}'.format(t)) angles = rot2eul(R) print('angles:{}'.format(angles)) Camera_points3D = self.Lidar_3D[0].dot(c * R) + t #Camera_points3D = self.Lidar_3D[0].dot(R) + t ax1.scatter(*Camera_points3D.T, label='Transformed LiDAR') ax1.legend() plt.show() #project on image =========================================================== l = '/home/eugeniu/catkin_ws/src/testNode/CAMERA_CALIBRATION/data/charuco/left/left_4.png' img = cv2.imread(l) cloud_file = '/home/eugeniu/catkin_ws/src/testNode/CAMERA_CALIBRATION/data/charuco/cloud_4.npy' i = 12 #l = '/home/eugeniu/catkin_ws/src/testNode/CAMERA_CALIBRATION/cool/left_{}.png'.format(i) #img = cv2.imread(l) #cloud_file = '/home/eugeniu/catkin_ws/src/testNode/CAMERA_CALIBRATION/cool/cloud_{}.npy'.format(i) img = cv2.remap(src=img, map1=self.leftMapX, map2=self.leftMapY,interpolation=cv2.INTER_LINEAR, dst=None, borderMode=cv2.BORDER_CONSTANT) LiDAR_points3D = np.array(np.load(cloud_file, mmap_mode='r'), dtype=np.float32)[:, :3] # Camera_points3D = LiDAR_points3D.dot(c * R) + t #LiDAR points in camera frame print('LiDAR_points3D:{}, Camera_points3D:{}'.format(np.shape(LiDAR_points3D), np.shape(Camera_points3D))) homogen = lambda x: np.array([x[0],x[1],x[2],1]) invhomogen = lambda x: np.array([x[0]/x[-1], x[1]/x[-1]]) cam = np.array([homogen(x) for x in Camera_points3D[:, :3]]) points2D = self.P1.dot(cam.T).T points2D = np.array([invhomogen(x) for x in points2D[:]]) print('points2D -> {}'.format(np.shape(points2D))) inrange = np.where( (points2D[:, 0] >= 0) & (points2D[:, 1] >= 0) & (points2D[:, 0] < img.shape[1]) & (points2D[:, 1] < img.shape[0]) ) points2D = points2D[inrange[0]].round().astype('int') for i in range(len(points2D)): cv2.circle(img, tuple(points2D[i]), 2, (0, 255, 0), -1) projection_2D_3D = self.project3D_2D_onImage(cv2.imread(l), LiDAR_points3D) #cv2.imshow('3D-3D estimation', cv2.resize(img,None,fx=.4,fy=.4)) #cv2.imshow('2D-3D estimation', cv2.resize(projection_2D_3D,None,fx=.4,fy=.4)) cv2.putText(img, '3D-3D', (20, 1200), cv2.FONT_HERSHEY_SIMPLEX, 2, (0, 0, 255), 3) cv2.putText(projection_2D_3D, '3D-2D', (20, 1200), cv2.FONT_HERSHEY_SIMPLEX, 2, (0, 0, 255), 3) scale = .4 _horizontal = np.hstack( (cv2.resize(img, None, fx=scale, fy=scale), cv2.resize(projection_2D_3D, None, fx=scale, fy=scale))) cv2.imshow('Estimation', _horizontal) cv2.waitKey(0) cv2.destroyAllWindows() print('self.P1->{}'.format(np.shape(self.P1))) print(self.P1) #------------------------------------------------------------- l = '/home/eugeniu/catkin_ws/src/testNode/CAMERA_CALIBRATION/data/chess/left/left_5.png' img = cv2.imread(l) gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) ret, corners = cv2.findChessboardCorners(gray, (10, 7), None) print('ret ->{}'.format(ret)) if ret == True: corners2 = cv2.cornerSubPix(gray, corners, (11, 11), (-1, -1), self.criteria) # Find the rotation and translation vectors. success, rvecs, tvecs, inliers = cv2.solvePnPRansac(self.objp, corners2, self.K, self.D) print('success->{} rvecs:{}, tvecs:{}, inliers:{}'.format(success, np.shape(rvecs), np.shape(tvecs), np.shape(inliers))) #print(rvecs) #print(tvecs) rvecs,_ = cv2.Rodrigues(rvecs) print('self.objp->{}'.format(np.shape(self.objp))) _3Dpoints = self.objp # project 3D points to image plane _2Dpoints, jac = cv2.projectPoints(_3Dpoints, rvecs, tvecs, self.K, self.D) _2Dpoints = np.array(_2Dpoints, dtype=np.float32).squeeze() print('_2Dpoints -> {}'.format(np.shape(_2Dpoints))) for i in range(len(_2Dpoints)): cv2.circle(img, tuple(_2Dpoints[i]), 5, (0, 255, 0), 3) _3Dpoints = rvecs.dot(_3Dpoints.T)+tvecs _3Dpoints = _3Dpoints.T #rvecs, tvecs, _3Dpoints, _2Dpoints print('_3Dpoints->{}'.format(np.shape(_3Dpoints))) print(_3Dpoints) dist_mat = distance_matrix(_3Dpoints,_3Dpoints) print('dist_mat') print(dist_mat) self.fig = plt.figure(figsize=plt.figaspect(1.)) ax1 = self.fig.add_subplot(1, 1, 1, projection='3d') ax1.scatter(*_3Dpoints.T, label='OpenCV') #ax1.scatter(*self.Image_3D[0].T, s=25, c='red', label='Stereo Cam points') ax1.legend() cv2.imshow('img', cv2.resize(img, None, fx=.4, fy=.4)) cv2.waitKey(0) plt.show() cv2.destroyAllWindows() def doSomePlots(self): points3D = np.array(self.Lidar_3D).reshape(-1, 3) points2D = np.array(self.Image_2D).reshape(-1, 2) print('points3D:{}, points2D:{}'.format(np.shape(points3D), np.shape(points2D))) def readCalibrationExtrinsic(): calib_file = '/home/eugeniu/catkin_ws/src/testNode/CAMERA_CALIBRATION/solvePnP_extrinsics{}.npz'.format( 'chess' if self.chess else 'charuco') calib_file = '/home/eugeniu/catkin_ws/src/testNode/CAMERA_CALIBRATION/combined_extrinsics{}.npz' with open(calib_file, 'r') as f: data = f.read().split() #print('data:{}'.format(data)) qx = float(data[0]) qy = float(data[1]) qz = float(data[2]) qw = float(data[3]) tx = float(data[4]) ty = float(data[5]) tz = float(data[6]) q = Quaternion(qw, qx, qy, qz).transformation_matrix q[0, 3],q[1, 3],q[2, 3] = tx,ty,tz tvec = q[:3, 3] rot_mat = q[:3, :3] #rvec, _ = cv2.Rodrigues(rot_mat) rvec = rot_mat print('tvec -> {}'.format(tvec)) return rvec, tvec, q #ground truth estimation rvec, tvec, q = readCalibrationExtrinsic() ground_truth_rotation = euler_from_matrix(rvec) ground_truth_translation = np.array(tvec).squeeze() ground_truth_rotation = np.array([(180.0 / math.pi) * i for i in ground_truth_rotation]).squeeze() print('ground_truth_rotation: ', ground_truth_rotation) print('ground_truth_translation: ', ground_truth_translation) #randomly select 5%, 10%, 15%, ..., 100% of data points #compute the transformation #estimate the error between the ground truth #save for later plot and plot it percentage = np.linspace(2,100,20) N = len(points3D) # Idx = np.arange(0,len(points3D)) print('N -> {}'.format(N)) print('percentage -> {}'.format(percentage)) rot_, tran_ = [], [] for i in range(20): rot, tran = [], [] for p in percentage: nr_points = int(p*N/100) #print(nr_points) idx_points = np.random.choice(Idx, nr_points) train_lidar = points3D[idx_points] train_camera = points2D[idx_points] imgp = np.array([train_camera], dtype=np.float32).squeeze() objp = np.array([train_lidar], dtype=np.float32).squeeze() retval, rvec, tvec = cv2.solvePnP(objp, imgp, self.K, self.D, flags=cv2.SOLVEPNP_ITERATIVE) rvec,_ = cv2.Rodrigues(rvec) tvec = np.array(tvec).squeeze() _rotation = euler_from_matrix(rvec) _rotation = np.array([(180.0 / math.pi) * i for i in _rotation]) err_rotation = np.abs(_rotation-ground_truth_rotation) err_translation = np.abs(tvec - ground_truth_translation) #print('err_rotation->{}, err_translation->{}'.format(np.shape(err_rotation), np.shape(err_translation))) rot.append(err_rotation) tran.append(err_translation) print('rot->{}, tran->{}'.format(np.shape(rot), np.shape(tran))) rot_.append(rot) tran_.append(tran) print('rot_->{}, tran_->{}'.format(np.shape(rot_), np.shape(tran_))) rot_ = np.mean(rot_, axis=0) tran_ = np.mean(tran_, axis=0) print('rot_->{}, tran_->{}'.format(np.shape(rot_), np.shape(tran_))) ticks = percentage * N / 100 print('ticks -> {}'.format(np.shape(ticks))) plt.plot(ticks,rot_[:,0], label='X') plt.plot(ticks,rot_[:, 1], label='Y') plt.plot(ticks,rot_[:, 2], label='Z') plt.legend() plt.xlabel("n-points") plt.ylabel("mean rotation error (degree)") plt.xticks(ticks) plt.show() plt.plot(ticks,tran_[:, 0], label='X') plt.plot(ticks,tran_[:, 1], label='Y') plt.plot(ticks,tran_[:, 2], label='Z') plt.xlabel("n-points") plt.ylabel("mean translation error (m)") plt.legend() plt.show() def do_holy_Final_calibration(self,viewData = False): #get data self.Lidar_3D = np.array(self.Lidar_3D)[:,-1,:] self.Image_3D = np.array(self.Image_3D)[:, -1, :] self.Image_2D = np.array(self.Image_2D)[:, -1, :] self.Image_2D2 = np.array(self.Image_2D2)[:, -1, :] print('self.Lidar_3D ->{}, self.Image_3D->{}'.format(np.shape(self.Lidar_3D), np.shape(self.Image_3D))) points3D_Lidar = np.array(self.Lidar_3D, dtype=np.float32).reshape(-1, 3) points3D_Camera = np.array(self.Image_3D, dtype=np.float32).reshape(-1, 3) points2DLeft = np.array(self.Image_2D, dtype=np.float32).reshape(-1, 2) points2DRight = np.array(self.Image_2D2, dtype=np.float32).reshape(-1, 2) print('points3D_Lidar:{},points3D_Camera:{}, points2DLeft:{}, points2DRight:{}'.format(np.shape(points3D_Lidar),np.shape(points3D_Camera), np.shape(points2DLeft), np.shape(points2DRight))) #visualize the data if viewData: for i in range(len(self.Lidar_3D)): fig = plt.figure() ax0 = fig.add_subplot(2, 2, 1, projection='3d') # Lidar ax0.set_title('Lidar points') ax1 = fig.add_subplot(2, 2, 2, projection='3d') # camera 3d ax1.set_title('Camera 3D') ax2 = fig.add_subplot(2, 2, 3) # left pixels ax2.set_title('Left px') ax3 = fig.add_subplot(2, 2, 4) # right pixels ax3.set_title('Right px') print(i) ax0.clear() ax0.scatter(*self.Lidar_3D[i].T) ax0.set_title('Lidar points') dist_Lidar = distance_matrix(self.Lidar_3D[i],self.Lidar_3D[i]) print('dist_Lidar---------------------------------------------------------') print(dist_Lidar[0,:11]) ax1.clear() ax1 = plt.axes(projection='3d') ax1.scatter(*self.Image_3D[i].T, c='k', marker='v', alpha=1) ax1.set_title('Camera 3D') dist_Cam = distance_matrix(self.Image_3D[i], self.Image_3D[i]) print('dist_Cam---------------------------------------------------------') print(dist_Cam[0,:11]) data = np.array(self.Image_3D).squeeze() #ax1.plot_wireframe(data[i,:,0], data[i,:,1], data[i,:,2], rstride=1, cstride=1) ax1.plot_trisurf(data[i,:,0], data[i,:,1], data[i,:,2], alpha=.4, color='grey', shade=False) ax1.set_xlabel('X') ax1.set_ylabel('Y') ax1.set_zlabel('Z') ax1.set_xticks([]) ax1.set_yticks([]) ax1.set_zticks([]) ax1.set_axis_off() plt.show() ax2.clear() ax2.scatter(*self.Image_2D[i].T) ax2.set_title('Left px') ax3.clear() ax3.scatter(*self.Image_2D2[i].T) ax3.set_title('Right px') plt.show() break #Calibrate LiDAR3d-Camera3D self.fig = plt.figure(figsize=plt.figaspect(1.)) ax1 = self.fig.add_subplot(1, 1, 1, projection='3d') ax1.set_xlabel('X', fontsize=8) ax1.set_ylabel('Y', fontsize=8) ax1.set_zlabel('Z', fontsize=8) ax1.set_xlim([-3, 3]) ax1.set_ylim([-3, 3]) ax1.set_zlim([-3, 3]) # ax1.set_axis_off() ax1.scatter(*self.Lidar_3D[0].T, c='blue', label='LiDAR points') ax1.scatter(*self.Image_3D[0].T, s=25, c='red', label='Stereo Cam points') #ax1.scatter(*points3D_Lidar.T, c='blue', label='LiDAR points2') #ax1.scatter(*points3D_Camera.T, s=25, c='red', label='Stereo Cam points2') # estimate transformation ==================================================== c, R, t = self.estimate(points3D_Lidar, points3D_Camera) pad = lambda x: np.hstack([x, np.ones((x.shape[0], 1))]) unpad = lambda x: x[:, :-1] # Solve the least squares problem X * A = Y # to find our transformation matrix A A, res, rank, s = np.linalg.lstsq(pad(points3D_Lidar), pad(points3D_Camera)) transform = lambda x: unpad(np.dot(pad(x), A)) #Camera_points3D = transform(np.array(self.Lidar_3D[0])) # transformation estimated with LS #ax1.scatter(*Camera_points3D.T, label='least square sol') print('t:{}'.format(t)) angles = euler_from_matrix(R) print('euler angles ', [(180.0 / math.pi) * i for i in angles]) Camera_points3D = self.Lidar_3D[0].dot(c * R) + t #Camera_points3D = self.Lidar_3D[0].dot(R) + t ax1.scatter(*Camera_points3D.T, label='SVD') ax1.legend() plt.show() left_src = '/home/eugeniu/catkin_ws/src/testNode/CAMERA_CALIBRATION/data/chess/left/left_0.png' left_src = '/home/eugeniu/catkin_ws/src/testNode/CAMERA_CALIBRATION/data/charuco/left/left_4.png' left_img = cv2.imread(left_src) cloud_file = '/home/eugeniu/catkin_ws/src/testNode/CAMERA_CALIBRATION/data/chess/cloud_0.npy' cloud_file = '/home/eugeniu/catkin_ws/src/testNode/CAMERA_CALIBRATION/data/charuco/cloud_4.npy' _3DPoints = np.array(np.load(cloud_file, mmap_mode='r'), dtype=np.float32)[:, :3] # Left image-------------------------------------------------------------------------------------------- objPoints_left = _3DPoints.copy() objPoints_left = objPoints_left.dot(c * R) + t #objPoints_left = np.array(transform(_3DPoints), dtype=np.float32).squeeze() # transformation estimated with LS #objPoints_left = Camera_points3D print('objPoints_left ->{}'.format(np.shape(objPoints_left))) print(objPoints_left) points2D_left, _ = cv2.projectPoints(objPoints_left, np.eye(3), np.zeros(3), self.K_left, self.D_left) points2D_left = np.squeeze(points2D_left) print('objPoints_left -> {}, points2D_left -> {}, '.format(np.shape(objPoints_left), np.shape(points2D_left))) inrange_left = np.where((points2D_left[:, 0] > 0) & (points2D_left[:, 1] > 0) & (points2D_left[:, 0] < left_img.shape[1] - 1) & ( points2D_left[:, 1] < left_img.shape[0] - 1)) points2D_left = points2D_left[inrange_left[0]].round().astype('int') for i in range(len(points2D_left)): cv2.circle(left_img, tuple(points2D_left[i]), 2, (0, 255, 0), -1) cv2.imshow('left_img 3D-3D estimation', cv2.resize(left_img, None, fx=.4, fy=.4)) cv2.waitKey(0) # cv2.destroyAllWindows() #calibrate Lidar-> left camera print('Calibrate LiDAR->Left camera===============================================================') imgp = np.array([points2DLeft], dtype=np.float32).squeeze() objp = np.array([points3D_Lidar], dtype=np.float32).squeeze() print('imgp->{},objp->{}'.format(np.shape(imgp), np.shape(objp))) retval, rvec, tvec = cv2.solvePnP(objp, imgp, self.K, self.D, flags=cv2.SOLVEPNP_ITERATIVE) #success, rvec, tvec, inliers = cv2.solvePnPRansac(objp,imgp, self.K, self.D,flags=cv2.SOLVEPNP_ITERATIVE) rvec, tvec = cv2.solvePnPRefineLM(objp, imgp, self.K, self.D, rvec, tvec) print('rvec is {}=============='.format(rvec)) rvec, jac = cv2.Rodrigues(rvec) print("RMSE in pixel = %f" % self.rmse(objp, imgp, self.K_left, self.D_left, rvec, tvec)) print("T = ") print(tvec) print('Euler angles') angles = euler_from_matrix(rvec) self.Lidar_left_tvec = tvec self.Lidar_left_rvec = rvec print('euler angles ', [(180.0 / math.pi) * i for i in angles]) #test calibration LiDAR->Left camera left_src = '/home/eugeniu/catkin_ws/src/testNode/CAMERA_CALIBRATION/data/chess/left/left_0.png' left_src = '/home/eugeniu/catkin_ws/src/testNode/CAMERA_CALIBRATION/data/charuco/left/left_4.png' left_img = cv2.imread(left_src) cloud_file = '/home/eugeniu/catkin_ws/src/testNode/CAMERA_CALIBRATION/data/chess/cloud_0.npy' cloud_file = '/home/eugeniu/catkin_ws/src/testNode/CAMERA_CALIBRATION/data/charuco/cloud_4.npy' _3DPoints = np.array(np.load(cloud_file, mmap_mode='r'), dtype=np.float32)[:, :3] #Left image-------------------------------------------------------------------------------------------- objPoints_left = _3DPoints.copy() points2D_left, _ = cv2.projectPoints(objPoints_left, rvec, tvec, self.K_right, self.D_right) points2D_left = np.squeeze(points2D_left) print('objPoints_left -> {}, points2D_left -> {}, '.format(np.shape(objPoints_left), np.shape(points2D_left))) inrange_left = np.where((points2D_left[:, 0] > 0) & (points2D_left[:, 1] > 0) & (points2D_left[:, 0] < left_img.shape[1] - 1) & (points2D_left[:, 1] < left_img.shape[0] - 1)) points2D_left = points2D_left[inrange_left[0]].round().astype('int') for i in range(len(points2D_left)): cv2.circle(left_img, tuple(points2D_left[i]), 2, (0,255,0), -1) q = Quaternion(matrix=rvec) # tvec[2] = -.59 result_file = 'final_extrinsic.npz' with open(result_file, 'w') as f: f.write("%f %f %f %f %f %f %f" % (q.x, q.y, q.z, q.w, tvec[0], tvec[1], tvec[2])) cv2.imshow('left_img',cv2.resize(left_img,None,fx=.4,fy=.4)) cv2.waitKey(0) #cv2.destroyAllWindows() #======================================================================================= # calibrate Lidar-> right camera print('Calibrate LiDAR->right camera===============================================================') imgp = np.array([points2DRight], dtype=np.float32).squeeze() objp = np.array([points3D_Lidar], dtype=np.float32).squeeze() print('imgp->{},objp->{}'.format(np.shape(imgp), np.shape(objp))) retval, rvec, tvec = cv2.solvePnP(objp, imgp, self.K, self.D, flags=cv2.SOLVEPNP_ITERATIVE) #success, rvec, tvec, inliers = cv2.solvePnPRansac(objp,imgp, self.K, self.D,flags=cv2.SOLVEPNP_ITERATIVE) rvec, tvec = cv2.solvePnPRefineLM(objp, imgp, self.K, self.D, rvec, tvec) rmat, jac = cv2.Rodrigues(rvec) print("RMSE in pixel = %f" % self.rmse(objp, imgp, self.K, self.D, rvec, tvec)) print("T = ") print(tvec) print('Euler angles') self.Lidar_right_tvec = tvec self.Lidar_right_rvec = rmat angles = euler_from_matrix(rmat) print('euler angles ', [(180.0 / math.pi) * i for i in angles]) print("Quaternion = ") q = Quaternion(matrix=rmat).transformation_matrix #tvec[2] = -.59 q[0, 3], q[1, 3], q[2, 3] = tvec[0], tvec[1], tvec[2] # test calibration LiDAR->Left camera src = '/home/eugeniu/catkin_ws/src/testNode/CAMERA_CALIBRATION/data/chess/right/right_0.png' src = '/home/eugeniu/catkin_ws/src/testNode/CAMERA_CALIBRATION/data/charuco/right/right_4.png' img = cv2.imread(src) cloud_file = '/home/eugeniu/catkin_ws/src/testNode/CAMERA_CALIBRATION/data/chess/cloud_0.npy' cloud_file = '/home/eugeniu/catkin_ws/src/testNode/CAMERA_CALIBRATION/data/charuco/cloud_4.npy' _3DPoints = np.array(np.load(cloud_file, mmap_mode='r'), dtype=np.float32)[:, :3] # Left image-------------------------------------------------------------------------------------------- objPoints_left = _3DPoints.copy() Z = self.get_z(q, objPoints_left, self.K) objPoints_left = objPoints_left[Z > 0] points2D_left, _ = cv2.projectPoints(objPoints_left, rvec, tvec, self.K_right, self.D_right) points2D_left = np.squeeze(points2D_left) print('objPoints_left -> {}, points2D_left -> {}, '.format(np.shape(objPoints_left), np.shape(points2D_left))) inrange_left = np.where((points2D_left[:, 0] > 0) & (points2D_left[:, 1] > 0) & (points2D_left[:, 0] < left_img.shape[1] - 1) & ( points2D_left[:, 1] < left_img.shape[0] - 1)) points2D_left = points2D_left[inrange_left[0]].round().astype('int') for i in range(len(points2D_left)): cv2.circle(img, tuple(points2D_left[i]), 2, (0, 255, 0), -1) cv2.imshow('right_img', cv2.resize(img, None, fx=.4, fy=.4)) cv2.waitKey(0) cv2.destroyAllWindows() print('=============================================================') #test stereo calibration based on lidar extrinsics stere_tvec = np.array([-0.96, 0., 0.12])[:, np.newaxis] angles = euler_from_matrix(self.R) stereo_angles = np.array([(180.0 / math.pi) * i for i in angles]) print('Stereo camera calibration extrinsics') print('angles -> {}'.format(stereo_angles)) print('tvec -> {}'.format(stere_tvec.ravel())) T_lidar_leftCam = np.vstack((np.hstack((self.Lidar_left_rvec, self.Lidar_left_tvec)), np.array([0, 0, 0, 1])[:,np.newaxis].T)) T_lidar_rightCam = np.vstack((np.hstack((self.Lidar_right_rvec, self.Lidar_right_tvec)), np.array([0, 0, 0, 1])[:,np.newaxis].T)) #T left cam to right cam is T1^-1 * T2 T_leftCam_rightCam = np.dot(T_lidar_rightCam,np.linalg.inv(T_lidar_leftCam)) rvec, tvec = T_leftCam_rightCam[:3, :3], T_leftCam_rightCam[:3, -1] angles = euler_from_matrix(rvec) angles = np.array([(180.0 / math.pi) * i for i in angles]) print('') print('Lidar based camera calibration extrinsics') print('angles -> {}'.format(angles)) print('tvec -> {}'.format(tvec)) def do_holy_Final_calibration2(self): def hsv_to_rgb(h, s, v): if s == 0.0: return v, v, v i = int(h * 6.0) f = (h * 6.0) - i p = v * (1.0 - s) q = v * (1.0 - s * f) t = v * (1.0 - s * (1.0 - f)) i = i % 6 if i == 0: return v, t, p if i == 1: return q, v, p if i == 2: return p, v, t if i == 3: return p, q, v if i == 4: return t, p, v if i == 5: return v, p, q def filterOcclusion(data): print('data -> {}'.format(np.shape(data))) # ---create a pandas Dataframe with X,Y,Z print('Create a DataFrame') df = pd.DataFrame(data, columns=['X','Y','Z','X3D','Y3X','Z3D','R','G','B']) # ---sort it ascend by Z print('Sort by Z') df = df.sort_values(by=['Z'],kind='quicksort') print('Data point after sorting------------------------------') #---For each point create rectangle centered in current point xGap,yGap = 20, 50 xOffset, yOffset = int(xGap / 2), int(yGap / 2) def create_rectange(x,y,depth): bl = [x-xOffset, y+yOffset] #bottom left tr = [x+xOffset, y-yOffset] #top right return [bl,tr,depth] print('Adding rectangles') #Rectangles = np.array([create_rectange(x=row['X'],y=row['Y'], depth = row['Z']) for index, row in df.iterrows()]) vfunc = np.vectorize(create_rectange) Rectangles = vfunc(df['X'].values, df['Y'].values, df['Z'].values) df['Rectangles'] = Rectangles #Rectangles = np.asarray(Rectangles.tolist()) #print('Rectangles -> {}'.format(np.shape(Rectangles))) #bl,tr = np.asarray(Rectangles[:,0].tolist()),np.asarray(Rectangles[:,0].tolist()) # 'bl0 -> {}'.format(np.shape(bl), np.shape(tr)) #df['bl0'] = bl[:,0] #df['bl1'] = bl[:, 1] #df['tr0'] = tr[:, 0] #df['tr1'] = tr[:, 1] # For each point, project it if it does not belong in prev 5 points t = .5 def lies_inside(bl, tr, p, dist): #bottom_left, top_right, poin, distance_left, distance_right if (p[0] > bl[0] and p[0] < tr[0] and p[1] < bl[1] and p[1] > tr[1]): if abs(p[-1]-dist)>t: return True else: return False else: return False def lies_inside_(bl0,bl1, tr0,tr1, p0,p1,p2, dist): #bottom_left, top_right, poin, distance_left, distance_right if (p0 > bl0 and p0 < tr0 and p1 < bl1 and p1 > tr1): if abs(p2-dist)>t: return True else: return False else: return False lies_inside_ = np.vectorize(lies_inside_) occluded = np.zeros_like(Z, dtype=bool) projected = np.zeros_like(Z, dtype=bool) df['occluded'] = occluded df['projected'] = projected idx = range(len(df)) df['idx'] = idx df = df.set_index(['idx']) # for each point check if the prev 5 points belongs to its rectangle -> if yes-> discard it print('Compute neighbors') from sklearn.neighbors import NearestNeighbors X = np.array(df.iloc[:,0:2]) k=10 print('X -> {}'.format(np.shape(X))) nbrs = NearestNeighbors(n_neighbors=k, algorithm='ball_tree').fit(X) distances, indices = nbrs.kneighbors(X) print('distances -> {}, indices->{}, df->{}'.format(np.shape(distances), np.shape(indices), np.shape(df))) df['nbrs_indices'] = indices[:,1:].tolist() print(df.head()) import time start = time.time() print('Start projection') def soc_iter(i): print(i) # take the neighbours that are already projected and not occluded nbrs = df.iloc[i, -1] prev_points = df.iloc[nbrs] # .query('projected == 1 & occluded == 0') #5.82813405991 s condition = (prev_points.projected == True) & (prev_points.occluded == False) prev_points = prev_points[condition] # time = 156.481780052 s # print('nbrs -> {}, prev_points->{}, condition1->{}'.format(np.shape(nbrs), np.shape(prev_points), np.shape(condition))) if len(prev_points) > 0: p = np.array(df.iloc[i, 0:3]) # current_point # time = 156.481780052 s Rectangles = prev_points['Rectangles'] occlusion = [lies_inside(bl=point[0], tr=point[1], p=p, dist=point[-1]) for point in Rectangles] # time = 156.481780052 s #occlusion = lies_inside_(prev_points['bl0'].values, prev_points['bl1'].values, prev_points['tr0'].values, prev_points['tr1'].values, p[0], p[1], p[-1], prev_points['Z'].values) if np.any(occlusion): # print('point {} is occluded'.format(p)) df.loc[i, 'occluded'] = True df.loc[i, 'projected'] = True soc_iter_vect = np.vectorize(soc_iter) N = len(df) m = np.linspace(start=1, stop=N-1, num=N-1, dtype=int) print('m->{}, N:{}'.format(np.shape(m),N)) soc_iter_vect(m) # uncomment this '''for i in range(1,2): #len(df) print i # take the neighbours that are already projected and not occluded nbrs = df.iloc[i, -1] prev_points = df.iloc[nbrs]#.query('projected == 1 & occluded == 0') #5.82813405991 s condition = (prev_points.projected == True) & (prev_points.occluded == False) prev_points = prev_points[condition] #time = 156.481780052 s #print('nbrs -> {}, prev_points->{}, condition1->{}'.format(np.shape(nbrs), np.shape(prev_points), np.shape(condition))) if len(prev_points)>0: p = np.array(df.iloc[i, 0:3]) #current_point # time = 303.82229900 #occlusion = (p[0] > (prev_points.X-xOffset)) & (p[0] < (prev_points.X+xOffset)) & (p[1] < (prev_points.Y+yOffset)) & (p[1] > (prev_points.Y-yOffset)) & (abs(p[-1] - prev_points.Z) > .3) #time = 156.481780052 s Rectangles = prev_points['Rectangles'] occlusion = np.array([lies_inside(bl=point[0], tr=point[1], p=p, dist=point[-1]) for point in Rectangles]) if np.any(occlusion): #print('point {} is occluded'.format(p)) df.loc[i,'occluded'] = True df.loc[i, 'projected'] = True''' #soc_iter_vect(1) end = time.time() print('the publish took {}'.format(end - start)) print(df.head()) Points = np.array(df[df['occluded']==False]).squeeze() good_points = Points[:,0:2].astype('int') distance = Points[:,2] _3Dpoint = Points[:,3:6] _3Dcolor = Points[:, 6:9] MIN_DISTANCE, MAX_DISTANCE = np.min(distance), np.max(distance) colours = (distance - MIN_DISTANCE) / (MAX_DISTANCE - MIN_DISTANCE) colours = np.asarray([np.asarray(hsv_to_rgb( c, np.sqrt(1), 1.0)) for c in colours]) cols = 255 * colours return good_points, cols,_3Dpoint, _3Dcolor #get data #use only the center #self.Lidar_3D = np.array(self.Lidar_3D)[:,-1,:] #self.Image_2D = np.array(self.Image_2D)[:,-1, :] #self.Lidar_3D = np.array(self.Lidar_3D)[:, :4, :] #self.Image_2D = np.array(self.Image_2D)[:, :4, :] self.Lidar_3D = np.array(self.Lidar_3D)[:, :, :] self.Image_2D = np.array(self.Image_2D)[:, :, :] print('self.Lidar_3D ->{}, self.Image_2D->{}'.format(np.shape(self.Lidar_3D), np.shape(self.Image_2D))) points3D_Lidar = np.array(self.Lidar_3D, dtype=np.float32).reshape(-1, 3) points2DLeft = np.array(self.Image_2D, dtype=np.float32).reshape(-1, 2) print('points3D_Lidar->{}, points2DLeft->{}'.format(np.shape(points3D_Lidar), np.shape(points2DLeft))) #calibrate Lidar-> left camera print('Calibrate LiDAR->Left camera===============================================================') imgp = np.array([points2DLeft], dtype=np.float32).squeeze() objp = np.array([points3D_Lidar], dtype=np.float32).squeeze() print('imgp->{},objp->{}'.format(np.shape(imgp), np.shape(objp))) #retval, rvec, tvec = cv2.solvePnP(objp, imgp, self.K, self.D, flags=cv2.SOLVEPNP_ITERATIVE) retval, rvec, tvec, inliers = cv2.solvePnPRansac(objp,imgp, self.K, self.D,flags=cv2.SOLVEPNP_ITERATIVE) #rvec, tvec = cv2.solvePnPRefineLM(objp, imgp, self.K, self.D, rvec, tvec) print('rvec is {}=============='.format(rvec)) print("T = ") print(tvec) tvec = np.array([[0.73698884], [1.3237537], [-0.74695895]]) #tvec = np.array([[0.673698884], [1.3237537], [-0.4]]) rvec, jac = cv2.Rodrigues(rvec) q = Quaternion(matrix=rvec).transformation_matrix #test calibration LiDAR->Left camera left_src = '/home/eugeniu/catkin_ws/src/testNode/CAMERA_CALIBRATION/data/chess/left/left_0.png' left_src = '/home/eugeniu/catkin_ws/src/testNode/CAMERA_CALIBRATION/data/charuco/left/left_4.png' i = 11 left_src = '/home/eugeniu/catkin_ws/src/testNode/CAMERA_CALIBRATION/cool/left_{}.png'.format(i) left_src = '/home/eugeniu/cool/left_100.png' left_img = cv2.imread(left_src) cloud_file = '/home/eugeniu/catkin_ws/src/testNode/CAMERA_CALIBRATION/data/chess/cloud_0.npy' cloud_file = '/home/eugeniu/catkin_ws/src/testNode/CAMERA_CALIBRATION/data/charuco/cloud_4.npy' cloud_file = '/home/eugeniu/catkin_ws/src/testNode/CAMERA_CALIBRATION/cool/cloud_{}.npy'.format(i) cloud_file = '/home/eugeniu/cool/cloud_100.npy' _3DPoints = np.array(np.load(cloud_file, mmap_mode='r'), dtype=np.float32)[:, :3] _3DPoints = np.dot(_3DPoints, Rot_matrix) print('_3DPoints - > {}'.format(np.shape(_3DPoints))) distance = np.linalg.norm(_3DPoints, axis=1)[:, np.newaxis] MIN_DISTANCE, MAX_DISTANCE = np.min(distance), np.max(distance) colours = (distance - MIN_DISTANCE) / (MAX_DISTANCE - MIN_DISTANCE) colours = np.asarray([hsv_to_rgb(c[0], np.sqrt(1), 1.0) for c in colours]) cols = 255 * colours print('distance - > {}, cols ->{}'.format(np.shape(distance), np.shape(cols))) #Left image-------------------------------------------------------------------------------------------- objPoints_left = _3DPoints.copy() Z = self.get_z(q, objPoints_left, self.K_left) objPoints_left = objPoints_left[Z > 0] points2D_left, _ = cv2.projectPoints(objPoints_left, rvec, tvec, self.K_right, self.D_right) points2D_left = np.squeeze(points2D_left) print('objPoints_left -> {}, points2D_left -> {}, '.format(np.shape(objPoints_left), np.shape(points2D_left))) inrange_left = np.where((points2D_left[:, 0] > 0) & (points2D_left[:, 1] > 0) & (points2D_left[:, 0] < left_img.shape[1] - 1) & (points2D_left[:, 1] < left_img.shape[0] - 1)) points2D_left = points2D_left[inrange_left[0]].round().astype('int') colours = cols[inrange_left[0]] objPoints_left = objPoints_left[inrange_left[0]] for i in range(len(points2D_left)): cv2.circle(left_img, tuple(points2D_left[i]), 2, colours[i], -1) '''Z = distance[inrange_left[0]] data = np.hstack((points2D_left, Z)) # N x 3 (x,y,distance) data = np.hstack((data,objPoints_left)) # N x 6 colorImageLeft = cv2.imread(left_src) colors_left = colorImageLeft[points2D_left[:, 1], points2D_left[:, 0], :] data = np.hstack((data,colors_left)) # N x 9 (x,y,distance, X,Y,Z,R,G,B) good_points, cols,_3Dpoint, _3Dcolor = filterOcclusion(data = data) print('good_points->{}, cols->{}, _3Dpoint->{}, _3Dcolor->{}'.format(np.shape(good_points), np.shape(cols), np.shape(_3Dpoint), np.shape(_3Dcolor))) for i in range(len(good_points)): cv2.circle(left_img, tuple(good_points[i]), 2, cols[i], -1)''' cv2.imshow('left_img',cv2.resize(left_img,None,fx=.4,fy=.4)) cv2.waitKey(0) #points = _3Dpoint #np.vstack((_3Dpoint, _3Dpoint_)) #color = _3Dcolor #np.vstack((_3Dcolor, _3Dcolor_)) #print('points->{}, color->{}'.format(np.shape(points), np.shape(color))) #self.write_ply('Lidar_cam_filtered_compareCamera.ply', points, color) #self.view() cv2.destroyAllWindows() def filter_for_video_(self): def hsv_to_rgb(h, s, v): if s == 0.0: return v, v, v i = int(h * 6.0) f = (h * 6.0) - i p = v * (1.0 - s) q = v * (1.0 - s * f) t = v * (1.0 - s * (1.0 - f)) i = i % 6 if i == 0: return v, t, p if i == 1: return q, v, p if i == 2: return p, v, t if i == 3: return p, q, v if i == 4: return t, p, v if i == 5: return v, p, q import time from sklearn.neighbors import NearestNeighbors #from numba import jit #init 191.438015938 s def filterOcclusion(data): start = time.time() print('data -> {}'.format(np.shape(data))) # ---create a pandas Dataframe with X,Y,Z print('Create a DataFrame') df = pd.DataFrame(data, columns=['X','Y','Z','X3D','Y3X','Z3D','R','G','B']) # ---sort it ascend by Z print('Sort by Z') df = df.sort_values(by=['Z'],kind='quicksort') print('Data point after sorting------------------------------') #---For each point create rectangle centered in current point xGap,yGap = 70, 150 xGap, yGap = 100, 200 xOffset, yOffset = int(xGap / 2), int(yGap / 2) def create_rectange(x,y,depth): bl = [x-xOffset, y+yOffset] #bottom left tr = [x+xOffset, y-yOffset] #top right return [bl,tr,depth] print('Adding rectangles') #Rectangles = np.array([create_rectange(x=row['X'],y=row['Y'], depth = row['Z']) for index, row in df.iterrows()]) vfunc = np.vectorize(create_rectange) Rectangles = vfunc(df['X'].values, df['Y'].values, df['Z'].values) df['Rectangles'] = Rectangles t = .5 def lies_inside(bl, tr, p, dist): #bottom_left, top_right, poin, distance_left, distance_right if (p[0] > bl[0] and p[0] < tr[0] and p[1] < bl[1] and p[1] > tr[1]): if abs(p[-1]-dist)>t: return True else: return False else: return False occluded = np.zeros_like(Z, dtype=bool) projected = np.zeros_like(Z, dtype=bool) df['occluded'] = occluded df['projected'] = projected idx = range(len(df)) df['idx'] = idx df = df.set_index(['idx']) # for each point check if the prev 5 points belongs to its rectangle -> if yes-> discard it print('Compute neighbors') X = np.array(df.iloc[:,0:2]) k=15 print('X -> {}'.format(np.shape(X))) nbrs = NearestNeighbors(n_neighbors=k, algorithm='ball_tree').fit(X) distances, indices = nbrs.kneighbors(X) print('distances -> {}, indices->{}, df->{}'.format(np.shape(distances), np.shape(indices), np.shape(df))) df['nbrs_indices'] = indices[:,1:].tolist() print(df.head()) print('Start projection') #@jit(nopython=True) def soc_iter(i): #print(i) # take the neighbours that are already projected and not occluded nbrs = df.iloc[i, -1] prev_points = df.iloc[nbrs] # .query('projected == 1 & occluded == 0') #5.82813405991 s condition = (prev_points.projected == True) & (prev_points.occluded == False) prev_points = prev_points[condition] # time = 156.481780052 s # print('nbrs -> {}, prev_points->{}, condition1->{}'.format(np.shape(nbrs), np.shape(prev_points), np.shape(condition))) if len(prev_points) > 0: p = np.array(df.iloc[i, 0:3]) # current_point # time = 156.481780052 s Rectangles = prev_points['Rectangles'] occlusion = [lies_inside(bl=point[0], tr=point[1], p=p, dist=point[-1]) for point in Rectangles] # time = 156.481780052 s #occlusion = lies_inside_(prev_points['bl0'].values, prev_points['bl1'].values, prev_points['tr0'].values, prev_points['tr1'].values, p[0], p[1], p[-1], prev_points['Z'].values) if np.any(occlusion): # print('point {} is occluded'.format(p)) df.loc[i, 'occluded'] = True df.loc[i, 'projected'] = True #soc_iter_vect = np.vectorize(soc_iter) N = len(df) m = np.linspace(start=1, stop=N-1, num=N-1, dtype=int) print('m->{}, N:{}'.format(np.shape(m),N)) #soc_iter_vect(m) # uncomment this for i in m: soc_iter(i) print(df.head()) Points = np.array(df[df['occluded']==False]).squeeze() good_points = Points[:,0:2].astype('int') distance = Points[:,2] _3Dpoint = Points[:,3:6] _3Dcolor = Points[:, 6:9] MIN_DISTANCE, MAX_DISTANCE = np.min(distance), np.max(distance) MIN_DISTANCE, MAX_DISTANCE = 1.5, 60 colours = (distance - MIN_DISTANCE) / (MAX_DISTANCE - MIN_DISTANCE) colours = np.asarray([np.asarray(hsv_to_rgb( c, np.sqrt(1), 1.0)) for c in colours]) cols = 255 * colours end = time.time() print('the publish took {}'.format(end - start)) return good_points, cols,_3Dpoint, _3Dcolor def readCalibrationExtrinsic(): self.chess = True calib_file = '/home/eugeniu/catkin_ws/src/testNode/CAMERA_CALIBRATION/solvePnP_extrinsics{}.npz'.format( 'chess' if self.chess else 'charuco') #calib_file = '/home/eugeniu/catkin_ws/src/testNode/CAMERA_CALIBRATION/combined_extrinsics{}.npz' with open(calib_file, 'r') as f: data = f.read().split() #print('data:{}'.format(data)) qx = float(data[0]) qy = float(data[1]) qz = float(data[2]) qw = float(data[3]) tx = float(data[4]) ty = float(data[5]) tz = float(data[6]) q = Quaternion(qw, qx, qy, qz).transformation_matrix q[0, 3],q[1, 3],q[2, 3] = tx,ty,tz tvec = q[:3, 3] rot_mat = q[:3, :3] #rvec, _ = cv2.Rodrigues(rot_mat) rvec = rot_mat #tvec = np.array([ 0.673738, -0.428458, -0.650393]) #tvec = np.array([0.69, -0.428458, -0.650393]) #tvec = np.array([0.71, -0.428458, -0.650393]) #rvec = np.array([np.deg2rad(90.06), np.deg2rad(-8.5), np.deg2rad(0.71)]) rvec = np.array([np.deg2rad(90.3), np.deg2rad(-8.5), np.deg2rad(0.71)]) rvec = eulerAnglesToRotationMatrix2(rvec) print('tvec -> {}'.format(tvec)) return rvec, tvec, q rvec, tvec, q = readCalibrationExtrinsic() files = glob.glob('/home/eugeniu/myFolder/*png') currentFile = -1# 27 for currentFile_, fil in enumerate(files): currentFile += 1 print('current image {}'.format(currentFile)) img_path = '/home/eugeniu/myFolder/left_{}.png'.format(currentFile) pcl_path = '/home/eugeniu/myFolder/cloud_{}.npy'.format(currentFile) img = cv2.imread(img_path) _3DPoints = np.array(np.load(pcl_path, mmap_mode='r'), dtype=np.float32)[:, :3] objPoints_left = _3DPoints.copy() Z = self.get_z(q, objPoints_left, self.K) objPoints_left = objPoints_left[Z > 0] print('objPoints_left:{}'.format(np.shape(objPoints_left))) points2D_left, _ = cv2.projectPoints(objPoints_left, rvec, tvec, self.K, self.D) points2D_left = np.squeeze(points2D_left) print('objPoints_left -> {}, points2D_left -> {}, '.format(np.shape(objPoints_left), np.shape(points2D_left))) inrange_left = np.where((points2D_left[:, 0] > 0) & (points2D_left[:, 1] > 0) & (points2D_left[:, 0] < img.shape[1] - 1) & ( points2D_left[:, 1] < img.shape[0] - 1)) print('inrange_left : {}'.format(np.shape(inrange_left))) points2D_left = points2D_left[inrange_left[0]].round().astype('int') print('points2D_left:{}, '.format(np.shape(points2D_left))) #for i, point in enumerate(points2D_left): # cv2.circle(img, (point[0],point[1]), 2, (0,255,0), -1) #cv2.imshow('img',cv2.resize(img,None,fx=.4,fy=.4)) #cv2.waitKey(0) # columns=["X", "Y", "Z","intens","ring"] colors = np.array(np.load(pcl_path, mmap_mode='r'))[:, 4] # # Color map for the points colors = colors[inrange_left[0]] cmap = matplotlib.cm.get_cmap('hsv') colors = cmap(colors / np.max(colors)) print('colors -> {}, min:{}, max:{}'.format(np.shape(colors), np.min(colors), np.max(colors))) colorImageLeft = img.copy() points_left = objPoints_left[inrange_left[0]] print('points_left -> {}, colorImageLeft->{}'.format(np.shape(points_left), np.shape(colorImageLeft))) colors_left = colorImageLeft[points2D_left[:, 1], points2D_left[:, 0], :] print('colors_left -> {}'.format(np.shape(colors_left))) Z = np.linalg.norm(points_left, axis=1)[:, np.newaxis] data = np.hstack((points2D_left, Z)) # N x 3 (x,y,distance) data = np.hstack((data, points_left)) # N x 6 data = np.hstack((data, colors_left)) # N x 9 (x,y,distance, X,Y,Z,R,G,B) good_points, cols, _3Dpoint, _3Dcolor = filterOcclusion(data=data) print('good_points->{}, cols->{}, _3Dpoint->{}, _3Dcolor->{}'.format( np.shape(good_points), np.shape(cols), np.shape(_3Dpoint), np.shape(_3Dcolor))) for i in range(len(good_points)): cv2.circle(img, tuple(good_points[i]), 2, cols[i], -1) cv2.imshow('img ',img) cv2.waitKey(0) cv2.destroyAllWindows() #cv2.imwrite('/home/eugeniu/myFolder/img_synchro_{}.png'.format(currentFile), img) #with open('/home/eugeniu/myFolder/good_points_{}.npy'.format(currentFile), 'wb') as f: # np.save(f, good_points) #with open('/home/eugeniu/myFolder/cols_{}.npy'.format(currentFile), 'wb') as f: # np.save(f, cols) #with open('/home/eugeniu/myFolder/_3Dpoint_{}.npy'.format(currentFile), 'wb') as f: # np.save(f, _3Dpoint) #with open('/home/eugeniu/myFolder/_3Dcolor_{}.npy'.format(currentFile), 'wb') as f: # np.save(f, _3Dcolor) break def filter_for_video(self): def hsv_to_rgb(h, s, v): if s == 0.0: return v, v, v i = int(h * 6.0) f = (h * 6.0) - i p = v * (1.0 - s) q = v * (1.0 - s * f) t = v * (1.0 - s * (1.0 - f)) i = i % 6 if i == 0: return v, t, p if i == 1: return q, v, p if i == 2: return p, v, t if i == 3: return p, q, v if i == 4: return t, p, v if i == 5: return v, p, q import time from sklearn.neighbors import NearestNeighbors #from numba import jit def filterOcclusion(data): print('data -> {}'.format(np.shape(data))) start = time.time() # ---create a pandas Dataframe with X,Y,Z print('Create a DataFrame') df = pd.DataFrame(data, columns=['X','Y','Z','X3D','Y3X','Z3D','R','G','B']) # ---sort it ascend by Z print('Sort by Z') df = df.sort_values(by=['Z'],kind='quicksort') print('Data point after sorting------------------------------') #---For each point create rectangle centered in current point xGap,yGap = 70, 150 xGap, yGap = 100, 200 xOffset, yOffset = int(xGap / 2), int(yGap / 2) def create_rectange(x,y,depth): bl = [x-xOffset, y+yOffset] #bottom left tr = [x+xOffset, y-yOffset] #top right return [bl,tr,depth] print('Adding rectangles') #Rectangles = np.array([create_rectange(x=row['X'],y=row['Y'], depth = row['Z']) for index, row in df.iterrows()]) vfunc = np.vectorize(create_rectange) Rectangles = vfunc(df['X'].values, df['Y'].values, df['Z'].values) df['Rectangles'] = Rectangles t = .5 def lies_inside(bl, tr, p, dist): #bottom_left, top_right, poin, distance_left, distance_right if (p[0] > bl[0] and p[0] < tr[0] and p[1] < bl[1] and p[1] > tr[1]): if abs(p[-1]-dist)>t: return True return False occluded = np.zeros_like(Z, dtype=bool) projected = np.zeros_like(Z, dtype=bool) df['occluded'] = occluded df['projected'] = projected idx = range(len(df)) df['idx'] = idx df = df.set_index(['idx']) # for each point check if the prev 5 points belongs to its rectangle -> if yes-> discard it print('Compute neighbors') X = np.array(df.iloc[:,0:2]) k=15 print('X -> {}'.format(np.shape(X))) nbrs = NearestNeighbors(n_neighbors=k, algorithm='ball_tree').fit(X) distances, indices = nbrs.kneighbors(X) print('distances -> {}, indices->{}, df->{}'.format(np.shape(distances), np.shape(indices), np.shape(df))) df['nbrs_indices'] = indices[:,1:].tolist() #print(df.head()) print('Start projection') #print(df.columns) #from numba import njit # #list_idx = np.array(['X', 'Y', 'Z', 'X3D', 'Y3X', 'Z3D', 'R', 'G', 'B', 'Rectangles','occluded', 'projected', 'nbrs_indices']) df_numpy = np.array(df.to_numpy()).squeeze() #(45783, 13) print('df_numpy -> {}, df -> {}, df_numpy type is {}'.format(np.shape(df_numpy),
np.shape(df)
numpy.shape
""" SORT: A Simple, Online and Realtime Tracker Copyright (C) 2016 <NAME> <EMAIL> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. """ from __future__ import print_function import numpy as np from filterpy.kalman import KalmanFilter from numba import jit from scipy.optimize import linear_sum_assignment @jit(forceobj=True) def iou(bbox_test, bbox_gt): """Computes IOU between two bboxes in the form [x1, y1, x2, y2] """ x1, y1 = np.maximum(bbox_test[0:2], bbox_gt[0:2]) x2, y2 = np.minimum(bbox_test[2:4], bbox_gt[2:4]) w = np.maximum(0, x2-x1) h = np.maximum(0, y2-y1) area = lambda x: (x[2]-x[0])*(x[3]-x[1]) union = w * h intersection = area(bbox_test)+area(bbox_gt)-union return union / intersection def convert_bbox_to_z(bbox): """Convert bbox (x1, y1, x2, y2) to KF.z (x, y, s, r) x, y is the center of the box s is the scale/ area r is the aspect ratio """ x1, y1, x2, y2 = bbox[:4] w, h = (x2 - x1), (y2 - y1) x, y = (x1 + w/2), (y1 + h/2) s, r = (w * h), (w / float(h)) return np.array([x, y, s, r]).reshape((4, 1)) def convert_x_to_bbox(x, score=None): """Convert KF.x (x, y, s, r) to bbox (x1, y1, x2, y2) x1, y1 is the top left x2, y2 is the bottom right """ w = np.sqrt(x[2] * x[3]) h = x[2] / w x1, y1, x2, y2 = (x[0] - w/2), (x[1] - h/2), (x[0] + w/2), (x[1] + h/2) if score is None: return np.array((x1, y1, x2, y2)).reshape((1, 4)) else: return np.array((x1, y1, x2, y2, score)).reshape(1, 5) class KalmanBBoxTracker(object): count = 0 def __init__(self, bbox): """Init the internel Kalman Filter using bbox dim_x = 7, Number of state variables for the Kalman filter dim_z = 4, Number of of measurement inputs KF.x: init state (x, y, s, r, x', y', s') (dim_x, 1) x, y is the bbox center s is the bbox area (w * h) r is the bbox aspect ratio (w / h) x' is the velocity/ variance of x y' is the velocity/ variance of y s' is the velocity/ variance of s update(), predict() will update this variable KF.F: state transition matrix (dim_x, dim_x) KF.H: measurement function (dim_z, dim_x) KF.P: covariance matrix (dim_x, dim_x) update(), predict() will update this variable KF.R: measurement noise covariance (dim_z, dim_z) KF.Q: process uncertainty (dim_x, dim_x) """ # define internel kalman filter dim_x, dim_z = 7, 4 self.kf = KalmanFilter(dim_x=dim_x, dim_z=dim_z) self.kf.x[:4] = convert_bbox_to_z(bbox) self.kf.F = np.array([[1,0,0,0,1,0,0], [0,1,0,0,0,1,0], [0,0,1,0,0,0,1], [0,0,0,1,0,0,0], [0,0,0,0,1,0,0], [0,0,0,0,0,1,0], [0,0,0,0,0,0,1]]) self.kf.H = np.array([[1,0,0,0,0,0,0], [0,1,0,0,0,0,0], [0,0,1,0,0,0,0], [0,0,0,1,0,0,0]]) self.kf.P[4:, 4:] *= 1000. # set unobservable initial velocities with high uncertainty self.kf.P *= 10. self.kf.R[2:, 2:] *= 10. self.kf.Q[-1, -1] *= 0.01 self.kf.Q[4:, 4:] *= 0.01 self.id = KalmanBBoxTracker.count KalmanBBoxTracker.count += 1 self.time_since_update = 0 self.history = [] self.hits = 0 self.hit_streak = 0 self.age = 0 # record the tracker preserved time self.objclass = bbox[6] self.detect_conf = bbox[4] def update(self, bbox): """Update the state vector with observed bbox""" self.time_since_update = 0 self.history = [] self.hits += 1 self.hit_streak += 1 self.detect_conf = bbox[4] self.kf.update(convert_bbox_to_z(bbox)) def predict(self): """Advances the state vector and returns the predicted bounding box estimate KF.x: init state (x, y, s, r, x', y', s') """ # area and the area velocity if self.kf.x[6] + self.kf.x[2] <= 0: self.kf.x[6] *= 0.0 self.kf.predict() self.age += 1 if self.time_since_update > 0: self.hit_streak = 0 self.time_since_update += 1 self.history.append(convert_x_to_bbox(self.kf.x)) return self.history[-1] def get_state(self): """Returns the current bounding box estimate""" return convert_x_to_bbox(self.kf.x) def associate_detections_to_trackers(detections, trackers, iou_threshold=0.3): """Assigns detections to tracked object with Apply Hungarian algorithm by linear_assignment from sklearn Returns (matches, unmatched_detections, unmatched_tackers) """ if len(trackers) == 0: return (np.empty((0, 2), dtype=int), np.arange(len(detections)), np.empty((0, 5), dtype=int)) # row: detection, col: trackers iou_matrix = np.zeros((len(detections), len(trackers)), dtype=np.float32) for d, det in enumerate(detections): for t, trk in enumerate(trackers): iou_matrix[d, t] = iou(det, trk) # matched_indices = linear_assignment(-iou_matrix) matched_indices = linear_sum_assignment(-iou_matrix) matched_indices =
np.asarray(matched_indices)
numpy.asarray
import os import argparse import pandas as pd import matplotlib.pyplot as plt import numpy as np prs = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter, description="""Plot Traffic Signal Metrics""") prs.add_argument('-f', nargs='+', required=True, help="Measures files\n") args = prs.parse_args() df = pd.read_csv(args.f[0], sep=',') valores = {} val = {} for i, value in enumerate(df['groups']): groups = df['groups'][i].split('}, ') for id, group in enumerate(groups): # print(i, valores, group, eval(group.split(', Reward:')[1].replace('}', ''))) g = group.split(', Neighbours')[0][17:].strip().split(':')[1].strip() r = eval(group.split(', Reward:')[1].replace('}', '')) if g in valores: valores[g]['reward'] += r val[g].append(r) valores[g]['times'] += 1 else: valores[g] = {'reward': r, 'times': 0, 'mean': 0, 'std': 0} val[g] = [r] # print(i, valores) # exit() newDF = pd.DataFrame.from_dict(valores) for g in val: mean = np.mean(val[g]) std =
np.std(val[g])
numpy.std
""" This script calls the Spatial Lag SAR functionality from the PySAL Module within the ArcGIS environment. Author(s): <NAME>, <NAME>, <NAME>, <NAME> """ import arcpy as ARCPY import numpy as NUM import pysal as PYSAL import os as OS import sys as SYS import SSDataObject as SSDO import SSUtilities as UTILS import pysal2ArcUtils as AUTILS FIELDNAMES = ["Predy", "Resid", "Predy_e", "e_Pred"] FIELDALIAS = ["Predicted {0}", "Residual", "Predicted {0} (Reduced Form)", "Prediced Error (Reduced Form)"] MODELTYPES = ["GMM_COMBO", "GMM_HAC", "ML"] class Lag_PySAL(object): """Computes SAR Lag linear regression via GMM/ML using PySAL.""" def __init__(self, ssdo, depVarName, indVarNames, patW, modelType = "GMM_COMBO", kernelType = "Uniform", kernelKNN = 2): #### Set Initial Attributes #### UTILS.assignClassAttr(self, locals()) #### Validate Model Type #### if modelType not in MODELTYPES: ARCPY.AddError("The input model type {0} is not in {1}".format(modelType, ", ".join(MODELTYPES))) raise SystemExit() #### Initialize Data #### self.initialize() #### Calculate Statistic #### self.calculate() def initialize(self): """Performs additional validation and populates the SSDataObject.""" ARCPY.SetProgressor("default", ("Starting to perform Spatial Lag " "regression. Loading features...")) #### Shorthand Attributes #### ssdo = self.ssdo #### MasterField Can Not Be The Dependent Variable #### if ssdo.masterField == self.depVarName: ARCPY.AddIDMessage("ERROR", 945, ssdo.masterField, ARCPY.GetIDMessage(84112)) raise SystemExit() #### Remove the MasterField from Independent Vars #### if ssdo.masterField in self.indVarNames: self.indVarNames.remove(ssdo.masterField) ARCPY.AddIDMessage("Warning", 736, ssdo.masterField) #### Remove the Dependent Variable from Independent Vars #### if self.depVarName in self.indVarNames: self.indVarNames.remove(self.depVarName) ARCPY.AddIDMessage("Warning", 850, self.depVarName) #### Raise Error If No Independent Vars #### if not len(self.indVarNames): ARCPY.AddIDMessage("Error", 737) raise SystemExit() #### Create Dependent Variable #### self.allVars = [self.depVarName] + self.indVarNames self.y = ssdo.fields[self.depVarName].returnDouble() self.n = ssdo.numObs self.y.shape = (self.n, 1) #### Assure that Variance is Larger than Zero #### yVar =
NUM.var(self.y)
numpy.var
import abc import logging from math import exp, sin import numpy as np from ape.intcoords.elem_data import COVALENT_RADII as CR from ape.intcoords.derivatives import d2q_b, d2q_a, dq_lb, d2q_lb, dq_ld, d2q_ld, d2q_d, dq_oop, d2q_oop from ape.intcoords.rotate import get_expmap, get_expmap_der, is_linear, calc_rot_vec_diff from ape.intcoords import nifty, math_utils class Primitive(metaclass=abc.ABCMeta): def __init__(self, indices, periodic=False, calc_kwargs=None): self.indices = list(indices) self.periodic = periodic if calc_kwargs is None: calc_kwargs = () self.calc_kwargs = calc_kwargs self.logger = logging.getLogger("internal_coords") def log(self, msg, lvl=logging.DEBUG): self.logger.log(lvl, msg) @staticmethod def parallel(u, v, thresh=1e-6): dot = u.dot(v) / (np.linalg.norm(u) * np.linalg.norm(v)) return (1 - abs(dot)) < thresh @staticmethod def _get_cross_vec(coords3d, indices): m, o, n = indices # Select initial vector for cross product, similar to # geomeTRIC. It must NOT be parallel to u and/or v. x_dash = coords3d[n] - coords3d[m] x = x_dash / np.linalg.norm(x_dash) cross_vecs = np.eye(3) min_ind = np.argmin([np.dot(cv, x) ** 2 for cv in cross_vecs]) return cross_vecs[min_ind] def set_cross_vec(self, coords3d, indices): self.cross_vec = self._get_cross_vec(coords3d, self.indices) self.log(f"Cross vector for {self} set to {self.cross_vec}") @abc.abstractmethod def _calculate(*, coords3d, indices, gradient, **kwargs): pass @abc.abstractmethod def _weight(self, atoms, coords3d, indices, f_damping): pass def weight(self, atoms, coords3d, f_damping=0.12): return self._weight(atoms, coords3d, self.indices, f_damping) @staticmethod def rho(atoms, coords3d, indices): i, j = indices distance = np.linalg.norm(coords3d[i] - coords3d[j]) cov_rad_sum = CR[atoms[i].lower()] + CR[atoms[j].lower()] return exp(-(distance / cov_rad_sum - 1)) def calculate(self, coords3d, indices=None, gradient=False): if indices is None: indices = self.indices # Gather calc_kwargs calc_kwargs = {key: getattr(self, key) for key in self.calc_kwargs} return self._calculate( coords3d=coords3d, indices=indices, gradient=gradient, **calc_kwargs, ) def jacobian(self, coords3d, indices=None): if indices is None: indices = self.indices # Gather calc_kwargs calc_kwargs = {key: getattr(self, key) for key in self.calc_kwargs} return self._jacobian( coords3d=coords3d, indices=indices, **calc_kwargs, ) def __str__(self): return f"{self.__class__.__name__}({self.indices})" def __repr__(self): return self.__str__() class CartesianX(Primitive): @staticmethod def _weight(atoms, coords3d, indices, f_damping): pass @staticmethod def _calculate(coords3d, indices, gradient=False, w=1.0): ind = indices[0] value = coords3d[ind][0] if gradient: row = np.zeros_like(coords3d) row[ind][0] = w row = row.flatten() return value, row return value class CartesianY(Primitive): @staticmethod def _weight(atoms, coords3d, indices, f_damping): pass @staticmethod def _calculate(coords3d, indices, gradient=False, w=1.0): ind = indices[0] value = coords3d[ind][1] if gradient: row = np.zeros_like(coords3d) row[ind][1] = w row = row.flatten() return value, row return value class CartesianZ(Primitive): @staticmethod def _weight(atoms, coords3d, indices, f_damping): pass @staticmethod def _calculate(coords3d, indices, gradient=False, w=1.0): ind = indices[0] value = coords3d[ind][2] if gradient: row = np.zeros_like(coords3d) row[ind][2] = w row = row.flatten() return value, row return value class TranslationX(Primitive): @staticmethod def _weight(atoms, coords3d, indices, f_damping): pass @staticmethod def _calculate(coords3d, indices, gradient=False): indices = np.array(indices) w = np.ones(len(indices))/len(indices) value = np.sum(coords3d[indices, 0] * w) if gradient: row = np.zeros_like(coords3d) for i, a in enumerate(indices): row[a][0] = w[i] row = row.flatten() return value, row return value class TranslationY(Primitive): @staticmethod def _weight(atoms, coords3d, indices, f_damping): pass @staticmethod def _calculate(coords3d, indices, gradient=False): indices = np.array(indices) w = np.ones(len(indices))/len(indices) value = np.sum(coords3d[indices, 1] * w) if gradient: row = np.zeros_like(coords3d) for i, a in enumerate(indices): row[a][1] = w[i] row = row.flatten() return value, row return value class TranslationZ(Primitive): @staticmethod def _weight(atoms, coords3d, indices, f_damping): pass @staticmethod def _calculate(coords3d, indices, gradient=False): indices = np.array(indices) w = np.ones(len(indices))/len(indices) value = np.sum(coords3d[indices, 2] * w) if gradient: row = np.zeros_like(coords3d) for i, a in enumerate(indices): row[a][2] = w[i] row = row.flatten() return value, row return value class Rotator(object): def __init__(self, a, x0): self.a = list(tuple(sorted(a))) x0 = x0.reshape(-1, 3) self.x0 = x0.copy() self.stored_valxyz = np.zeros_like(x0) self.stored_value = None # A second set of xyz coordinates used only when computing # differences in rotation coordinates self.stored_valxyz2 = np.zeros_like(x0) self.stored_value2 = None self.stored_derxyz = np.zeros_like(x0) self.stored_deriv = None self.stored_deriv2xyz = np.zeros_like(x0) self.stored_deriv2 = None self.stored_norm = 0.0 # Extra variables to account for the case of linear molecules # The reference axis used for computing dummy atom position self.e0 = None # Dot-squared measures alignment of molecule long axis with reference axis. # If molecule becomes parallel with reference axis, coordinates must be reset. self.stored_dot2 = 0.0 # Flag that records linearity of molecule self.linear = False def reset(self, x0): x0 = x0.reshape(-1, 3) self.x0 = x0.copy() self.stored_valxyz = np.zeros_like(x0) self.stored_value = None self.stored_valxyz2 = np.zeros_like(x0) self.stored_value2 = None self.stored_derxyz = np.zeros_like(x0) self.stored_deriv = None self.stored_deriv2xyz = np.zeros_like(x0) self.stored_deriv2 = None self.stored_norm = 0.0 self.e0 = None self.stored_dot2 = 0.0 self.linear = False def __eq__(self, other): if type(self) is not type(other): return False eq = set(self.a) == set(other.a) if eq and np.sum((self.x0-other.x0)**2) > 1e-6: logger.warning("Warning: Rotator same atoms, different reference positions\n") return eq def __repr__(self): return "Rotator %s" % commadash(self.a) def __ne__(self, other): return not self.__eq__(other) @property def w(self): sel = self.x0[self.a,:] sel -= np.mean(sel, axis=0) rg = np.sqrt(np.mean(np.sum(sel ** 2, axis=1))) return rg def calc_e0(self): """ Compute the reference axis for adding dummy atoms. Only used in the case of linear molecules. We first find the Cartesian axis that is "most perpendicular" to the molecular axis. Next we take the cross product with the molecular axis to create a perpendicular vector. Finally, this perpendicular vector is normalized to make a unit vector. """ ysel = self.x0[self.a, :] vy = ysel[-1]-ysel[0] ev = vy / np.linalg.norm(vy) # Cartesian axes. ex = np.array([1.0,0.0,0.0]) ey = np.array([0.0,1.0,0.0]) ez = np.array([0.0,0.0,1.0]) self.e0 = np.cross(vy, [ex, ey, ez][np.argmin([np.dot(i, ev)**2 for i in [ex, ey, ez]])]) self.e0 /= np.linalg.norm(self.e0) def value(self, xyz, store=True): xyz = xyz.reshape(-1, 3) if np.max(np.abs(xyz-self.stored_valxyz)) < 1e-12: return self.stored_value else: xsel = xyz[self.a, :] ysel = self.x0[self.a, :] xmean = np.mean(xsel,axis=0) ymean = np.mean(ysel,axis=0) if not self.linear and is_linear(xsel, ysel): # print "Setting linear flag for", self self.linear = True if self.linear: # Handle linear molecules. vx = xsel[-1]-xsel[0] vy = ysel[-1]-ysel[0] # Calculate reference axis (if needed) if self.e0 is None: self.calc_e0() #log.debug(vx) ev = vx / np.linalg.norm(vx) # Measure alignment of molecular axis with reference axis self.stored_dot2 = np.dot(ev, self.e0)**2 # Dummy atom is located one Bohr from the molecular center, direction # given by cross-product of the molecular axis with the reference axis xdum = np.cross(vx, self.e0) ydum = np.cross(vy, self.e0) exdum = xdum / np.linalg.norm(xdum) eydum = ydum / np.linalg.norm(ydum) xsel =
np.vstack((xsel, exdum+xmean))
numpy.vstack
# -*- coding: utf-8 -*- """ Created on Mon Jan 30 20:43:05 2017 @author: michael """ import parameters as params import numpy as np from scipy import special import gaussian_quadrature as gq def fill_z_mat_orig(node_coords, num_elem, elem_nodes): z = np.zeros((num_elem, num_elem), dtype=complex) for m in range(0, num_elem): xm = (node_coords[elem_nodes[m][0]][0] + node_coords[elem_nodes[m][1]][0])/2 ym = (node_coords[elem_nodes[m][0]][1] + node_coords[elem_nodes[m][1]][1])/2 for n in range(0, num_elem): if m == n: wm = np.sqrt( np.power((node_coords[elem_nodes[m][0]][0] - node_coords[elem_nodes[m][1]][0]), 2) + np.power((node_coords[elem_nodes[m][0]][1] + node_coords[elem_nodes[m][1]][1]), 2) ) z[m][n] = ( params.k0*params.eta0*(wm)/4 )*( 1 - (1j*2/params.pi)*(np.log(params.gam*params.k0*wm/4) - 1 ) ) else: xn = ((node_coords[elem_nodes[n][0]][0]) + (node_coords[elem_nodes[n][1]][0]))/2 yn = ((node_coords[elem_nodes[n][0]][1]) + (node_coords[elem_nodes[n][1]][1]))/2 r = np.sqrt( np.power((xm - xn), 2) + np.power((ym - yn), 2) ) xx = params.k0*r wn = np.sqrt( np.power((node_coords[elem_nodes[n][0]][0] - node_coords[elem_nodes[n][1]][0]), 2) + np.power((node_coords[elem_nodes[n][0]][1] + node_coords[elem_nodes[n][1]][1]), 2) ) z[m][n] = (params.k0*params.eta0/4)*wn*(np.sqrt(2/(params.pi*xx))*np.exp(-1j*(xx-(params.pi/4)))) return -z def fill_z_mat(node_coords, num_elem, elem_nodes, n_gaus=params.gaus_default): z = np.zeros((num_elem, num_elem), dtype=complex) gaus = gq.getGaussianQuadrature(n_gaus) const = params.k0*params.eta0/4 for m in range(0, num_elem): xm = (node_coords[elem_nodes[m][0]][0] + node_coords[elem_nodes[m][1]][0])/2 ym = (node_coords[elem_nodes[m][0]][1] + node_coords[elem_nodes[m][1]][1])/2 for n in range(0, num_elem): if m == n: wm = np.sqrt( np.power((node_coords[elem_nodes[m][0]][0] - node_coords[elem_nodes[m][1]][0]), 2) + np.power((node_coords[elem_nodes[m][0]][1] + node_coords[elem_nodes[m][1]][1]), 2) ) z[m][n] = const*( 1 - (1j*2/params.pi)*(np.log(params.gam*params.k0*wm/4) - 1 ) ) else: start_node_x = node_coords[elem_nodes[n][0]][0] start_node_y = node_coords[elem_nodes[n][0]][1] end_node_x = node_coords[elem_nodes[n][1]][0] end_node_y = node_coords[elem_nodes[n][1]][1] vec_x = end_node_x - start_node_x vec_y = end_node_y - start_node_y wn = np.sqrt( np.power((start_node_x - end_node_x), 2) + np.power((start_node_y - end_node_y), 2) ) for k in range(0, n_gaus): xn = start_node_x + vec_x*gaus[k][0] yn = start_node_y + vec_y*gaus[k][0] r = np.sqrt( np.power((xm - xn), 2) + np.power((ym - yn), 2) ) xx = params.k0*r z[m][n] = z[m][n] + const*wn*special.hankel2(0, xx) return -z def create_e_inc(node_coords, num_elem, elem_nodes): b_vec = np.zeros((num_elem, 1), dtype=complex) for m in range(0, num_elem): x = (node_coords[elem_nodes[m][0]][0] + node_coords[elem_nodes[m][1]][0])/2 y = (node_coords[elem_nodes[m][0]][1] + node_coords[elem_nodes[m][1]][1])/2 b_vec[m][0] = np.exp(1j*params.k0*(x*np.cos(params.phi_inc) + y*np.sin(params.phi_inc))) return b_vec.reshape(num_elem, 1) def calculate_scat(curr, node_coords, num_elem, elem_nodes, n_gaus=params.gaus_default): e_scat = np.zeros((params.num_fieldpoints, 1), dtype=complex) const = params.k0*params.eta0/4 gaus = gq.getGaussianQuadrature(n_gaus) for obs in range(0, params.num_fieldpoints): x_obs = params.rad_fieldpoints*np.cos(params.phi_fieldpoints[obs]) y_obs = params.rad_fieldpoints*np.sin(params.phi_fieldpoints[obs]) for n in range(0, num_elem): xn = (node_coords[elem_nodes[n][0]][0] + node_coords[elem_nodes[n][1]][0])/2 yn = (node_coords[elem_nodes[n][0]][1] + node_coords[elem_nodes[n][1]][1])/2 r = np.sqrt( np.power((x_obs - xn), 2) + np.power((y_obs - yn), 2) ) xx = params.k0*r wn = np.sqrt( np.power((node_coords[elem_nodes[n][0]][0] - node_coords[elem_nodes[n][1]][0]), 2) + np.power((node_coords[elem_nodes[n][0]][1] + node_coords[elem_nodes[n][1]][1]), 2) ) # z = (params.k0*params.eta0/4)*wn*(np.sqrt(2/(params.pi*xx))*np.exp(-1j*(xx-(params.pi/4)))) z = const*wn*special.hankel2(0, xx) # start_node_x = node_coords[elem_nodes[n][0]][0] # start_node_y = node_coords[elem_nodes[n][0]][1] # # end_node_x = node_coords[elem_nodes[n][1]][0] # end_node_y = node_coords[elem_nodes[n][1]][1] # # vec_x = end_node_x - start_node_x # vec_y = end_node_y - start_node_y # # wn = np.sqrt( np.power((start_node_x - end_node_x), 2) + np.power((start_node_y - end_node_y), 2) ) # # for k in range(0, n_gaus): # xn = start_node_x + vec_x*gaus[k][0] # yn = start_node_y + vec_y*gaus[k][0] # # r = np.sqrt( np.power((x_obs - xn), 2) + np.power((y_obs - yn), 2) ) # xx = params.k0*r # # z = const*wn*special.hankel2(0, xx) e_scat[obs][0] = e_scat[obs][0] + z*curr[n][0] return e_scat def calculate_db_scat(scat): return 20*np.log10(np.sqrt(2*np.pi*params.rad_fieldpoints)*np.abs(scat)) # Not sure if this should be 10 or 20 def calculate_mom_different_quads(node_coords, num_elem, elem_nodes): data =
np.ndarray((params.num_quads, 1, params.num_fieldpoints, 1), dtype=complex)
numpy.ndarray
from scipy import integrate import numpy as np from quaternion_euler_utility import euler_quat, quat_euler, deriv_quat, quat_rot_mat from numpy.linalg import norm from mpl_toolkits.mplot3d import Axes3D import matplotlib from matplotlib import pyplot as plt from scipy.spatial.transform import Rotation """"" QUADROTOR ENVIRONMENT DEVELOPED BY: <NAME> PROGRAMA DE PÓS GRADUAÇÃO EM ENGENHARIA MECÂNICA, UNIVERSIDADE FEDERAL DO ABC SP - SANTO ANDRÉ - BRASIL FURTHER DOCUMENTATION ON README.MD """"" # matplotlib.use("pgf") # matplotlib.rcParams.update({ # "pgf.texsystem": "pdflatex", # 'font.family': 'serif', # 'text.usetex': True, # 'pgf.rcfonts': False, # 'pgf.preamble':[ # '\DeclareUnicodeCharacter{2212}{-}'] # }) ## SIMULATION BOUNDING BOXES ## BB_POS = 5 BB_VEL = 10 BB_CONTROL = 9 BB_ANG = np.pi/2 # QUADROTOR MASS AND GRAVITY VALUE M, G = 1.03, 9.82 # AIR DENSITY RHO = 1.2041 #DRAG COEFFICIENT C_D = 1.1 # ELETRIC MOTOR THRUST AND MOMENT K_F = 1.435e-5 K_M = 2.4086e-7 I_R = 5e-5 T2WR = 2 # INERTIA MATRIX J = np.array([[16.83e-3, 0, 0], [0, 16.83e-3, 0], [0, 0, 28.34e-3]]) # ELETRIC MOTOR DISTANCE TO CG D = 0.26 #PROJECTED AREA IN X_b, Y_b, Z_b BEAM_THICKNESS = 0.05 A_X = BEAM_THICKNESS*2*D A_Y = BEAM_THICKNESS*2*D A_Z = BEAM_THICKNESS*2*D*2 A = np.array([[A_X,A_Y,A_Z]]).T ## REWARD PARAMETERS ## SOLVED_REWARD = 20 BROKEN_REWARD = -20 SHAPING_WEIGHT = 5 SHAPING_INTERNAL_WEIGHTS = [15, 4, 1] # CONTROL REWARD PENALITIES # P_C = 0.003 P_C_D = 0 ## TARGET STEADY STATE ERROR ## TR = [0.005, 0.01, 0.1] TR_P = [3, 2, 1] ## ROBUST CONTROL PARAMETERS class robust_control(): def __init__(self): self.D_KF = 0.1 self.D_KM = 0.1 self.D_M = 0.3 self.D_IR = 0.1 self.D_J = np.ones(3) * 0.1 self.reset() self.gust_std = [[5], [5], [2]] self.gust_period = 500 # integration steps self.i_gust = 0 self.gust = np.zeros([3, 1]) def reset(self): self.episode_kf = np.random.random(4) * self.D_KF self.episode_m = np.random.normal(0, self.D_M, 1) self.episode_ir = np.random.random(4) * self.D_IR self.episode_J = np.eye(3)*np.random.normal(np.zeros(3), self.D_J, [3]) def wind(self, i): index = (i % self.gust_period) - 1 if index % self.gust_period == 0: self.last_gust = self.gust self.gust = np.random.normal(np.zeros([3, 1]), self.gust_std, [3, 1]) self.linear_wind_change = np.linspace(self.last_gust, self.gust, self.gust_period) return self.linear_wind_change[index] class quad(): def __init__(self, t_step, n, training = True, euler=0, direct_control=1, T=1, clipped = True): """" inputs: t_step: integration time step n: max timesteps euler: flag to set the states return in euler angles, if off returns quaternions deep learning: deep learning flag: If on, changes the way the env. outputs data, optimizing it to deep learning use. T: Number of past history of states/actions used as inputs in the neural network debug: If on, prints a readable reward funcion, step by step, for a simple reward weight debugging. """ self.clipped = clipped if training: self.ppo_training = True else: self.ppo_training = False self.mass = M self.gravity = G self.i = 0 self.T = T #Initial Steps self.bb_cond = np.array([BB_VEL, BB_VEL, BB_VEL, BB_ANG, BB_ANG, 3/4*np.pi, BB_VEL*2, BB_VEL*2, BB_VEL*2]) #Bounding Box Conditions Array if not self.ppo_training: self.bb_cond = self.bb_cond*1 #Quadrotor states dimension self.state_size = 13 #Quadrotor action dimension self.action_size = 4 #Env done Flag self.done = True #Env Maximum Steps self.n = n+self.T self.t_step = t_step #Neutral Action (used in reset and absolute action penalty) if direct_control: self.zero_control = np.ones(4)*(2/T2WR - 1) else: self.zero_control = np.array([M*G, 0, 0, 0]) self.direct_control_flag = direct_control self.ang_vel = np.zeros(3) self.prev_ang = np.zeros(3) self.J_mat = J #Absolute sum of control efforts over the episode self.abs_sum = 0 self.d_xx = np.linspace(0, D, 10) self.d_yy = np.linspace(0, D, 10) self.d_zz = np.linspace(0, D, 10) self.robust_parameters = robust_control() self.robust_control = False ev_cd = 'Training' if self.ppo_training else 'Eval' ct_cd = ' with robust environment' if self.robust_control else '' print('Environment Condition: ' + ev_cd + ct_cd) def seed(self, seed): """" Set random seeds for reproducibility """ np.random.seed(seed) def f2w(self,f,m): """"" Translates F (Thrust) and M (Body x, y and z moments) into eletric motor angular velocity (rad/s) input: f - thrust m - body momentum in np.array([[mx, my, mz]]).T outputs: F - Proppeler Thrust - engine 1 to 4 w - Proppeler angular velocity - engine 1 to 4 F_new - clipped thrust (if control surpasses engine maximum) M_new - clipped momentum (same as above) """"" x = np.array([[K_F, K_F, K_F, K_F], [-D*K_F, 0, D*K_F, 0], [0, D*K_F, 0, -D*K_F], [-K_M, +K_M, -K_M, +K_M]]) y = np.array([f, m[0,0], m[1,0], m[2,0]]) u = np.linalg.solve(x, y) if self.clipped: u = np.clip(u, 0, T2WR*M*G/4/K_F) w_1 = np.sqrt(u[0]) w_2 = np.sqrt(u[1]) w_3 = np.sqrt(u[2]) w_4 = np.sqrt(u[3]) else: modules = np.zeros(4) for k in range(4): modules[k] = -1 if u[k] < 0 else 1 w_1 = np.sqrt(np.abs(u[0]))*modules[0] w_2 = np.sqrt(np.abs(u[1]))*modules[1] w_3 = np.sqrt(np.abs(u[2]))*modules[2] w_4 = np.sqrt(np.abs(u[3]))*modules[3] w = np.array([[w_1,w_2,w_3,w_4]]).T if self.robust_control: u -= u*self.robust_parameters.episode_kf FM_new = np.dot(x, u) F_new = FM_new[0] M_new = FM_new[1:4] step_effort = (u*K_F/(T2WR*M*G/4)*2)-1 return step_effort, w, F_new, M_new def f2F(self, f_action): """"" Translates Proppeler thrust to body trhust and body angular momentum. input: f_action - proppeler thrust written as np.array([f1, f2, f3, f4]) the proppeler thrust if normalized in [-1, 1] domain, where -1 is 0 thrust and 1 is maximum thrust output: w - proppeler angular velocity F_new - body thrust M_new - body angular momentum """"" f = (f_action + 1) * T2WR * M * G / 8 w = np.array([[np.sqrt(f[0]/K_F)], [np.sqrt(f[1]/K_F)], [np.sqrt(f[2]/K_F)], [np.sqrt(f[3]/K_F)]]) if self.robust_control: f = f - self.robust_parameters.episode_kf * f F_new = np.sum(f) M_new = np.array([[(f[2]-f[0])*D], [(f[1]-f[3])*D], [(-f[0]+f[1]-f[2]+f[3])*K_M/K_F]]) return w, F_new, M_new def drone_eq(self, t, x, action): """" Main differential equation, not used directly by the user, rather used in the step function integrator. Dynamics based in: MODELAGEM DINÂMICA E CONTROLE DE UM VEÍCULO AÉREO NÃO TRIPULADO DO TIPO QUADRIRROTOR by <NAME> BRASIL, SP-SANTO ANDRÉ, UFABC - 2019 Incorporates: Drag Forces, Gyroscopic Forces In indirect mode: Force clipping (preventing motor shutoff and saturates over Thrust to Weight Ratio) In direct mode: maps [-1,1] to forces [0,T2WR*G*M/4] """ if self.direct_control_flag: self.w, f_in, m_action = self.f2F(action) else: f_in = action[0] m_action = np.array([action[1::]]).T #BODY INERTIAL VELOCITY vel_x = x[1] vel_y = x[3] vel_z = x[5] #QUATERNIONS q0 = x[6] q1 = x[7] q2 = x[8] q3 = x[9] #BODY ANGULAR VELOCITY w_xx = x[10] w_yy = x[11] w_zz = x[12] #QUATERNION NORMALIZATION (JUST IN CASE) q = np.array([[q0, q1, q2, q3]]).T q = q/np.linalg.norm(q) # DRAG FORCES ESTIMATION (BASED ON BODY VELOCITIES) self.mat_rot = quat_rot_mat(q) v_inertial = np.array([[vel_x, vel_y, vel_z]]).T if self.robust_control: wind = self.robust_parameters.wind(self.i) v_inertial += wind v_body = np.dot(self.mat_rot.T, v_inertial) f_drag = -0.5*RHO*C_D*np.multiply(A,np.multiply(abs(v_body),v_body)) # DRAG MOMENTS ESTIMATION (BASED ON BODY ANGULAR VELOCITIES) #Discretization over 10 steps (linear velocity varies over the body) m_x = 0 m_y = 0 m_z = 0 for xx,yy,zz in zip(self.d_xx, self.d_yy, self.d_zz): m_x += -RHO*C_D*BEAM_THICKNESS*D/10*(abs(xx*w_xx)*(xx*w_xx))*xx m_y += -RHO*C_D*BEAM_THICKNESS*D/10*(abs(yy*w_yy)*(yy*w_yy))*yy m_z += -2*RHO*C_D*BEAM_THICKNESS*D/10*(abs(zz*w_zz)*(zz*w_zz))*zz m_drag = np.array([[m_x], [m_y], [m_z]]) #GYROSCOPIC EFFECT ESTIMATION (BASED ON ELETRIC MOTOR ANGULAR VELOCITY) if self.robust_control: ir = I_R*(np.ones(4)+self.robust_parameters.episode_ir) omega_r = (-self.w[0]*ir[0]+self.w[1]*ir[1]-self.w[2]*ir[2]+self.w[3]*ir[3])[0] else: omega_r = (-self.w[0]+self.w[1]-self.w[2]+self.w[3])[0]*I_R m_gyro = np.array([[-w_xx*omega_r], [+w_yy*omega_r], [0]]) #BODY FORCES self.f_in = np.array([[0, 0, f_in]]).T self.f_body = self.f_in+f_drag #BODY FORCES ROTATION TO INERTIAL self.f_inertial = np.dot(self.mat_rot, self.f_body) #INERTIAL ACCELERATIONS if self.robust_control: quad_m = M * (1 + self.robust_parameters.episode_m) else: quad_m = M accel_x = self.f_inertial[0, 0]/quad_m accel_y = self.f_inertial[1, 0]/quad_m accel_z = self.f_inertial[2, 0]/quad_m-G self.accel = np.array([[accel_x, accel_y, accel_z]]).T # self.accelerometer_read = self.f_body/quad_m self.accelerometer_read = self.mat_rot.T @ (self.accel.flatten() + np.array([0, 0, -G])) #BODY MOMENTUM W = np.array([[w_xx], [w_yy], [w_zz]]) m_in = m_action + m_gyro + m_drag - np.cross(W.flatten(), np.dot(J, W).flatten()).reshape((3,1)) #INERTIAL ANGULAR ACCELERATION if self.robust_control: self.inv_j = np.linalg.inv(J + J*self.robust_parameters.episode_J) else: self.inv_j = np.linalg.inv(J) accel_ang = np.dot(self.inv_j, m_in).flatten() accel_w_xx = accel_ang[0] accel_w_yy = accel_ang[1] accel_w_zz = accel_ang[2] #QUATERNION ANGULAR VELOCITY (INERTIAL) self.V_q = deriv_quat(W, q).flatten() dq0=self.V_q[0] dq1=self.V_q[1] dq2=self.V_q[2] dq3=self.V_q[3] # RESULTS ORDER: # 0 x, 1 vx, 2 y, 3 vy, 4 z, 5 vz, 6 q0, 7 q1, 8 q2, 9 q3, 10 w_xx, 11 w_yy, 12 w_zz out = np.array([vel_x, accel_x, vel_y, accel_y, vel_z, accel_z, dq0, dq1, dq2, dq3, accel_w_xx, accel_w_yy, accel_w_zz]) return out def reset(self, det_state = None): """"" inputs:_, self.w, f_in, m_action = self.f2w(f_in, m_action) det_state: if == 0 randomized initial state else det_state is the actual initial state, depending on the euler flag if euler flag is on: [x, dx, y, dy, z, dz, phi, theta, psi, w_xx, w_yy, w_zz] if euler flag is off: [x, dx, y, dy, z, dz, q_0, q_1, q_2, q_3, w_xx, w_yy, w_zz] outputs: previous_state: system's initial state """"" state = [] action = [] self.action_hist = [] self.robust_parameters.reset() self.solved = 0 self.done = False self.i = 0 self.prev_shaping = None self.previous_state = np.zeros(self.state_size) self.abs_sum = 0 if det_state is not None: self.previous_state = det_state q = np.array([self.previous_state[6:10]]).T self.ang = quat_euler(q) else: self.ang = np.random.rand(3)-0.5 Q_in = euler_quat(self.ang) self.previous_state[0:5:2] = np.clip((np.random.normal([0, 0, 0], 2)), -BB_POS/2, BB_POS/2) self.previous_state[1:6:2] = np.clip((np.random.normal([0, 0, 0], 2)), -BB_VEL/2, BB_VEL/2) self.previous_state[6:10] = Q_in.T self.previous_state[10:13] = np.clip((np.random.normal([0, 0, 0], 2)), -BB_VEL*1.5, BB_POS*1.5) for i in range(self.T): self.action = self.zero_control self.action_hist.append(self.action) state_t, reward, done = self.step(self.action) state.append(state_t.flatten()) action.append(self.zero_control) return np.array(state), np.array(action) def step(self, action): """"" inputs: action: action to be applied on the system outputs: state: system's state in t+t_step actuated by the action done: False, else the system has breached any bounding box, exceeded maximum timesteps, or reached goal. """"" self.i += 1 if self.direct_control_flag: self.action = np.clip(action,-1,1) u = self.action self.clipped_action = self.action self.step_effort = self.action else: self.action = action self.step_effort, self.w, f_in, m_action = self.f2w(action[0], np.array([action[1::]]).T) self.clipped_action = np.append([f_in], m_action) u = self.clipped_action self.action_hist.append(self.clipped_action) self.y = (integrate.solve_ivp(self.drone_eq, (0, self.t_step), self.previous_state, args=(u, ))).y self.state = np.transpose(self.y[:, -1]) self.quat_state = np.array([np.concatenate((self.state[0:10], self.V_q))]) q = np.array([self.state[6:10]]).T q = q/np.linalg.norm(q) self.ang = quat_euler(q) self.ang_vel = (self.ang - self.prev_ang)/self.t_step self.prev_ang = self.ang self.previous_state = self.state self.done_condition() self.reward_function() self.control_effort() return self.state, self.reward, self.done def done_condition(self): """"" Checks if bounding boxes done condition have been met """"" cond_x = np.concatenate((self.state[1:6:2], self.ang, self.state[-3:])) for x, c in zip(np.abs(cond_x), self.bb_cond): if x >= c: self.done = True def reward_function(self, debug=0): """"" Reward Function: Working with PPO great results. Shaping with some ideas based on Continuous Lunar Lander v.2 gym environment: https://gym.openai.com/envs/LunarLanderContinuous-v2/ """"" self.reward = 0 velocity = self.state[1:6:2] euler_angles = self.ang psi = self.ang[2] body_ang_vel = self.state[-3:] action = self.action shaping = -SHAPING_WEIGHT/np.sum(SHAPING_INTERNAL_WEIGHTS)*(SHAPING_INTERNAL_WEIGHTS[0]*norm(velocity/BB_VEL)+ SHAPING_INTERNAL_WEIGHTS[1]*norm(psi/4)+ SHAPING_INTERNAL_WEIGHTS[2]*norm(euler_angles[0:2]/BB_ANG)) #CASCADING REWARDS r_state = np.concatenate((velocity, [psi])) for TR_i, TR_Pi in zip(TR, TR_P): if norm(r_state) < norm(np.ones(len(r_state))*TR_i): shaping += TR_Pi if norm(euler_angles[0:2]) < norm(np.ones(2)*TR_i*4): shaping += TR_Pi break if self.prev_shaping is not None: self.reward = shaping - self.prev_shaping self.prev_shaping = shaping #ABSOLUTE CONTROL PENALTY ## TOTAL REWARD SHAPING ## abs_control = -np.sum(np.square(action - self.zero_control)) * P_C self.reward += + abs_control #SOLUTION ACHIEVED? self.target_state = 9*(TR[0]**2) self.current_state = np.sum(np.square(np.concatenate((velocity, euler_angles, body_ang_vel)))) if self.current_state < self.target_state: self.reward += SOLVED_REWARD self.solved = 1 if self.ppo_training: self.done = True elif self.i >= self.n: self.reward = self.reward self.solved = 0 self.done=True elif self.done: self.reward += BROKEN_REWARD self.solved = 0 def control_effort(self): instant_effort = np.sqrt(np.sum(np.square(self.step_effort-np.array([0*M*G, 0, 0, 0])))) self.abs_sum += instant_effort class sensor(): """Sensor class - simulates onboard sensors, given standard deviation and bias. Aimed to simulate kallman filters or to execute robust control, etc. Self explanatory, adds standard deviation noise and bias to quadrotor real state. """ def __init__(self, env, accel_std = 0.1, accel_bias_drift = 0.0005, gyro_std = 0.035, gyro_bias_drift = 0.00015, magnet_std = 15, magnet_bias_drift = 0.075, gps_std_p = 1.71, gps_std_v=0.5): self.std = [accel_std, gyro_std, magnet_std, gps_std_p, gps_std_v] self.b_d = [accel_bias_drift, gyro_bias_drift, magnet_bias_drift] self.quad = env self.error = True self.bias_reset() def bias_reset(self): self.a_std = self.std[0]*self.error self.a_b_d = (np.random.random()-0.5)*2*self.b_d[0]*self.error self.g_std = self.std[1]*self.error self.g_b_d = (np.random.random()-0.5)*2*self.b_d[1]*self.error self.m_std = self.std[2]*self.error self.m_b_d = (np.random.random()-0.5)*2*self.b_d[2]*self.error self.gps_std_p = self.std[3]*self.error self.gps_std_v = self.std[4]*self.error self.R = np.eye(3) def accel(self): self.a_b_accel = self.a_b_accel + self.a_b_d*self.quad.t_step read_error = np.random.normal(self.a_b_accel, self.a_std, 3) read_accel_body = self.quad.accelerometer_read.flatten() return read_accel_body+read_error def accel_grav(self, norm=True): gravity_vec = np.array([0, 0, -9.81]) self.a_b_grav = self.a_b_grav + self.a_b_d*self.quad.t_step #Gravity vector as read from body sensor gravity_body = np.dot(self.quad.mat_rot.T, gravity_vec)+ np.random.normal(np.random.random(3)*self.a_b_grav, self.a_std, 3) if norm: ax = gravity_body[0] ay = gravity_body[1] az = gravity_body[2] if ax !=0 and ay != 0 and az != 0: # Normalise accelerometer measurement recipNorm = 1/(math.sqrt(ax * ax + ay * ay + az * az)) ax *= recipNorm ay *= recipNorm az *= recipNorm gravity_body = np.array([[ax, ay, az]], dtype='float32') return gravity_body def mag_gauss(self, norm=True): magnet_vec = np.array([-65.269, 165.115, -144.205]) self.m_b = self.m_b + self.m_b_d*self.quad.t_step magnet_body = np.dot(self.quad.mat_rot.T, magnet_vec) + np.random.normal(np.random.random(3)*self.m_b, self.m_std, 3) mx = magnet_body[0] my = magnet_body[1] mz = magnet_body[2] if norm: recipNorm = 1/math.sqrt(mx * mx + my * my + mz * mz) mx *= recipNorm my *= recipNorm mz *= recipNorm magnet_body = np.array([mx, my, mz]) return magnet_body def gyro(self): self.g_b = self.g_b + self.g_b_d*self.quad.t_step read_error = np.random.normal(self.g_b, self.g_std, 3) read_gyro = self.quad.state[-3:].flatten() return np.array([read_error+read_gyro], dtype='float32').T def reset(self): self.a_b_grav = 0 self.a_b_accel = 0 self.m_b = 0 self.g_b = 0 self.acceleration_t0 = np.zeros(3) self.position_t0 = self.quad.state[0:5:2] self.velocity_t0 = self.quad.state[1:6:2] self.quaternion_t0 = self.quad.state[6:10] self.bias_reset() def gps(self): read_error_pos = np.random.normal(0, self.gps_std_p, 3) read_error_vel = np.random.normal(0, self.gps_std_v, 3) gps_pos = self.quad.state[0:5:2].flatten() gps_vel = self.quad.state[1:6:2].flatten() return read_error_pos+gps_pos, read_error_vel+gps_vel def triad(self): gravity_vec = np.array([0, 0, -G]) magnet_vec = np.array([-65.269, 165.115,-144.205]) #mGauss #Magnetic Vector of Santo André - Brasil in MiliGauss #https://www.ngdc.noaa.gov/geomag/calculators/magcalc.shtml#igrfwmm #Gravity vector as read from body sensor induced_acceleration = self.quad.f_in.flatten()/M - (self.R @ np.array([[0, 0, -G]]).T).flatten() gravity_body = self.accel() - induced_acceleration #Magnetic Field vector as read from body sensor magnet_body = self.quad.mat_rot.T @ (np.random.normal(magnet_vec, self.m_std)) #Accel vector is more accurate #Body Coordinates gravity_body = gravity_body / np.linalg.norm(gravity_body) magnet_body = magnet_body / np.linalg.norm(magnet_body) t1b = gravity_body/np.linalg.norm(gravity_body) t2b = np.cross(gravity_body, magnet_body) t2b = t2b/np.linalg.norm(t2b) t3b = np.cross(t1b, t2b) t3b = t3b/np.linalg.norm(t3b) tb = np.vstack((t1b, t2b, t3b)).T #Inertial Coordinates gravity_vec = gravity_vec/np.linalg.norm(gravity_vec) magnet_vec = magnet_vec / np.linalg.norm(magnet_vec) t1i = gravity_vec/np.linalg.norm(gravity_vec) t2i = np.cross(gravity_vec, magnet_vec) t2i = t2i/np.linalg.norm(t2i) t3i =
np.cross(t1i, t2i)
numpy.cross
import numpy as np import matplotlib.pylab as plt import scipy import scipy.linalg import sys def lu_decomposition(A): m, n = A.shape LU = np.copy(A) pivots = np.empty(n, dtype=int) # initialise the pivot row and column h = 0 k = 0 while h < m and k < n: # Find the k-th pivot: pivots[k] = np.argmax(LU[h:, k]) + h if LU[pivots[k], k] == 0: # No pivot in this column, pass to next column k = k+1 else: # swap rows LU[[h, pivots[k]], :] = LU[[pivots[k], h], :] # Do for all rows below pivot: for i in range(h+1, m): f = LU[i, k] / LU[h, k] # Store f as the new L column values LU[i, k] = f # Do for all remaining elements in current row: for j in range(k + 1, n): LU[i, j] = LU[i, j] - LU[h, j] * f # Increase pivot row and column h = h + 1 k = k + 1 return LU, pivots def random_matrix(n): R = np.random.rand(n, n) A = np.zeros((n, n)) triu =
np.triu_indices(n)
numpy.triu_indices
import os import math import numpy as np import matplotlib.pyplot as plt from scipy import interpolate from django.shortcuts import render from django.conf import settings def get_res(D_o: float): for i in range(1,7): plt.figure(i) plt.cla() plt.clf() teta_HO=[] input_teta_txt=open(settings.STATICFILES_DIRS[1]/'input_teta.txt','r+') for num in input_teta_txt.readlines(): teta_HO.append(float(num)) # D_o=0.324 t=0.0205 D_in=D_o-(2*t) A_out=math.pi*(D_o**2)/4 A_in=math.pi*(D_in**2)/4 Area=A_out-A_in I=math.pi*(D_o**4-D_in**4)/64 ro_s=7850 ro_c=494 ro_w=1025 m_s=Area*ro_s m_c=A_in*ro_c m_bouy=A_out*ro_w m_subm=m_s+m_c-m_bouy g=9.81 Depth=1800 k=300000 E=207000000000 delta_Z=1600 Z_A=delta_Z-(D_o/2) size_teta=len(teta_HO) # teta_HO should be positive values. # creating list with teta size teta_HO_rad=[0]*size_teta H_T=[0]*size_teta X_TDP_cat=[0]*size_teta S_TDP_cat=[0]*size_teta landa=[0]*size_teta K_BLM=[0]*size_teta cur_BLM_0=[0]*size_teta kesi_f=[0]*size_teta s_f=[0]*size_teta S_TDP_BLM=[0]*size_teta X_TDP_BLM=[0]*size_teta x=np.arange(-3500,9601)/10 size_x=len(x) kesi=np.array([[0.0]*size_teta]*size_x) cur_BLM=np.array([[0.0]*size_teta]*size_x) mom_BLM=np.array([[0.0]*size_teta]*size_x) mom_cat=np.array([[0.0]*size_teta]*size_x) s=np.array([[0.0]*size_teta]*size_x) mom_fin=np.array([[0.0]*size_teta]*size_x) Eff_T=np.array([[0.0]*size_teta]*size_x) z=np.array([[0.0]*size_teta]*size_x) h=np.array([[0.0]*size_teta]*size_x) Ext_Force=np.array([[0.0]*size_teta]*size_x) Int_Force=np.array([[0.0]*size_teta]*size_x) Wall_T=np.array([[0.0]*size_teta]*size_x) x_from_ho=np.array([[0.0]*size_teta]*size_x) z_from_ho=
np.array([[0.0]*size_teta]*size_x)
numpy.array
""" setinit: this routine creates local directories and makes topo, qinit, and aux DEMs to be used by setrun.py If you have other files, modify this and/or your setrun.py accordingly. """ import numpy as np import dclaw.topotools as gt import os #import pylab #import pdb cdir = os.path.abspath(os.environ['PWD']) #---create local directories for data if they do not exist---------- indatadir=os.path.join(cdir,'init_data') topodir = os.path.join(cdir,indatadir,'topo') auxdir = os.path.join(cdir,indatadir,'aux') qinitdir = os.path.join(cdir,indatadir,'qinit') if not os.path.isdir(indatadir): execstr = 'mkdir '+indatadir os.system(execstr) if not os.path.isdir(topodir): execstr = 'mkdir '+topodir os.system(execstr) if not os.path.isdir(auxdir): execstr = 'mkdir '+auxdir os.system(execstr) if not os.path.isdir(qinitdir): execstr = 'mkdir '+qinitdir os.system(execstr) #------------------------------------------------------------------------ #---------------- functions for flume geometry to build DEMs ------------ def zero(X,Y): yind1 = np.where((Y[:,0]>=-0.5)&(Y[:,0]<=0.0))[0] yind2 = np.where((Y[:,0]>=2.0)&(Y[:,0]<=2.5))[0] xind = np.where((X[0,:]>=-15.0)&(X[0,:]<=90.0))[0] Z = np.zeros(np.shape(X)) return Z def wallzero(X,Y): yind1 = np.where((Y[:,0]>=-0.5)&(Y[:,0]<=0.0))[0] yind2 = np.where((Y[:,0]>=2.0)&(Y[:,0]<=2.5))[0] xind = np.where((X[0,:]>=-15.0)&(X[0,:]<=82.5))[0] xhopperind = np.where((X[0,:]>=-15.0)&(X[0,:]<=0.0))[0] Z = np.zeros(np.shape(X)) Z[np.ix_(yind1,xind)] = 1.6 Z[np.ix_(yind2,xind)] = 1.6 Z[np.ix_(yind1,xhopperind)] = 2.5 Z[np.ix_(yind2,xhopperind)] = 2.5 return Z def zero_backstop(X,Y): yind1 = np.where((Y[:,0]>=-0.5)&(Y[:,0]<=0.0))[0] yind2 = np.where((Y[:,0]>=2.0)&(Y[:,0]<=2.5))[0] xind = np.where((X[0,:]>=-15.0)&(X[0,:]<=90.0))[0] xbackstopind = np.where(X[0,:]<=-4.0)[0] ybackstopind = np.where((Y[:,0]>=-0.5)&(Y[:,0]<=2.5))[0] Z = np.zeros(np.shape(X)) Z[np.ix_(ybackstopind,xbackstopind)] = 2.5 return Z def wallzero_backstop(X,Y): yind1 = np.where((Y[:,0]>=-0.5)&(Y[:,0]<=0.0))[0] yind2 = np.where((Y[:,0]>=2.0)&(Y[:,0]<=2.5))[0] xind = np.where((X[0,:]>=-15.0)&(X[0,:]<=82.5))[0] xhopperind = np.where((X[0,:]>=-15.0)&(X[0,:]<=0.0))[0] Z = np.zeros(np.shape(X)) xbackstopind = np.where(X[0,:]<=-4.0)[0] ybackstopind = np.where((Y[:,0]>=-0.5)&(Y[:,0]<=2.5))[0] Z[np.ix_(yind1,xind)] = 1.6 Z[np.ix_(yind2,xind)] = 1.6 Z[np.ix_(yind1,xhopperind)] = 2.5 Z[np.ix_(yind2,xhopperind)] = 2.5 Z[np.ix_(ybackstopind,xbackstopind)] = 2.5 return Z def flume_eta(X,Y): hopperlen = 4.7 hmax = 1.9 hoppertop = 3.3 topangle = 17.0*np.pi/180.0 flumeangle = 31.0*np.pi/180.0 x0 = -hopperlen x2 = -hmax*np.cos(0.5*np.pi - flumeangle) x1 = x2 - hoppertop*np.cos(flumeangle-topangle) x3 = 0.0 y2 = hmax*np.sin(0.5*np.pi - flumeangle) y1 = y2 - hoppertop*np.sin(flumeangle-topangle) slope0 = y1/(x1-x0) slope1 = (y2-y1)/(x2-x1) slope2 = -y2/(x3-x2) yind = np.where((Y[:,0]<=2.0)&(Y[:,0]>=0.0))[0] x0ind = np.where((X[0,:]>=x0)&(X[0,:]<x1))[0] x1ind = np.where((X[0,:]>=x1)&(X[0,:]<x2))[0] x2ind = np.where((X[0,:]>=x2)&(X[0,:]<x3))[0] #pdb.set_trace() Z=np.zeros(np.shape(X)) Z[np.ix_(yind,x0ind)] = (X[np.ix_(yind,x0ind)]-x0)*slope0 Z[np.ix_(yind,x1ind)] = y1+(X[np.ix_(yind,x1ind)]-x1)*slope1 Z[np.ix_(yind,x2ind)] = -(x3-X[np.ix_(yind,x2ind)])*slope2 return Z def flume_eta_res(X,Y): hopperlen = 4.7 hmax = 1.9 hoppertop = 3.3 topangle = 17.0*np.pi/180.0 flumeangle = 31.0*np.pi/180.0 x0 = -hopperlen x2 = -hmax*np.cos(0.5*np.pi - flumeangle) x1 = x2 - hoppertop*np.cos(flumeangle-topangle) x3 = 0.0 y2 = hmax*np.sin(0.5*np.pi - flumeangle) y1 = y2 - hoppertop*np.sin(flumeangle-topangle) xm1 = x1 - y1*np.tan(0.5*np.pi - flumeangle) slope0 = y1/(x1-xm1) slope1 = (y2-y1)/(x2-x1) slope2 = -y2/(x3-x2) yind = np.where((Y[:,0]<=2.0)&(Y[:,0]>=0.0))[0] xm1ind = np.where((X[0,:]>=xm1)&(X[0,:]<x1))[0] x1ind = np.where((X[0,:]>=x1)&(X[0,:]<x2))[0] x2ind = np.where((X[0,:]>=x2)&(X[0,:]<x3))[0] #pdb.set_trace() Z=np.zeros(np.shape(X)) Z[np.ix_(yind,xm1ind)] = (X[np.ix_(yind,xm1ind)]-xm1)*slope0 Z[np.ix_(yind,x1ind)] = y1+(X[np.ix_(yind,x1ind)]-x1)*slope1 Z[np.ix_(yind,x2ind)] = -(x3-X[np.ix_(yind,x2ind)])*slope2 return Z def flume_eta_res_half(X,Y): hopperlen = 4.7 hmax = 1.9 hoppertop = 3.3 topangle = 17.0*np.pi/180.0 flumeangle = 31.0*np.pi/180.0 x0 = -hopperlen x2 = -hmax*np.cos(0.5*np.pi - flumeangle) x1 = x2 - hoppertop*np.cos(flumeangle-topangle) x3 = 0.0 y2 = hmax*np.sin(0.5*np.pi - flumeangle) y1 = y2 - hoppertop*np.sin(flumeangle-topangle) xm1 = x1 - y1*np.tan(0.5*np.pi - flumeangle) xmhalf = 0.5*(x0 + xm1) slope0 = y1/(x1-xm1) slopehalf = y1/(x1-xmhalf) slope1 = (y2-y1)/(x2-x1) slope2 = -y2/(x3-x2) yind = np.where((Y[:,0]<=2.0)&(Y[:,0]>=0.0))[0] xmhalfind = np.where((X[0,:]> xmhalf)&(X[0,:]<x1))[0] x1ind = np.where((X[0,:]>=x1)&(X[0,:]<x2))[0] x2ind = np.where((X[0,:]>=x2)&(X[0,:]<x3))[0] #pdb.set_trace() Z=np.zeros(
np.shape(X)
numpy.shape
""" Module for neural analysis """ import numpy as np from typing import Any, Callable, Dict, List, NamedTuple, Optional, Tuple def get_isi(spk_ts_list: list): """ Get inter-analysis interval of spikes Parameters ---------- spk_ts_list : list Returns ------- isi : class object class object for inter-spike intervals """ isi = np.array([], dtype=np.float64) for spk in spk_ts_list: isi = np.append(isi, np.diff(spk)) isi = ISI(isi) # return the class object return isi def get_peth(evt_ts_list: list, spk_ts_list: list, pre_evt_buffer=None, duration=None, bin_size=None, nb_bins=None ): """ Get peri-event histogram & firing rates Parameters ---------- evt_ts_list : list Timestamps for behavioral events (e.g., syllable onset/offsets) spk_ts_list : list Spike timestamps pre_evt_buffer : int, default=None Size of buffer window prior to the first event (in ms) duration : int, optional Duration of the peth (in ms). Truncate the bin_size : int, default=None Time bin size nb_bins : int, default=None Number of bins Returns ------- peth : np.ndarray Peri-event time histograms time_bin : np.ndarray Time bin vector parameter : dict Parameters for draw peth Notes ----- If pre_evt_buffer, bin_size, nb_bins not specified, take values from analysis ..analysis.parameters """ from ..analysis.parameters import peth_parm import copy import math parameter = peth_parm.copy() if pre_evt_buffer is None: pre_evt_buffer = parameter['buffer'] if bin_size is None: bin_size = parameter['bin_size'] if nb_bins is None: nb_bins = parameter['nb_bins'] time_bin = np.arange(0, nb_bins, bin_size) - pre_evt_buffer peth = np.zeros((len(evt_ts_list), nb_bins)) # nb of trials x nb of time bins for trial_ind, (evt_ts, spk_ts) in enumerate(zip(evt_ts_list, spk_ts_list)): spk_ts_new = copy.deepcopy(spk_ts) if not isinstance(evt_ts, np.float64): # evt_ts = np.asarray(list(map(float, evt_ts))) + pre_evt_buffer # spk_ts_new -= evt_ts[0] evt_ts = np.asarray(list(map(float, evt_ts))) spk_ts_new -= evt_ts[0] spk_ts_new += pre_evt_buffer else: spk_ts_new -= evt_ts spk_ts_new += pre_evt_buffer for spk in spk_ts_new: ind = math.ceil(spk / bin_size) # print("spk = {}, bin index = {}".format(spk, ind)) # for debugging if ind < 0: raise Exception("Index out of bound") peth[trial_ind, ind] += 1 # Truncate the array leaving out only the portion of our interest if duration: ind = np.where(((0 - pre_evt_buffer) <= time_bin) & (time_bin < duration))[0] peth = peth[:, ind[0]:ind[-1]+1] time_bin = time_bin[ind[0]:ind[-1]+1] return peth, time_bin, parameter def get_pcc(fr_array: np.ndarray) -> dict: """ Get pairwise cross-correlation Parameters ---------- fr_array : np.ndarray (trial x time_bin) Returns ------- pcc_dict : dict """ pcc_dict = {} pcc_arr = np.array([]) for ind1, fr1 in enumerate(fr_array): for ind2, fr2 in enumerate(fr_array): if ind2 > ind1: if np.linalg.norm((fr1 - fr1.mean()), ord=1) * np.linalg.norm((fr2 - fr2.mean()), ord=1): if not np.isnan(np.corrcoef(fr1, fr2)[0, 1]): pcc_arr = np.append(pcc_arr, np.corrcoef(fr1, fr2)[0, 1]) # get correlation coefficient pcc_dict['array'] = pcc_arr pcc_dict['mean'] = round(pcc_arr.mean(), 3) return pcc_dict def jitter_spk_ts(spk_ts_list, shuffle_limit, reproducible=True): """ Add a random temporal jitter to the spike Parameters ---------- reproducible : bool Make the results reproducible by setting the seed as equal to index """ spk_ts_jittered_list = [] for ind, spk_ts in enumerate(spk_ts_list): np.random.seed() if reproducible: # randomization seed seed = ind np.random.seed(seed) # make random jitter reproducible else: seed = np.random.randint(len(spk_ts_list), size=1) np.random.seed(seed) # make random jitter reproducible nb_spk = spk_ts.shape[0] jitter = np.random.uniform(-shuffle_limit, shuffle_limit, nb_spk) spk_ts_jittered_list.append(spk_ts + jitter) return spk_ts_jittered_list def pcc_shuffle_test(ClassObject, PethInfo, plot_hist=False, alpha=0.05): """ Run statistical test to see if baseline pairwise cross-correlation obtained by spike time shuffling is significant Parameters ---------- ClassObject : class object (e.g., NoteInfo, MotifInfo) PethInfo : peth info class object plot_hist : bool Plot histogram of bootstrapped pcc values (False by default) Returns ------- p_sig : dict True if the pcc is significantly above the baseline """ from ..analysis.parameters import peth_shuffle from collections import defaultdict from functools import partial import scipy.stats as stats import matplotlib.pyplot as plt pcc_shuffle = defaultdict(partial(np.ndarray, 0)) for i in range(peth_shuffle['shuffle_iter']): ClassObject.jitter_spk_ts(peth_shuffle['shuffle_limit']) pi_shuffle = ClassObject.get_note_peth(shuffle=True) # peth object pi_shuffle.get_fr() # get firing rates pi_shuffle.get_pcc() # get pcc for context, pcc in pi_shuffle.pcc.items(): pcc_shuffle[context] = np.append(pcc_shuffle[context], pcc['mean']) # One-sample t-test (one-sided) p_val = {} p_sig = {} for context in pcc_shuffle.keys(): (_, p_val[context]) = stats.ttest_1samp(a=pcc_shuffle[context], popmean=PethInfo.pcc[context]['mean'], nan_policy='omit', alternative='less') # one-tailed t-test for context, value in p_val.items(): p_sig[context] = value < alpha # Plot histogram if plot_hist: from ..utils.draw import remove_right_top fig, axes = plt.subplots(1, 2, figsize=(6, 3)) plt.suptitle('PCC shuffle distribution', y=.98, fontsize=10) for axis, context in zip(axes, pcc_shuffle.keys()): axis.set_title(context) axis.hist(pcc_shuffle[context], color='k') axis.set_xlim([-0.1, 0.6]) axis.set_xlabel('PCC'), axis.set_ylabel('Count') if p_sig[context]: axis.axvline(x=PethInfo.pcc[context]['mean'], color='r', linewidth=1, ls='--') else: axis.axvline(x=PethInfo.pcc[context]['mean'], color='k', linewidth=1, ls='--') remove_right_top(axis) plt.tight_layout() plt.show() return p_sig class ClusterInfo: def __init__(self, path, channel_nb, unit_nb, format='rhd', *name, update=False, time_unit='ms'): """ Load information about cluster Parameters ---------- path : path path that contains recording files for the cluster channel_nb : int number of the channel that recorded the cluster unit_nb : int number id of the cluster (needed because multiple neurons could have been recorded in the same session & channel) format : str 'rhd' by default (Intan) name : name of the cluster e.g., ('096-g70r40-Predeafening-D07(20191106)-S03-Ch17-Cluster01') update : bool If not exists, create a .npz cache file in the same folder so that it doesn't read from the raw data every time the class is called. time_unit : str 'ms' by default """ from ..analysis.load import load_song self.path = path if channel_nb: # if a neuron was recorded if len(str(channel_nb)) == 1: self.channel_nb = 'Ch0' + str(channel_nb) elif len(str(channel_nb)) == 2: self.channel_nb = 'Ch' + str(channel_nb) else: self.channel_nb = 'Ch' self.unit_nb = unit_nb self.format = format if name: self.name = name[0] else: self.name = self.path self._print_name() # Load events file_name = self.path / "ClusterInfo_{}_Cluster{}.npy".format(self.channel_nb, self.unit_nb) if update or not file_name.exists(): # if .npy doesn't exist or want to update the file song_info = load_song(self.path) # Save cluster_info as a numpy object np.save(file_name, song_info) else: song_info = np.load(file_name, allow_pickle=True).item() # Set the dictionary values to class attributes for key in song_info: setattr(self, key, song_info[key]) # Load spike if channel_nb and unit_nb: self._load_spk(time_unit) def __repr__(self): # print attributes return str([key for key in self.__dict__.keys()]) def _print_name(self) -> None: print('') print('Load cluster {self.name}'.format(self=self)) def list_files(self, ext: str): from ..utils.functions import list_files return list_files(self.path, ext) def _load_spk(self, time_unit, delimiter='\t') -> None: """ Load spike information Parameters ---------- time_unit : str time unit (e.g., 'ms') delimiter : str delimiter of the cluster file (tab (\t) by default) Returns ------- sets spk_wf, spk_ts, nb_spk as attributes """ spk_txt_file = list(self.path.glob('*' + self.channel_nb + '(merged).txt')) if not spk_txt_file: print("spk text file doesn't exist !") return spk_txt_file = spk_txt_file[0] spk_info = np.loadtxt(spk_txt_file, delimiter=delimiter, skiprows=1) # skip header # Select only the unit (there could be multiple isolated units in the same file) if self.unit_nb: # if the unit number is specified spk_info = spk_info[spk_info[:, 1] == self.unit_nb, :] spk_ts = spk_info[:, 2] # analysis time stamps spk_wf = spk_info[:, 3:] # analysis waveform nb_spk = spk_wf.shape[0] # total number of spikes self.spk_wf = spk_wf # individual waveforms self.nb_spk = nb_spk # the number of spikes # Units are in second by default, but convert to millisecond with the argument if time_unit == 'ms': spk_ts *= 1E3 # Output analysis timestamps per file in a list spk_list = [] for file_start, file_end in zip(self.file_start, self.file_end): spk_list.append(spk_ts[np.where((spk_ts >= file_start) & (spk_ts <= file_end))]) self.spk_ts = spk_list # analysis timestamps in ms # print("spk_ts, spk_wf, nb_spk attributes added") def analyze_waveform(self, align_wf=True, interpolate=True, interp_factor=None ): """ Perform waveform analysis Parameters ---------- align_wf : bool align all spike waveforms relative to the max location interpolate : bool Set to true if waveform interpolation is needed interp_factor : int Factor by which to increase the sampling frequency of the waveform e.g., 100 if you want to increase the data points by 100 fold """ from ..analysis.functions import align_waveform, get_half_width from ..analysis.parameters import sample_rate if align_wf: self.spk_wf = align_waveform(self.spk_wf) def _get_spk_profile(wf_ts, avg_wf, interpolate=interpolate): spk_height = np.abs(np.max(avg_wf) - np.min(avg_wf)) # in microseconds if interpolate: spk_width = abs(((np.argmax(avg_wf) - np.argmin(avg_wf)) + 1)) * ( (1 / sample_rate[self.format]) / interp_factor) * 1E6 # in microseconds else: spk_width = abs(((np.argmax(avg_wf) - np.argmin(avg_wf)) + 1)) * ( 1 / sample_rate[self.format]) * 1E6 # in microseconds deflection_range, half_width = get_half_width(wf_ts, avg_wf) # get the half width from the peak deflection return spk_height, spk_width, half_width, deflection_range if not interp_factor: from ..analysis.parameters import interp_factor interp_factor = interp_factor self.avg_wf = np.nanmean(self.spk_wf, axis=0) self.wf_ts = np.arange(0, self.avg_wf.shape[0]) / sample_rate[self.format] * 1E3 # x-axis in ms if interpolate: # interpolate the waveform to increase sampling frequency from scipy import interpolate f = interpolate.interp1d(self.wf_ts, self.avg_wf) wf_ts_interp = np.arange(0, self.wf_ts[-1], ((self.wf_ts[1] - self.wf_ts[0]) * (1 / interp_factor))) assert (np.diff(wf_ts_interp)[0] * interp_factor) == np.diff(self.wf_ts)[0] avg_wf_interp = f(wf_ts_interp) # use interpolation function returned by `interp1d` # Replace the original value with interpolated ones self.wf_ts_interp = wf_ts_interp self.avg_wf_interp = avg_wf_interp spk_height, spk_width, half_width, deflection_range = _get_spk_profile(wf_ts_interp, avg_wf_interp) else: spk_height, spk_width, half_width, deflection_range = _get_spk_profile(self.wf_ts, self.avg_wf) self.spk_height = round(spk_height, 3) # in microvolts self.spk_width = round(spk_width, 3) # in microseconds self.half_width = half_width self.deflection_range = deflection_range # the range where half width was calculated # print("avg_wf, spk_height (uv), spk_width (us), wf_ts (ms) added") def get_conditional_spk(self) -> dict: """Get spike timestamps from different contexts""" conditional_spk = {} conditional_spk['U'] = [spk_ts for spk_ts, context in zip(self.spk_ts, self.contexts) if context == 'U'] conditional_spk['D'] = [spk_ts for spk_ts, context in zip(self.spk_ts, self.contexts) if context == 'D'] return conditional_spk def get_correlogram(self, ref_spk_list, target_spk_list, normalize=False) -> dict: """Get auto- or cross-correlogram""" from ..analysis.parameters import spk_corr_parm import math correlogram = {} for social_context in set(self.contexts): # Compute spk correlogram corr_temp = np.zeros(len(spk_corr_parm['time_bin'])) for ref_spks, target_spks, context in zip(ref_spk_list, target_spk_list, self.contexts): if context == social_context: for ref_spk in ref_spks: for target_spk in target_spks: diff = target_spk - ref_spk # time difference between two spikes if (diff) and (diff <= spk_corr_parm['lag'] and diff >= -spk_corr_parm['lag']): if diff < 0: ind = np.where(spk_corr_parm['time_bin'] <= -math.ceil(abs(diff)))[0][-1] elif diff > 0: ind = np.where(spk_corr_parm['time_bin'] >= math.ceil(diff))[0][0] # print("diff = {}, bin index = {}".format(diff, spk_corr_parm['time_bin'][ind])) # for debugging corr_temp[ind] += 1 # Make sure the array is symmetrical first_half = np.fliplr([corr_temp[:int((spk_corr_parm['lag'] / spk_corr_parm['bin_size']))]])[0] second_half = corr_temp[int((spk_corr_parm['lag'] / spk_corr_parm['bin_size'])) + 1:] assert np.sum(first_half - second_half) == 0 # Normalize correlogram by the total sum (convert to probability density ) if normalize: corr_temp /= np.sum(correlogram) correlogram[social_context] = corr_temp correlogram['parameter'] = spk_corr_parm # store parameters in the dictionary return correlogram def jitter_spk_ts(self, shuffle_limit, reproducible=True): """ Add a random temporal jitter to the spike Parameters ---------- shuffle_limit : int shuffling limit (in ms) e.g., If set to 5, any integer values between -5 to 5 drawn from uniform distribution will be added to the spike timestamp reproducible : bool make the results reproducible by setting the seed as equal to index """ spk_ts_jittered_list = [] for ind, spk_ts in enumerate(self.spk_ts): np.random.seed() if reproducible: # randomization seed seed = ind np.random.seed(seed) # make random jitter reproducible else: seed = np.random.randint(len(self.spk_ts), size=1) np.random.seed(seed) # make random jitter reproducible nb_spk = spk_ts.shape[0] jitter = np.random.uniform(-shuffle_limit, shuffle_limit, nb_spk) spk_ts_jittered_list.append(spk_ts + jitter) self.spk_ts_jittered = spk_ts_jittered_list def get_jittered_corr(self) -> dict: """Get spike correlogram from time-jittered spikes""" from ..analysis.parameters import corr_shuffle from collections import defaultdict correlogram_jitter = defaultdict(list) for iter in range(corr_shuffle['shuffle_iter']): self.jitter_spk_ts(corr_shuffle['shuffle_limit']) corr_temp = self.get_correlogram(self.spk_ts_jittered, self.spk_ts_jittered) # Combine correlogram from two contexts for key, value in corr_temp.items(): if key != 'parameter': try: correlogram_jitter[key].append(value) except: correlogram_jitter[key] = value # Convert to array for key, value in correlogram_jitter.items(): correlogram_jitter[key] = (np.array(value)) return correlogram_jitter def get_isi(self, add_premotor_spk=False): """ Get inter-spike interval Parameters ---------- add_premotor_spk : bool Add spikes from the premotor window for calculation """ isi_dict = {} list_zip = zip(self.onsets, self.offsets, self.spk_ts) if not add_premotor_spk: # Include spikes from the pre-motif buffer for calculation # Pre-motor spikes are included in spk_list by default spk_list = [] for onset, offset, spks in list_zip: onset = np.asarray(list(map(float, onset))) offset = np.asarray(list(map(float, offset))) spk_list.append(spks[np.where((spks >= onset[0]) & (spks <= offset[-1]))]) for context1 in set(self.contexts): if not add_premotor_spk: spk_list_context = [spk_ts for spk_ts, context2 in zip(spk_list, self.contexts) if context2 == context1] else: spk_list_context = [spk_ts for spk_ts, context2 in zip(self.spk_ts, self.contexts) if context2 == context1] isi_dict[context1] = get_isi(spk_list_context) return isi_dict @property def nb_files(self) -> dict: """ Return the number of files per context Returns ------- nb_files : dict Number of files per context ('U', 'D', 'All') """ nb_files = {} nb_files['U'] = len([context for context in self.contexts if context == 'U']) nb_files['D'] = len([context for context in self.contexts if context == 'D']) nb_files['All'] = nb_files['U'] + nb_files['D'] return nb_files def nb_bouts(self, song_note: str) -> dict: """ Return the number of bouts per context Parameters ---------- song_note : str song motif syllables Returns ------- nb_bouts : dict """ from ..analysis.functions import get_nb_bouts nb_bouts = {} syllable_list = [syllable for syllable, context in zip(self.syllables, self.contexts) if context == 'U'] syllables = ''.join(syllable_list) nb_bouts['U'] = get_nb_bouts(song_note, syllables) syllable_list = [syllable for syllable, context in zip(self.syllables, self.contexts) if context == 'D'] syllables = ''.join(syllable_list) nb_bouts['D'] = get_nb_bouts(song_note, syllables) nb_bouts['All'] = nb_bouts['U'] + nb_bouts['D'] return nb_bouts def nb_motifs(self, motif: str) -> dict: """ Return the number of motifs per context Parameters ---------- motf : str Song motif (e.g., 'abcd') Returns ------- nb_motifs : dict """ from ..utils.functions import find_str nb_motifs = {} syllable_list = [syllable for syllable, context in zip(self.syllables, self.contexts) if context == 'U'] syllables = ''.join(syllable_list) nb_motifs['U'] = len(find_str(syllables, motif)) syllable_list = [syllable for syllable, context in zip(self.syllables, self.contexts) if context == 'D'] syllables = ''.join(syllable_list) nb_motifs['D'] = len(find_str(syllables, motif)) nb_motifs['All'] = nb_motifs['U'] + nb_motifs['D'] return nb_motifs def get_note_info(self, target_note, pre_buffer=0, post_buffer=0 ): """ Obtain a class object (NoteInfo) for individual note spikes will be collected from note onset (+- pre_buffer) to offset (+- post_buffer) Parameters ---------- target_note : str Get information from this note pre_buffer : int Amount of time buffer relative to the event onset (e.g., syllable onset) post_buffer : int Amount of time buffer relative to the event offset (e.g., syllable onset) Returns ------- NoteInfo : class object """ from ..utils.functions import find_str syllables = ''.join(self.syllables) onsets = np.hstack(self.onsets) offsets = np.hstack(self.offsets) durations = np.hstack(self.durations) contexts = '' for i in range(len(self.contexts)): # concatenate contexts contexts += self.contexts[i] * len(self.syllables[i]) ind = np.array(find_str(syllables, target_note)) # get note indices if not ind.any(): # skil if the note does not exist return note_onsets = np.asarray(list(map(float, onsets[ind]))) note_offsets = np.asarray(list(map(float, offsets[ind]))) note_durations = np.asarray(list(map(float, durations[ind]))) note_contexts = ''.join(np.asarray(list(contexts))[ind]) # Get the note that immeidately follows next_notes = '' for i in ind: next_notes += syllables[i + 1] # Get spike info spk_ts = np.hstack(self.spk_ts) note_spk_ts_list = [] for onset, offset in zip(note_onsets, note_offsets): note_spk_ts_list.append( spk_ts[np.where((spk_ts >= onset - pre_buffer) & (spk_ts <= offset + post_buffer))]) # Organize data into a dictionary note_info = { 'note': target_note, 'next_notes' : next_notes, 'onsets': note_onsets, 'offsets': note_offsets, 'durations': note_durations, 'contexts': note_contexts, 'median_dur': np.median(note_durations, axis=0), 'spk_ts': note_spk_ts_list, 'path': self.path, # directory where the data exists 'pre_buffer' : pre_buffer, 'post_buffer' : post_buffer } return NoteInfo(note_info) # return note info @property def open_folder(self) -> None: """Open the data folder""" from ..utils.functions import open_folder open_folder(self.path) class NoteInfo: """ Class for storing information about a single note syllable and its associated spikes """ def __init__(self, note_dict): # Set the dictionary values to class attributes for key in note_dict: setattr(self, key, note_dict[key]) # Perform PLW (piecewise linear warping) self.spk_ts_warp = self._piecewise_linear_warping() def __repr__(self): return str([key for key in self.__dict__.keys()]) def select_index(self, index) -> None: """ Select only the notes with the matching index Parameters ---------- index : np.array or list Note indices to keep """ if isinstance(index, list): index = np.array(index) self.contexts = ''.join(np.array(list(self.contexts))[index]) self.onsets, self.offsets, self.durations, self.spk_ts, self.spk_ts_warp \ = self.onsets[index], self.offsets[index], self.durations[index], self.spk_ts[index], self.spk_ts_warp[index] def select_context(self, target_context : str, keep_median_duration=True ) -> None: """ Select one context Parameters ---------- target_context : str 'U' or 'D' keep_median_duration : bool Normally medial note duration is calculated using all syllables regardless of the context one may prefer to use this median to reduce variability when calculating pcc if set False, new median duration will be calculated using the selected notes """ zipped_list = \ list(zip(self.contexts, self.next_notes, self.onsets, self.offsets, self.durations, self.spk_ts, self.spk_ts_warp)) zipped_list = list(filter(lambda x: x[0] == target_context, zipped_list)) # filter context unzipped_object = zip(*zipped_list) self.contexts, self.next_notes, self.onsets, self.offsets, self.durations, self.spk_ts, self.spk_ts_warp = \ list(unzipped_object) self.contexts = ''.join(self.contexts) self.next_notes = ''.join(self.next_notes) self.onsets = np.array(self.onsets) self.offsets = np.array(self.offsets) self.durations = np.array(self.durations) self.spk_ts = np.array(self.spk_ts) self.spk_ts_warp = np.array(self.spk_ts_warp) if not keep_median_duration: self.median_dur = np.median(self.median_dur, axis=0) def get_entropy(self, normalize=True, mode='spectral'): """ Calculate syllable entropy from all renditions and get the average Two versions : spectro-temporal entropy & spectral entropy """ from ..analysis.parameters import nb_note_crit from ..analysis.functions import get_spectral_entropy, get_spectrogram from ..utils.functions import find_str entropy_mean = {} entropy_var = {} audio = AudioData(self.path) for context in ['U', 'D']: se_mean_arr = np.array([], dtype=np.float32) se_var_arr = np.array([], dtype=np.float32) ind = np.array(find_str(self.contexts, context)) if ind.shape[0] >= nb_note_crit: for (start, end) in zip(self.onsets[ind], self.offsets[ind]): timestamp, data = audio.extract([start, end]) # audio object _, spect, _ = get_spectrogram(timestamp, data, audio.sample_rate) se = get_spectral_entropy(spect, normalize=normalize, mode=mode) if isinstance(se, dict): se_mean_arr = np.append(se_mean_arr, se['mean']) # spectral entropy averaged over time bins per rendition se_var_arr = np.append(se_var_arr, se['var']) # spectral entropy variance per rendition else: se_mean_arr = np.append(se_mean_arr, se) # spectral entropy time-resolved entropy_mean[context] = round(se_mean_arr.mean(), 3) entropy_var[context] = round(se_var_arr.mean(), 5) if mode == 'spectro_temporal': return entropy_mean, entropy_var else: # spectral entropy (does not have entropy variance) return entropy_mean def _piecewise_linear_warping(self): """Perform piecewise linear warping per note""" import copy note_spk_ts_warp_list = [] for onset, duration, spk_ts in zip(self.onsets, self.durations, self.spk_ts): spk_ts_new = copy.deepcopy(spk_ts) ratio = self.median_dur / duration origin = 0 spk_ts_temp, ind = spk_ts[spk_ts >= onset], np.where(spk_ts >= onset) spk_ts_temp = ((ratio * ((spk_ts_temp - onset))) + origin) + onset np.put(spk_ts_new, ind, spk_ts_temp) # replace original spk timestamps with warped timestamps note_spk_ts_warp_list.append(spk_ts_new) return note_spk_ts_warp_list def get_note_peth(self, time_warp=True, shuffle=False, pre_evt_buffer=None, duration=None, bin_size=None, nb_bins=None ): """ Get peri-event time histograms for single syllable Parameters ---------- time_warp : perform piecewise linear transform shuffle : add jitter to spike timestamps duration : duration of the peth bin_size : size of single bin (in ms) (take values from peth_parm by default) nb_bins : number of time bins (take values from peth_parm by default) Returns ------- PethInfo : class object """ peth_dict = {} if shuffle: peth, time_bin, peth_parm = \ get_peth(self.onsets, self.spk_ts_jittered, pre_evt_buffer=pre_evt_buffer, duration=duration, bin_size=bin_size, nb_bins=nb_bins ) else: if time_warp: # peth calculated from time-warped spikes by default # peth, time_bin = get_note_peth(self.onsets, self.spk_ts_warp, self.median_durations.sum()) # truncated version to fit the motif duration peth, time_bin, peth_parm = \ get_peth(self.onsets, self.spk_ts_warp, pre_evt_buffer=pre_evt_buffer, duration=duration, bin_size = bin_size, nb_bins = nb_bins ) else: peth, time_bin, peth_parm = \ get_peth(self.onsets, self.spk_ts, pre_evt_buffer=pre_evt_buffer, duration=duration, bin_size=bin_size, nb_bins=nb_bins ) peth_dict['peth'] = peth peth_dict['time_bin'] = time_bin peth_dict['parameters'] = peth_parm peth_dict['contexts'] = self.contexts peth_dict['median_duration'] = self.median_dur return PethInfo(peth_dict) # return peth class object for further analysis def jitter_spk_ts(self, shuffle_limit): """ Add a random temporal jitter to the spike This version limit the jittered timestamp within the motif window """ from ..analysis.parameters import pre_motor_win_size spk_ts_jittered_list = [] list_zip = zip(self.onsets, self.offsets, self.spk_ts) for ind, (onset, offset, spk_ts) in enumerate(list_zip): # Find motif onset & offset onset = float(onset) - pre_motor_win_size # start from the premotor window jittered_spk = np.array([], dtype=np.float32) for spk_ind, spk in enumerate(spk_ts): while True: jitter = np.random.uniform(-shuffle_limit, shuffle_limit, 1) new_spk = spk + jitter if onset < new_spk < offset: jittered_spk = np.append(jittered_spk, spk + jitter) break spk_ts_jittered_list.append(jittered_spk) self.spk_ts_jittered = spk_ts_jittered_list @property def nb_note(self) -> dict: """Return number of notes per context""" from ..utils.functions import find_str nb_note = {} for context in ['U', 'D']: nb_note[context] = len(find_str(self.contexts, context)) return nb_note @property def mean_fr(self) -> dict: """Return mean firing rates for the note (includes pre-motor window) per context""" from ..analysis.parameters import nb_note_crit, pre_motor_win_size from ..utils.functions import find_str note_spk = {} note_fr = {} for context1 in ['U', 'D']: if self.nb_note[context1] >= nb_note_crit: note_spk[context1] = \ sum([len(spk) for context2, spk in zip(self.contexts, self.spk_ts) if context2 == context1]) note_fr[context1] = \ round(note_spk[context1] / ((self.durations[find_str(self.contexts, context1)] + pre_motor_win_size).sum() / 1E3), 3) else: note_fr[context1] = np.nan return note_fr # @property # def open_folder(self) -> None: # """Open the data folder""" # from ..utils.functions import open_folder # # open_folder(self.path) class MotifInfo(ClusterInfo): """ Class object for motif information child class of ClusterInfo """ def __init__(self, path, channel_nb, unit_nb, motif, format='rhd', *name, update=False): super().__init__(path, channel_nb, unit_nb, format, *name, update=False) self.motif = motif if name: self.name = name[0] else: self.name = str(self.path) # Load motif info file_name = self.path / "MotifInfo_{}_Cluster{}.npy".format(self.channel_nb, self.unit_nb) if update or not file_name.exists(): # if .npy doesn't exist or want to update the file motif_info = self._load_motif() # Save info dict as a numpy object np.save(file_name, motif_info) else: motif_info = np.load(file_name, allow_pickle=True).item() # Set the dictionary values to class attributes for key in motif_info: setattr(self, key, motif_info[key]) # Delete un-used attributes self._delete_attr() def _delete_attr(self): """Delete un-used attributes/methods inheritied from the parent class """ delattr(self, 'spk_wf') delattr(self, 'nb_spk') delattr(self, 'file_start') delattr(self, 'file_end') def _load_motif(self): """Load motif info""" from ..analysis.parameters import peth_parm from ..utils.functions import find_str # Store values here file_list = [] spk_list = [] onset_list = [] offset_list = [] syllable_list = [] duration_list = [] context_list = [] list_zip = zip(self.files, self.spk_ts, self.onsets, self.offsets, self.syllables, self.contexts) for file, spks, onsets, offsets, syllables, context in list_zip: print('Loading... ' + file) onsets = onsets.tolist() offsets = offsets.tolist() # Find motifs motif_ind = find_str(syllables, self.motif) # Get syllable, analysis time stamps for ind in motif_ind: # start (first syllable) and stop (last syllable) index of a motif start_ind = ind stop_ind = ind + len(self.motif) - 1 motif_onset = float(onsets[start_ind]) motif_offset = float(offsets[stop_ind]) # Includes pre-motor spikes motif_spk = spks[np.where((spks >= motif_onset - peth_parm['buffer']) & (spks <= motif_offset))] onsets_in_motif = onsets[start_ind:stop_ind + 1] # list of motif onset timestamps offsets_in_motif = offsets[start_ind:stop_ind + 1] # list of motif offset timestamps file_list.append(file) spk_list.append(motif_spk) duration_list.append(motif_offset - motif_onset) onset_list.append(onsets_in_motif) offset_list.append(offsets_in_motif) syllable_list.append(syllables[start_ind:stop_ind + 1]) context_list.append(context) # Organize event-related info into a single dictionary object motif_info = { 'files': file_list, 'spk_ts': spk_list, 'onsets': onset_list, 'offsets': offset_list, 'durations': duration_list, # this is motif durations 'syllables': syllable_list, 'contexts': context_list, 'parameter': peth_parm } # Set the dictionary values to class attributes for key in motif_info: setattr(self, key, motif_info[key]) # Get duration note_duration_list, median_duration_list = self.get_note_duration() self.note_durations = note_duration_list self.median_durations = median_duration_list motif_info['note_durations'] = note_duration_list motif_info['median_durations'] = median_duration_list # Get PLW (piecewise linear warping) spk_ts_warp_list = self.piecewise_linear_warping() # self.spk_ts_warp = spk_ts_warp_list motif_info['spk_ts_warp'] = spk_ts_warp_list return motif_info def select_context(self, target_context : str, keep_median_duration=True ) -> None: """ Select one context Parameters ---------- target_context : str 'U' or 'D' keep_median_duration : bool Normally medial note duration is calculated using all syllables regardless of the context. One may prefer to use this median to reduce variability when calculating pcc. IF set False, new median duration will be calculated using the selected notes. """ zipped_list = \ list(zip(self.contexts, self.files, self.onsets, self.offsets, self.durations, self.spk_ts, self.spk_ts_warp, self.note_durations)) zipped_list = list(filter(lambda x: x[0] == target_context, zipped_list)) # filter context unzipped_object = zip(*zipped_list) self.contexts, self.files, self.onsets, self.offsets, self.durations, self.spk_ts, self.spk_ts_warp, self.note_durations = \ list(unzipped_object) if not keep_median_duration: _, self.median_durations = self.get_note_duration() def get_note_duration(self): """ Calculate note & gap duration per motif """ note_durations = np.empty((len(self), len(self.motif) * 2 - 1)) list_zip = zip(self.onsets, self.offsets) for motif_ind, (onset, offset) in enumerate(list_zip): # Convert from string to array of floats onset = np.asarray(list(map(float, onset))) offset = np.asarray(list(map(float, offset))) # Calculate note & interval duration timestamp = [[onset, offset] for onset, offset in zip(onset, offset)] timestamp = sum(timestamp, []) for i in range(len(timestamp) - 1): note_durations[motif_ind, i] = timestamp[i + 1] - timestamp[i] # Get median duration median_durations = np.median(note_durations, axis=0) return note_durations, median_durations def piecewise_linear_warping(self): """ Performs piecewise linear warping on raw analysis timestamps Based on each median note and gap durations """ import copy from ..utils.functions import extract_ind spk_ts_warped_list = [] list_zip = zip(self.note_durations, self.onsets, self.offsets, self.spk_ts) for motif_ind, (durations, onset, offset, spk_ts) in enumerate(list_zip): # per motif onset = np.asarray(list(map(float, onset))) offset = np.asarray(list(map(float, offset))) # Make a deep copy of spk_ts so as to make it modification won't affect the original spk_ts_new = copy.deepcopy(spk_ts) # Calculate note & interval duration timestamp = [[onset, offset] for onset, offset in zip(onset, offset)] timestamp = sum(timestamp, []) for i in range(0, len(self.median_durations)): ratio = self.median_durations[i] / durations[i] diff = timestamp[i] - timestamp[0] if i == 0: origin = 0 else: origin = sum(self.median_durations[:i]) # Add spikes from motif ind, spk_ts_temp = extract_ind(spk_ts, [timestamp[i], timestamp[i + 1]]) spk_ts_temp = ((ratio * ((spk_ts_temp - timestamp[0]) - diff)) + origin) + timestamp[0] # spk_ts_new = np.append(spk_ts_new, spk_ts_temp) np.put(spk_ts_new, ind, spk_ts_temp) # replace original spk timestamps with warped timestamps spk_ts_warped_list.append(spk_ts_new) return spk_ts_warped_list def get_mean_fr(self, add_pre_motor=False): """ Calculate mean firing rates during motif Parameters ---------- add_pre_motor : bool Set True if you want to include spikes from the pre-motor window for calculating firing rates (False by default) """ from ..analysis.parameters import peth_parm fr_dict = {} motif_spk_list = [] list_zip = zip(self.onsets, self.offsets, self.spk_ts) # Make sure spikes from the pre-motif buffer is not included in calculation for onset, offset, spks in list_zip: onset = np.asarray(list(map(float, onset))) offset = np.asarray(list(map(float, offset))) if add_pre_motor: motif_spk_list.append(spks[np.where((spks >= (onset[0] - peth_parm['buffer'])) & (spks <= offset[-1]))]) else: motif_spk_list.append(spks[np.where((spks >= onset[0]) & (spks <= offset[-1]))]) for context1 in set(self.contexts): nb_spk = sum([len(spk) for spk, context2 in zip(motif_spk_list, self.contexts) if context2 == context1]) if add_pre_motor: total_duration = sum([duration + peth_parm['buffer'] for duration, context2 in zip(self.durations, self.contexts) if context2 == context1]) else: total_duration = sum([duration for duration, context2 in zip(self.durations, self.contexts) if context2 == context1]) mean_fr = nb_spk / (total_duration / 1E3) fr_dict[context1] = round(mean_fr, 3) # print("mean_fr added") self.mean_fr = fr_dict def jitter_spk_ts(self, shuffle_limit: int, **kwargs): """ Add a random temporal jitter to the spike This version limit the jittered timestamp within the motif window """ from ..analysis.parameters import pre_motor_win_size spk_ts_jittered_list = [] list_zip = zip(self.onsets, self.offsets, self.spk_ts) for ind, (onset, offset, spk_ts) in enumerate(list_zip): # Find motif onset & offset onset = float(onset[0]) - pre_motor_win_size # start from the premotor window offset = float(offset[-1]) jittered_spk = np.array([], dtype=np.float32) for spk_ind, spk in enumerate(spk_ts): while True: jitter = np.random.uniform(-shuffle_limit, shuffle_limit, 1) new_spk = spk + jitter if onset < new_spk < offset: jittered_spk = np.append(jittered_spk, spk + jitter) break spk_ts_jittered_list.append(jittered_spk) self.spk_ts_jittered = spk_ts_jittered_list def get_peth(self, time_warp=True, shuffle=False): """ Get peri-event time histogram & raster during song motif Parameters ---------- time_warp : bool perform piecewise linear transform shuffle : bool add jitter to spike timestamps Returns ------- PethInfo : class object """ peth_dict = {} if shuffle: # Get peth with shuffled (jittered) spikes peth, time_bin, peth_parm = get_peth(self.onsets, self.spk_ts_jittered) else: if time_warp: # peth calculated from time-warped spikes by default # peth, time_bin = get_note_peth(self.onsets, self.spk_ts_warp, self.median_durations.sum()) # truncated version to fit the motif duration peth, time_bin, peth_parm = get_peth(self.onsets, self.spk_ts_warp) else: peth, time_bin, peth_parm = get_peth(self.onsets, self.spk_ts) peth_parm.pop('time_bin'); peth_parm.pop('nb_bins') peth_dict['peth'] = peth peth_dict['time_bin'] = time_bin peth_dict['parameters'] = peth_parm peth_dict['contexts'] = self.contexts peth_dict['median_duration'] = self.median_durations.sum() return PethInfo(peth_dict) # return peth class object for further analysis def __len__(self): return len(self.files) def __repr__(self): # print attributes return str([key for key in self.__dict__.keys()]) @property def open_folder(self): """Open the data folder""" from ..utils.functions import open_folder open_folder(self.path) def _print_name(self): print('') print('Load motif {self.name}'.format(self=self)) class PethInfo(): def __init__(self, peth_dict: dict): """ Class object for peri-event time histogram (PETH) Parameters ---------- peth_dict : dict "peth" : array (nb of trials (motifs) x time bins), numbers indicate analysis counts in that bin "contexts" : list of strings, social contexts """ # Set the dictionary values to class attributes for key in peth_dict: setattr(self, key, peth_dict[key]) # Get conditional peth, fr, spike counts peth_dict = {} peth_dict['All'] = self.peth for context in set(self.contexts): if type(self.contexts) == str: self.contexts = list(self.contexts) ind = np.array(self.contexts) == context peth_dict[context] = self.peth[ind, :] self.peth = peth_dict def get_fr(self, gaussian_std=None, smoothing=True): """ Get trials-by-trial firing rates by default Parameters ---------- gaussian_std : int gaussian smoothing parameter. If not specified, read from analysis.parameters smoothing : bool performs gaussian smoothing on the firing rates """ # if duration: # ind = (((0 - peth_parm['buffer']) <= time_bin) & (time_bin <= duration)) # peth = peth[:, ind] # time_bin = time_bin[ind] from ..analysis.parameters import peth_parm, gauss_std, nb_note_crit from scipy.ndimage import gaussian_filter1d if not gaussian_std: # if not specified, get the value fromm analysis.parameters gaussian_std = gauss_std # Get trial-by-trial firing rates fr_dict = {} for k, v in self.peth.items(): # loop through different conditions in peth dict if v.shape[0] >= nb_note_crit: fr = v / (peth_parm['bin_size'] / 1E3) # in Hz if smoothing: # Gaussian smoothing fr = gaussian_filter1d(fr, gaussian_std) # Truncate values outside the range ind = (((0 - peth_parm['buffer']) <= self.time_bin) & (self.time_bin <= self.median_duration)) fr = fr[:, ind] fr_dict[k] = fr self.fr = fr_dict self.time_bin = self.time_bin[ind] # Get mean firing rates mean_fr_dict = {} for context, fr in self.fr.items(): fr = np.mean(fr, axis=0) mean_fr_dict[context] = fr if smoothing: mean_fr_dict['gauss_std'] = gauss_std self.mean_fr = mean_fr_dict def get_pcc(self): """Get pairwise cross-correlation""" from ..analysis.parameters import nb_note_crit pcc_dict = {} for k, v in self.fr.items(): # loop through different conditions in peth dict if k != 'All': if v.shape[0] >= nb_note_crit: pcc = get_pcc(v) pcc_dict[k] = pcc self.pcc = pcc_dict def get_fr_cv(self): """Get coefficient of variation (CV) of firing rates""" if not self.mean_fr: self.get_fr() fr_cv = {} for context, fr in self.mean_fr.items(): # loop through different conditions in peth dict if context in ['U', 'D']: fr_cv[context] = round(fr.std(axis=0) / fr.mean(axis=0), 3) return fr_cv def get_sparseness(self, bin_size=None): """ Get sparseness index Parameters ---------- bin_size : int By default, it uses the same time bin size used in peth calculation (in ms) Returns ------- sparseness : dict """ from ..analysis.parameters import gauss_std, nb_note_crit import math mean_fr = dict() sparseness = dict() if bin_size != None and bin_size != self.parameters['bin_size']: for context, peth in self.peth.items(): if context == 'All': continue new_peth = np.empty([peth.shape[0], 0]) nb_bins = math.ceil(peth.shape[1] / bin_size) bin_ind = 0 start_ind = 0 end_ind = 0 + bin_size while bin_ind < nb_bins: if end_ind > peth.shape[1]: end_ind = peth.shape[1] # print(start_ind, end_ind) peth_bin = peth[:, start_ind: end_ind].sum(axis=1).reshape(peth.shape[0], 1) new_peth = np.append(new_peth, peth_bin, axis=1) start_ind += bin_size end_ind += bin_size bin_ind += 1 fr = new_peth / (bin_size / 1E3) # in Hz mean_fr[context] = np.mean(fr, axis=0) else: mean_fr = self.mean_fr # Calculate sparseness for context, fr in mean_fr.items(): if context not in ['U', 'D']: continue norm_fr = fr / np.sum(fr) sparseness[context] = round(1 + (np.nansum(norm_fr * np.log10(norm_fr)) / np.log10(len(norm_fr))), 3) return sparseness def get_spk_count(self): """ Calculate the number of spikes within a specified time window """ from ..analysis.parameters import peth_parm, spk_count_parm win_size = spk_count_parm['win_size'] spk_count_dict = {} fano_factor_dict = {} spk_count_cv_dict = {} for k, v in self.peth.items(): # loop through different conditions in peth dict spk_arr = np.empty((v.shape[0], 0), int) # (renditions x time bins) if k != 'All': # skip all trials win_inc = 0 for i in range(v.shape[1] - win_size): count = v[:, i: win_size + win_inc].sum(axis=1) # print(f"from {i} to {win_size + win_inc}, count = {count}") spk_arr = np.append(spk_arr, np.array([count]).transpose(), axis=1) win_inc += 1 # Truncate values outside the range ind = (((0 - peth_parm['buffer']) <= self.time_bin) & (self.time_bin <= self.median_duration)) spk_arr = spk_arr[:, :ind.shape[0]] spk_count = spk_arr.sum(axis=0) fano_factor = spk_arr.var(axis=0) / spk_arr.mean( axis=0) # per time window (across renditions) (renditions x time window) spk_count_cv = spk_count.std(axis=0) / spk_count.mean(axis=0) # cv across time (single value) # store values in a dictionary spk_count_dict[k] = spk_count fano_factor_dict[k] = fano_factor spk_count_cv_dict[k] = round(spk_count_cv, 3) self.spk_count = spk_count_dict self.fano_factor = fano_factor_dict self.spk_count_cv = spk_count_cv_dict def __repr__(self): # print attributes return str([key for key in self.__dict__.keys()]) class BoutInfo(ClusterInfo): """ Get song & spike information for a song bout Child class of ClusterInfo """ def __init__(self, path, channel_nb, unit_nb, song_note, format='rhd', *name, update=False): super().__init__(path, channel_nb, unit_nb, format, *name, update=False) self.song_note = song_note if name: self.name = name[0] else: self.name = str(self.path) # Load bout info file_name = self.path / "BoutInfo_{}_Cluster{}.npy".format(self.channel_nb, self.unit_nb) if update or not file_name.exists(): # if .npy doesn't exist or want to update the file bout_info = self._load_bouts() # Save info dict as a numpy object np.save(file_name, bout_info) else: bout_info = np.load(file_name, allow_pickle=True).item() # Set the dictionary values to class attributes for key in bout_info: setattr(self, key, bout_info[key]) def _print_name(self): print('') print('Load bout {self.name}'.format(self=self)) def __len__(self): return len(self.files) def _load_bouts(self): # Store values here from ..utils.functions import find_str file_list = [] spk_list = [] onset_list = [] offset_list = [] syllable_list = [] duration_list = [] context_list = [] list_zip = zip(self.files, self.spk_ts, self.onsets, self.offsets, self.syllables, self.contexts) for file, spks, onsets, offsets, syllables, context in list_zip: bout_ind = find_str(syllables, '*') for ind in range(len(bout_ind)): if ind == 0: start_ind = 0 else: start_ind = bout_ind[ind - 1] + 1 stop_ind = bout_ind[ind] - 1 # breakpoint() bout_onset = float(onsets[start_ind]) bout_offset = float(offsets[stop_ind]) bout_spk = spks[np.where((spks >= bout_onset) & (spks <= bout_offset))] onsets_in_bout = onsets[start_ind:stop_ind + 1] # list of bout onset timestamps offsets_in_bout = offsets[start_ind:stop_ind + 1] # list of bout offset timestamps file_list.append(file) spk_list.append(bout_spk) duration_list.append(bout_offset - bout_onset) onset_list.append(onsets_in_bout) offset_list.append(offsets_in_bout) syllable_list.append(syllables[start_ind:stop_ind + 1]) context_list.append(context) # Organize event-related info into a single dictionary object bout_info = { 'files': file_list, 'spk_ts': spk_list, 'onsets': onset_list, 'offsets': offset_list, 'durations': duration_list, # this is bout durations 'syllables': syllable_list, 'contexts': context_list, } return bout_info def plot(self): #TODO: this function needs revision from ..analysis.parameters import bout_buffer, freq_range, bout_color from ..utils import save from ..utils.draw import remove_right_top import matplotlib.colors as colors import matplotlib.pyplot as plt import numpy as np from ..database.load import ProjectLoader, DBInfo from scipy import stats import warnings warnings.filterwarnings('ignore') # Parameters save_fig = False update = False dir_name = 'RasterBouts' fig_ext = '.png' # .png or .pdf font_size = 12 # figure font size rec_yloc = 0.05 rect_height = 0.2 text_yloc = 1 # text height nb_row = 13 nb_col = 1 tick_length = 1 tick_width = 1 # Load database db = ProjectLoader().load_db() # SQL statementwa # query = "SELECT * FROM cluster" # query = "SELECT * FROM cluster WHERE ephysOK" query = "SELECT * FROM cluster WHERE id = 12" db.execute(query) # Loop through db for row in db.cur.fetchall(): # Load cluster info from db cluster_db = DBInfo(row) name, path = cluster_db.load_cluster_db() unit_nb = int(cluster_db.unit[-2:]) channel_nb = int(cluster_db.channel[-2:]) format = cluster_db.format ci = ClusterInfo(path, channel_nb, unit_nb, format, name, update=update) # cluster object bi = BoutInfo(path, channel_nb, unit_nb, cluster_db.songNote, format, name, update=update) # bout object list_zip = zip(bi.files, bi.spk_ts, bi.onsets, bi.offsets, bi.syllables, bi.contexts) for bout_ind, (file, spks, onsets, offsets, syllables, context) in enumerate(list_zip): # Convert from string to array of floats onsets = np.asarray(list(map(float, onsets))) offsets = np.asarray(list(map(float, offsets))) spks = spks - onsets[0] # bout start and end start = onsets[0] - bout_buffer end = offsets[-1] + bout_buffer duration = offsets[-1] - onsets[0] # Get spectrogram audio = AudioData(path, update=update).extract([start, end]) # audio object audio.spectrogram() audio.spect_time = audio.spect_time - audio.spect_time[0] - bout_buffer # Plot figure fig = plt.figure(figsize=(8, 7)) fig.tight_layout() fig_name = f"{file} - Bout # {bout_ind}" print("Processing... " + fig_name) fig.suptitle(fig_name, y=0.95) # Plot spectrogram ax_spect = plt.subplot2grid((nb_row, nb_col), (2, 0), rowspan=2, colspan=1) ax_spect.pcolormesh(audio.spect_time, audio.spect_freq, audio.spect, # data cmap='hot_r', norm=colors.SymLogNorm(linthresh=0.05, linscale=0.03, vmin=0.5, vmax=100 )) remove_right_top(ax_spect) ax_spect.set_ylim(freq_range[0], freq_range[1]) ax_spect.set_ylabel('Frequency (Hz)', fontsize=font_size) plt.yticks(freq_range, [str(freq_range[0]), str(freq_range[1])]) plt.setp(ax_spect.get_xticklabels(), visible=False) plt.xlim([audio.spect_time[0] - 100, audio.spect_time[-1] + 100]) # Plot syllable duration ax_syl = plt.subplot2grid((nb_row, nb_col), (1, 0), rowspan=1, colspan=1, sharex=ax_spect) note_dur = offsets - onsets # syllable duration onsets -= onsets[0] # start from 0 offsets = onsets + note_dur # Mark syllables for i, syl in enumerate(syllables): rectangle = plt.Rectangle((onsets[i], rec_yloc), note_dur[i], rect_height, linewidth=1, alpha=0.5, edgecolor='k', facecolor=bout_color[syl]) ax_syl.add_patch(rectangle) ax_syl.text((onsets[i] + (offsets[i] - onsets[i]) / 2), text_yloc, syl, size=font_size) ax_syl.axis('off') # Plot song amplitude audio.data = stats.zscore(audio.data) audio.timestamp = audio.timestamp - audio.timestamp[0] - bout_buffer ax_amp = plt.subplot2grid((nb_row, nb_col), (4, 0), rowspan=2, colspan=1, sharex=ax_spect) ax_amp.plot(audio.timestamp, audio.data, 'k', lw=0.1) ax_amp.axis('off') # Plot rasters ax_raster = plt.subplot2grid((nb_row, nb_col), (6, 0), rowspan=2, colspan=1, sharex=ax_spect) # spks2 = spks - start -peth_parm['buffer'] -peth_parm['buffer'] ax_raster.eventplot(spks, colors='k', lineoffsets=0.5, linelengths=tick_length, linewidths=tick_width, orientation='horizontal') ax_raster.axis('off') # Plot raw neural data nd = NeuralData(path, channel_nb, format, update=update).extract([start, end]) # raw neural data nd.timestamp = nd.timestamp - nd.timestamp[0] - bout_buffer ax_nd = plt.subplot2grid((nb_row, nb_col), (8, 0), rowspan=2, colspan=1, sharex=ax_spect) ax_nd.plot(nd.timestamp, nd.data, 'k', lw=0.5) # Add a scale bar plt.plot([ax_nd.get_xlim()[0] + 50, ax_nd.get_xlim()[0] + 50], [-250, 250], 'k', lw=3) # for amplitude plt.text(ax_nd.get_xlim()[0] - (bout_buffer / 2), -200, '500 µV', rotation=90) plt.subplots_adjust(wspace=0, hspace=0) remove_right_top(ax_nd) ax_nd.spines['left'].set_visible(False) plt.yticks([], []) ax_nd.set_xlabel('Time (ms)') # Save results if save_fig: save_path = save.make_dir(ProjectLoader().path / 'Analysis', 'RasterBouts') save.save_fig(fig, save_path, fig_name, fig_ext=fig_ext) else: plt.show() print('Done!') class BaselineInfo(ClusterInfo): def __init__(self, path, channel_nb, unit_nb, format='rhd', *name, update=False): super().__init__(path, channel_nb, unit_nb, format, *name, update=False) from ..analysis.parameters import baseline from ..utils.functions import find_str if name: self.name = name[0] else: self.name = str(self.path) # Load baseline info file_name = self.path / "BaselineInfo_{}_Cluster{}.npy".format(self.channel_nb, self.unit_nb) if update or not file_name.exists(): # if .npy doesn't exist or want to update the file # Store values in here file_list = [] spk_list = [] nb_spk_list = [] duration_list = [] context_list = [] baseline_info = {} list_zip = zip(self.files, self.spk_ts, self.file_start, self.onsets, self.offsets, self.syllables, self.contexts) for file, spks, file_start, onsets, offsets, syllables, context in list_zip: bout_ind_list = find_str(syllables, '*') bout_ind_list.insert(0, -1) # start from the first index for bout_ind in bout_ind_list: # print(bout_ind) if bout_ind == len(syllables) - 1: # skip if * indicates the end syllable continue baseline_onset = float(onsets[bout_ind + 1]) - baseline['time_buffer'] - baseline['time_win'] if bout_ind > 0 and baseline_onset < float(offsets[ bout_ind - 1]): # skip if the baseline starts before the offset of the previous syllable continue if baseline_onset < file_start: baseline_onset = file_start baseline_offset = float(onsets[bout_ind + 1]) - baseline['time_buffer'] if baseline_offset - baseline_onset < 0: # skip if there's not enough baseline period at the start of a file continue if baseline_onset > baseline_offset: print('start time ={} to end time = {}'.format(baseline_onset, baseline_offset)) baseline_spk = spks[np.where((spks >= baseline_onset) & (spks <= baseline_offset))] file_list.append(file) spk_list.append(baseline_spk) nb_spk_list.append(len(baseline_spk)) duration_list.append( (baseline_offset - baseline_onset)) # convert to seconds for calculating in Hz context_list.append(context) baseline_info = { 'files': file_list, 'spk_ts': spk_list, 'nb_spk': nb_spk_list, 'durations': duration_list, 'contexts': context_list, 'parameter': baseline } # Save baseline_info as a numpy object np.save(file_name, baseline_info) else: baseline_info = np.load(file_name, allow_pickle=True).item() # Set the dictionary values to class attributes for key in baseline_info: setattr(self, key, baseline_info[key]) def _print_name(self): print('') print('Load baseline {self.name}'.format(self=self)) def get_correlogram(self, ref_spk_list, target_spk_list, normalize=False): """ Override the parent method Combine correlogram from undir and dir since no contextual differentiation is needed in baseline """ from ..analysis.parameters import spk_corr_parm correlogram_all = super().get_correlogram(ref_spk_list, target_spk_list, normalize=False) correlogram = np.zeros(len(spk_corr_parm['time_bin'])) # Combine correlogram from two contexts for key, value in correlogram_all.items(): if key in ['U', 'D']: correlogram += value return correlogram # return class object for further analysis def get_jittered_corr(self) -> np.ndarray: """Get spike correlogram from time-jittered spikes""" from ..analysis.parameters import corr_shuffle correlogram_jitter = [] for iter in range(corr_shuffle['shuffle_iter']): self.jitter_spk_ts(corr_shuffle['shuffle_limit']) corr_temp = self.get_correlogram(self.spk_ts_jittered, self.spk_ts_jittered) correlogram_jitter.append(corr_temp) return np.array(correlogram_jitter) def get_isi(self): """Get inter-spike interval""" return get_isi(self.spk_ts) @property def mean_fr(self): """Mean firing rates""" nb_spk = sum([len(spk_ts) for spk_ts in self.spk_ts]) total_duration = sum(self.durations) mean_fr = nb_spk / (total_duration / 1E3) return round(mean_fr, 3) def __repr__(self): # print attributes return str([key for key in self.__dict__.keys()]) class AudioData: """ Create an object that has concatenated audio signal and its timestamps Get all data by default; specify time range if needed """ def __init__(self, path, format='.wav', update=False): from ..analysis.load import load_audio self.path = path self.format = format file_name = self.path / "AudioData.npy" if update or not file_name.exists(): # if .npy doesn't exist or want to update the file audio_info = load_audio(self.path, self.format) else: audio_info = np.load(file_name, allow_pickle=True).item() # Set the dictionary values to class attributes for key in audio_info: setattr(self, key, audio_info[key]) def __repr__(self): # print attributes return str([key for key in self.__dict__.keys()]) @property def open_folder(self): """Open the data folder""" from ..utils.functions import open_folder open_folder(self.path) def extract(self, time_range: list): """ Extracts data from the specified range Parameters ---------- time_range : list """ start = time_range[0] end = time_range[-1] ind = np.where((self.timestamp >= start) & (self.timestamp <= end)) return self.timestamp[ind], self.data[ind] def spectrogram(self, timestamp, data, freq_range=[300, 8000]): """Calculate spectrogram""" from ..utils.spect import spectrogram spect, spect_freq, _ = spectrogram(data, self.sample_rate, freq_range=freq_range) spect_time = np.linspace(timestamp[0], timestamp[-1], spect.shape[1]) # timestamp for spectrogram return spect_time, spect, spect_freq def get_spectral_entropy(self, spect, normalize=True, mode=None): """ Calculate spectral entropy Parameters ---------- normalize : bool Get normalized spectral entropy mode : {'spectral', ''spectro_temporal'} Returns ------- array of spectral entropy """ from ..analysis.functions import get_spectral_entropy return get_spectral_entropy(spect, normalize=normalize, mode=mode) class NeuralData: def __init__(self, path, channel_nb, format='rhd', update=False): self.path = path self.channel_nb = str(channel_nb).zfill(2) self.format = format # format of the file (e.g., rhd), this info should be in the database file_name = self.path / f"NeuralData_Ch{self.channel_nb}.npy" if update or not file_name.exists(): # if .npy doesn't exist or want to update the file data_info = self.load_neural_data() # Save event_info as a numpy object else: data_info = np.load(file_name, allow_pickle=True).item() # Set the dictionary values to class attributes for key in data_info: setattr(self, key, data_info[key]) def __repr__(self): # print attributes return str([key for key in self.__dict__.keys()]) def load_neural_data(self): """ Load and concatenate all neural data files (e.g., .rhd) in the input dir (path) """ from ..analysis.load import read_rhd from ..analysis.parameters import sample_rate print("") print("Load neural data") # List .rhd files files = list(self.path.glob(f'*.{self.format}')) # Initialize timestamp_concat = np.array([], dtype=np.float64) amplifier_data_concat = np.array([], dtype=np.float64) # Store values in these lists file_list = [] if self.format == 'cbin': # if the neural data is in .cbin format, read from .mat files that has contains concatenated data # currently does not have files to extract data from .cbin files in python import scipy.io mat_file = list(self.path.glob(f'*Ch{self.channel_nb}(merged).mat'))[0] timestamp_concat = scipy.io.loadmat(mat_file)['t_amplifier'][0].astype(np.float64) amplifier_data_concat = scipy.io.loadmat(mat_file)['amplifier_data'][0].astype(np.float64) else: # Loop through Intan .rhd files for file in files: # Load data file print('Loading... ' + file.stem) file_list.append(file.name) intan = read_rhd(file) # note that the timestamp is in second # Concatenate timestamps intan['t_amplifier'] -= intan['t_amplifier'][0] # start from t = 0 if timestamp_concat.size == 0: timestamp_concat = np.append(timestamp_concat, intan['t_amplifier']) else: intan['t_amplifier'] += (timestamp_concat[-1] + (1 / sample_rate[self.format])) timestamp_concat = np.append(timestamp_concat, intan['t_amplifier']) # Concatenate neural data for ind, ch in enumerate(intan['amplifier_channels']): if int(self.channel_nb) == int(ch['native_channel_name'][-2:]): amplifier_data_concat = np.append(amplifier_data_concat, intan['amplifier_data'][ind, :]) timestamp_concat *= 1E3 # convert to microsecond # Organize data into a dictionary data_info = { 'files': file_list, 'timestamp': timestamp_concat, 'data': amplifier_data_concat, 'sample_rate': sample_rate[self.format] } file_name = self.path / f"NeuralData_Ch{self.channel_nb}.npy" np.save(file_name, data_info) return data_info def extract(self, time_range: list): """ Extracts data from the specified range Parameters ---------- time_range : list list of time stamps [start, end] Returns ------- timestamp : arr data : arr """ start = time_range[0] end = time_range[-1] ind = np.where((self.timestamp >= start) & (self.timestamp <= end)) return self.timestamp[ind], self.data[ind] @property def open_folder(self): """Open the data folder""" from ..utils.functions import open_folder open_folder(self.path) class Correlogram(): """ Class for correlogram analysis """ def __init__(self, correlogram): from ..analysis.parameters import spk_corr_parm, burst_hz corr_center = round(correlogram.shape[0] / 2) + 1 # center of the correlogram self.data = correlogram self.time_bin = np.arange(-spk_corr_parm['lag'], spk_corr_parm['lag'] + spk_corr_parm['bin_size'], spk_corr_parm['bin_size']) if self.data.sum(): self.peak_ind = np.min( np.abs(np.argwhere(correlogram == np.amax(correlogram)) - corr_center)) + corr_center # index of the peak self.peak_latency = self.time_bin[self.peak_ind] - 1 self.peak_value = self.data[self.peak_ind] burst_range = np.arange(corr_center - (1000 / burst_hz) - 1, corr_center + (1000 / burst_hz), dtype='int') # burst range in the correlogram self.burst_index = round(self.data[burst_range].sum() / self.data.sum(), 3) else: self.peak_ind = self.peak_latency = self.peak_value = self.burst_index = np.nan def __repr__(self): # print attributes return str([key for key in self.__dict__.keys()]) def category(self, correlogram_jitter: np.ndarray) -> str: """ Get bursting category of a neuron based on autocorrelogram Parameters ---------- correlogram_jitter : np.ndarray Random time-jittered correlogram for baseline setting Returns ------- Category of a neuron ('Bursting' or 'Nonbursting') """ from ..analysis.parameters import corr_burst_crit corr_mean = correlogram_jitter.mean(axis=0) if corr_mean.sum(): corr_std = correlogram_jitter.std(axis=0) upper_lim = corr_mean + (corr_std * 2) lower_lim = corr_mean - (corr_std * 2) self.baseline = upper_lim # Check peak significance if self.peak_value > upper_lim[self.peak_ind] and self.peak_latency <= corr_burst_crit: self.category = 'Bursting' else: self.category = 'NonBursting' else: self.baseline = self.category = np.array(np.nan) return self.category def plot_corr(self, ax, time_bin, correlogram, title, xlabel=None, ylabel=None, font_size=10, peak_line_width=0.8, normalize=False, peak_line=True, baseline=True): """ Plot correlogram Parameters ---------- ax : axis object axis to plot the figure time_bin : np.ndarray correlogram : np.ndarray title : str font_size : int title font size normalize : bool normalize the correlogram """ import matplotlib.pyplot as plt from ..utils.draw import remove_right_top from ..utils.functions import myround if correlogram.sum(): ax.bar(time_bin, correlogram, color='k', rasterized=True) ymax = max([self.baseline.max(), correlogram.max()]) round(ymax / 10) * 10 ax.set_ylim(0, ymax) plt.yticks([0, ax.get_ylim()[1]], [str(0), str(int(ymax))]) ax.set_title(title, size=font_size) ax.set_xlabel(xlabel) if normalize: ax.set_ylabel(ylabel) else: ax.set_ylabel(ylabel) remove_right_top(ax) if peak_line and not np.isnan(self.peak_ind): # peak_time_ind = np.where(self.time_bin == self.peak_latency) ax.axvline(x=self.time_bin[self.peak_ind], color='r', linewidth=peak_line_width, ls='--') if baseline and not np.isnan(self.baseline.mean()): ax.plot(self.time_bin, self.baseline, 'm', lw=0.5, ls='--') else: ax.axis('off') ax.set_title(title, size=font_size) class BurstingInfo: def __init__(self, ClassInfo, *input_context): from ..analysis.parameters import burst_hz # ClassInfo can be BaselineInfo, MotifInfo etc if input_context: # select data based on social context spk_list = [spk_ts for spk_ts, context in zip(ClassInfo.spk_ts, ClassInfo.contexts) if context == input_context[0]] duration_list = [duration for duration, context in zip(ClassInfo.durations, ClassInfo.contexts) if context == input_context[0]] self.context = input_context else: spk_list = ClassInfo.spk_ts duration_list = ClassInfo.durations # Bursting analysis burst_spk_list = [] burst_duration_arr = [] nb_bursts = [] nb_burst_spk_list = [] for ind, spks in enumerate(spk_list): # spk = bi.spk_ts[8] isi = np.diff(spks) # inter-spike interval inst_fr = 1E3 / np.diff(spks) # instantaneous firing rates (Hz) bursts = np.where(inst_fr >= burst_hz)[0] # burst index # Skip if no bursting detected if not bursts.size: continue # Get the number of bursts temp = np.diff(bursts)[np.where(np.diff(bursts) == 1)].size # check if the spikes occur in bursting nb_bursts = np.append(nb_bursts, bursts.size - temp) # Get burst onset temp = np.where(np.diff(bursts) == 1)[0] spk_ind = temp + 1 # Remove consecutive spikes in a burst and just get burst onset burst_onset_ind = bursts for i, ind in enumerate(temp): burst_spk_ind = spk_ind[spk_ind.size - 1 - i] burst_onset_ind = np.delete(burst_onset_ind, burst_spk_ind) # Get burst offset index burst_offset_ind = np.array([], dtype=np.int) for i in range(bursts.size - 1): if bursts[i + 1] - bursts[i] > 1: # if not successive spikes burst_offset_ind = np.append(burst_offset_ind, bursts[i] + 1) # Need to add the subsequent spike time stamp since it is not included (burst is the difference between successive spike time stamps) burst_offset_ind = np.append(burst_offset_ind, bursts[bursts.size - 1] + 1) burst_onset = spks[burst_onset_ind] burst_offset = spks[burst_offset_ind] burst_spk_list.append(spks[burst_onset_ind[0]: burst_offset_ind[0] + 1]) burst_duration_arr =
np.append(burst_duration_arr, burst_offset - burst_onset)
numpy.append
from __future__ import print_function import itertools import math import os import random import shutil import tempfile import unittest import uuid import numpy as np import tensorflow as tf import coremltools import coremltools.models.datatypes as datatypes from coremltools.models import _MLMODEL_FULL_PRECISION, _MLMODEL_HALF_PRECISION from coremltools.models import neural_network as neural_network from coremltools.models.utils import macos_version from coremltools.models.neural_network import flexible_shape_utils np.random.seed(10) MIN_MACOS_VERSION_REQUIRED = (10, 13) LAYERS_10_15_MACOS_VERSION = (10, 15) def _get_unary_model_spec(x, mode, alpha=1.0): input_dim = x.shape input_features = [('data', datatypes.Array(*input_dim))] output_features = [('output', datatypes.Array(*input_dim))] builder = neural_network.NeuralNetworkBuilder(input_features, output_features) builder.add_unary(name='unary', input_name='data', output_name='output', mode=mode, alpha=alpha) return builder.spec class CorrectnessTest(unittest.TestCase): def runTest(self): pass def _compare_shapes(self, np_preds, coreml_preds): return np.squeeze(np_preds).shape == np.squeeze(coreml_preds).shape def _compare_nd_shapes(self, np_preds, coreml_preds, shape=()): if shape: return coreml_preds.shape == shape else: return coreml_preds.shape == np_preds.shape def _compare_predictions(self, np_preds, coreml_preds, delta=.01): np_preds = np_preds.flatten() coreml_preds = coreml_preds.flatten() for i in range(len(np_preds)): max_den = max(1.0, np_preds[i], coreml_preds[i]) if np.abs( np_preds[i] / max_den - coreml_preds[i] / max_den) > delta: return False return True @staticmethod def _compare_moments(model, inputs, expected, use_cpu_only=True, num_moments=10): """ This utility function is used for validate random distributions layers. It validates the first 10 moments of prediction and expected values. """ def get_moment(data, k): return np.mean(np.power(data - np.mean(data), k)) if isinstance(model, str): model = coremltools.models.MLModel(model) model = coremltools.models.MLModel(model, useCPUOnly=use_cpu_only) prediction = model.predict(inputs, useCPUOnly=use_cpu_only) for output_name in expected: np_preds = expected[output_name] coreml_preds = prediction[output_name] np_moments = [get_moment(np_preds.flatten(), k) for k in range(num_moments)] coreml_moments = [get_moment(coreml_preds.flatten(), k) for k in range(num_moments)] np.testing.assert_almost_equal(np_moments, coreml_moments, decimal=2) # override expected values to allow element-wise compares for output_name in expected: expected[output_name] = prediction[output_name] def _test_model(self, model, input, expected, model_precision=_MLMODEL_FULL_PRECISION, useCPUOnly=False, output_name_shape_dict={}, validate_shapes_only=False): model_dir = None # if we're given a path to a model if isinstance(model, str): model = coremltools.models.MLModel(model) # If we're passed in a specification, save out the model # and then load it back up elif isinstance(model, coremltools.proto.Model_pb2.Model): model_dir = tempfile.mkdtemp() model_name = str(uuid.uuid4()) + '.mlmodel' model_path = os.path.join(model_dir, model_name) coremltools.utils.save_spec(model, model_path) model = coremltools.models.MLModel(model, useCPUOnly=useCPUOnly) # If we want to test the half precision case if model_precision == _MLMODEL_HALF_PRECISION: model = coremltools.utils.convert_neural_network_weights_to_fp16( model) prediction = model.predict(input, useCPUOnly=useCPUOnly) for output_name in expected: if self.__class__.__name__ == "SimpleTest": assert (self._compare_shapes(expected[output_name], prediction[output_name])) else: if output_name in output_name_shape_dict: output_shape = output_name_shape_dict[output_name] else: output_shape = [] if len(output_shape) == 0 and len(expected[output_name].shape) == 0: output_shape = (1,) assert (self._compare_nd_shapes(expected[output_name], prediction[output_name], output_shape)) if not validate_shapes_only: assert (self._compare_predictions(expected[output_name], prediction[output_name])) # Remove the temporary directory if we created one if model_dir and os.path.exists(model_dir): shutil.rmtree(model_dir) @unittest.skipIf(macos_version() < MIN_MACOS_VERSION_REQUIRED, 'macOS 10.13+ is required. Skipping tests.') class SimpleTest(CorrectnessTest): def test_tiny_upsample_linear_mode(self): input_dim = (1, 1, 3) # (C,H,W) input_features = [('data', datatypes.Array(*input_dim))] output_features = [('output', None)] builder = neural_network.NeuralNetworkBuilder(input_features, output_features) builder.add_upsample(name='upsample', scaling_factor_h=2, scaling_factor_w=3, input_name='data', output_name='output', mode='BILINEAR') input = { 'data': np.reshape(np.array([1.0, 2.0, 3.0]), (1, 1, 3)) } expected = { 'output': np.array( [[1, 1.333, 1.666, 2, 2.333, 2.666, 3, 3, 3], [1, 1.333, 1.6666, 2, 2.33333, 2.6666, 3, 3, 3] ]) } self._test_model(builder.spec, input, expected) def test_LRN(self): input_dim = (1, 3, 3) input_features = [('data', datatypes.Array(*input_dim))] output_features = [('output', datatypes.Array(*input_dim))] builder = neural_network.NeuralNetworkBuilder(input_features, output_features) builder.add_lrn(name='lrn', input_name='data', output_name='output', alpha=2, beta=3, local_size=1, k=8) input = { 'data': np.ones((1, 3, 3)) } expected = { 'output': 1e-3 * np.ones((1, 3, 3)) } self._test_model(builder.spec, input, expected) def test_MVN(self): input_dim = (2, 2, 2) input_features = [('data', datatypes.Array(*input_dim))] output_features = [('output', datatypes.Array(*input_dim))] builder = neural_network.NeuralNetworkBuilder(input_features, output_features) builder.add_mvn(name='mvn', input_name='data', output_name='output', across_channels=False, normalize_variance=False) input = { 'data': np.reshape(np.arange(8, dtype=np.float32), (2, 2, 2)) } expected = { 'output': np.reshape(np.arange(8) - np.array( [1.5, 1.5, 1.5, 1.5, 5.5, 5.5, 5.5, 5.5]), (2, 2, 2)) } self._test_model(builder.spec, input, expected) def test_L2_normalize(self): input_dim = (1, 2, 2) input_features = [('data', datatypes.Array(*input_dim))] output_features = [('output', datatypes.Array(*input_dim))] builder = neural_network.NeuralNetworkBuilder(input_features, output_features) builder.add_l2_normalize(name='mvn', input_name='data', output_name='output') input = { 'data': np.reshape(np.arange(4, dtype=np.float32), (1, 2, 2)) } expected = { 'output': np.reshape(np.arange(4, dtype=np.float32), (1, 2, 2)) / np.sqrt(14) } self._test_model(builder.spec, input, expected) def test_unary_sqrt(self): x = np.reshape(np.arange(1, 5, dtype=np.float32), (1, 2, 2)) input = {'data': x} expected = {'output': np.sqrt(x)} spec = _get_unary_model_spec(x, 'sqrt') self._test_model(spec, input, expected) def test_unary_rsqrt(self): x = np.reshape(np.arange(1, 5, dtype=np.float32), (1, 2, 2)) input = {'data': x} expected = {'output': 1 / np.sqrt(x)} spec = _get_unary_model_spec(x, 'rsqrt') self._test_model(spec, input, expected) def test_unary_inverse(self): x = np.reshape(np.arange(1, 5, dtype=np.float32), (1, 2, 2)) input = {'data': x} expected = {'output': 1 / x} spec = _get_unary_model_spec(x, 'inverse') self._test_model(spec, input, expected) def test_unary_power(self): x = np.reshape(np.arange(1, 5, dtype=np.float32), (1, 2, 2)) input = {'data': x} expected = {'output': x ** 3} spec = _get_unary_model_spec(x, 'power', 3) self._test_model(spec, input, expected) def test_unary_exp(self): x = np.reshape(np.arange(1, 5, dtype=np.float32), (1, 2, 2)) input = {'data': x} expected = {'output': np.exp(x)} spec = _get_unary_model_spec(x, 'exp') self._test_model(spec, input, expected) def test_unary_log(self): x = np.reshape(np.arange(1, 5, dtype=np.float32), (1, 2, 2)) input = {'data': x} expected = {'output': np.log(x)} spec = _get_unary_model_spec(x, 'log') self._test_model(spec, input, expected) def test_unary_abs(self): x = np.reshape(np.arange(1, 5, dtype=np.float32), (1, 2, 2)) input = {'data': x} expected = {'output': np.abs(x)} spec = _get_unary_model_spec(x, 'abs') self._test_model(spec, input, expected) def test_unary_threshold(self): x = np.reshape(np.arange(1, 5, dtype=np.float32), (1, 2, 2)) input = {'data': x} expected = {'output': np.maximum(x, 2)} spec = _get_unary_model_spec(x, 'threshold', 2) self._test_model(spec, input, expected) def test_split(self): input_dim = (9, 2, 2) x = np.random.rand(*input_dim) input_features = [('data', datatypes.Array(*input_dim))] output_names = [] output_features = [] for i in range(3): out = 'out_' + str(i) output_names.append(out) output_features.append((out, None)) builder = neural_network.NeuralNetworkBuilder(input_features, output_features) builder.add_split(name='split', input_name='data', output_names=output_names) input = {'data': x} expected = { 'out_0': x[0: 3, :, :], 'out_1': x[3: 6, :, :], 'out_2': x[6: 9, :, :] } self._test_model(builder.spec, input, expected) def test_scale_constant(self): input_dim = (1, 2, 2) input_features = [('data', datatypes.Array(*input_dim))] output_features = [('output', None)] builder = neural_network.NeuralNetworkBuilder(input_features, output_features) builder.add_scale(name='scale', W=5, b=45, has_bias=True, input_name='data', output_name='output') x = np.reshape(np.arange(4, dtype=np.float32), (1, 2, 2)) input = {'data': x} expected = {'output': 5 * x + 45} self._test_model(builder.spec, input, expected) def test_scale_matrix(self): input_dim = (1, 2, 2) input_features = [('data', datatypes.Array(*input_dim))] output_features = [('output', None)] builder = neural_network.NeuralNetworkBuilder(input_features, output_features) W = np.reshape(np.arange(5, 9), (1, 2, 2)) builder.add_scale(name='scale', W=W, b=None, has_bias=False, input_name='data', output_name='output', shape_scale=[1, 2, 2]) x = np.reshape(np.arange(4, dtype=np.float32), (1, 2, 2)) input = {'data': x} expected = {'output': W * x} self._test_model(builder.spec, input, expected) def test_bias_constant(self): input_dim = (1, 2, 2) input_features = [('data', datatypes.Array(*input_dim))] output_features = [('output', None)] builder = neural_network.NeuralNetworkBuilder(input_features, output_features) builder.add_bias(name='bias', b=45, input_name='data', output_name='output') x = np.reshape(np.arange(4, dtype=np.float32), (1, 2, 2)) input = {'data': x} expected = {'output': x + 45} self._test_model(builder.spec, input, expected) def test_bias_matrix(self): input_dim = (1, 2, 2) input_features = [('data', datatypes.Array(*input_dim))] output_features = [('output', None)] builder = neural_network.NeuralNetworkBuilder(input_features, output_features) b = np.reshape(np.arange(5, 9), (1, 2, 2)) builder.add_bias(name='bias', b=b, input_name='data', output_name='output', shape_bias=[1, 2, 2]) x = np.reshape(np.arange(4, dtype=np.float32), (1, 2, 2)) input = {'data': x} expected = {'output': x + b} self._test_model(builder.spec, input, expected) def test_load_constant(self, model_precision=_MLMODEL_FULL_PRECISION): input_dim = (1, 2, 2) input_features = [('data', datatypes.Array(*input_dim))] output_features = [('output', None)] builder = neural_network.NeuralNetworkBuilder(input_features, output_features) b = np.reshape(np.arange(5, 9), (1, 2, 2)) builder.add_load_constant(name='load_constant', output_name='bias', constant_value=b, shape=[1, 2, 2]) builder.add_elementwise(name='add', input_names=['data', 'bias'], output_name='output', mode='ADD') x = np.reshape(np.arange(4, dtype=np.float32), (1, 2, 2)) input = {'data': x} expected = {'output': x + b} self._test_model(builder.spec, input, expected, model_precision) def test_load_constant_half_precision(self): self.test_load_constant(model_precision=_MLMODEL_HALF_PRECISION) def test_min(self): input_dim = (1, 2, 2) input_features = [('data_0', datatypes.Array(*input_dim)), ('data_1', datatypes.Array(*input_dim))] output_features = [('output', None)] builder = neural_network.NeuralNetworkBuilder(input_features, output_features) builder.add_elementwise(name='min', input_names=['data_0', 'data_1'], output_name='output', mode='MIN') x1 = np.reshape(np.arange(4, dtype=np.float32), (1, 2, 2)) x2 = np.reshape(np.arange(2, 6, dtype=np.float32), (1, 2, 2)) input = {'data_0': x1, 'data_1': x2} expected = {'output': np.minimum(x1, x2)} self._test_model(builder.spec, input, expected) def test_conv_same_padding(self): input_dim = (10, 15, 15) input_features = [('data', datatypes.Array(*input_dim))] output_features = [('output', None)] builder = neural_network.NeuralNetworkBuilder(input_features, output_features) W = np.random.rand(3, 3, 10, 20) builder.add_convolution(name='conv', kernel_channels=10, output_channels=20, height=3, width=3, stride_height=2, stride_width=2, border_mode='same', groups=1, W=W, b=None, has_bias=False, input_name='data', output_name='output', same_padding_asymmetry_mode='TOP_LEFT_HEAVY') x = np.random.rand(*input_dim) input = {'data': x} expected = {'output': np.random.rand(20, 8, 8)} self._test_model( builder.spec, input, expected, validate_shapes_only=True) def test_deconv_valid_padding(self): input_dim = (10, 15, 15) input_features = [('data', datatypes.Array(*input_dim))] output_features = [('output', None)] builder = neural_network.NeuralNetworkBuilder(input_features, output_features) W = np.random.rand(3, 3, 10, 20) builder.add_convolution(name='deconv', kernel_channels=10, output_channels=20, height=3, width=3, stride_height=2, stride_width=2, border_mode='valid', groups=1, W=W, b=None, has_bias=False, is_deconv=True, input_name='data', output_name='output', padding_top=2, padding_bottom=3, padding_left=2, padding_right=3) x = np.random.rand(*input_dim) input = {'data': x} expected = {'output': np.random.rand(20, 26, 26)} self._test_model( builder.spec, input, expected, validate_shapes_only=True) def test_deconv_non_unit_groups(self): input_dim = (16, 15, 15) input_features = [('data', datatypes.Array(*input_dim))] output_features = [('output', None)] builder = neural_network.NeuralNetworkBuilder( input_features, output_features) W = np.random.rand(3, 3, 16, 5) builder.add_convolution(name='deconv', kernel_channels=16, output_channels=20, height=3, width=3, stride_height=2, stride_width=2, border_mode='valid', groups=4, W=W, b=None, has_bias=False, is_deconv=True, input_name='data', output_name='output', padding_top=2, padding_bottom=3, padding_left=2, padding_right=3) x = np.random.rand(*input_dim) input = {'data': x} expected = {'output': np.random.rand(20, 26, 26)} self._test_model( builder.spec, input, expected, validate_shapes_only=True) def test_linear_activation(self): input_dim = (10, 15, 15) input_features = [('data', datatypes.Array(*input_dim))] output_features = [('output', None)] builder = neural_network.NeuralNetworkBuilder(input_features, output_features) builder.add_activation(name='activation', non_linearity='LINEAR', input_name='data', output_name='output', params=[34.0, 67.0]) x = np.random.rand(*input_dim) input = {'data': x} expected = {'output': 34.0 * x + 67.0} self._test_model(builder.spec, input, expected) def test_padding_constant(self): input_dim = (1, 2, 3) input_features = [('data', datatypes.Array(*input_dim))] output_features = [('output', None)] builder = neural_network.NeuralNetworkBuilder( input_features, output_features) builder.add_padding(name='pad', left=1, right=0, top=2, bottom=0, value=-1, input_name='data', output_name='output') x = np.reshape(np.array([[1, 2, 3], [4, 5, 6]]), (1, 2, 3)).astype( np.float32) input = {'data': x} y = np.reshape( np.array([[-1, -1, -1, -1], [-1, -1, -1, -1], [-1, 1, 2, 3], [-1, 4, 5, 6]]), (1, 4, 4)).astype(np.float32) expected = {'output': y} self._test_model(builder.spec, input, expected) def test_padding_replication(self): input_dim = (1, 2, 3) input_features = [('data', datatypes.Array(*input_dim))] output_features = [('output', None)] builder = neural_network.NeuralNetworkBuilder(input_features, output_features) builder.add_padding(name='pad', left=1, top=2, input_name='data', output_name='output', padding_type='replication') x = np.reshape(np.array([[1, 2, 3], [4, 5, 6]]), (1, 2, 3)).astype( np.float32) input = {'data': x} y = np.reshape(np.array([[1, 1, 2, 3], [1, 1, 2, 3], [1, 1, 2, 3], [4, 4, 5, 6]]), (1, 4, 4)).astype(np.float32) expected = {'output': y} self._test_model(builder.spec, input, expected) def test_reshape_target_shape_3(self): input_dim = (1, 2, 5) # (C,H,W) input_features = [('data', datatypes.Array(*input_dim))] output_features = [('output', None)] builder = neural_network.NeuralNetworkBuilder(input_features, output_features) builder.add_reshape(name='reshape', input_name='data', output_name='output', target_shape=(10, 1, 1), mode=0) x = np.random.rand(*input_dim) input = {'data': x} expected = {'output': np.reshape(x, (10, 1, 1))} self._test_model(builder.spec, input, expected) def test_reshape_target_shape_4(self): input_dim = (1, 2, 5) # (C,H,W) input_features = [('data', datatypes.Array(*input_dim))] output_features = [('output', None)] builder = neural_network.NeuralNetworkBuilder(input_features, output_features) builder.add_reshape(name='reshape', input_name='data', output_name='output', target_shape=(1, 10, 1, 1), mode=0) x = np.random.rand(*input_dim) input = {'data': x} expected = {'output': np.reshape(x, (1, 10, 1, 1))} self._test_model(builder.spec, input, expected) def test_bias_matrix_cpu(self): input_dim = (1, 2, 2) input_features = [('data', datatypes.Array(*input_dim))] output_features = [('output', None)] builder = neural_network.NeuralNetworkBuilder(input_features, output_features) b = np.reshape(np.arange(5, 9), (1, 2, 2)) builder.add_bias(name='bias', b=b, input_name='data', output_name='output', shape_bias=[1, 2, 2]) x = np.reshape(np.arange(4, dtype=np.float32), (1, 2, 2)) input = {'data': x} expected = {'output': x + b} self._test_model(builder.spec, input, expected, useCPUOnly=True) def test_linear_activation_cpu(self): input_dim = (10, 15, 15) input_features = [('data', datatypes.Array(*input_dim))] output_features = [('output', None)] builder = neural_network.NeuralNetworkBuilder(input_features, output_features) builder.add_activation(name='activation', non_linearity='LINEAR', input_name='data', output_name='output', params=[34.0, 67.0]) x = np.random.rand(*input_dim) input = {'data': x} expected = {'output': 34.0 * x + 67.0} self._test_model(builder.spec, input, expected, useCPUOnly=True) @unittest.skipIf(macos_version() < LAYERS_10_15_MACOS_VERSION, 'macOS 10.15+ required. Skipping tests.') class NewLayersSimpleTest(CorrectnessTest): def test_shape_flexibility_range(self): input_features = [('data', datatypes.Array(*(3,4)))] builder = neural_network.NeuralNetworkBuilder(input_features, [('output', None)], disable_rank5_shape_mapping=True) builder.add_sin(name='sin', input_name='data', output_name='output') spec = builder.spec flexible_shape_utils.set_multiarray_ndshape_range(spec, feature_name='data', lower_bounds=[1,1], upper_bounds=[-1,5]) shapes = [(3,4), (1,5), (60,5), (22,4), (5,3)] for s in shapes: x = np.random.rand(*s) expected = {'output': np.sin(x)} self._test_model(spec, {'data': x}, expected, useCPUOnly=True) @unittest.skip('TO FIX') def test_shape_flexibility_enumeration(self): input_features = [('data', datatypes.Array(*(3,4,6)))] builder = neural_network.NeuralNetworkBuilder(input_features, [('output', None)], disable_rank5_shape_mapping=True) builder.add_sin(name='sin', input_name='data', output_name='output') spec = builder.spec shapes = [(1, 5, 7), (60, 5, 2), (22, 4, 9), (5, 3, 56)] flexible_shape_utils.add_multiarray_ndshape_enumeration(spec, feature_name='data', enumerated_shapes=shapes) shapes.append((3,4,6)) for s in shapes: x = np.random.rand(*s) expected = {'output': np.sin(x)} self._test_model(spec, {'data': x}, expected, useCPUOnly=True) def test_transpose_cpu(self): for rank in range(1, 6): axes = np.random.permutation(rank) axes = [axis - rank if np.random.choice([True, False]) else axis for axis in axes] input_shape = np.random.randint(low=2, high=6, size=rank) input_features = [('data', datatypes.Array(*input_shape))] output_features = [('output', None)] builder = neural_network.NeuralNetworkBuilder( input_features, output_features, disable_rank5_shape_mapping=True) builder.add_transpose(name='TransposeND', axes=axes, input_name='data', output_name='output') x = np.random.rand(*input_shape) input = {'data': x} expected = {'output': np.transpose(x, axes)} self._test_model(builder.spec, input, expected, useCPUOnly=True) def test_batched_mat_mul_cpu(self): a_shapes = [(10,), (4, 10), (10,), (10,), (2, 3), (1, 3, 4), (1, 3, 1, 2, 3), (2, 3, 1, 3, 4)] b_shapes = [(10,), (10,), (10, 3), (2, 10, 3), (3, 4), (3, 2, 4, 5), (1, 4, 3, 2), (2, 1, 2, 4, 5)] out_shapes = [(1, 1), (4, 1), (1, 3), (2, 1, 3), (2, 4), (3, 2, 3, 5), (1, 3, 4, 2, 2), (2, 3, 2, 3, 5)] for a_shape, b_shape, outShape in zip(a_shapes, b_shapes, out_shapes): input_shapes = [a_shape, b_shape] input_features = [ ('A', datatypes.Array(*input_shapes[0])), ('B', datatypes.Array(*input_shapes[1])) ] output_features = [('output', None)] builder = neural_network.NeuralNetworkBuilder( input_features, output_features, disable_rank5_shape_mapping=True) builder.add_batched_mat_mul(name='batched_mat_mul', input_names=['A', 'B'], output_name='output', transpose_a=False, transpose_b=False) a = np.random.rand(*input_shapes[0]) b = np.random.rand(*input_shapes[1]) input = {'A': a, 'B': b} expected = {'output': np.array(np.matmul(a, b))} shape_dict = {'output': outShape} self._test_model(builder.spec, input, expected, useCPUOnly=True, output_name_shape_dict=shape_dict) def test_batched_mat_mul_with_transposes_cpu(self): for transpose_a, transpose_b in itertools.product([True, False], [True, False]): a_shape = (3, 4) b_shape = (4, 5) a_shape = a_shape[::-1] if transpose_a else a_shape b_shape = b_shape[::-1] if transpose_b else b_shape input_shapes = [a_shape, b_shape] input_features = [ ('A', datatypes.Array(*input_shapes[0])), ('B', datatypes.Array(*input_shapes[1])) ] output_features = [('output', None)] builder = neural_network.NeuralNetworkBuilder( input_features, output_features, disable_rank5_shape_mapping=True ) builder.add_batched_mat_mul( name='BatchedMatMul', input_names=['A', 'B'], output_name='output', transpose_a=transpose_a, transpose_b=transpose_b ) a = np.random.rand(*input_shapes[0]) b = np.random.rand(*input_shapes[1]) inputs = {'A': a, 'B': b} a = a.T if transpose_a else a b = b.T if transpose_b else b expected = {'output': np.matmul(a, b)} self._test_model(builder.spec, inputs, expected, useCPUOnly=True) def test_batched_mat_mul_single_input_cpu( self, model_precision=_MLMODEL_FULL_PRECISION): X1 = 11 X2 = 23 W = np.random.rand(X1, X2) bias = np.random.rand(X2) input_shapes = [(X1,), (5, X1), (2, 3, X1), (4, 1, X1), (12, 5, 8, X1), (2, 3, 1, 5, X1)] for input_shape in input_shapes: x = np.random.rand(*input_shape) np_out = np.matmul(x, W) + bias expected = {'output': np_out} input_features = [('data', datatypes.Array(*input_shape))] output_features = [('output', None)] builder = neural_network.NeuralNetworkBuilder( input_features, output_features, disable_rank5_shape_mapping=True) builder.add_batched_mat_mul(name='batched_mat_mul', input_names=['data'], output_name='output', weight_matrix_rows=X1, weight_matrix_columns=X2, W=W, bias=bias) inputs = {'data': x} self._test_model( builder.spec, inputs, expected, model_precision=model_precision, useCPUOnly=True) def test_batched_mat_mul_single_input_half_precision_cpu(self): self.test_batched_mat_mul_single_input_cpu( model_precision=_MLMODEL_HALF_PRECISION) def test_embedding_nd_cpu( self, model_precision=_MLMODEL_FULL_PRECISION, use_cpu_only=True): vocab_size = 10 embedding_size = 19 W = np.random.rand(embedding_size, vocab_size) input_shapes = [(5, 1), (2, 3, 1), (4, 1, 1), (12, 5, 8, 1), (2, 3, 1, 5, 1)] for input_shape in input_shapes: x = np.random.randint(vocab_size, size=input_shape) np_out = np.take(np.transpose(W), np.squeeze(x, axis=-1), axis=0) expected = {'output': np_out} input_features = [('data', datatypes.Array(*input_shape))] output_features = [('output', None)] builder = neural_network.NeuralNetworkBuilder( input_features, output_features, disable_rank5_shape_mapping=True) builder.add_embedding_nd(name='embedding_nd', input_name='data', output_name='output', vocab_size=vocab_size, embedding_size=embedding_size, W=W) input = {'data': x.astype(np.float32)} self._test_model( builder.spec, input, expected, model_precision=model_precision, useCPUOnly=use_cpu_only) def test_embedding_nd_half_precision_cpu(self): self.test_embedding_nd_cpu( model_precision=_MLMODEL_HALF_PRECISION, use_cpu_only=True) def test_embedding_nd_GPU(self): self.test_embedding_nd_cpu( model_precision=_MLMODEL_FULL_PRECISION, use_cpu_only=False) def test_embedding_nd_half_precision_GPU(self): self.test_embedding_nd_cpu( model_precision=_MLMODEL_HALF_PRECISION, use_cpu_only=False) def test_softmax_nd_cpu(self): for rank in range(1, 6): for axis in range(-rank, rank): input_shape = np.random.randint(low=2, high=5, size=rank) input_features = [('data', datatypes.Array(*input_shape))] output_features = [('output', None)] builder = neural_network.NeuralNetworkBuilder( input_features, output_features, disable_rank5_shape_mapping=True) builder.add_softmax_nd(name='softmax_nd', input_name='data', output_name='output', axis=axis) x = np.random.rand(*input_shape) input = {'data': x} y = np.exp(x - np.max(x, axis=axis, keepdims=True)) y = y / np.sum(y, axis=axis, keepdims=True) expected = {'output': y} self._test_model(builder.spec, input, expected, useCPUOnly=True) def test_concat_nd_cpu(self): for rank in range(1, 6): for axis in range(-rank, rank): n_inputs = np.random.choice(range(2, 5)) output_shape = np.random.randint(low=2, high=5, size=rank) output_shape[axis] = 0 input_shapes = [] input_features = [] input_names = [] for _ in range(n_inputs): input_shapes.append(np.copy(output_shape)) input_shapes[-1][axis] = np.random.choice(range(2, 8)) output_shape[axis] += input_shapes[-1][axis] for i, input_dim in enumerate(input_shapes): input_name = 'input_%s' % str(i) input_names.append(input_name) input_features.append((input_name, datatypes.Array(*input_dim))) output_features = [('output', None)] builder = neural_network.NeuralNetworkBuilder(input_features, output_features, disable_rank5_shape_mapping=True) builder.add_concat_nd(name='concat_nd', input_names=input_names, output_name='output', axis=axis) input_tensors = [] for input_dim in input_shapes: input_tensors.append(np.random.rand(*input_dim)) input = dict(zip(input_names, input_tensors)) expected = {'output': np.concatenate(input_tensors, axis)} self._test_model(builder.spec, input, expected, useCPUOnly=True) def test_fill_like_cpu(self): for rank in range(1, 6): target_shape = np.random.randint(low=2, high=6, size=rank) value = float(np.random.rand()) input_features = [('tensor', datatypes.Array(*target_shape))] builder = neural_network.NeuralNetworkBuilder( input_features, [('output', None)], disable_rank5_shape_mapping=True) builder.add_fill_like(name='fill_like', input_name='tensor', output_name='output', value=value) tensor = np.random.rand(*target_shape) input = {'tensor': tensor} expected = {'output': np.zeros(target_shape) + value} self._test_model(builder.spec, input, expected, useCPUOnly=True) def test_fill_static_cpu(self): for rank in range(1, 6): shape = np.random.randint(low=2, high=8, size=rank) input_features = [('data', datatypes.Array(*shape))] value = float(np.random.rand()) builder = neural_network.NeuralNetworkBuilder( input_features, [('output', None)], disable_rank5_shape_mapping=True) builder.add_fill_static(name='fill_static', output_name='tmp', output_shape=list(shape), value=value) builder.add_elementwise('add_layer', ['data', 'tmp'], 'output', mode='ADD') data = np.random.rand(*shape) input = {'data': data} expected = {'output': data + value} self._test_model(builder.spec, input, expected, useCPUOnly=True) def test_fill_dynamic_cpu(self): for rank in range(1, 6): input_shape = np.random.randint(low=2, high=8, size=rank) value = float(np.random.rand()) input_features = [('shape', datatypes.Array(len(input_shape)))] builder = neural_network.NeuralNetworkBuilder( input_features, [('output', None)], disable_rank5_shape_mapping=True) builder.add_fill_dynamic(name='fill_dynamic', input_name='shape', output_name='output', value=value) input = {'shape': np.array(input_shape, dtype='float')} expected = {'output': np.zeros(input_shape) + value} self._test_model(builder.spec, input, expected, useCPUOnly=True) def test_broadcast_to_like_cpu(self): for rank in range(1, 6): input_shape = np.random.randint(low=2, high=8, size=rank) mask = [np.random.choice([True, False, False]) for _ in range(rank)] input_shape = np.where(mask, 1, input_shape) target_rank = np.random.randint(low=rank, high=6) target_shape = [np.random.randint(low=2, high=8) if (-i > rank or input_shape[i] == 1) else input_shape[i] for i in range(-1, -target_rank - 1, -1)][::-1] input_features = [('data', datatypes.Array(*input_shape)), ('tensor', datatypes.Array(*target_shape))] builder = neural_network.NeuralNetworkBuilder( input_features, [('output', None)], disable_rank5_shape_mapping=True) builder.add_broadcast_to_like(name='broadcast_to_like', input_names=['data', 'tensor'], output_name='output') data = np.random.rand(*input_shape) tensor = np.random.rand(*target_shape) inputs = {'data': data, 'tensor': tensor} expected = {'output': np.broadcast_to(data, target_shape)} self._test_model(builder.spec, inputs, expected, useCPUOnly=True) def test_broadcast_to_static_cpu(self): for rank in range(1, 6): input_shape = np.random.randint(low=2, high=8, size=rank) mask = [np.random.choice([True, False, False]) for _ in range(rank)] input_shape = np.where(mask, 1, input_shape) target_rank = np.random.randint(low=rank, high=6) target_shape = [np.random.randint(low=2, high=8) if (-i > rank or input_shape[i] == 1) else input_shape[i] for i in range(-1, -target_rank - 1, -1)][::-1] input_features = [('data', datatypes.Array(*input_shape))] builder = neural_network.NeuralNetworkBuilder( input_features, [('output', None)], disable_rank5_shape_mapping=True) builder.add_broadcast_to_static(name='broadcast_to_static', input_name='data', output_name='output', output_shape=list(target_shape)) data = np.random.rand(*input_shape) input = {'data': data} expected = {'output': np.broadcast_to(data, target_shape)} self._test_model(builder.spec, input, expected, useCPUOnly=True) def test_broadcast_to_dynamic_cpu(self): for rank in range(1, 6): input_shape = np.random.randint(low=2, high=8, size=rank) mask = [np.random.choice([True, False, False]) for _ in range(rank)] input_shape = np.where(mask, 1, input_shape) target_rank = np.random.randint(low=rank, high=6) target_shape = [np.random.randint(low=2, high=8) if (-i > rank or input_shape[i] == 1) else input_shape[i] for i in range(-1, -target_rank - 1, -1)][::-1] input_features = [('data', datatypes.Array(*input_shape)), ('shape', datatypes.Array(len(target_shape)))] builder = neural_network.NeuralNetworkBuilder( input_features, [('output', None)], disable_rank5_shape_mapping=True) builder.add_broadcast_to_dynamic(name='broadcast_to_dynamic', input_names=['data', 'shape'], output_name='output') data = np.random.rand(*input_shape) inputs = {'data': data, 'shape': np.array(target_shape, dtype='float')} expected = {'output': np.broadcast_to(data, target_shape)} self._test_model(builder.spec, inputs, expected, useCPUOnly=True) def test_trigonometry_cpu(self): ops = ['sin', 'cos', 'tan', 'asin', 'acos', 'atan', 'sinh', 'cosh', 'tanh', 'asinh', 'acosh', 'atanh'] for op in ops: for rank in range(1, 6): shape = np.random.randint(low=2, high=8, size=rank) input_features = [('data', datatypes.Array(*shape))] builder = neural_network.NeuralNetworkBuilder( input_features, [('output', None)], disable_rank5_shape_mapping=True) x = np.random.rand(*shape) if op == 'sin': builder.add_sin(name=op, input_name='data', output_name='output') expected = {'output': np.sin(x)} elif op == 'cos': builder.add_cos(name=op, input_name='data', output_name='output') expected = {'output': np.cos(x)} elif op == 'tan': builder.add_tan(name=op, input_name='data', output_name='output') expected = {'output': np.tan(x)} elif op == 'asin': builder.add_asin(name=op, input_name='data', output_name='output') expected = {'output': np.arcsin(x)} elif op == 'acos': builder.add_acos(name=op, input_name='data', output_name='output') expected = {'output': np.arccos(x)} elif op == 'atan': builder.add_atan(name=op, input_name='data', output_name='output') expected = {'output': np.arctan(x)} elif op == 'sinh': builder.add_sinh(name=op, input_name='data', output_name='output') expected = {'output': np.sinh(x)} elif op == 'cosh': builder.add_cosh(name=op, input_name='data', output_name='output') expected = {'output': np.cosh(x)} elif op == 'tanh': builder.add_tanh(name=op, input_name='data', output_name='output') expected = {'output': np.tanh(x)} elif op == 'asinh': builder.add_asinh(name=op, input_name='data', output_name='output') expected = {'output': np.arcsinh(x)} elif op == 'acosh': x = np.random.choice([10, np.e, 1], tuple(shape)).astype(np.float32) builder.add_acosh(name=op, input_name='data', output_name='output') expected = {'output': np.arccosh(x)} elif op == 'atanh': builder.add_atanh(name=op, input_name='data', output_name='output') expected = {'output': np.arctanh(x)} self._test_model(builder.spec, {'data': x}, expected, useCPUOnly=True) def test_exp2_cpu(self): for rank in range(1, 6): shape = np.random.randint(low=2, high=8, size=rank) input_features = [('data', datatypes.Array(*shape))] builder = neural_network.NeuralNetworkBuilder( input_features, [('output', None)], disable_rank5_shape_mapping=True) builder.add_exp2(name='exp2', input_name='data', output_name='output') x = np.random.rand(*shape) input = {'data': x} expected = {'output': np.exp2(x)} self._test_model(builder.spec, input, expected, useCPUOnly=True) def test_elementwise_binary_cpu(self): input_names = ['A', 'B'] test_cases = ['greater', 'less', 'equal', 'not_equal', 'greater_equal', 'less_equal', 'logical_and', 'logical_or', 'logical_xor', 'add', 'subtract', 'multiply', 'divide', 'power', 'maximum', 'minimum', 'floor_divide', 'mod'] for test_case in test_cases: for _ in range(10): rank_a = np.random.randint(low=1, high=6) rank_b = np.random.randint(low=1, high=6) rank_out = max(rank_a, rank_b) shape_a = np.random.randint(low=2, high=8, size=rank_a) shape_b = np.random.randint(low=2, high=8, size=rank_b) for i in range(-1, -rank_out - 1, -1): dims = [] if -i <= rank_a: dims.append(shape_a[i]) if -i <= rank_b: dims.append(shape_b[i]) dim = np.random.choice(dims) if -i <= rank_a: shape_a[i] = np.random.choice([1, dim]) if -i <= rank_b: shape_b[i] = np.random.choice([1, dim]) input_shapes = [shape_a, shape_b] input_features = [('A', datatypes.Array(*input_shapes[0])), ('B', datatypes.Array(*input_shapes[1]))] builder = neural_network.NeuralNetworkBuilder(input_features, [ ('output', None)], disable_rank5_shape_mapping=True) func = getattr(np, test_case) if test_case == 'greater': builder.add_greater_than(test_case, input_names=input_names, output_name='output') elif test_case == 'less': builder.add_less_than(test_case, input_names=input_names, output_name='output') elif test_case == 'equal': builder.add_equal(test_case, input_names=input_names, output_name='output') elif test_case == 'not_equal': builder.add_not_equal(test_case, input_names=input_names, output_name='output') elif test_case == 'greater_equal': builder.add_greater_than(test_case, input_names=input_names, output_name='output', use_greater_than_equal=True) elif test_case == 'less_equal': builder.add_less_than(test_case, input_names=input_names, output_name='output', use_less_than_equal=True) elif test_case == 'logical_and': builder.add_logical(test_case, input_names=input_names, output_name='output', mode='AND') elif test_case == 'logical_or': builder.add_logical(test_case, input_names=input_names, output_name='output', mode='OR') elif test_case == 'logical_xor': builder.add_logical(test_case, input_names=input_names, output_name='output', mode='XOR') elif test_case == 'add': builder.add_add_broadcastable(test_case, input_names=input_names, output_name='output') elif test_case == 'subtract': builder.add_subtract_broadcastable(test_case, input_names=input_names, output_name='output') elif test_case == 'multiply': builder.add_multiply_broadcastable(test_case, input_names=input_names, output_name='output') elif test_case == 'divide': builder.add_divide_broadcastable(test_case, input_names=input_names, output_name='output') elif test_case == 'power': builder.add_pow_broadcastable(test_case, input_names=input_names, output_name='output') elif test_case == 'maximum': builder.add_max_broadcastable(test_case, input_names=input_names, output_name='output') elif test_case == 'minimum': builder.add_min_broadcastable(test_case, input_names=input_names, output_name='output') elif test_case == 'floor_divide': builder.add_floor_div_broadcastable(test_case, input_names=input_names, output_name='output') elif test_case == 'mod': builder.add_mod_broadcastable(test_case, input_names=input_names, output_name='output') a = np.random.rand(*input_shapes[0]) b = np.random.rand(*input_shapes[1]) input = {'A': a, 'B': b} expected = {'output': func(a, b, dtype=np.float32)} self._test_model(builder.spec, input, expected, useCPUOnly=True) def test_elementwise_boolean_unary_cpu(self): input_names = ['input'] shapes = [(1, 2, 3, 1), (3, 1, 2, 1, 2), (1, 2, 1, 3), (2, 3), (2, 1, 1), (2, 3, 4), (2, 4), (1,), (1,)] test_cases = ['greater', 'less', 'equal', 'not_equal', 'greater_equal', 'less_equal'] for test_case in test_cases: for shape in shapes: input_features = [('input', datatypes.Array(*shape))] b = np.random.rand() builder = neural_network.NeuralNetworkBuilder( input_features, [('output', None)], disable_rank5_shape_mapping=True) func = getattr(np, test_case) if test_case == 'greater': builder.add_greater_than(test_case, input_names=input_names, output_name='output', alpha=b) elif test_case == 'less': builder.add_less_than(test_case, input_names=input_names, output_name='output', alpha=b) elif test_case == 'equal': builder.add_equal(test_case, input_names=input_names, output_name='output', alpha=b) elif test_case == 'not_equal': builder.add_not_equal(test_case, input_names=input_names, output_name='output', alpha=b) elif test_case == 'greater_equal': builder.add_greater_than(test_case, input_names=input_names, output_name='output', use_greater_than_equal=True, alpha=b) elif test_case == 'less_equal': builder.add_less_than(test_case, input_names=input_names, output_name='output', use_less_than_equal=True, alpha=b) a = np.random.rand(*shape) input = {'input': a} expected = {'output': func(a, b, dtype=np.float32)} self._test_model(builder.spec, input, expected, useCPUOnly=True) def test_logical_not_cpu(self): input_names = ['input'] shapes = [(1, 2, 3, 1), (3, 1, 2, 1, 2), (1, 2, 1, 3), (2, 3), (2, 1, 1), (2, 3, 4), (2, 4), (1,), (1,)] for shape in shapes: input_features = [('input', datatypes.Array(*shape))] builder = neural_network.NeuralNetworkBuilder( input_features, [('output', None)], disable_rank5_shape_mapping=True) builder.add_logical('logical_not', input_names=input_names, output_name='output', mode='NOT') a = np.random.rand(*shape) input = {'input': a} expected = {'output': np.logical_not(a)} self._test_model(builder.spec, input, expected, useCPUOnly=True) def test_stack_cpu(self): for input_rank in range(1, 5): for axis in range(-input_rank - 1, input_rank + 1): n_inputs = np.random.choice(range(2, 5)) input_shape = np.random.randint(low=2, high=5, size=input_rank) input_features = [] input_names = [] for i in range(n_inputs): input_name = 'input_%s' % str(i) input_names.append(input_name) input_features.append( (input_name, datatypes.Array(*input_shape))) output_features = [('output', None)] builder = neural_network.NeuralNetworkBuilder( input_features, output_features, disable_rank5_shape_mapping=True) builder.add_stack(name='stack', input_names=input_names, output_name='output', axis=axis) input_tensors = [] for _ in range(n_inputs): input_tensors.append(np.random.rand(*input_shape)) input = dict(zip(input_names, input_tensors)) expected = {'output': np.stack(input_tensors, axis)} self._test_model(builder.spec, input, expected, useCPUOnly=True) def test_ceil_cpu(self): for rank in range(1, 6): shape = np.random.randint(low=2, high=8, size=rank) input_features = [('data', datatypes.Array(*shape))] output_features = [('output', datatypes.Array(*shape))] builder = neural_network.NeuralNetworkBuilder( input_features, output_features, disable_rank5_shape_mapping=True) builder.add_ceil(name='ceil', input_name='data', output_name='output') x = np.random.rand(*shape) inputs = {'data': x} expected = {'output': np.ceil(x)} self._test_model(builder.spec, inputs, expected, useCPUOnly=True) def test_floor_cpu(self): for rank in range(1, 6): shape = np.random.randint(low=2, high=8, size=rank) input_features = [('data', datatypes.Array(*shape))] output_features = [('output', datatypes.Array(*shape))] builder = neural_network.NeuralNetworkBuilder( input_features, output_features, disable_rank5_shape_mapping=True) builder.add_floor(name='floor', input_name='data', output_name='output') x = np.random.rand(*shape) inputs = {'data': x} expected = {'output': np.floor(x)} self._test_model(builder.spec, inputs, expected, useCPUOnly=True) def test_round_cpu(self): for rank in range(1, 6): shape = np.random.randint(low=2, high=8, size=rank) input_features = [('data', datatypes.Array(*shape))] output_features = [('output', datatypes.Array(*shape))] builder = neural_network.NeuralNetworkBuilder( input_features, output_features, disable_rank5_shape_mapping=True) builder.add_round(name='round', input_name='data', output_name='output') x = np.float32(np.random.rand(*shape) * np.random.randint(low=-100, high=101)) inputs = {'data': x} expected = {'output': np.around(x)} self._test_model(builder.spec, inputs, expected, useCPUOnly=True) def test_sign_cpu(self): for rank in range(1, 6): shape = np.random.randint(low=2, high=8, size=rank) input_features = [('data', datatypes.Array(*shape))] output_features = [('output', datatypes.Array(*shape))] builder = neural_network.NeuralNetworkBuilder( input_features, output_features, disable_rank5_shape_mapping=True) builder.add_sign(name='sign', input_name='data', output_name='output') x = np.random.choice([-np.random.rand(1), 0.0, np.random.rand(1)], tuple(shape)).astype(np.float32) inputs = {'data': x} expected = {'output': np.sign(x)} self._test_model(builder.spec, inputs, expected, useCPUOnly=True) def test_clip_cpu(self): for rank in range(1, 6): shape = np.random.randint(low=2, high=6, size=rank) input_features = [('data', datatypes.Array(*shape))] output_features = [('output', datatypes.Array(*shape))] x = np.random.rand(*shape) min_value = np.percentile(x, 25) max_value = np.percentile(x, 75) input = {'data': x} builder = neural_network.NeuralNetworkBuilder( input_features, output_features, disable_rank5_shape_mapping=True) builder.add_clip(name='clip', input_name='data', output_name='output', min_value=min_value, max_value=max_value) expected = {'output': np.clip(x, min_value, max_value)} self._test_model(builder.spec, input, expected, useCPUOnly=True) def test_split_nd_cpu(self): for rank in range(1, 6): for axis in range(-rank, rank): n_outputs = np.random.choice(range(2, 4)) input_shape = np.random.randint(low=2, high=5, size=rank) input_shape[axis] = 0 output_shapes = [] output_features = [] output_names = [] almost_equal = random.choice([True, False]) remainder = np.random.choice( range(1, n_outputs)) if almost_equal else 0 value = np.random.choice(range(2, 5)) for k in range(n_outputs): output_shapes.append(np.copy(input_shape)) output_shapes[-1][ axis] = value + 1 if k < remainder else value input_shape[axis] += output_shapes[-1][axis] for i in range(n_outputs): output_name = 'output_%s' % str(i) output_names.append(output_name) output_features.append( (output_name, None)) input_features = [('data', datatypes.Array(*input_shape))] builder = neural_network.NeuralNetworkBuilder( input_features, output_features, disable_rank5_shape_mapping=True) builder.add_split_nd(name='split_nd', input_name='data', output_names=output_names, axis=axis, num_splits=n_outputs) x = np.random.rand(*input_shape) input = {'data': x} expected = dict( zip( output_names, np.array_split(x, n_outputs, axis=axis) if almost_equal else np.split(x, n_outputs, axis=axis) ) ) # Explicitly trying to compare against both versions of numpy split self._test_model(builder.spec, input, expected, useCPUOnly=True) def test_split_nd_with_split_sizes_cpu(self): for rank in range(1, 6): for axis in range(-rank, rank): n_outputs = np.random.choice(range(2, 4)) input_shape = np.random.randint(low=2, high=5, size=rank) input_shape[axis] = 0 output_shapes, output_features, output_names = [], [], [] sections, split_sizes = [], [] for _ in range(n_outputs): output_shapes.append(np.copy(input_shape)) output_shapes[-1][axis] = np.random.choice(range(2, 5)) input_shape[axis] += output_shapes[-1][axis] sections.append(input_shape[axis]) split_sizes.append(output_shapes[-1][axis]) sections.pop() for i in range(n_outputs): output_name = 'output_%s' % str(i) output_names.append(output_name) output_features.append( (output_name, None)) input_features = [('data', datatypes.Array(*input_shape))] builder = neural_network.NeuralNetworkBuilder( input_features, output_features, disable_rank5_shape_mapping=True) builder.add_split_nd(name='split_nd', input_name='data', output_names=output_names, axis=axis, split_sizes=split_sizes) x = np.random.rand(*input_shape) input = {'data': x} expected = dict( zip(output_names, np.split(x, sections, axis=axis))) self._test_model(builder.spec, input, expected, useCPUOnly=True) def test_slice_static_cpu(self): for rank in range(1, 6): for _ in range(200): input_shape = np.array([5 for _ in range(rank)]) objs, strides, begin_masks, end_ids, end_masks, begin_ids = [], [], [], [], [], [] for dim in range(rank): stride = random.choice([-3, -1, 1, 2]) begin_mask = random.choice([True, False]) end_mask = random.choice([True, False]) length = 0 while length <= 0: begin_id = np.random.randint(low=-input_shape[dim], high=input_shape[dim]) end_id = np.random.randint(low=-input_shape[dim], high=input_shape[dim]) obj = slice(None if begin_mask else begin_id, None if end_mask else end_id, stride) length = np.arange(input_shape[dim])[(obj,)].shape[0] objs.append(obj), strides.append(stride), begin_masks.append( begin_mask) end_masks.append(end_mask), begin_ids.append( begin_id), end_ids.append(end_id) input_features = [('data', datatypes.Array(*input_shape))] output_features = [('output', None)] builder = neural_network.NeuralNetworkBuilder( input_features, output_features, disable_rank5_shape_mapping=True) builder.add_slice_static('slice_static', 'data', 'output', begin_ids=begin_ids, end_ids=end_ids, strides=strides, begin_masks=begin_masks, end_masks=end_masks) x = np.random.rand(*input_shape) inputs = {'data': x} expected = {'output': x[tuple(objs)]} self._test_model(builder.spec, inputs, expected, useCPUOnly=True) def test_slice_dynamic_cpu(self): for rank in range(1, 6): input_shape = np.array([5 for _ in range(rank)]) objs, strides, begin_masks, end_ids, end_masks, begin_ids = [], [], [], [], [], [] for dim in range(rank): stride = random.choice([-3, -1, 1, 2]) begin_mask = random.choice([True, False]) end_mask = random.choice([True, False]) length = 0 while length <= 0: begin_id = np.random.randint(low=-input_shape[dim], high=input_shape[dim]) end_id = np.random.randint(low=-input_shape[dim], high=input_shape[dim]) obj = slice(None if begin_mask else begin_id, None if end_mask else end_id, stride) length = np.arange(input_shape[dim])[(obj,)].shape[0] objs.append(obj), strides.append(stride), begin_masks.append( begin_mask) end_masks.append(end_mask), begin_ids.append( begin_id), end_ids.append(end_id) # test different number of inputs, from 2 inputs up to 6 inputs # when num_inputs == 2, begin_ids are inputs, rest are read from parameters # when num_inputs == 6, all read from inputs, none are read from parameters for num_inputs in [2, 3, 4, 5, 6]: x = np.random.rand(*input_shape) input_features = [('data', datatypes.Array(*input_shape))] input_names = ['data'] inputs = dict() inputs['data'] = x if num_inputs == 2: input_features = [('data', datatypes.Array(*input_shape)), ('begin_ids', datatypes.Array(len(begin_ids)))] input_names = ['data', 'begin_ids'] inputs['begin_ids'] = np.array(begin_ids, dtype=np.int32) elif num_inputs == 3: input_features = [('data', datatypes.Array(*input_shape)), ('begin_ids', datatypes.Array(len(begin_ids))), ('end_ids', datatypes.Array(len(end_ids)))] input_names = ['data', 'begin_ids', 'end_ids'] inputs['begin_ids'] = np.array(begin_ids, dtype=np.int32) inputs['end_ids'] = np.array(end_ids, dtype=np.int32) elif num_inputs == 4: input_features = [('data', datatypes.Array(*input_shape)), ('begin_ids', datatypes.Array(len(begin_ids))), ('end_ids', datatypes.Array(len(end_ids))), ('strides', datatypes.Array(len(strides)))] input_names = ['data', 'begin_ids', 'end_ids', 'strides'] inputs['begin_ids'] = np.array(begin_ids, dtype=np.int32) inputs['end_ids'] = np.array(end_ids, dtype=np.int32) inputs['strides'] = np.array(strides, dtype=np.int32) elif num_inputs == 5: input_features = [('data', datatypes.Array(*input_shape)), ('begin_ids', datatypes.Array(len(begin_ids))), ('end_ids', datatypes.Array(len(end_ids))), ('strides', datatypes.Array(len(strides))), ('begin_masks', datatypes.Array(len(begin_masks)))] input_names = ['data', 'begin_ids', 'end_ids', 'strides', 'begin_masks'] inputs['begin_ids'] = np.array(begin_ids, dtype=np.int32) inputs['end_ids'] = np.array(end_ids, dtype=np.int32) inputs['strides'] = np.array(strides, dtype=np.int32) inputs['begin_masks'] = np.array(begin_masks, dtype=np.int32) elif num_inputs == 6: input_features = [('data', datatypes.Array(*input_shape)), ('begin_ids', datatypes.Array(len(begin_ids))), ('end_ids', datatypes.Array(len(end_ids))), ('strides', datatypes.Array(len(strides))), ('begin_masks', datatypes.Array(len(begin_masks))), ('end_masks', datatypes.Array(len(end_masks)))] input_names = ['data', 'begin_ids', 'end_ids', 'strides', 'begin_masks', 'end_masks'] inputs['begin_ids'] = np.array(begin_ids, dtype=np.int32) inputs['end_ids'] = np.array(end_ids, dtype=np.int32) inputs['strides'] = np.array(strides, dtype=np.int32) inputs['begin_masks'] = np.array(begin_masks, dtype=np.int32) inputs['end_masks'] = np.array(end_masks, dtype=np.int32) builder = neural_network.NeuralNetworkBuilder( input_features, [('output', None)], disable_rank5_shape_mapping=True) if num_inputs == 2: builder.add_slice_dynamic('slice_dynamic', input_names, 'output', end_ids=end_ids, strides=strides, begin_masks=begin_masks, end_masks=end_masks) elif num_inputs == 3: builder.add_slice_dynamic('slice_dynamic', input_names, 'output', strides=strides, begin_masks=begin_masks, end_masks=end_masks) elif num_inputs == 4: builder.add_slice_dynamic('slice_dynamic', input_names, 'output', begin_masks=begin_masks, end_masks=end_masks) elif num_inputs == 5: builder.add_slice_dynamic('slice_dynamic', input_names, 'output', end_masks=end_masks) elif num_inputs == 6: builder.add_slice_dynamic('slice_dynamic', input_names, 'output') expected = {'output': x[tuple(objs)]} self._test_model(builder.spec, inputs, expected, useCPUOnly=True) @unittest.skip('fix') def test_tile_cpu(self): for rank in range(1, 6): input_shape = np.random.randint(low=2, high=5, size=rank) reps = list(np.random.randint(low=1, high=4, size=rank)) input_features = [('data', datatypes.Array(*input_shape))] output_features = [('output', None)] builder = neural_network.NeuralNetworkBuilder( input_features, output_features, disable_rank5_shape_mapping=True ) builder.add_tile('Tile', 'data', 'output', reps) x = np.random.rand(*input_shape) input = {'data': x} expected = {'output': np.tile(x, reps)} self._test_model(builder.spec, input, expected, useCPUOnly=True) def test_sliding_windows_cpu(self): def numpy_sliding_windows(a, np_axis, np_size, np_step): n = (a.shape[np_axis] - np_size) // np_step + 1 shape = list(a.shape) shape[np_axis] = n if np_axis < 0: np_axis += len(shape) shape.insert(np_axis + 1, np_size) strides = list(a.strides) effstride = strides[np_axis] * np_step strides.insert(np_axis, effstride) return np.lib.stride_tricks.as_strided(a, shape, strides) for rank in range(1, 5): for axis in range(-rank, rank): input_shape = np.random.randint(low=2, high=5, size=rank) output_shape = list(input_shape) window_size = np.random.randint(low=1, high=input_shape[axis]) length = 0 while length <= 0: step = np.random.randint(low=1, high=input_shape[axis]) length = (input_shape[axis] - window_size) // step + 1 output_shape[axis] = length pos_axis = axis if axis >= 0 else axis + rank output_shape.insert(pos_axis + 1, window_size) input_features = [('data', datatypes.Array(*input_shape))] output_features = [('output', None)] builder = neural_network.NeuralNetworkBuilder( input_features, output_features, disable_rank5_shape_mapping=True) builder.add_sliding_windows('sliding_windows', input_name='data', output_name='output', axis=axis, window_size=window_size, step=step) x = np.random.rand(*input_shape) input = {'data': x} expected = {'output': numpy_sliding_windows(x, axis, window_size, step)} self._test_model(builder.spec, input, expected, useCPUOnly=True) def test_range_static_cpu(self): params = [(-10.4, 23, 12.2), (0, 1000, 1), (50.5, 90.5, 1.5), (5, 8, 2), (5, 8, 98), (5, 8, 1.5), (10, 5, -0.6), (24, -65, -2)] for param in params: start, end, step = param input_features = [('multiplicative_input', datatypes.Array(1))] builder = neural_network.NeuralNetworkBuilder( input_features, [('output', None)], disable_rank5_shape_mapping=True) builder.add_range_static('range_static', 'output_range', end=end, start=start, step=step) builder.add_multiply_broadcastable( name='multiply_broadcastable', input_names=['multiplicative_input', 'output_range'], output_name='output') # save the model model_dir = tempfile.mkdtemp() model_path = os.path.join(model_dir, 'test_layer.mlmodel') coremltools.utils.save_spec(builder.spec, model_path) inputs = dict() inputs['multiplicative_input'] = np.ones((1,), dtype=np.float64) expected = {'output': np.arange(start, end, step)} self._test_model(builder.spec, inputs, expected, useCPUOnly=True) def test_range_dynamic_cpu(self): params = [(-10.4, 23, 12.2), (0, 1000, 1), (50.5, 90.5, 1.5), (5, 8, 2), (5, 8, 98), (5, 8, 1.5), (10, 5, -0.6), (24, -65, -2)] # input size == 1: end is input, start and step are read from parameters # input size == 2: end, start are inputs, step is read from parameters # input size == 3: start, end, step are all inputs, none of the parameters are used. for num_inputs in [1, 2, 3]: for param in params: inputs = dict() start, end, step = param if num_inputs == 1: input_features = [('end', datatypes.Array(1))] elif num_inputs == 2: input_features = [('end', datatypes.Array(1)), ('start', datatypes.Array(1))] elif num_inputs == 3: input_features = [('end', datatypes.Array(1)), ('start', datatypes.Array(1)), ('step', datatypes.Array(1))] builder = neural_network.NeuralNetworkBuilder( input_features, [('output', None)], disable_rank5_shape_mapping=True) if num_inputs == 1: inputs['end'] = end * np.ones((1,), dtype=np.float64) builder.add_range_dynamic('range_dynamic', output_name='output', input_names=['end'], start=start, step=step) elif num_inputs == 2: inputs['end'] = end * np.ones((1,), dtype=np.float64) inputs['start'] = start * np.ones((1,), dtype=np.float64) builder.add_range_dynamic('range_dynamic', output_name='output', input_names=['end', 'start'], step=step) elif num_inputs == 3: inputs['end'] = end * np.ones((1,), dtype=np.float64) inputs['start'] = start * np.ones((1,), dtype=np.float64) inputs['step'] = step * np.ones((1,), dtype=np.float64) builder.add_range_dynamic('range_dynamic', output_name='output', input_names=['end', 'start', 'step']) expected = {'output': np.arange(start, end, step)} self._test_model(builder.spec, inputs, expected, useCPUOnly=True) def test_linear_activation_different_ranks_cpu(self): for input_dim in [(10, 15), (10, 15, 2, 3), (10, 2, 4, 15, 1, 4), (6,)]: input_features = [('data', datatypes.Array(*input_dim))] output_features = [('output', datatypes.Array(*input_dim))] builder = neural_network.NeuralNetworkBuilder( input_features, output_features, disable_rank5_shape_mapping=True) builder.add_activation(name='activation', non_linearity='LINEAR', input_name='data', output_name='output', params=[34.0, 67.0]) x = np.random.rand(*input_dim) input = {'data': x} expected = {'output': 34.0 * x + 67.0} self._test_model(builder.spec, input, expected, useCPUOnly=True) def test_topk(self): test_input_shapes = [(9,), (8, 6), (9, 8, 10), (5, 9, 7, 9), (12, 8, 6, 6, 7)] K = [3, 5] axes = [[0], [0, 1], [1, 2], [0, 3, 1], [1, 3, 4]] for ii, input_shape in enumerate(test_input_shapes): for k in K: for n_inputs in [1, 2]: for bottom_k_flag in [False, True]: for axis in axes[ii]: for negative_axis in [False, True]: if negative_axis: axis = axis - len(input_shape) input_features = [('data', datatypes.Array(*input_shape))] output_features = [('values', None), ('indices', None)] input_names = ['data'] output_names = ['values', 'indices'] if n_inputs == 2: input_names.append('k_in') input_features.append(('k_in', datatypes.Array(1))) builder = neural_network.NeuralNetworkBuilder( input_features, output_features, disable_rank5_shape_mapping=True) builder.add_topk('topk', input_names, output_names, k=k, axis=axis, use_bottom_k=bottom_k_flag) data = np.random.randint(low=0, high=int(np.prod(input_shape)), size=input_shape) data = data.astype(np.float32) input = {'data': data} if n_inputs == 2: input['k_in'] = k * np.ones([1], dtype=np.float32) # numpy reference values if bottom_k_flag: ref_indices = np.argsort(data, axis=axis) else: ref_indices = np.argsort(-data, axis=axis) slc = [slice(None)] * len(input_shape) slc[axis] = slice(0, k) ref_indices = ref_indices[tuple(slc)] ref_values = np.take_along_axis(data, ref_indices, axis=axis) expected = {'values': ref_values, 'indices': ref_indices} self._test_model(builder.spec, input, expected, useCPUOnly=True) def test_rank_preserving_reshape(self): input_shapes = [(20, 10), (20, 10, 5), (10, 3, 5)] target_shapes = [(5, -1), (0, 2, 25), (25, 0, -1)] output_shapes = [(5, 40), (20, 2, 25), (25, 3, 2)] for i in range(len(input_shapes)): input_features = [('data', datatypes.Array(*input_shapes[i]))] output_features = [('output', None)] builder = neural_network.NeuralNetworkBuilder( input_features, output_features, disable_rank5_shape_mapping=True) builder.add_rank_preserving_reshape( name='rank_preserving_reshape', input_name='data', output_name='output', output_shape=target_shapes[i]) x = np.random.rand(*input_shapes[i]) input = {'data': x} expected = {'output': np.reshape(x, output_shapes[i])} self._test_model(builder.spec, input, expected, useCPUOnly=True) def test_expand_dims(self): input_shapes = [(10, 5), (10, 5), (10, 5), (10, 5), (10,)] axes = [(0, 1), (0, 2), (2, 0), (-2, -1), (1, 0, -2)] output_shapes = [(1, 1, 10, 5), (1, 10, 1, 5), (1, 10, 1, 5), (10, 5, 1, 1), (1, 1, 1, 10)] for i in range(len(input_shapes)): input_features = [('data', datatypes.Array(*input_shapes[i]))] output_features = [('output', None)] builder = neural_network.NeuralNetworkBuilder( input_features, output_features, disable_rank5_shape_mapping=True) builder.add_expand_dims( name='expand_dims', input_name='data', output_name='output', axes=axes[i] ) x = np.random.rand(*input_shapes[i]) input = {'data': x} expected = {'output': np.reshape(x, output_shapes[i])} self._test_model(builder.spec, input, expected, useCPUOnly=True) def test_squeeze(self): input_shapes = [(1, 1, 10, 5), (1, 10, 1, 5), (10, 5, 1, 1), (10, 5, 1, 1), (1,), (10, 5, 1, 1), (3, 1, 7)] axes = [(0, 1), (0, 2), (-2, -1), (-1, -2), (0,), (3, -2), (1,)] output_shapes = [(10, 5), (10, 5), (10, 5), (10, 5), (1,), (10, 5), (3, 7)] for i in range(len(input_shapes)): input_features = [('data', datatypes.Array(*input_shapes[i]))] output_features = [('output', None)] builder = neural_network.NeuralNetworkBuilder( input_features, output_features, disable_rank5_shape_mapping=True ) builder.add_squeeze(name='squeeze_layer', input_name='data', output_name='output', axes=list(axes[i])) x = np.random.rand(*input_shapes[i]) input = {'data': x} expected = {'output': np.reshape(x, output_shapes[i])} self._test_model(builder.spec, input, expected, useCPUOnly=True) def test_squeeze_all(self): input_shapes = [ (1, 1, 10, 5), (1, 10, 1, 5), (10, 5, 1, 1), (10, 5, 1, 1), (1,), (10, 5, 1, 1), (3, 1, 7), (3,), (5, 6) ] for input_shape in input_shapes: input_features = [('data', datatypes.Array(*input_shape))] output_features = [('output', None)] builder = neural_network.NeuralNetworkBuilder( input_features, output_features, disable_rank5_shape_mapping=True ) builder.add_squeeze(name='squeeze_layer', input_name='data', output_name='output', squeeze_all=True) x = np.random.rand(*input_shape) input = {'data': x} reference = np.squeeze(x) if not reference.shape: reference = np.reshape(reference, (1,)) expected = {'output': reference} self._test_model(builder.spec, input, expected, useCPUOnly=True) def test_argmax_argmin(self): test_input_shapes = [(9,), (8, 6), (9, 8, 10), (5, 9, 7, 9), (12, 8, 6, 6, 7)] # (1+2+3+4+5) * 2^3 = 120 test cases for input_shape in test_input_shapes: for negative_axis in [False, True]: for mode in ['argmax', 'argmin']: for keep_dims in [True, False]: for axis in np.arange(len(input_shape)): if negative_axis: axis_val = axis - len(input_shape) else: axis_val = axis input_features = [('data', datatypes.Array(*input_shape))] output_features = [('output', None)] builder = neural_network.NeuralNetworkBuilder( input_features, output_features, disable_rank5_shape_mapping=True ) x = np.random.rand(*input_shape) if mode == 'argmax': builder.add_argmax('argmax', 'data', 'output', axis=axis_val, keepdims=keep_dims) np_out = np.argmax(x, axis=axis_val) else: builder.add_argmin('argmin', 'data', 'output', axis=axis_val, keepdims=keep_dims) np_out = np.argmin(x, axis=axis_val) if keep_dims: np_out = np.expand_dims(np_out, axis=axis_val) elif len(input_shape) == 1: np_out = np.expand_dims(np_out, axis=axis_val) input = {'data': x} expected = {'output': np_out} self._test_model(builder.spec, input, expected, useCPUOnly=True) def test_get_shape(self): dims = [1, 2, 3, 4, 5] for rank in range(1, len(dims) + 1): input_shape = dims[:rank] input_features = [('data', datatypes.Array(*input_shape))] output_features = [('output', None)] builder = neural_network.NeuralNetworkBuilder( input_features, output_features, disable_rank5_shape_mapping=True ) builder.add_get_shape(name='get_shape_layer', input_name='data', output_name='output') feed = {'data': np.random.rand(*input_shape)} expected = {'output': np.array(input_shape)} self._test_model(builder.spec, feed, expected, useCPUOnly=True) def test_load_constant_nd(self): dims = [2, 3, 4, 5, 6] for rank in range(1, len(dims) + 1): input_shape = dims[:rank] input_features = [('data', datatypes.Array(*input_shape))] output_features = [('output', None)] builder = neural_network.NeuralNetworkBuilder( input_features, output_features, disable_rank5_shape_mapping=True ) builder.add_load_constant_nd('load_const_nd_layer', 'tmp', constant_value=np.ones(input_shape), shape=input_shape) builder.add_elementwise('add_layer', ['data', 'tmp'], 'output', mode='ADD') feed = {'data': np.random.rand(*input_shape)} expected = {'output': feed['data'] + 1} self._test_model(builder.spec, feed, expected, useCPUOnly=True) @unittest.skip('fix') def test_simple_array_alloc_scatter(self): alloc_shape = [2, 3, 4] value_shape = [1, 3, 4] input_features = [('alloc_shape', datatypes.Array(len(alloc_shape))), ('value', datatypes.Array(*value_shape)), ('index', datatypes.Array(1))] output_features = [('output', None)] builder = neural_network.NeuralNetworkBuilder( input_features, output_features, disable_rank5_shape_mapping=True) builder.add_fill_dynamic(name='fill_dynamic_layer', input_name='alloc_shape', output_name='array', value=np.float(0.0)) # CoreML input order: container (array), indices, slices (value) builder.add_scatter(name='scatter_layer', input_names=['array', 'index', 'value'], output_name='output') value = np.random.rand(*value_shape).astype('float') feed = {'alloc_shape': np.array(alloc_shape, dtype='float'), 'value': value, 'index': np.array([1], dtype='float')} ref = np.zeros(alloc_shape) ref[1, :, :] = value expected = {'output': ref} self._test_model(builder.spec, feed, expected, useCPUOnly=True) def test_erf_activation(self): input_features = [('data', datatypes.Array(10, 45))] output_features = [('output', datatypes.Array(10, 45))] builder = neural_network.NeuralNetworkBuilder( input_features, output_features, disable_rank5_shape_mapping=True) builder.add_erf(name='erf', input_name='data', output_name='output') x = np.random.rand(10, 45) input = {'data': x} expected = { 'output': np.asarray([math.erf(i) for i in x.flatten().tolist()]).reshape(10, 45) } self._test_model(builder.spec, input, expected, useCPUOnly=True) def test_gelu_activation(self): for mode in ['EXACT', 'TANH_APPROXIMATION', 'SIGMOID_APPROXIMATION']: for rank in range(1, 6): shape = np.random.randint(low=2, high=5, size=rank) input_features = [('data', datatypes.Array(*shape))] output_features = [('output', None)] builder = neural_network.NeuralNetworkBuilder( input_features, output_features, disable_rank5_shape_mapping=True) builder.add_gelu(name='gelu', input_name='data', output_name='output', mode=mode) x = np.random.rand(*shape) input = {'data': x} exact = np.asarray([0.5 * i * (1.0 + math.erf(i / math.sqrt(2))) for i in x.flatten().tolist()]).reshape(*shape) expected = {'output': exact} self._test_model(builder.spec, input, expected, useCPUOnly=True) def test_lower_triangular_cpu(self): for rank in range(2, 6): for k in range(-7, 8): shape = np.random.randint(low=2, high=6, size=rank) input_features = [('data', datatypes.Array(*shape))] output_features = [('output', None)] builder = neural_network.NeuralNetworkBuilder( input_features, output_features, disable_rank5_shape_mapping=True) builder.add_lower_triangular('tril', 'data', 'output', k=k) x = np.random.rand(*shape) input = {'data': x} expected = {'output': np.tril(x, k=k)} self._test_model(builder.spec, input, expected, useCPUOnly=True) def test_upper_triangular_cpu(self): for rank in range(2, 6): for k in range(-7, 8): shape = np.random.randint(low=2, high=6, size=rank) input_features = [('data', datatypes.Array(*shape))] output_features = [('output', None)] builder = neural_network.NeuralNetworkBuilder( input_features, output_features, disable_rank5_shape_mapping=True) builder.add_upper_triangular('triu', 'data', 'output', k=k) x = np.random.rand(*shape) input = {'data': x} expected = {'output': np.triu(x, k=k)} self._test_model(builder.spec, input, expected, useCPUOnly=True) def test_where_broadcastable_cpu(self): for _ in range(150): rank_cond = np.random.randint(low=1, high=6) rank_true = np.random.randint(low=1, high=6) rank_false = np.random.randint(low=1, high=6) rank_out = max(rank_cond, rank_true, rank_false) shape_cond = np.random.randint(low=2, high=8, size=rank_cond) shape_true = np.random.randint(low=2, high=8, size=rank_true) shape_false = np.random.randint(low=2, high=8, size=rank_false) for i in range(-1, -rank_out - 1, -1): dims = [] if -i <= rank_cond: dims.append(shape_cond[i]) if -i <= rank_true: dims.append(shape_true[i]) if -i <= rank_false: dims.append(shape_false[i]) dim = np.random.choice(dims) if -i <= rank_cond: shape_cond[i] = np.random.choice([1, dim]) if -i <= rank_true: shape_true[i] = np.random.choice([1, dim]) if -i <= rank_false: shape_false[i] = np.random.choice([1, dim]) input_features = [ ('cond', datatypes.Array(*shape_cond)), ('true', datatypes.Array(*shape_true)), ('false', datatypes.Array(*shape_false)) ] output_features = [('output', None)] builder = neural_network.NeuralNetworkBuilder( input_features, output_features, disable_rank5_shape_mapping=True) builder.add_where_broadcastable('if_broadcastable', input_names=['cond', 'true', 'false'], output_name='output') cond = np.random.choice([1.0, 0.0], size=shape_cond) true = np.random.rand(*shape_true) false = np.random.rand(*shape_false) input = {'cond': cond, 'true': true, 'false': false} expected = {'output': np.where(cond, true, false)} self._test_model(builder.spec, input, expected, useCPUOnly=True) def test_random_normal_like_cpu(self): mean, stddev, seed = 0., 1., 42 for rank in range(5, -1, -1): if rank > 0: low_factor = np.random.randint(low=2, high=4) low = int(np.power(1000, 1. / rank)) * low_factor high = int(np.power(2000, 1. / rank)) * np.random.randint(low=low_factor, high=4) shape = np.random.randint(low=low, high=high, size=rank) else: # one extra test to test more moments shape = np.array([10, 10, 10, 10, 10000]) input_features = [('tensor', datatypes.Array(*shape))] builder = neural_network.NeuralNetworkBuilder( input_features, [('output', None)], disable_rank5_shape_mapping=True) builder.add_random_normal_like(name='random_normal_like', input_name='tensor', output_name='output', mean=mean, stddev=stddev, seed=seed) inputs = {'tensor': np.random.rand(*shape)} expected = {'output': np.random.normal(mean, stddev, shape)} if rank > 0: CorrectnessTest._compare_moments(builder.spec, inputs, expected, num_moments=2) self._test_model(builder.spec, inputs, expected, useCPUOnly=True) else: # one extra test to test more moments CorrectnessTest._compare_moments(builder.spec, inputs, expected, num_moments=6) def test_random_normal_static_cpu(self): mean, stddev, seed = 0., 1., 42 for rank in range(1, 6): low_factor = np.random.randint(low=2, high=4) low = int(np.power(1000, 1. / rank)) * low_factor high = int(np.power(2000, 1. / rank)) * np.random.randint(low=low_factor, high=4) shape = np.random.randint(low=low, high=high, size=rank) input_features = [('data', datatypes.Array(*shape))] builder = neural_network.NeuralNetworkBuilder( input_features, [('output', None)], disable_rank5_shape_mapping=True) builder.add_random_normal_static(name='random_normal_static', output_name='tmp', output_shape=list(shape), mean=mean, stddev=stddev, seed=seed) builder.add_elementwise('add_layer', ['data', 'tmp'], 'output', mode='ADD') data = np.zeros(shape) inputs = {'data': data} expected = {'output': data + np.random.normal(mean, stddev, shape)} CorrectnessTest._compare_moments(builder.spec, inputs, expected, num_moments=2) self._test_model(builder.spec, inputs, expected, useCPUOnly=True) def test_random_normal_dynamic_cpu(self): mean, stddev, seed = 0., 1., 42 for rank in range(1, 6): low_factor = np.random.randint(low=2, high=4) low = int(np.power(1000, 1. / rank)) * low_factor high = int(np.power(2000, 1. / rank)) * np.random.randint(low=low_factor, high=4) shape = np.random.randint(low=low, high=high, size=rank) input_features = [('shape', datatypes.Array(len(shape)))] builder = neural_network.NeuralNetworkBuilder( input_features, [('output', None)], disable_rank5_shape_mapping=True) builder.add_random_normal_dynamic(name='random_normal_dynamic', input_names=['shape'], output_name='output', mean=mean, stddev=stddev, seed=seed) inputs = {'shape': np.array(shape, np.float)} expected = {'output': np.random.normal(mean, stddev, shape)} CorrectnessTest._compare_moments(builder.spec, inputs, expected, num_moments=2) self._test_model(builder.spec, inputs, expected, useCPUOnly=True) def test_random_uniform_like_cpu(self): minval, maxval, seed = 0., 1., 42 for rank in range(1, 6): low_factor = np.random.randint(low=2, high=4) low = int(np.power(1000, 1. / rank)) * low_factor high = int(np.power(2000, 1. / rank)) * np.random.randint(low=low_factor, high=4) shape = np.random.randint(low=low, high=high, size=rank) input_features = [('tensor', datatypes.Array(*shape))] builder = neural_network.NeuralNetworkBuilder( input_features, [('output', None)], disable_rank5_shape_mapping=True) builder.add_random_uniform_like(name='random_uniform_like', input_name='tensor', output_name='output', minval=minval, maxval=maxval, seed=seed) tensor = np.random.rand(*shape) inputs = {'tensor': tensor} expected = {'output': np.random.uniform(minval, maxval, shape)} CorrectnessTest._compare_moments(builder.spec, inputs, expected) self._test_model(builder.spec, inputs, expected, useCPUOnly=True) def test_random_uniform_static_cpu(self): minval, maxval, seed = 0., 1., 42 for rank in range(1, 6): low_factor = np.random.randint(low=2, high=4) low = int(np.power(1000, 1. / rank)) * low_factor high = int(np.power(2000, 1. / rank)) * np.random.randint(low=low_factor, high=4) shape = np.random.randint(low=low, high=high, size=rank) input_features = [('data', datatypes.Array(*shape))] builder = neural_network.NeuralNetworkBuilder( input_features, [('output', None)], disable_rank5_shape_mapping=True) builder.add_random_uniform_static(name='random_uniform_static', output_name='tmp', output_shape=list(shape), minval=minval, maxval=maxval, seed=seed) builder.add_elementwise('add_layer', ['data', 'tmp'], 'output', mode='ADD') data = np.zeros(shape) inputs = {'data': data} expected = {'output': data + np.random.uniform(minval, maxval, shape)} CorrectnessTest._compare_moments(builder.spec, inputs, expected) self._test_model(builder.spec, inputs, expected, useCPUOnly=True) def test_random_uniform_dynamic_cpu(self): minval, maxval, seed = 0., 1., 42 for rank in range(1, 6): low_factor = np.random.randint(low=2, high=4) low = int(np.power(1000, 1. / rank)) * low_factor high = int(np.power(2000, 1. / rank)) * np.random.randint(low=low_factor, high=4) shape = np.random.randint(low=low, high=high, size=rank) input_features = [('shape', datatypes.Array(len(shape)))] builder = neural_network.NeuralNetworkBuilder( input_features, [('output', None)], disable_rank5_shape_mapping=True) builder.add_random_uniform_dynamic(name='random_uniform_dynamic', input_names=['shape'], output_name='output', minval=minval, maxval=maxval, seed=seed) inputs = {'shape': np.array(shape, np.float)} expected = {'output': np.random.uniform(minval, maxval, shape)} CorrectnessTest._compare_moments(builder.spec, inputs, expected) self._test_model(builder.spec, inputs, expected, useCPUOnly=True) def test_random_bernoulli_like_cpu(self): prob, seed = 0.5, 42 for rank in range(1, 6): low_factor = np.random.randint(low=2, high=4) low = int(np.power(1000, 1. / rank)) * low_factor high = int(np.power(2000, 1. / rank)) * np.random.randint(low=low_factor, high=4) shape = np.random.randint(low=low, high=high, size=rank) input_features = [('tensor', datatypes.Array(*shape))] builder = neural_network.NeuralNetworkBuilder( input_features, [('output', None)], disable_rank5_shape_mapping=True) builder.add_random_bernoulli_like(name='random_bernoulli_like', input_name='tensor', output_name='output', prob=prob, seed=seed) tensor = np.random.rand(*shape) inputs = {'tensor': tensor} expected = {'output': np.random.binomial(1, prob, shape)} CorrectnessTest._compare_moments(builder.spec, inputs, expected) self._test_model(builder.spec, inputs, expected, useCPUOnly=True) def test_random_bernoulli_static_cpu(self): prob, seed = 0.5, 42 for rank in range(1, 6): low_factor = np.random.randint(low=2, high=4) low = int(np.power(1000, 1. / rank)) * low_factor high = int(np.power(2000, 1. / rank)) * np.random.randint(low=low_factor, high=4) shape = np.random.randint(low=low, high=high, size=rank) input_features = [('data', datatypes.Array(*shape))] builder = neural_network.NeuralNetworkBuilder( input_features, [('output', None)], disable_rank5_shape_mapping=True) builder.add_random_bernoulli_static(name='random_bernoulli_static', output_name='tmp', output_shape=list(shape), prob=prob, seed=seed) builder.add_elementwise('add_layer', ['data', 'tmp'], 'output', mode='ADD') data = np.zeros(shape) inputs = {'data': data} expected = {'output': data + np.random.binomial(1, prob, shape)} CorrectnessTest._compare_moments(builder.spec, inputs, expected) self._test_model(builder.spec, inputs, expected, useCPUOnly=True) def test_random_bernoulli_dynamic_cpu(self): prob, seed = 0.5, 42 for rank in range(1, 6): low_factor = np.random.randint(low=2, high=4) low = int(np.power(1000, 1. / rank)) * low_factor high = int(np.power(2000, 1. / rank)) * np.random.randint(low=low_factor, high=4) shape = np.random.randint(low=low, high=high, size=rank) input_features = [('shape', datatypes.Array(len(shape)))] builder = neural_network.NeuralNetworkBuilder( input_features, [('output', None)], disable_rank5_shape_mapping=True) builder.add_random_bernoulli_dynamic(name='random_bernoulli_dynamic', input_names=['shape'], output_name='output', prob=prob, seed=seed) inputs = {'shape': np.array(shape, np.float)} expected = {'output': np.random.binomial(1, prob, shape)} CorrectnessTest._compare_moments(builder.spec, inputs, expected) self._test_model(builder.spec, inputs, expected, useCPUOnly=True) def test_categorical_distribution_cpu_shapes(self): for rank in range(1, 6): shape = np.random.randint(low=2, high=8, size=rank) num_samples = np.random.randint(low=10, high=1000) input_features = [('data', datatypes.Array(*shape))] builder = neural_network.NeuralNetworkBuilder( input_features, [('output', None)], disable_rank5_shape_mapping=True) builder.add_categorical_distribution(name='categorical_distribution', input_name='data', output_name='output', num_samples=num_samples) x = np.random.randint(low=0, high=20, size=shape).astype(np.float32) inputs = {'data': x} shape[-1] = num_samples expected = {'output': np.random.rand(*shape)} self._test_model(builder.spec, inputs, expected, useCPUOnly=True, validate_shapes_only=True) def test_categorical_distribution_cpu_logits(self): def softmax(data): e_data = np.exp(data - np.max(data)) return e_data / e_data.sum() num_samples, num_class = 50000, 10 input_name, output_name = 'data', 'output' shapes = [(2, num_class), (2, 1, num_class), (1, 2, num_class), (2, 1, 1, num_class), (1, 2, 1, num_class), (1, 1, 2, num_class), (2, 1, 1, 1, num_class), (1, 2, 1, 1, num_class), (1, 1, 2, 1, num_class), (1, 1, 1, 2, num_class)] for shape in shapes: input_features = [('data', datatypes.Array(*shape))] builder = neural_network.NeuralNetworkBuilder( input_features, [('output', None)], disable_rank5_shape_mapping=True) builder.add_categorical_distribution(name='categorical_distribution', input_name=input_name, output_name=output_name, num_samples=num_samples, is_logits=True, seed=42) x = np.random.rand(*shape) inputs = {input_name: x} model = builder.spec if isinstance(model, str): model = coremltools.models.MLModel(model) model = coremltools.models.MLModel(model, useCPUOnly=True) prediction = model.predict(inputs, useCPUOnly=True) # validate each distribution separately logits = x.reshape(2, num_class) probs = [softmax(logits[0]), softmax(logits[1])] ref0 = np.random.multinomial(num_samples, probs[0]) ref1 = np.random.multinomial(num_samples, probs[1]) pre0 = prediction[output_name].reshape(2, num_samples)[0] pre1 = prediction[output_name].reshape(2, num_samples)[1] expected = {output_name: np.stack((pre0, pre1))} # convert to bincount and validate probabilities pre0 = np.bincount(np.array(pre0).astype(np.int), minlength=num_class) pre1 = np.bincount(np.array(pre1).astype(np.int), minlength=num_class) assert np.allclose(np.true_divide(pre0, num_samples), probs[0], atol=1e-2) assert np.allclose(np.true_divide(pre0, num_samples), np.true_divide(ref0, num_samples), atol=1e-2) assert np.allclose(np.true_divide(pre1, num_samples), probs[1], atol=1e-2) assert np.allclose(np.true_divide(pre1, num_samples), np.true_divide(ref1, num_samples), atol=1e-2) self._test_model(model, inputs, expected, useCPUOnly=True, output_name_shape_dict={'output': prediction['output'].shape}) def test_categorical_distribution_cpu_probs(self): def softmax(data): e_data = np.exp(data - np.max(data)) return e_data / e_data.sum() num_samples, num_class = 50000, 10 input_name, output_name = 'data', 'output' shapes = [(2, num_class), (2, 1, num_class), (1, 2, num_class), (2, 1, 1, num_class), (1, 2, 1, num_class), (1, 1, 2, num_class), (2, 1, 1, 1, num_class), (1, 2, 1, 1, num_class), (1, 1, 2, 1, num_class), (1, 1, 1, 2, num_class)] for shape in shapes: input_features = [('data', datatypes.Array(*shape))] builder = neural_network.NeuralNetworkBuilder( input_features, [('output', None)], disable_rank5_shape_mapping=True) builder.add_categorical_distribution(name='categorical_distribution', input_name=input_name, output_name=output_name, num_samples=num_samples, is_logits=False, seed=42) x = np.random.rand(*shape) probs = x.reshape(2, num_class) probs[0], probs[1] = softmax(probs[0]), softmax(probs[1]) inputs = {input_name: np.reshape(probs, shape)} model = builder.spec if isinstance(model, str): model = coremltools.models.MLModel(model) model = coremltools.models.MLModel(model, useCPUOnly=True) prediction = model.predict(inputs, useCPUOnly=True) # validate each distribution separately probs = probs.reshape(2, num_class) ref0 = np.random.multinomial(num_samples, probs[0]) ref1 = np.random.multinomial(num_samples, probs[1]) pre0 = prediction[output_name].reshape(2, num_samples)[0] pre1 = prediction[output_name].reshape(2, num_samples)[1] expected = {output_name: np.stack((pre0, pre1))} # convert to bincount and validate probabilities pre0 = np.bincount(np.array(pre0).astype(np.int), minlength=num_class) pre1 = np.bincount(np.array(pre1).astype(np.int), minlength=num_class) assert np.allclose(np.true_divide(pre0, num_samples), probs[0], atol=1e-2) assert np.allclose(np.true_divide(pre0, num_samples), np.true_divide(ref0, num_samples), atol=1e-2) assert np.allclose(np.true_divide(pre1, num_samples), probs[1], atol=1e-2) assert np.allclose(np.true_divide(pre1, num_samples), np.true_divide(ref1, num_samples), atol=1e-2) self._test_model(model, inputs, expected, useCPUOnly=True, output_name_shape_dict={'output': prediction['output'].shape}) def test_reverse_cpu(self): for rank in range(1, 6): for _ in range(20): input_shape = np.random.randint(low=2, high=8, size=rank) reverse_dim = [np.random.choice([True, False]) for _ in range(rank)] axes = [i for i in range(rank) if reverse_dim[i] == True] input_features = [('data', datatypes.Array(*input_shape))] output_features = [('output', None)] builder = neural_network.NeuralNetworkBuilder( input_features, output_features, disable_rank5_shape_mapping=True) builder.add_reverse('reverse', 'data', 'output', reverse_dim) x = np.random.rand(*input_shape) input = {'data': x} expected = {'output': np.flip(x, axis=axes)} self._test_model(builder.spec, input, expected, useCPUOnly=True) def test_matrix_band_part_cpu(self): for rank in range(2, 6): for _ in range(20): num_lower = np.random.randint(low=-7, high=8) num_upper = np.random.randint(low=-7, high=8) shape = np.random.randint(low=2, high=6, size=rank) input_features = [('data', datatypes.Array(*shape))] output_features = [('output', None)] builder = neural_network.NeuralNetworkBuilder( input_features, output_features, disable_rank5_shape_mapping=True) builder.add_matrix_band_part('matrix_band_part', 'data', 'output', num_lower=num_lower, num_upper=num_upper) x = np.random.rand(*shape) input = {'data': x} rows, cols = shape[-2:] band = np.ones((rows, cols)) for m in range(rows): for n in range(cols): band[m, n] = (num_lower < 0 or (m - n) <= num_lower) and (num_upper < 0 or (n - m) <= num_upper) expected = {'output': np.multiply(band, x)} self._test_model(builder.spec, input, expected, useCPUOnly=True) def test_flatten_to_2d_cpu(self): for rank in range(1, 6): for axis in range(-rank, rank + 1): shape = np.random.randint(low=2, high=6, size=rank) input_features = [('data', datatypes.Array(*shape))] output_features = [('output', None)] builder = neural_network.NeuralNetworkBuilder( input_features, output_features, disable_rank5_shape_mapping=True) builder.add_flatten_to_2d('flatten_to_2d', 'data', 'output', axis=axis) x = np.random.rand(*shape) np_axis = axis + rank if axis < 0 else axis pl, pr = 1, 1 for i in range(0, np_axis): pl *= shape[i] for i in range(np_axis, len(shape)): pr *= shape[i] new_shape = [pl, pr] ref = x.reshape(new_shape) input = {'data': x} expected = {'output': ref} self._test_model(builder.spec, input, expected, useCPUOnly=True) def test_reshape_like_cpu(self): for rank in range(1, 6): for _ in range(20): input_shape = np.random.randint(low=2, high=8, size=rank) n = int(np.prod(input_shape)) divisors = [d for d in range(1, n) if n % d == 0] target_rank = np.random.randint(low=2, high=6) target_shape = [1] for i in range(target_rank - 1): dim_size = np.random.choice(divisors) while n % (np.prod(target_shape) * dim_size) != 0: dim_size = np.random.choice(divisors) target_shape.append(dim_size) target_shape[0] = n / np.prod(target_shape) np.random.shuffle(target_shape) input_features = [('data', datatypes.Array(*input_shape)), ('tensor', datatypes.Array(*target_shape))] builder = neural_network.NeuralNetworkBuilder( input_features, [('output', None)], disable_rank5_shape_mapping=True) builder.add_reshape_like(name='reshape_like', input_names=['data', 'tensor'], output_name='output') data = np.random.rand(*input_shape) tensor = np.random.rand(*target_shape) inputs = {'data': data, 'tensor': tensor} expected = {'output': np.reshape(data, target_shape)} self._test_model(builder.spec, inputs, expected, useCPUOnly=True) def test_reshape_static_cpu(self): for rank in range(1, 6): for _ in range(20): input_shape = np.random.randint(low=2, high=8, size=rank) n = int(np.prod(input_shape)) divisors = [d for d in range(1, n) if n % d == 0] target_rank = np.random.randint(low=2, high=6) target_shape = [1] for i in range(target_rank - 1): dim_size = np.random.choice(divisors) while n % (np.prod(target_shape) * dim_size) != 0: dim_size = np.random.choice(divisors) target_shape.append(dim_size) target_shape[0] = -1 np.random.shuffle(target_shape) input_features = [('data', datatypes.Array(*input_shape))] builder = neural_network.NeuralNetworkBuilder( input_features, [('output', None)], disable_rank5_shape_mapping=True) builder.add_reshape_static(name='reshape_static', input_name='data', output_name='output', output_shape=target_shape) data = np.random.rand(*input_shape) inputs = {'data': data} expected = {'output': np.reshape(data, target_shape)} self._test_model(builder.spec, inputs, expected, useCPUOnly=True) def test_reshape_dynamic_cpu(self): for rank in range(1, 6): for _ in range(20): input_shape = np.random.randint(low=2, high=8, size=rank) n = int(np.prod(input_shape)) divisors = [d for d in range(1, n) if n % d == 0] target_rank = np.random.randint(low=2, high=6) target_shape = [1] for i in range(target_rank - 1): dim_size = np.random.choice(divisors) while n % (np.prod(target_shape) * dim_size) != 0: dim_size = np.random.choice(divisors) target_shape.append(dim_size) target_shape[0] = -1 np.random.shuffle(target_shape) input_features = [('data', datatypes.Array(*input_shape)), ('shape', datatypes.Array(len(target_shape)))] builder = neural_network.NeuralNetworkBuilder( input_features, [('output', None)], disable_rank5_shape_mapping=True) builder.add_reshape_dynamic(name='reshape_dynamic', input_names=['data', 'shape'], output_name='output') data = np.random.rand(*input_shape) inputs = {'data': data, 'shape': np.array(target_shape, dtype='float')} expected = {'output': np.reshape(data, target_shape)} self._test_model(builder.spec, inputs, expected, useCPUOnly=True) def test_reduce_sum_cpu(self): for rank in range(1, 6): axes_list = [axes for len in range(1, rank + 1) for axes in itertools.combinations(range(rank), len)] axes_list.append(None) for axes in axes_list: if axes: axes = tuple([axis if np.random.choice([True, False]) else axis - rank for axis in axes]) reduce_all = False else: reduce_all = True for keep_dims in [True, False]: input_shape = np.random.randint(low=2, high=5, size=rank) input_features = [('data', datatypes.Array(*input_shape))] output_features = [('output', None)] builder = neural_network.NeuralNetworkBuilder( input_features, output_features, disable_rank5_shape_mapping=True ) builder.add_reduce_sum('reduce', 'data', 'output', axes, keepdims=keep_dims, reduce_all=reduce_all) x =
np.random.rand(*input_shape)
numpy.random.rand
# !/usr/bin/env python # -*- coding: utf-8 -*- """ Defines unit tests for :mod:`colour.appearance.hunt` module. """ from __future__ import division, unicode_literals import numpy as np from colour.appearance import Hunt_InductionFactors, XYZ_to_Hunt from colour.appearance.tests.common import ColourAppearanceModelTest __author__ = 'Colour Developers' __copyright__ = 'Copyright (C) 2013 - 2014 - Colour Developers' __license__ = 'New BSD License - http://opensource.org/licenses/BSD-3-Clause' __maintainer__ = 'Colour Developers' __email__ = '<EMAIL>' __status__ = 'Production' __all__ = ['TestHuntColourAppearanceModel'] class TestHuntColourAppearanceModel(ColourAppearanceModelTest): """ Defines :mod:`colour.appearance.hunt` module unit tests methods for *Hunt* colour appearance model. """ FIXTURE_BASENAME = 'hunt.csv' OUTPUT_ATTRIBUTES = {'J': 'J', 'C_94': 'C', 'h_S': 'h', 's': 's', 'Q': 'Q', 'M94': 'M'} def output_specification_from_data(self, data): """ Returns the *Hunt* colour appearance model output specification from given data. Parameters ---------- data : list Fixture data. Returns ------- Hunt_Specification *Hunt* colour appearance model specification. """ XYZ = np.array([data['X'], data['Y'], data['Z']]) XYZ_w =
np.array([data['X_w'], data['Y_w'], data['Z_w']])
numpy.array
'''Meeus: Astronomical Algorithms (2nd ed.), chapter 15''' import numpy as np def rising(dec,lat): '''local hour angle for rising (alt=0 deg) - without refraction''' #type of output (same as input - number, list, numpy.array) out_type='lst' if (isinstance(dec,int) or isinstance(dec,float)) and (isinstance(lat,int) or isinstance(lat,float)): #all input args are numbers out_type='num' if isinstance(dec,np.ndarray) or isinstance(lat,np.ndarray): #numpy.array out_type='np' if isinstance(dec,list): dec=np.array(dec) if isinstance(lat,list): lat=np.array(lat) if out_type=='num': dec=np.array([dec]) dec=np.deg2rad(dec) lat=np.deg2rad(lat) ha=np.arccos(-
np.tan(lat)
numpy.tan
import copy import sys sys.path.append('SetsClustering') from multiprocessing import Process ,Manager import numpy as np import LinearProgrammingInTheDarkClassVersion as LPD from multiprocessing import Pool from jgrapht.algorithms.shortestpaths import johnson_allpairs import jgrapht from SetsClustering import Utils, PointSet, KMeansAlg from SetsClustering import KMeansForSetsSensitivityBounder as SensBounder from SetsClustering import Coreset as CS from scipy.spatial.distance import cdist import seaborn as sns from copy import deepcopy import itertools from scipy.ndimage import convolve from timeit import default_timer as timer from tqdm import tqdm import dill import matplotlib matplotlib.use('agg') import matplotlib.pyplot as plt import matplotlib.pylab as pl from scipy.linalg import null_space import scipy.ndimage as ndi from scipy.spatial import ConvexHull import argparse, os, pickle from scipy.io import netcdf POWER = 4 FORCE_NEIGHBORING = 20 import psutil CPUS = psutil.cpu_count() # import multiprocessing # # from pathos.multiprocessing import ProcessingPool as Pool # # from sklearn.externals.joblib import Parallel, delayed # from multiprocessing import Process parser = argparse.ArgumentParser(description='Initial Location Generator') parser.add_argument('-d', type=str, default=None, help='Directory containing all maps') parser.add_argument('-pp', default=False, action='store_true', help='preprocess map') parser.add_argument('-ft', default='.nc', type=str, help='Type of map file') parser.add_argument('-nf', default=1, type=int, help='Number of files describing a map of velocities') parser.add_argument('-eps_g', default=None, type=float, help=r'resolution of the \varepsilon-grid') parser.add_argument('-eps_b', default=0.08, type=float, help=r'epsilon approximation for each of the patches of the currents') parser.add_argument('-k', default=10, type=int, help='Desired number of drifters') parser.add_argument('-bs', default=2, type=int, help='size of the blob prior to the clustering phase') parser.add_argument('-coreset_sample_size', default=1000, type=int, help='The size of the coreset for the clustering phase') parser.add_argument('-time', default=False, action='store_true', help='Apply our system over time') parser.add_argument('-tol', default=0.2, type=float, help='Tolerance for minimum volume ellipsoid') parser.add_argument('-resume', default=False, action='store_true', help='In case of code being killed, you can resume from last map') parser.add_argument('-show', default=False, action='store_true', help='Show only our segementation and clustering. Must have preporcessed these data before') 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' NORMAL = '\033[0m' plt.rcParams.update({'font.size': 16}) manager = Manager() def removeInclusionsJob(lst, ids, path_str): global resdict for i in range(len(lst)): resdict[ids[i]] = True if lst[i] in path_str: resdict[ids[i]] = False def removeInclusions(unified_paths, file_path='', file_prefix=''): global manager global resdict global A unified_paths_strings = [str(x[0]).strip('[]') for x in unified_paths] unified_paths_strings.sort(key=(lambda x: len(x.split(',')))) lst = [list(grp) for i, grp in itertools.groupby(unified_paths_strings, key=(lambda x: len(x.split(','))))] sizes = np.cumsum([len(x) for x in lst]) unique_ids = [list(range(sizes[i-1], sizes[i]) if i > 0 else range(sizes[i])) for i in range(len(sizes))] if len(unified_paths_strings) > 10000: with Manager() as manager: proc_list = [] resdict = manager.dict() for i, item in enumerate(lst): if i != (len(lst) - 1): proc_list.append( Process(target=removeInclusionsJob, args=(item, unique_ids[i], '\n'.join(unified_paths_strings[sizes[i]:]))) ) proc_list[-1].start() for proc in proc_list: proc.join() mask = [x[1] for x in resdict.items()] else: resdict = dict() for i, item in enumerate(lst): if i != (len(lst) - 1): removeInclusionsJob(item, unique_ids[i], '\n'.join(unified_paths_strings[sizes[i]:])) mask = [x[1] for x in resdict.items()] mask.extend([True for _ in range(len(lst[-1]))]) np.save('{}mask_unified_paths_{}.npy'.format(file_path, file_prefix), mask) return [[int(y) for y in x.split(', ')] for x in list(itertools.compress(unified_paths_strings, mask))] def removeDuplicates(list_1): list2 = list(set(list_1)) list2.sort(key=list_1.index) return list2 def makedir(dir_path): try: os.mkdir(dir_path) except OSError as error: print(error) def saveVels(data, file_path, smoothed=True): if smoothed: file_path += 'Smoothed_Vel/' else: file_path += 'Original_Vel/' makedir(file_path) temp = np.tile(data[:, :, 0][:, :, np.newaxis], 10) temp.dump(file_path + 'matrix_vel_x.dat') temp = np.tile(data[:, :, 1][:, :, np.newaxis], 10) temp.dump(file_path + 'matrix_vel_y.dat') def readNetCDFFile(file_path, over_time): file2read = netcdf.NetCDFFile(file_path, 'r') U = file2read.variables['u'].data # velocity in x-axis V = file2read.variables['v'].data # velocity in y-axis mask = np.logical_and(np.abs(U) <= 1e3, np.abs(V) <= 1e3) V = np.multiply(V, mask) U = np.multiply(U, mask) if not over_time: U = U[0, :, :, :] V = V[0, :, :, :] return U,V def innerFunction(current_possible_combs, unique_keys): global resdict for i, element in enumerate(current_possible_combs): resdict[unique_keys[i]] = (removeDuplicates(element[0][0] + element[1][0]), element[0][1] + element[1][1]) def getAllPossiblePaths(list1, list2): global CPUS global manager global resdict if len(list1) * len(list2) > 10000: manager = Manager() resdict = manager.dict() all_possible_combs = np.array_split(list(itertools.product(list1, list2)), CPUS) unique_ids = np.array_split(np.arange(sum([x.size for x in all_possible_combs])), CPUS) proc_list = [] for i, item in enumerate(all_possible_combs): proc_list.append( Process(target=innerFunction, args=(item, unique_ids[i])) ) proc_list[-1].start() for proc in proc_list: proc.join() temp = list(resdict.values()) else: temp = [] for element in itertools.product(list1, list2): temp.append((removeDuplicates(element[0][0] + element[1][0]), element[0][1] + element[1][1])) return temp class CurrentEstimation(object): def __init__(self, grid, k=10, epsilon_grid=0.06, tolerance=0.001, epsilon_body=2, is_grid=True, is_data_vectorized=True, blob_size=3, sens_file_name='sens.npz', coreset_sample_size = int(1e3), save_mode=True, matrix_of_velocities=True, save_path='', file_prefix='', show=False, verbose=False): self.grid = grid self.is_grid=is_grid self.d = (self.grid.ndim - 1) if matrix_of_velocities else self.grid.ndim self.epsilon_grid = epsilon_grid self.epsilon_body = epsilon_body self.tolerance = tolerance self.g = jgrapht.create_graph(directed=True) self.cost_func = (lambda x: self.grid[tuple(x.astype("int") if is_grid else x)]) # create a simple membership cost function self.iocsAlg = None self.segments = [] self.eps_star = None self.bodies = [] self.full_bodies = [] self.is_data_vectorized = is_data_vectorized self.k = k self.blob_size = blob_size self.coreset_sample_size = coreset_sample_size self.save_mode = save_mode self.binary_grid = None self.matrix_of_velocities = matrix_of_velocities self.sens_file_name = sens_file_name self.ellipsoids = [] self.convex_hulls = [] self.verbose = verbose self.save_path = save_path self.file_prefix = file_prefix self.show = show def polynomialGridSearchParallelizedVersion(self): with Pool() as pool: pass def checkIfContained(self, point): for i,body in enumerate((self.full_bodies if self.epsilon_body == 0 else self.bodies)): if body.ndim > 1: temp_in_body = np.equal(body, point).all(1).any() temp_in_CH = False if self.convex_hulls[i] is not None: temp_in_CH = np.all(self.convex_hulls[i][:,:-1].dot(point) <= -self.convex_hulls[i][:,-1]) if temp_in_body or temp_in_CH: return True else: if np.linalg.norm(body - point) == 0: return True return False def IOCS(self, p): cost_func = lambda x: 0.85 <= np.dot(np.nan_to_num(self.grid[tuple(p)]/np.linalg.norm(self.grid[tuple(p)])), np.nan_to_num(self.grid[tuple(x)]/np.linalg.norm(self.grid[tuple(x)]))) \ <= 1 and 0.5 <= np.linalg.norm(self.grid[tuple(p)])/np.linalg.norm(self.grid[tuple(x)]) <= 2 self.iocsAlg = LPD.LinearProgrammingInTheDark(P=self.grid,cost_func=cost_func, point=p, d=self.d, epsilon=self.tolerance, hull_hyper=None, matrix_of_vecs=True) if self.iocsAlg.lower_d <= 1: if self.iocsAlg.lower_d == 0: self.bodies.append(p) self.full_bodies.append(p) self.ellipsoids.append(None) self.convex_hulls.append(None) else: idxs = np.where(self.iocsAlg.oracle.flattened_data == 1)[0] Z = np.empty((idxs.shape[0], p.shape[0])) Z[:, self.iocsAlg.irrelevant_dims] = p[self.iocsAlg.irrelevant_dims] Z[:, self.iocsAlg.dims_to_keep[0]] = \ np.arange(*(self.iocsAlg.oracle.bounding_box[self.iocsAlg.dims_to_keep].flatten() + np.array([0, 1])).tolist())[idxs] self.bodies.append(Z) self.full_bodies.append(Z) self.ellipsoids.append(None) self.convex_hulls.append(None) elif self.iocsAlg.get_all_points: idxs = np.where(self.iocsAlg.oracle.flattened_data == 1)[0] Z = self.iocsAlg.oracle.coordinates[:-1, idxs].T self.bodies.append(Z) self.full_bodies.append(Z) self.ellipsoids.append(None) self.convex_hulls.append(None) else: self.ellipsoids.append(self.iocsAlg.computeAMVEE() + (p, )) if self.epsilon_body > 0: s = timer() self.approximateBody(self.ellipsoids[-1][0][-1], self.ellipsoids[-1][0][-2], idx_dims_retrieve=self.ellipsoids[-1][-3], dims_value=self.ellipsoids[-1][-1], rest_dims=self.ellipsoids[-1][-2]) else: self.attainWholeBody(self.ellipsoids[-1][0][-1], self.ellipsoids[-1][0][-2], idx_dims_retrieve=self.ellipsoids[-1][-3], dims_value=self.ellipsoids[-1][-1], rest_dims=self.ellipsoids[-1][-2]) def polynomialGridSearch(self): dims = list(self.grid.shape[:-1] if self.matrix_of_velocities else self.grid.shape) for i in range(len(dims)): dims[i] = np.arange(0, dims[i], int(np.round(dims[i] * self.epsilon_grid))) try: X = np.array(
np.meshgrid(*dims)
numpy.meshgrid
import pandas as pd import numpy as np def split_line(): print('--------------------') print('创建 Series') s = pd.Series([1, 2, 3, 4, np.nan, 6, 7]) print(s) split_line() print('创建日期 DataFrame') dates = pd.date_range('20200314', periods=6) print(dates) split_line() print('通过 numpy 创建 DataFrame') df = pd.DataFrame(np.random.randn(6, 4), index=dates, columns=list('ABCD')) print(df) split_line() print('通过 dict 创建 DataFrame') df2 = pd.DataFrame({ 'A' : 1., 'B' : pd.Timestamp('20130102'), 'C' : pd.Series(1,index=list(range(4)),dtype='float32'), 'D' : np.array([3]*4,dtype='int32'), 'E' : pd.Categorical(["test","train","test","train"]), 'F' : 'foo' }) print(df2) print(df2.dtypes) split_line() print('查看头部几行') print(df.head()) print('查看尾部几行') print(df.tail()) split_line() print('显示索引、列名及底层 numpy 数据') print(df.index) print(df.columns) print(df.values) split_line() print('对数据进行快读统计') print(df.describe()) split_line() print('对数据进行转置') print(df.T) split_line() print('按照列名排序') print(df.sort_index(axis=1, ascending=False)) split_line() print('按照某一列的值进行排序') print(df.sort_values(by='B')) split_line() print('虽然标准的Python/Numpy的表达式能完成选择与赋值等功能,但我们仍推荐使用优化过的pandas数据访问方法:.at,.iat,.loc,.iloc和.ix') print('') print('选择某一列数据,返回 Series') print(df['A']) print('使用 [] 切片') print(df[0:3]) split_line() print('通过标签选取') print(df.loc[dates[0]]) print('选取多列') print(df.loc[:, ['A', 'C']]) print('行列同时选择') print(df.loc['2020-03-14': '2020-03-16', ['A', 'C']]) print('快速获取某个值') print(df.at[dates[0], 'D']) split_line() print('通过位置选取,直接传递整型') print(df.iloc[3]) print('行列同时选择') print(df.iloc[3:5, 0:2]) print('只选取行') print(df.iloc[1:3, :]) print('只选取列') print(df.iloc[:, 1:3]) print('取具体的值(两种方法)') print(df.iloc[2,1], df.iat[2, 1]) split_line() print('通过布尔索引取值,即通过判断过滤') print('选取 A 列 >0') print(df[df.A > 0]) print('选取 >0,小于 0 的会变成 NaN') print(df[df > 0]) print('通过 isin() 过滤数据,主要针对字符串') df2 = df.copy() df2['E'] = ['one', 'one', 'two', 'three', 'four', 'three'] print('before', df2) print('after', df2[df2['E'].isin(['one', 'two'])]) split_line() print('赋值一个新的列,通过索引来自动对齐数据') s1 = pd.Series([1,2,3,4,5], index=pd.date_range('20200314',periods=5)) print(s1) df['F'] = s1 print(df) print('通过标签赋值') df.at[dates[0], 'A'] = 0 print(df) print('通过位置赋值') df.iat[0, 1] = 0 print('通过 numpy 赋值') df.loc[:, 'D'] = np.array([5]*len(df)) print(df) print('通过 where 赋值') df2 = df.copy() df2[df2 > 0] = -df2 print(df2) split_line() print('缺失值处理,在pandas中,用np.nan来代表缺失值,这些值默认不会参与运算') df1 = df.reindex(index=dates[0:4], columns=list(df.columns)+['E']) df1.loc[dates[0]:dates[1],'E'] = 1 print(df1) print('删除所有包含缺失值的行数据') print(df1.dropna(how='any')) print('填充缺失值') print(df1.fillna(value=5)) print('获取值是否为nan的布尔标记') print(pd.isnull(df1)) split_line() print('按列求平均') print(df.mean()) print('按行求平均') print(df.mean(1)) split_line() print('apply 函数默认会按列进行运算') print('apply 按列累加') print('before', df) print('after', df.apply(np.cumsum)) print('apply 找到每列的差值') print(df.apply(lambda x:x.max() - x.min())) split_line() print('频数统计') s = pd.Series(np.random.randint(0, 7, size=10)) print('origin data', s) print(s.value_counts()) split_line() print('处理字符串') s = pd.Series(['A', 'B', 'C', 'Aaba', 'Baca', np.nan, 'CABA', 'dog', 'cat']) print('before', s) print('after', s.str.lower()) split_line() print('连接 Series,DataFrame 和 Panel 对象') df = pd.DataFrame(np.random.randn(10,4)) print(df) print('拆分成不同元素') pieces = [df[:3], df[3:7], df[7:]] print(pieces[0]) print('再合并起来') print(pd.concat(pieces)) split_line() print('Join 操作') left = pd.DataFrame({'key':['foo', 'foo'], 'lval':[1,2]}) right = pd.DataFrame({'key':['bar', 'foo'], 'lval':[4,5]}) print('left', left) print('right', right) print('merge', pd.merge(left, right, on='key')) split_line() print('添加行到 DataFrame 后面') df = pd.DataFrame(np.random.randn(8, 4), columns=['A', 'B', 'C', 'D']) print('before', df) s = df.iloc[3] print('after', df.append(s, ignore_index=True)) split_line() print('分组操作,针对每组进行不同的计算,最后合并到某一个数据结构') df = pd.DataFrame({'A' : ['foo', 'bar', 'foo', 'bar', 'foo', 'bar', 'foo', 'bar'], 'B' : ['one', 'one', 'two', 'three', 'two', 'two', 'one', 'three'], 'C' : np.random.randn(8), 'D' : np.random.randn(8)}) print(df) print('对 A 列进行 group by') print(df.groupby('A').sum()) print('对 A 和 B 列进行 group by') print(df.groupby(['A', 'B']).sum()) split_line() print('数据透视表') df = pd.DataFrame({'A' : ['one', 'one', 'two', 'three'] * 3, 'B' : ['A', 'B', 'C'] * 4, 'C' : ['foo', 'foo', 'foo', 'bar', 'bar', 'bar'] * 2, 'D' : np.random.randn(12), 'E' :
np.random.randn(12)
numpy.random.randn
#! python3 # coding: utf-8 # * ===================================================================================== # * # * Filename: AMT_final.py # * # * Description: Python program for AMT2018 final thesis # * # * Version: 1.0 # * Created: 06/07/2018 07:09:10 PM # * Revision: none # * Interpreter: Python3.6 # * # * Author: <NAME>, <EMAIL> # * Organization: Tinjin University # * # * ===================================================================================== # #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 matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D import numpy as np from scipy.fftpack import fft import math_tool def polyfunc(r, theta): # description: Definition of the Zernike polynomial. Takes in r and theta, which is # the position based on cylindrical coordinate (CC), returns Z value on that # position, just like the literal function do. # param: r, theta # return: sum, which represents the value of Z ci = np.array([0 ,0, 0, 0, 1.205834, 1.209232, -0.073527, 0.283878, -0.047157, 0.69305, 0.0821, -0.520752, -0.054379, -0.092302, 0.02262, -0.009395], dtype=np.double) zi = np.array([1, r*np.cos(theta), r*np.sin(theta), 2*r**2-1, r**2*np.cos(2*theta), r**2*np.sin(2*theta), (3*r**2-2)*r*np.cos(theta), (3*r**2-2)*r*np.sin(theta), 6*r**4-6*r**2+1, r**3*np.cos(3*theta), r**3*np.sin(3*theta), (4*r**2-3)*r**2*np.cos(2*theta), (4*r**2-3)*r**2*np.sin(2*theta), (10*r**4-12*r**2+3)*r*np.cos(theta), (10*r**4-12*r**2+3)*r*np.sin(theta), 20*r**6-30*r**4+12*r**2-1], dtype = np.double) sum = 0 for i in np.arange(0, np.shape(ci)[0]): sum = sum+ci[i]*zi[i] return sum def rot(r, theta): # description: Definition of the conical section. Similar to polyfunc # param: r, theta # return: result, which represents the value of Z c = 1/594.51107 k = 0 numerator = c*r**2 denominator = 1+(1-(1+k)*c**2*r**2)**0.5 result = numerator/denominator return result def zfunc(r, theta): # description: Definition of the surface shape function. This function # is a combination of polyfunc and rot. Meanwhile, normalization # for r is processed. # param: r, theta # return: result, which represents the value of Z result = polyfunc(r/200, theta)+rot(r, theta) return result def rtheta2xy(func, x, y): # description: Takes a combination of x and y (under rectangular coordinates)(RC), # and gives the Z value of a function which takes cylindrical # coordinate (CC) at that point. # param: x, y: coordinate in rectangular coordinates (RC). # return: result, which represents the value of Z r = (x**2+y**2)**0.5 if x > 0: theta = np.arctan(y/x) elif x < 0: theta = np.arctan(y/x)+np.pi else: if y>=0: theta = np.pi/2 else: theta = -np.pi/2 result = func(r, theta) return result def get_rad_seq(rtfunc, r, N): # description: For a given function in cylindrical coordinate (CC), generate a # sample sequence of Z value on a specific circle with radius r. # param: rtfunc: the target function which is based on CC # r: radius of the circle # N: number of sample points # return: result, which is a generated sequence with length N result = np.zeros(N) vtheta = np.linspace(0, 2*np.pi, N) for i in np.arange(0, N): result[i] = rtfunc(r, vtheta[i]) return result def get_rad_fft(rtfunc, r, N, T, with_column_zero=1, abs = 1): # description: Generate a FFT sequence for a given function (CC). # param: rtfunc: the target function which is based on CC # r: radius of the circle # N: number of sample points # T: sample spacing # with_column_zero: controls whether the FFT sequence will # have 0th term, 1 (by default) # represents yes, 0 represents no # return: xf: frequency scale # yf: amplitude scale if (with_column_zero==1): x = np.linspace(0.0, N*T, N) y = get_rad_seq(rtfunc, r, N) yf_complex = fft(y) if (abs==1): yf = 1.0/N * np.abs(yf_complex) else: yf = 1.0/N * yf_complex xf = np.linspace(0.0, 1.0/T-1, N) return xf, yf elif (with_column_zero==0): x = np.linspace(0.0, N*T, N) y = get_rad_seq(rtfunc, r, N) yf_complex = fft(y)[1:] # yf = 1.0/N * np.abs(yf_complex) if (abs==1): yf = 1.0/N * np.abs(yf_complex) else: yf = 1.0/N * yf_complex xf = np.linspace(0.0, 1.0/T-1, N)[1:] return xf, yf def get_average_mean(func, r): # description: Calculate the mean z value at a certain r for a given function (CC). # param: func: the target function which is based on CC # r: radius of the circle # return: result: z value for given r and func count = 50 scale = np.linspace(0, 2*np.pi, count) samples = np.zeros(count) for i in np.arange(0, count): samples[i] = func(r, scale[i]) # print(samples) result = np.mean(samples) return result def get_average_fft(func, r): # description: Calculate the mean z value at a certain r for a given function (CC) # using the 2nd method: Process FFT, then pick up the zeroth term # NOTE:######################critical############################ # THERE MIGHT BE SOMETHING WRONG WITH THIS METHOD, USE "get_average" INSTEAD!!!!! # BECAUSE "get_rad_fft" RETURNS COMPLEX, THE RESULT IS NOT RELIABLE. # param: func: the target function which is based on CC # return: func_out: function that represents the rot composition, # whose input and output are similar to that of zfunc xf, yf = get_rad_fft(func, r, 50, 1.0/50.0, with_column_zero=1, abs=0) result = yf[0] return result def get_rot_part(func): # description: Get the rotation part in a given surface shape function # param: func: the target function which is based on CC # return: func_out: function that represents the rot composition, # whose input and output are similar to that of zfunc def func_out(r, theta): # return get_average_fft(func, r) return get_average_mean(func, r) return func_out def get_nonrot_part(func): # description: Get the non-rotation part in a given surface shape function, # similar to get_rot_part # param: func: the target function which is based on CC # return: func_out: function that represents the non-rot composition, # whose input and output are similar to that of zfunc rot_part = get_rot_part(func) def func_out(r, theta): value = func(r, theta)-rot_part(r, theta) return value return func_out def tool_rad_compensate(func, r_tool): # description: decorate func to output a compensated surface shape function # param: func: the target function which is based on CC # r_tool: radius of lathe tool # return: func_out: function that represents the compensated surface shape # function whose input and output are similar to that of zfunc def func_out(r, theta): def f(x): val = func(x, theta) return val df = math_tool.deriv_func(f) def diff_var_g(x): val = x - r_tool*df(x)/np.sqrt(1+df(x)**2)-r return val x = math_tool.solve_newton_method(diff_var_g, r) result = f(x)-r_tool/np.sqrt(1+df(x)**2) return result return func_out def plot_surface(func ,edge_r=15, title_sub='NO TITLE'): X=np.linspace(-edge_r, edge_r, 2*2*int(edge_r)+1) Y=np.linspace(-edge_r, edge_r, 2*2*int(edge_r)+1) #X, Y represent all possible values in the coordinate #using all possible values in linspace object to map all possible points X,Y=
np.meshgrid(X,Y)
numpy.meshgrid
"""Script for sampling COV, burstiness and memory coeficient, and their uncertainties, on many faults and plotting them <NAME> University of Otago 2020 """ import os, sys import ast from glob import glob from operator import itemgetter from re import finditer import numpy as np from scipy.optimize import curve_fit from scipy.odr import Model, RealData, ODR import scipy.odr.odrpack as odrpack from scipy.stats import expon, gamma, weibull_min, ks_2samp, kstest # !!! Dangerous hack to swap Weibull for gamma #from scipy.stats import weibull_min as gamma # # !!! from matplotlib import pyplot from matplotlib.patches import PathPatch import matplotlib.gridspec as gridspec from matplotlib.ticker import FormatStrFormatter from scipy.stats import binom, kde from adjustText import adjust_text from QuakeRates.dataman.event_dates import EventSet from QuakeRates.dataman.parse_oxcal import parse_oxcal from QuakeRates.dataman.parse_age_sigma import parse_age_sigma from QuakeRates.dataman.parse_params import parse_param_file, \ get_event_sets, file_len from QuakeRates.utilities.bilinear import bilinear_reg_zero_slope, \ bilinear_reg_fix, bilinear_reg_fix_zero_slope from QuakeRates.utilities.memory_coefficient import burstiness, memory_coefficient filepath = '../params' param_file_list = glob(os.path.join(filepath, '*.txt')) param_file_list_NZ = ['Akatore_TaylorSilva_2019.txt', 'AlpineHokuriCk_Berryman_2012_simple.txt', 'AlpineSouthWestland_Cochran_2017_simple.txt', 'AwatereEast_Nicol_2016_simple.txt', 'ClarenceEast_Nicol_2016_simple.txt', 'CloudyFault_Nicol_2016_simple.txt', 'Dunstan_GNS_unpub_simple.txt', 'HopeConway_Hatem_2019_simple.txt', 'Hope_Khajavi_2016_simple.txt', 'Ihaia_Nicol_2016_simple.txt', 'Oaonui_Nicol_2016_simple.txt', 'Ohariu_Nicol_2016_simple.txt', 'Paeroa_Nicol_2016_simple.txt', 'Pihama_Nicol_2016_simple.txt', 'PortersPassEast_Nicol_2016_simple.txt', 'Ngakuru_Nicol_2016_simple.txt', 'Mangatete_Nicol_2016_simple.txt', 'Rangipo_Nicol_2016_simple.txt', 'Rotoitipakau_Nicol_2016_simple.txt', 'Rotohauhau_Nicol_2016_simple.txt', 'Snowden_Nicol_2016_simple.txt', 'Vernon_Nicol_2016_simple.txt', 'WairarapaSouth_Nicol_2016_simple.txt', 'Wairau_Nicol_2018_simple.txt', 'Waimana_Nicol_2016_simple.txt', 'Wellington_Langridge_2011_simple.txt', 'Waitangi_GNS_unpub_simple.txt', 'Whakatane_Nicol_2016_simple.txt', 'Whirinaki_Nicol_2016_simple.txt'] # List of faults in study by Williams et al 2019 # Note this is not entirely the same, as there are some records from # that study that are not included in ours. param_file_list_W = ['AlpineHokuriCk_Berryman_2012_simple.txt', 'HaywardTysons_Lienkaemper_2007_simple.txt', 'SanJacintoMysticLake_Onderdonk_2018_simple.txt', 'NorthAnatolianElmacik_Fraser_2010_simple.txt', 'SanAndreasWrightwood_Weldon_2004_simple.txt', 'SanAndreasCarizzo_Akciz_2010_simple.txt', 'SanJacintoHogLake_Rockwell_2015_simple.txt', 'SanAndreasMissionCk_Fumal_2002_simple.txt', 'SanAndreasPalletCk_Scharer_2011_simple.txt', 'Xorkoli_Altyn_Tagh_Yuan_2018.txt', 'NorthAnatolianYaylabeli_Kozaci_2011_simple.txt', 'ElsinoreTemecula_Vaughan_1999_simple.txt', 'DeadSeaJordan_Ferry_2011_simple.txt', 'SanAndreasBigBend_Scharer_2017_simple.txt', 'WasatchBrigham_McCalpin_1996_simple.txt', 'Irpinia_Pantosti_1993_simple.txt', 'WasatchWeber_Duross_2011_simple.txt', 'WasatchNilphi_Duross_2017_simple.txt', 'LomaBlanca_Williams_2017_simple.txt', 'AlaskaPWSCopper_Plafker_1994_simple.txt', 'NankaiTrough_Hori_2004_simple.txt', 'CascadiaNth_Adams_1994_simple.txt', 'CascadiaSth_Goldfinger_2003_simple.txt', 'JavonCanyon_SarnaWojicki_1987_simple.txt', 'NewGuinea_Ota_1996_simple.txt', 'ChileMargin_Moernaut_2018_simple.txt'] #param_file_list = [] #for f in param_file_list_NZ: #for f in param_file_list_W: # param_file_list.append(os.path.join(filepath, f)) n_samples = 10000 # Number of Monte Carlo samples of the eq chronologies half_n = int(n_samples/2) print(half_n) annotate_plots = False # If True, lable each fault on the plot plot_folder = './plots' if not os.path.exists(plot_folder): os.makedirs(plot_folder) # Define subset to take #faulting_styles = ['Reverse'] #faulting_styles = ['Normal'] #faulting_styles = ['Strike_slip'] faulting_styles = ['all'] tectonic_regions = ['all'] #tectonic_regions = ['Intraplate_noncratonic', 'Intraplate_cratonic', 'Near_plate_boundary'] #tectonic_regions = ['Plate_boundary_master', 'Plate_boundary_network'] #tectonic_regions = ['Plate_boundary_network', 'Near_plate_boundary'] #tectonic_regions = ['Plate_boundary_master'] #tectonic_regions = ['Subduction'] #tectonic_regions = ['Near_plate_boundary'] min_number_events = 5 # Use for all other calculations. min_num_events_mem = 6 # Use for memory coefficient #Summarise for comment to add to figure filename fig_comment = '' #fig_comment = 'NZ_examples_' #fig_comment = 'Williams2019_' for f in faulting_styles: fig_comment += f fig_comment += '_' for t in tectonic_regions: fig_comment += t fig_comment += '_' fig_comment += str(min_number_events) #fig_comment += 'test_add_event_data' def piecewise_linear(x, x0, y0, k1, k2): return np.piecewise(x, [x < x0], [lambda x:k1*x + y0-k1*x0, lambda x:k2*x + y0-k2*x0]) def camel_case_split(identifier): matches = finditer('.+?(?:(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|$)', identifier) return [m.group(0) for m in matches] plot_colours = [] all_ie_times = [] added_events = [] # Store names of records where we've added an event due to # exceptionally long current open interval covs = [] cov_bounds = [] burstinesses = [] burstiness_bounds = [] burstiness_stds = [] burstinesses_expon = [] burstinesses_gamma = [] ie_gamma_alpha = [] memory_coefficients = [] memory_bounds = [] memory_stds = [] memory_spearman_coefficients = [] memory_spearman_bounds = [] memory_spearman_lag2_coef = [] memory_spearman_lag2_bounds = [] long_term_rates = [] long_term_rate_stds = [] slip_rates = [] slip_rate_stds = [] slip_rate_bounds = [] max_interevent_times = [] min_interevent_times = [] min_paired_interevent_times = [] std_min_paired_interevent_times = [] std_min_interevent_times = [] std_max_interevent_times = [] max_interevent_times_bounds = [] min_interevent_times_bounds = [] min_paired_interevent_times_bounds = [] ratio_min_pair_max = [] ratio_min_max = [] std_ratio_min_pair_max = [] std_ratio_min_max = [] ratio_min_pair_max_bounds =[] ratio_min_max_bounds = [] names, event_sets, event_certainties, num_events, tect_regions, fault_styles = \ get_event_sets(param_file_list, tectonic_regions, faulting_styles, min_number_events) references = [] # Get citations for each dataset from filename for s in param_file_list: sp = s.split('_') if sp[0].split('/')[2] in names: references.append(sp[1] + ' ' + sp[2]) n_faults = len(names) print('Number of faults', n_faults) for i, event_set in enumerate(event_sets): # Handle cases with uncertain number of events. Where events identification is # unsure, event_certainty is given a value of 0, compared with 1 for certain # events # First generate chronologies assuming all events are certain # event_set.name = names[i] event_set.gen_chronologies(n_samples, observation_end=2020, min_separation=1) event_set.calculate_cov() event_set.cov_density() event_set.memory_coefficient() event_set.memory_spearman_rank_correlation() # Store all inter-event times for global statistics all_ie_times.append(event_set.interevent_times) # Now calculate some statistics on the sampled chronologies event_set.basic_chronology_stats() # Plot histogram of interevent times figfile = os.path.join(plot_folder, ('interevent_times_%s.png' % names[i])) event_set.plot_interevent_time_hist(fig_filename=figfile) # Fit gamma distirbution to event set data event_set.fit_gamma() ie_gamma_alpha.append(event_set.mean_gamma_alpha_all) # Get mean estimate of alpha min_paired_interevent_times.append(event_set.mean_minimum_pair_interevent_time) max_interevent_times.append(event_set.mean_maximum_interevent_time) min_interevent_times.append(event_set.mean_minimum_interevent_time) std_min_paired_interevent_times.append(event_set.std_minimum_pair_interevent_time) std_min_interevent_times.append(event_set.std_minimum_interevent_time) std_max_interevent_times.append(event_set.std_maximum_interevent_time) if event_set.std_maximum_interevent_time == 0: print('Zero std_maximum_interevent_time for ', names[i]) slip_rates.append(event_set.slip_rates[0]) slip_rate_bounds.append([event_set.slip_rates[1], event_set.slip_rates[2]]) slip_rate_stds.append(abs(np.log10(event_set.slip_rates[2]) - \ np.log10(event_set.slip_rates[1]))/4) # Approx from 95% intervals max_interevent_times_bounds.append([abs(event_set.mean_maximum_interevent_time - event_set.maximum_interevent_time_lb), abs(event_set.mean_maximum_interevent_time - event_set.maximum_interevent_time_ub)]) min_interevent_times_bounds.append([abs(event_set.mean_minimum_interevent_time - event_set.minimum_interevent_time_lb), abs(event_set.mean_minimum_interevent_time - event_set.minimum_interevent_time_ub)]) min_paired_interevent_times_bounds.append([abs(event_set.mean_minimum_pair_interevent_time - event_set.minimum_pair_interevent_time_lb), abs(event_set.mean_minimum_pair_interevent_time - event_set.minimum_pair_interevent_time_ub)]) ratio_min_pair_max.append(event_set.mean_ratio_min_pair_max) ratio_min_max.append(event_set.mean_ratio_min_max) std_ratio_min_pair_max.append(event_set.std_ratio_min_pair_max) std_ratio_min_max.append(event_set.std_ratio_min_max) ratio_min_pair_max_bounds.append([abs(event_set.mean_ratio_min_pair_max - event_set.ratio_min_pair_max_lb), abs(event_set.mean_ratio_min_pair_max - event_set.ratio_min_pair_max_ub)]) ratio_min_max_bounds.append([abs(event_set.mean_ratio_min_max - event_set.ratio_min_max_lb), abs(event_set.mean_ratio_min_max - event_set.ratio_min_max_ub)]) # Generate random exponentially and gamma distributed samples of length num_events - 1 # i.e. the number of inter-event times in the chronology. These will be used # later for testing scale = 100 # Fix scale, as burstiness is independent of scale for exponentiall distribution ie_times_expon = expon(scale=scale).rvs(size=(n_samples*(event_set.num_events-1))) ie_times_expon = np.reshape(np.array(ie_times_expon), (n_samples, (event_set.num_events-1))) ie_times_expon_T = ie_times_expon.T burst_expon = burstiness(ie_times_expon_T) # Gamma alpha_g = 2.3 #2.2 #1.6 ##2.35 #2.4 #2.0 ie_times_g = gamma(alpha_g, scale=scale).rvs(size=(n_samples*(event_set.num_events-1))) ie_times_g = np.reshape(np.array(ie_times_g), (n_samples, (event_set.num_events-1))) ie_times_g_T = ie_times_g.T burst_g = burstiness(ie_times_g_T) # Now generate chronologies assuming uncertain events did not occur if sum(event_certainties[i]) < event_set.num_events: indices = np.where(event_certainties[i] == 1) indices = list(indices[0]) # print(indices[0], type(indices)) events_subset = list(itemgetter(*indices)(event_set.event_list)) event_set_certain = EventSet(events_subset) event_set_certain.name = names[i] event_set_certain.gen_chronologies(n_samples, observation_end=2019, min_separation=1) event_set_certain.calculate_cov() event_set_certain.cov_density() event_set_certain.basic_chronology_stats() event_set_certain.memory_coefficient() event_set_certain.memory_spearman_rank_correlation() # Generate random exponentially distributed samples of length num_events - 1 # i.e. the number of inter-event times in the chronology. These will be used # later for testing ie_times_expon_certain = expon(scale=scale).rvs(size=(n_samples*(len(indices)-1))) ie_times_expon_certain = np.reshape(np.array(ie_times_expon_certain), (n_samples, (len(indices)-1))) ie_times_expon_certain_T = ie_times_expon_certain.T burst_expon_certain = burstiness(ie_times_expon_certain_T) ie_times_g_certain = gamma(alpha_g, scale=scale).rvs(size=(n_samples*(event_set.num_events-1))) ie_times_g_certain = np.reshape(np.array(ie_times_g_certain), (n_samples, (event_set.num_events-1))) ie_times_g_certain_T = ie_times_g_certain.T burst_g_certain = burstiness(ie_times_g_T) # Now combine results from certain chronolgies with uncertain ones combined_covs = np.concatenate([event_set.covs[:half_n], event_set_certain.covs[:half_n]]) combined_burstiness = np.concatenate([event_set.burstiness[:half_n], event_set_certain.burstiness[:half_n]]) combined_memory = np.concatenate([event_set.mem_coef[:half_n], event_set_certain.mem_coef[:half_n]]) combined_memory_spearman = np.concatenate([event_set.rhos[:half_n], event_set_certain.rhos[:half_n]]) combined_memory_spearman_lag2 = np.concatenate([event_set.rhos2[:half_n], event_set_certain.rhos2[:half_n]]) combined_burst_expon = np.concatenate([burst_expon[:half_n], burst_expon_certain[:half_n]]) combined_burst_g = np.concatenate([burst_g[:half_n], burst_g_certain[:half_n]]) covs.append(combined_covs) burstinesses.append(combined_burstiness) memory_coefficients.append(combined_memory) memory_stds.append(np.std(np.array(combined_memory))) memory_spearman_coefficients.append(combined_memory_spearman) memory_spearman_lag2_coef.append(combined_memory_spearman_lag2) burstinesses_expon.append(combined_burst_expon) burstinesses_gamma.append(combined_burst_g) cov_bounds.append([abs(np.mean(combined_covs) - \ min(event_set.cov_lb, event_set_certain.cov_lb)), abs(np.mean(combined_covs) - \ max(event_set.cov_ub, event_set_certain.cov_ub))]) burstiness_bounds.append([abs(np.mean(combined_burstiness) - \ min(event_set.burstiness_lb, event_set_certain.burstiness_lb)), abs(np.mean(combined_burstiness) - \ max(event_set.burstiness_ub, event_set_certain.burstiness_ub))]) memory_bounds.append([abs(np.mean(combined_memory) - \ min(event_set.memory_lb, event_set_certain.memory_lb)), abs(np.mean(combined_memory) - \ max(event_set.memory_ub, event_set_certain.memory_ub))]) memory_spearman_bounds.append([abs(np.mean(combined_memory_spearman) - \ min(event_set.rho_lb, event_set_certain.rho_lb)), abs(np.mean(combined_memory_spearman) - \ max(event_set.rho_ub, event_set_certain.rho_ub))]) memory_spearman_lag2_bounds.append([abs(np.mean(combined_memory_spearman_lag2) - \ min(event_set.rho2_lb, event_set_certain.rho2_lb)), abs(np.mean(combined_memory_spearman_lag2) - \ max(event_set.rho2_ub, event_set_certain.rho2_ub))]) # Combine, taking n/2 samples from each set combined_ltrs = np.concatenate([event_set.long_term_rates[:half_n], event_set_certain.long_term_rates[:half_n]]) burstiness_stds.append(np.std(combined_burstiness)) print(len(combined_ltrs)) long_term_rates.append(combined_ltrs) long_term_rate_stds.append(np.std(combined_ltrs)) else: covs.append(event_set.covs) burstinesses.append(event_set.burstiness) memory_coefficients.append(event_set.mem_coef) memory_stds.append(np.std(np.array(event_set.mem_coef))) memory_spearman_coefficients.append(event_set.rhos) memory_spearman_lag2_coef.append(event_set.rhos2) long_term_rates.append(event_set.long_term_rates) burstinesses_expon.append(burst_expon) burstinesses_gamma.append(burst_g) cov_bounds.append([abs(event_set.mean_cov - event_set.cov_lb), abs(event_set.mean_cov - event_set.cov_ub)]) burstiness_bounds.append([abs(event_set.mean_burstiness - event_set.burstiness_lb), abs(event_set.mean_burstiness - event_set.burstiness_ub)]) memory_bounds.append([abs(event_set.mean_mem_coef - event_set.memory_lb), abs(event_set.mean_mem_coef - event_set.memory_ub)]) memory_spearman_bounds.append([abs(event_set.mean_rho - event_set.rho_lb), abs(event_set.mean_rho - event_set.rho_ub)]) memory_spearman_lag2_bounds.append([abs(event_set.mean_rho2 - event_set.rho2_lb), abs(event_set.mean_rho2 - event_set.rho2_ub)]) burstiness_stds.append(event_set.std_burstiness) long_term_rate_stds.append(np.mean(long_term_rates)) # Get colours for plotting later if event_set.faulting_style == 'Normal': plot_colours.append('r') elif event_set.faulting_style == 'Reverse': plot_colours.append('b') elif event_set.faulting_style == 'Strike_slip': plot_colours.append('g') else: plot_colours.append('k') if event_set.add_events: # List of records where we model long open interval added_events.append(event_set.name) # Convert to numpy arrays and transpose where necessary num_events = np.array(num_events) all_ie_times = np.array(all_ie_times) max_interevent_times = np.array(max_interevent_times) min_interevent_times = np.array(min_interevent_times) min_paired_interevent_times = np.array(min_paired_interevent_times) std_max_interevent_times = np.array(std_max_interevent_times) std_min_interevent_times = np.array(std_min_interevent_times) std_min_paired_interevent_times = np.array(std_min_paired_interevent_times) max_interevent_times_bounds = np.array(max_interevent_times_bounds).T min_interevent_times_bounds = np.array(min_interevent_times_bounds).T min_paired_interevent_times_bounds = np.array(min_paired_interevent_times_bounds).T long_term_rates_T = np.array(long_term_rates).T mean_ltr = np.mean(long_term_rates_T, axis = 0) long_term_rate_stds = np.array(long_term_rate_stds) slip_rates = np.array(slip_rates).T slip_rate_bounds = np.array(slip_rate_bounds).T slip_rate_stds = np.array(slip_rate_stds).T print('Mean_ltr', mean_ltr) std_ltr = np.std(long_term_rates_T, axis = 0) ltr_bounds = np.array([abs(mean_ltr - (np.percentile(long_term_rates_T, 2.5, axis=0))), abs(mean_ltr - (np.percentile(long_term_rates_T, 97.5, axis=0)))]) ratio_min_pair_max = np.array(ratio_min_pair_max) ratio_min_max = np.array(ratio_min_max) std_ratio_min_pair_max = np.array(std_ratio_min_pair_max) std_ratio_min_max = np.array(std_ratio_min_max) ratio_min_pair_max_bounds = np.array(ratio_min_pair_max_bounds).T ratio_min_max_bounds = np.array(ratio_min_max_bounds).T cov_bounds = np.array(cov_bounds).T burstiness_bounds = np.array(burstiness_bounds).T burstiness_stds = np.array(burstiness_stds) burstiness_expon = np.array(burstinesses_expon) burstiness_gamma = np.array(burstinesses_gamma) inds = np.where(num_events >= min_num_events_mem) # Get memory coefficients for more than 6 events memory_coefficients = np.array(memory_coefficients) memory_coefficients_min = memory_coefficients[inds] memory_stds = np.array(memory_stds) memory_stds_min = memory_stds[inds] memory_bounds_min = np.array(memory_bounds)[inds].T memory_bounds = np.array(memory_bounds).T memory_spearman_bounds = np.array(memory_spearman_bounds).T memory_spearman_lag2_bounds = np.array(memory_spearman_lag2_bounds).T ie_gamma_alpha = np.array(ie_gamma_alpha) # Now plot the means and 95% error bars of COV pyplot.clf() ax = pyplot.subplot(111) mean_covs = [] for i, cov_set in enumerate(covs): mean_cov = np.mean(cov_set) mean_covs.append(mean_cov) colours = [] for mean_cov in mean_covs: if mean_cov <= 0.9: colours.append('b') elif mean_cov > 0.9 and mean_cov <= 1.1: colours.append('g') else: colours.append('r') pyplot.errorbar(mean_ltr, mean_covs, xerr = ltr_bounds, ecolor = '0.3', elinewidth=0.7, linestyle="None", zorder=1) pyplot.errorbar(mean_ltr, mean_covs, yerr = cov_bounds, ecolor = '0.3', elinewidth=0.7, linestyle="None", zorder=1) pyplot.scatter(mean_ltr, mean_covs, marker = 's', c=plot_colours, s=25, zorder=2) for i, txt in enumerate(names): if max_interevent_times[i] > 10 and annotate_plots: ax.annotate(txt[:4], (mean_ltr[i], mean_covs[i]), fontsize=8) ax.set_ylim([0, 2.5]) ax.set_xlim([1./1000000, 1./40]) ax.set_xscale('log') ax.set_xlabel('Long-term rate (events per year)') ax.set_ylabel('COV') figname = 'mean_cov_vs_lt_rate_%s.png' % fig_comment pyplot.savefig(figname) ################################ # Plot burstiness against mean ltr pyplot.clf() ax = pyplot.subplot(111) mean_bs = [] for i, b_set in enumerate(burstinesses): mean_b = np.mean(b_set) mean_bs.append(mean_b) colours = [] for mean_b in mean_bs: if mean_b <= -0.05: colours.append('b') elif mean_b > -0.05 and mean_b <= 0.05: colours.append('g') else: colours.append('r') pyplot.errorbar(mean_ltr, mean_bs, xerr = ltr_bounds, ecolor = '0.3', elinewidth=0.7, linestyle="None", zorder=1) pyplot.errorbar(mean_ltr, mean_bs, yerr = burstiness_bounds, ecolor = '0.3', elinewidth=0.7, linestyle="None", zorder=1) pyplot.scatter(mean_ltr, mean_bs, marker = 's', c=plot_colours, s=25, zorder=2) for i, txt in enumerate(names): if max_interevent_times[i] > 10 and annotate_plots: ax.annotate(txt[:4], (mean_ltr[i], mean_bs[i]), fontsize=8) # Add B=0 linear pyplot.plot([1./1000000, 1./40], [0, 0], linestyle='dashed', linewidth=1, c='0.5') ax.set_xscale('log') ax.set_xlabel('Long-term rate (events per year)') ax.set_ylabel('B') # Now do a bi-linear fit to the data mean_bs = np.array(mean_bs) indices = np.flatnonzero(mean_ltr > 3e-4) indices = indices.flatten() indices_slow_faults = np.flatnonzero(mean_ltr <= 3e-4) indices_slow_faults = indices_slow_faults.flatten() # Fit fast rate faults lf = np.polyfit(np.log10(mean_ltr[indices]), mean_bs[indices], 1) # Now force to be a flat line1 lf[0] = 0. lf[1] = np.mean(mean_bs[indices]) std_lf = np.std(mean_bs[indices]) xvals_short = np.arange(1.5e-4, 2e-2, 1e-4) yvals = lf[0]*np.log10(xvals_short) + lf[1] pyplot.plot(xvals_short, yvals, c='0.2') # Fit slow faults if len(indices_slow_faults > 1): lf_slow = np.polyfit(np.log10(mean_ltr[indices_slow_faults]), mean_bs[indices_slow_faults], 1) xvals_short = np.arange(1e-6, 1.5e-4, 1e-6) yvals = lf_slow[0]*np.log10(xvals_short) + lf_slow[1] pyplot.plot(xvals_short, yvals, c='0.2') # Add formula for linear fits of data print('Fits for B vs LTR') txt = 'Y = {:=+6.2f} +/- {:4.2f}'.format(lf[1], std_lf) print(txt) ax.annotate(txt, (2e-4, 0.2), fontsize=8) try: txt = 'Y = {:4.2f}Log(x) {:=+6.2f}'.format(lf_slow[0], lf_slow[1]) print(txt) ax.annotate(txt, (1.5e-6, 0.75), fontsize=8) except: pass # Now try bilinear ODR linear fit data = odrpack.RealData(np.log10(mean_ltr), mean_bs, sx=np.log10(long_term_rate_stds), sy=burstiness_stds) bilin = odrpack.Model(bilinear_reg_zero_slope) odr = odrpack.ODR(data, bilin, beta0=[-3, -1.0, -4]) # array are starting values odr.set_job(fit_type=0) out = odr.run() print(out.sum_square) out.pprint() a = out.beta[0] b = out.beta[1] hx = out.beta[2] xvals = np.arange(1.e-6, 2e-2, 1e-6) yrng = a*np.log10(xvals) + b #10**(b + a * xvals) ylevel = a*hx + b #10**(b + a * hx) print('ylevel', ylevel) print(10**ylevel) idx = xvals > 10**hx yrng[idx] = (ylevel) print('yrng', yrng) print('hx', hx) pyplot.plot(xvals, yrng, c='g') # Bilinear fixed hinge hxfix = np.log10(2e-4) bilin_hxfix_cons_slope = odrpack.Model(bilinear_reg_fix_zero_slope) odr = odrpack.ODR(data, bilin_hxfix_cons_slope, beta0=[-3, -1.0]) odr.set_job(fit_type=0) out = odr.run() print('bilinear hxfix_cons_slope') print(out.sum_square) out.pprint() a = out.beta[0] b = out.beta[1] yrng = a*np.log10(xvals) + b ylevel = a*hxfix + b print('ylevel hxfix zero slope', ylevel) print(10**ylevel) idx = xvals > 10**hxfix yrng[idx] = (ylevel) print('yrng', yrng) print('hx', hxfix) pyplot.plot(xvals, yrng, c='r') figname = 'burstiness_vs_lt_rate_%s.png' % fig_comment pyplot.savefig(figname) ######################### # Plot burstiness against slip rate pyplot.clf() ax = pyplot.subplot(111) pyplot.errorbar(slip_rates, mean_bs, xerr = slip_rate_bounds, ecolor = '0.3', elinewidth=0.7, linestyle="None", zorder=1) pyplot.errorbar(slip_rates, mean_bs, yerr = burstiness_bounds, ecolor = '0.3', elinewidth=0.7, linestyle="None", zorder=1) pyplot.scatter(slip_rates, mean_bs, marker = 's', c=plot_colours, s=25, zorder=2) ax.set_ylim([-1, 1]) ax.set_xlim([1./1000, 100]) # Add B=0 linear pyplot.plot([1./1000, 100], [0, 0], linestyle='dashed', linewidth=1, c='0.5') ax.set_xscale('log') ax.set_xlabel('Slip rate (mm/yr)') ax.set_ylabel('B') # Now try linear ODR linear fit def f(B, x): return B[0]*x + B[1] print(slip_rates) print(np.log10(slip_rates)) print(slip_rate_stds) print(np.log10(slip_rate_stds)) print(burstiness_stds) wd = 1./np.power(burstiness_stds, 2) print(wd) we = 1./np.power(slip_rate_stds, 2) print(we) # Std dev already in log-space data = odrpack.RealData(np.log10(slip_rates), mean_bs, sx=np.sqrt(slip_rate_stds), sy=np.sqrt(burstiness_stds)) linear = odrpack.Model(f) odr = odrpack.ODR(data, linear, beta0=[-1, -1.0,]) odr.set_job(fit_type=0) out = odr.run() out.pprint() a = out.beta[0] b = out.beta[1] xvals = np.arange(1.e-4, 1e2, 1e-2) yrng = a*np.log10(xvals) + b #10**(b + a * xvals) pyplot.plot(xvals, yrng, c='0.6') txt = 'Y = {:4.2f}Log(x) {:=+6.2f}'.format(a, b) print(txt) ax.annotate(txt, (1e0, 0.9), color='0.6') # Now try bilinear fixed hinge bilin = odrpack.Model(bilinear_reg_fix_zero_slope) odr = odrpack.ODR(data, bilin, beta0=[-1, -1.0, -1]) odr.set_job(fit_type=0) out = odr.run() out.pprint() a = out.beta[0] b = out.beta[1] yrng = a*np.log10(xvals) + b ylevel = a*hxfix + b print('ylevel hxfix zero slope', ylevel) print(10**ylevel) idx = xvals > 10**hxfix yrng[idx] = (ylevel) print('yrng', yrng) print('hx', hxfix) pyplot.plot(xvals, yrng, c='0.2') txt = 'Y = {:4.2f}Log(x) {:=+6.2f}, x < {:4.2f}'.format(a, b, np.power(10,hxfix)) print(txt) ax.annotate(txt, (2e-3, 0.9), color='0.2') txt = 'Y = {:4.2f}, x >= {:4.2f}'.format(ylevel, np.power(10,hxfix)) print(txt) ax.annotate(txt, (1.2e-2, 0.8), color='0.2') figname = 'burstiness_vs_slip_rate_%s.png' % fig_comment pyplot.savefig(figname) figname = 'burstiness_vs_slip_rate_%s.pdf' % fig_comment pyplot.savefig(figname) # Plot memory coefficients against long term rates pyplot.clf() ax = pyplot.subplot(111) mean_mems = [] mean_ltr_mem = mean_ltr[inds] ltr_bounds_mem = ltr_bounds.T[inds].T for i, mem_set in enumerate(memory_coefficients): mean_mem = np.mean(mem_set) # print('Mean memory coefficient combined', mean_mem) mean_mems.append(mean_mem) mean_mems = np.array(mean_mems) colours = [] plot_colours_mem = list(np.array(plot_colours)[inds]) for mean_mem in mean_mems: if mean_mem <= -0.05: colours.append('b') elif mean_mem > -0.05 and mean_mem <= 0.05: colours.append('g') else: colours.append('r') pyplot.errorbar(mean_ltr_mem, mean_mems[inds], xerr = ltr_bounds_mem, ecolor = '0.3', elinewidth=0.7, linestyle="None", zorder=1) pyplot.errorbar(mean_ltr_mem, mean_mems[inds], yerr = memory_bounds_min, ecolor = '0.3', elinewidth=0.7, linestyle="None", zorder=1) pyplot.scatter(mean_ltr_mem, mean_mems[inds], marker = 's', c=plot_colours_mem, s=25, zorder=2) for i, txt in enumerate(names): if max_interevent_times[i] > 10 and annotate_plots: ax.annotate(txt[:4], (mean_ltr[i], mean_mems[i]), fontsize=8) ax.set_xlim([1./1000000, 1./40]) ax.set_xscale('log') ax.set_xlabel('Long-term rate (events per year)') ax.set_ylabel('M') figname = 'memory_coefficient_vs_lt_rate_%s.png' % fig_comment pyplot.savefig(figname) # Plot Spearman Rank coefficients against long term rates pyplot.clf() ax = pyplot.subplot(111) mean_mems_L1 = [] for i, mem_set in enumerate(memory_spearman_coefficients): mean_mem = np.mean(mem_set) mean_mems_L1.append(mean_mem) colours = [] for mean_mem in mean_mems_L1: if mean_mem <= -0.05: colours.append('b') elif mean_mem > -0.05 and mean_mem <= 0.05: colours.append('g') else: colours.append('r') pyplot.errorbar(mean_ltr, mean_mems_L1, xerr = ltr_bounds, ecolor = '0.3', elinewidth=0.7, linestyle="None", zorder=1) pyplot.errorbar(mean_ltr, mean_mems_L1, yerr = memory_spearman_bounds, elinewidth=0.7, ecolor = '0.3', linestyle="None", zorder=1) pyplot.scatter(mean_ltr, mean_mems_L1, marker = 's', c=plot_colours, s=25, zorder=2) for i, txt in enumerate(names): if max_interevent_times[i] > 10 and annotate_plots: ax.annotate(txt[:4], (mean_ltr[i], mean_mems_L1[i]), fontsize=8) ax.set_xlim([1./1000000, 1./40]) ax.set_xscale('log') ax.set_xlabel('Long-term rate (events per year)') ax.set_ylabel('M (Spearman Rank)') figname = 'memory_coefficient_Spearman_vs_lt_rate_%s.png' % fig_comment pyplot.savefig(figname) # Plot Spearman Rank (Lag-2) coefficients against long term rates pyplot.clf() ax = pyplot.subplot(111) mean_mems_L2 = [] for i, mem_set in enumerate(memory_spearman_lag2_coef): mean_mem = np.mean(mem_set) mean_mems_L2.append(mean_mem) colours = [] for mean_mem in mean_mems_L2: if mean_mem <= -0.05: colours.append('b') elif mean_mem > -0.05 and mean_mem <= 0.05: colours.append('g') else: colours.append('r') pyplot.errorbar(mean_ltr, mean_mems_L2, xerr = ltr_bounds, ecolor = '0.3', elinewidth=0.7, linestyle="None", zorder=1) pyplot.errorbar(mean_ltr, mean_mems_L2, yerr = memory_spearman_lag2_bounds, ecolor = '0.3', elinewidth=0.7, linestyle="None", zorder=1) pyplot.scatter(mean_ltr, mean_mems_L2, marker = 's', c=plot_colours, s=25, zorder=2) for i, txt in enumerate(names): if max_interevent_times[i] > 10 and annotate_plots: ax.annotate(txt[:4], (mean_ltr[i], mean_mems_L2[i]), fontsize=8) ax.set_xlim([1./1000000, 1./40]) ax.set_xscale('log') ax.set_xlabel('Long-term rate (events per year)') ax.set_ylabel('M (Spearman Rank Lag-2)') figname = 'memory_coefficient_Spearman_Lag2_vs_lt_rate_%s.png' % fig_comment pyplot.savefig(figname) # Plot Spearman rank Lag-1 against Lag-2 # Plot Spearman Rank coefficients against long term rates pyplot.clf() ax = pyplot.subplot(111) colours = [] for mean_mem in mean_mems_L1: if mean_mem <= -0.05: colours.append('b') elif mean_mem > -0.05 and mean_mem <= 0.05: colours.append('g') else: colours.append('r') pyplot.errorbar(mean_mems_L1, mean_mems_L2, xerr = memory_spearman_bounds, ecolor = '0.3', elinewidth=0.7, linestyle="None", zorder=1) pyplot.errorbar(mean_mems_L1, mean_mems_L2, yerr = memory_spearman_lag2_bounds, ecolor = '0.3', elinewidth=0.7, linestyle="None", zorder=1) pyplot.scatter(mean_mems_L1, mean_mems_L2, marker = 's', c=plot_colours, s=25, zorder=2) for i, txt in enumerate(names): if max_interevent_times[i] > 10 and annotate_plots: ax.annotate(txt[:4], (mean_mems_L1[i], mean_mems_L2[i]), fontsize=8) ax.set_xlabel('M (Spearman Rank Lag-1)') ax.set_ylabel('M (Spearman Rank Lag-2)') figname = 'memory_coefficient_Spearman_L1_vs_L2_%s.png' % fig_comment pyplot.savefig(figname) # Plot COV against number of events to look at sampling biases pyplot.clf() ax = pyplot.subplot(111) mean_covs = [] for i, cov_set in enumerate(covs): mean_cov = np.mean(cov_set) mean_covs.append(mean_cov) colours = [] for mean_cov in mean_covs: if mean_cov <= 0.9: colours.append('b') elif mean_cov > 0.9 and mean_cov <= 1.1: colours.append('g') else: colours.append('r') pyplot.errorbar(mean_covs, num_events, xerr = cov_bounds, ecolor = '0.6', linestyle="None") pyplot.scatter(mean_covs, num_events, marker = 's', c=plot_colours, s=25) for i, txt in enumerate(names): if max_interevent_times[i] > 10 and annotate_plots: ax.annotate(txt[:4], (mean_covs[i], num_events[i]), fontsize=8) ax.set_xlabel('COV') ax.set_ylabel('Number of events in earthquake record') figname = 'mean_cov_vs_number_events_%s.png' % fig_comment pyplot.savefig(figname) # Now plot basic statistics pyplot.clf() ax = pyplot.subplot(111) pyplot.errorbar(max_interevent_times, min_interevent_times, yerr = min_interevent_times_bounds, ecolor = '0.3', elinewidth=0.7, linestyle="None", zorder=1) pyplot.errorbar(max_interevent_times, min_interevent_times, xerr = max_interevent_times_bounds, ecolor = '0.3', elinewidth=0.7, linestyle="None", zorder=1) pyplot.scatter(max_interevent_times, min_interevent_times, marker = 's', c=colours, s=25, zorder=2) ax.set_xlabel('Maximum interevent time') ax.set_ylabel('Minimum interevent time') ax.set_xscale('log') ax.set_yscale('log') # Label low-slip rate faults for i, txt in enumerate(names): if max_interevent_times[i] > 10 and annotate_plots: ax.annotate(txt[:4], (max_interevent_times[i], min_interevent_times[i]), fontsize=8) # Linear fit only bottom end of data indices = np.argwhere(max_interevent_times < 10000).flatten() indices_slow_faults = np.argwhere(max_interevent_times >= 10000).flatten() lf = np.polyfit(np.log10(max_interevent_times[indices]), np.log10(min_interevent_times[indices]), 1) xvals_short = np.arange(100, 1e4, 100) log_yvals = lf[0]*np.log10(xvals_short) + lf[1] yvals = np.power(10, log_yvals) pyplot.plot(xvals_short, yvals) # Add formula for linear fit to low-end of data txt = 'Log(Y) = %.2fLog(x) + %.2f' % (lf[0], lf[1]) print(txt) ax.annotate(txt, (800, 10000)) figname = 'min_vs_max_interevent_time_%s.png' % fig_comment pyplot.savefig(figname) # Plot minimum pairs pyplot.clf() ax = pyplot.subplot(111) pyplot.errorbar(max_interevent_times, min_paired_interevent_times, yerr = min_paired_interevent_times_bounds, ecolor = '0.3', elinewidth=0.7, linestyle="None", zorder=1) pyplot.errorbar(max_interevent_times, min_paired_interevent_times, xerr = max_interevent_times_bounds, ecolor = '0.3', elinewidth=0.7, linestyle="None", zorder=1) pyplot.scatter(max_interevent_times, min_paired_interevent_times, marker = 's', c=colours, s=25, zorder=2) ax.set_xlabel('Maximum interevent time') ax.set_ylabel('Minimum interevent time \n(mean of two shortest consecutive interevent times)') ax.set_xscale('log') ax.set_yscale('log') # Label low-slip rate faults for i, txt in enumerate(names): if max_interevent_times[i] > 10 and annotate_plots: ax.annotate(txt[:4], (max_interevent_times[i], min_paired_interevent_times[i]), fontsize=8) # Now fit with a regression in log-log space xvals = np.arange(100, 2e6, 100) # For plotting # Linear fit lf = np.polyfit(np.log10(max_interevent_times), np.log10(min_paired_interevent_times), 1) log_yvals = lf[0]*np.log10(xvals) + lf[1] yvals = np.power(10, log_yvals) pyplot.plot(xvals, yvals) # Linear fit only bottom end of data indices = np.argwhere(max_interevent_times < 10000).flatten() lf = np.polyfit(np.log10(max_interevent_times[indices]), np.log10(min_paired_interevent_times[indices]), 1) xvals_short = np.arange(100, 1e4, 100) log_yvals = lf[0]*np.log10(xvals_short) + lf[1] yvals = np.power(10, log_yvals) pyplot.plot(xvals_short, yvals) # Add formula for linear fit to low-end of data txt = 'Log(Y) = %.2fLog(x) + %.2f' % (lf[0], lf[1]) print(txt) ax.annotate(txt, (100, 10000)) # Quadratic fit qf = np.polyfit(np.log10(max_interevent_times), np.log10(min_paired_interevent_times), 2) print(qf) log_yvals = qf[0]*np.log10(xvals)**2 + qf[1]*np.log10(xvals) + qf[2] yvals = np.power(10, log_yvals) pyplot.plot(xvals, yvals) figname = 'min_pair_vs_max_interevent_time_%s.png' % fig_comment pyplot.savefig(figname) # Similar plots, against long term rates pyplot.clf() ax = pyplot.subplot(111) pyplot.errorbar(mean_ltr, min_interevent_times, yerr = min_interevent_times_bounds, ecolor = '0.3', elinewidth=0.7, linestyle="None", zorder=1) pyplot.errorbar(mean_ltr, min_interevent_times, xerr = ltr_bounds, ecolor = '0.3', elinewidth=0.7, linestyle="None", zorder=1) pyplot.scatter(mean_ltr, min_interevent_times, marker='s', c=colours, s=25, zorder=2) ax.set_xlabel('Long-term rate') ax.set_ylabel('Minimum interevent time') ax.set_xscale('log') ax.set_yscale('log') # Label low-slip rate faults for i, txt in enumerate(names): if max_interevent_times[i] > 10 and annotate_plots: ax.annotate(txt[:4], (mean_ltr[i], min_interevent_times[i]), fontsize=8) # Linear fit only bottom end of data indices = np.argwhere(mean_ltr > 2e-4).flatten() lf = np.polyfit(np.log10(mean_ltr[indices]), np.log10(min_interevent_times[indices]), 1) xvals_short = np.arange(5e-4, 1e-2, 1e-4) log_yvals = lf[0]*np.log10(xvals_short) + lf[1] yvals = np.power(10, log_yvals) pyplot.plot(xvals_short, yvals) # Add formula for linear fit to low-end of data txt = 'Log(Y) = %.2fLog(x) + %.2f' % (lf[0], lf[1]) ax.annotate(txt, (1e-4, 10000)) figname = 'min_interevent_time_vs_ltr_%s.png' % fig_comment pyplot.savefig(figname) # Plot long term rate against minimum pair pyplot.clf() ax = pyplot.subplot(111) pyplot.errorbar(mean_ltr, min_paired_interevent_times, yerr = min_paired_interevent_times_bounds, ecolor = '0.3', elinewidth=0.7, linestyle="None", zorder=1) pyplot.errorbar(mean_ltr, min_paired_interevent_times, xerr = ltr_bounds, ecolor = '0.3', elinewidth=0.7, linestyle="None", zorder=1) pyplot.scatter(mean_ltr, min_paired_interevent_times, marker='s', c=colours, s=25, zorder=2) ax.set_xlabel('Long-term rate') ax.set_ylabel('Minimum interevent time \n(mean of two shortest consecutive interevent times)') ax.set_xscale('log') ax.set_yscale('log') # Label low-slip rate faults for i, txt in enumerate(names): if max_interevent_times[i] > 10 and annotate_plots: ax.annotate(txt[:4], (mean_ltr[i], min_paired_interevent_times[i]), fontsize=8) # Linear fit only bottom end of data indices = np.argwhere(mean_ltr > 2e-4).flatten() lf = np.polyfit(np.log10(mean_ltr[indices]), np.log10(min_paired_interevent_times[indices]), 1) xvals_short = np.arange(5e-4, 1e-2, 1e-4) log_yvals = lf[0]*np.log10(xvals_short) + lf[1] yvals = np.power(10, log_yvals) pyplot.plot(xvals_short, yvals) # Add formula for linear fit to low-end of data txt = 'Log(Y) = %.2fLog(x) + %.2f' % (lf[0], lf[1]) print(txt) ax.annotate(txt, (1e-4, 10000)) figname = 'min_pair_vs_ltr_%s.png' % fig_comment pyplot.savefig(figname) # Plot long term rate against maximum interevent time pyplot.clf() ax = pyplot.subplot(111) pyplot.errorbar(mean_ltr, max_interevent_times, yerr = max_interevent_times_bounds, ecolor = '0.3', elinewidth=0.7, linestyle="None", zorder=1) pyplot.errorbar(mean_ltr, max_interevent_times, xerr = ltr_bounds, ecolor = '0.3', elinewidth=0.7, linestyle="None", zorder=1) pyplot.scatter(mean_ltr, max_interevent_times, marker='s', c=plot_colours, s=25, zorder=2) ax.set_xlabel('Long-term rate') ax.set_ylabel('Maximum interevent time') ax.set_xscale('log') ax.set_yscale('log') # Label low-slip rate faults for i, txt in enumerate(names): if max_interevent_times[i] > 10 and annotate_plots: ax.annotate(txt[:4], (mean_ltr[i], max_interevent_times[i]), fontsize=8) # Linear fit only bottom end of data indices = np.argwhere(mean_ltr > 2e-10).flatten() # All data for now lf = np.polyfit(np.log10(mean_ltr[indices]), np.log10(max_interevent_times[indices]), 1) xvals_short = np.arange(2e-6, 1e-2, 1e-6) log_yvals = lf[0]*np.log10(xvals_short) + lf[1] yvals = np.power(10, log_yvals) pyplot.plot(xvals_short, yvals) # Add formula for linear fit to low-end of data txt = 'Log(Y) = %.2fLog(x) + %.2f' % (lf[0], lf[1]) print(txt) ax.annotate(txt, (1e-4, 100000)) figname = 'max_interevent_time_vs_ltr_%s.png' % fig_comment pyplot.savefig(figname) # Now plot ratios against long term rates pyplot.clf() ax = pyplot.subplot(111) pyplot.errorbar(mean_ltr, ratio_min_pair_max, yerr = ratio_min_pair_max_bounds, ecolor = '0.3', elinewidth=0.7, linestyle="None", zorder=1) pyplot.errorbar(mean_ltr, ratio_min_pair_max, xerr = ltr_bounds, ecolor = '0.3', elinewidth=0.7, linestyle="None", zorder=1) pyplot.scatter(mean_ltr, ratio_min_pair_max, marker='s', c=plot_colours, s=25, zorder=2) ax.set_xlabel('Long-term rate') ax.set_ylabel('Minimum pair interevent time: maximum interevent time') ax.set_xscale('log') ax.set_yscale('log') # Label low-slip rate faults for i, txt in enumerate(names): if max_interevent_times[i] > 10 and annotate_plots: ax.annotate(txt[:4], (mean_ltr[i], ratio_min_pair_max[i]), fontsize=8) # Linear fit high and low long term rate data separately indices = np.argwhere(mean_ltr > 4e-4).flatten() indices_slow_faults = np.argwhere(mean_ltr <= 4e-4).flatten() lf = np.polyfit(np.log10(mean_ltr[indices]), np.log10(ratio_min_pair_max[indices]), 1) xvals_short = np.arange(2e-4, 5e-2, 1e-4) log_yvals = lf[0]*np.log10(xvals_short) + lf[1] yvals = np.power(10, log_yvals) pyplot.plot(xvals_short, yvals, c='k') # Add formula for linear fit to low-end of data txt = 'Log(Y) = %.2fLog(x) + %.2f' % (lf[0], lf[1]) print(txt) ax.annotate(txt, (5e-4, 1e-2)) # Slow long-term rates print('At if statement') if len(indices_slow_faults) > 0: print('Plotting slow faults') lf = np.polyfit(np.log10(mean_ltr[indices_slow_faults]), np.log10(ratio_min_pair_max[indices_slow_faults]), 1) xvals_short = np.arange(2e-6, 4e-4, 1e-6) log_yvals = lf[0]*np.log10(xvals_short) + lf[1] yvals = np.power(10, log_yvals) pyplot.plot(xvals_short, yvals, c='k') # Add formula for linear fit to low-end of data txt = 'Log(Y) = %.2fLog(x) + %.2f' % (lf[0], lf[1]) print(txt) ax.annotate(txt, (1e-5, 5e-3)) figname = 'min_pair_max_ratio_vs_ltr_%s.png' % fig_comment pyplot.savefig(figname) # Now plot ratios against long term rates pyplot.clf() ax = pyplot.subplot(111) pyplot.errorbar(mean_ltr, ratio_min_max, yerr = ratio_min_max_bounds, ecolor = '0.3', elinewidth=0.7, linestyle="None", zorder=1) pyplot.errorbar(mean_ltr, ratio_min_max, xerr = ltr_bounds, ecolor = '0.3', elinewidth=0.7, linestyle="None", zorder=1) pyplot.scatter(mean_ltr, ratio_min_max, marker = 's', c=plot_colours, s=25, zorder=2) ax.set_xlabel('Long-term rate') ax.set_ylabel('Minimum interevent time: maximum interevent time') ax.set_xscale('log') ax.set_yscale('log') # Label low-slip rate faults for i, txt in enumerate(names): if max_interevent_times[i] > 10 and annotate_plots: ax.annotate(txt[:4], (mean_ltr[i], ratio_min_max[i]), fontsize=8) # Linear fit only bottom end of data indices =
np.argwhere(mean_ltr > 9e-5)
numpy.argwhere
#!/usr/bin/env python import numpy as np import matplotlib.pyplot as plt import scipy.interpolate, scipy.integrate from scipy import special plt.ion() binprec = '>f4' flag_plot = 0 flag_bt = 0 # 1: barotropic vortex, 0: baroclinic vortex flag_eddy = 1 # 1: isolated eddy, 2: modon flag_surf = 0 # 0: non perturbated surface field # # physical constants rho_const = 999.8 alphaK = 2.0e-4 g0 = 9.8 f0 = 1e-4 eps = 1e-10 # a small number #% ================== NEW GRID ===================================== def stretch(xf,yf,Lx,si_x,rev): hh = np.linspace(0,1,si_x+1) xf = Lx*np.interp(hh,xf,yf) dx = np.diff(xf) # reverse order to get high resolution near the bottom if rev: dx = dx[::-1] xf[1:] = np.cumsum(dx) xc = xf[0:-1] + 0.5*dx return xc,xf,dx si_x = 100 si_y = 100 si_z = 20 si_x1 = si_x + 1 si_y1 = si_y + 1 si_z1 = si_z + 1 # in m Lx = 300.0e3 Ly = 300.0e3 Lz = 1300 dx = Lx/si_x; dy = Ly/si_y; xx = Lx*(np.arange(0,si_x) + 0.5)/(1.0*si_x) yy = Ly*(np.arange(0,si_y) + 0.5)/(1.0*si_y) xx1 = Lx*(np.arange(0,si_x+1) )/(1.0*si_x) yy1 = Ly*(np.arange(0,si_y+1) )/(1.0*si_y) xg,yg = np.meshgrid(xx,yy) xu,yu = np.meshgrid(xx1[:-1],yy) xv,yv = np.meshgrid(xx,yy1[:-1]) xc,yc = np.meshgrid(xx1,yy1) dx1 = dx*np.ones((si_x)) dy1 = dy*np.ones((si_y)) slope = 4 xfz = np.linspace(0,1,1000) yfz = np.sinh(slope*xfz)/np.sinh(slope) zc,zf,dz1 = stretch(xfz,yfz,Lz,si_z,0) iz = np.argmin(np.abs(zf-500.0)) print ('dx= ', dx) print ('min dz: ', np.min(dz1)) print ('max dz: ', np.max(dz1)) print ('nb layers above 500m:', iz, '/', si_z) if np.sum(dz1 < 0) > 0: print ('you need you change the polynomial fit!') dx1.astype(binprec).tofile('dx.box') dy1.astype(binprec).tofile('dy.box') dz1.astype(binprec).tofile('dz.box') #% ============== background density profile =================== N2 = 3e-5 #N2 = 0. tref = -N2/g0/alphaK*zc tref = tref - tref[-1] # tref_dat = np.loadtxt('temp_winter.dat') # # add upper and lower boundary for interpolation # si_tref,naux = tref_dat.shape # tref_dat2 = np.zeros((si_tref+2,2)) # tref_dat2[1:-1,:] = tref_dat # tref_dat2[0,1] = tref_dat[0,1] # tref_dat2[-1,:] = tref_dat[-1,:] # tref_dat2[-1,0] = -10000 # t_interp = scipy.interpolate.interp1d(tref_dat2[:,0], tref_dat2[:,1]) # tref = t_interp(-zc) tref = tref.reshape((si_z,1,1)) #%==================== SST - LAND =================================== landh = np.zeros((si_y,si_x)); H = dz1.cumsum()[-1] landh = -H + landh #==================== Velocity and temperature profiles=============== eta = np.zeros((si_y,si_x)); theta =
np.zeros((si_z,si_y,si_x))
numpy.zeros
#------------------------------------------Single Rectangle dection-------------------------------------------# ## Adapted from https://github.com/jrieke/shape-detection by <NAME> # Import libraries: import numpy as np import matplotlib.pyplot as plt import matplotlib import time import os # Import tensorflow to use GPUs on keras: import tensorflow as tf # Set keras with GPUs import keras config = tf.ConfigProto( device_count = {'GPU': 1 , 'CPU': 12} ) sess = tf.Session(config=config) keras.backend.set_session(sess) # Import keras tools: from keras.models import Sequential from keras.layers import Dense, Activation, Dropout from keras.optimizers import SGD # Create images with random rectangles and bounding boxes: num_imgs = 50000 img_size = 8 min_object_size = 1 max_object_size = 4 num_objects = 1 bboxes = np.zeros((num_imgs, num_objects, 4)) imgs = np.zeros((num_imgs, img_size, img_size)) # set background to # Generating random images and bounding boxes: for i_img in range(num_imgs): for i_object in range(num_objects): w, h = np.random.randint(min_object_size, max_object_size, size=2) # bbox width (w) and height (h) x = np.random.randint(0, img_size - w) # bbox x lower left corner coordinate y = np.random.randint(0, img_size - h) # bbox y lower left corner coordinate imgs[i_img, x:x+w, y:y+h] = 1. # set rectangle to 1 bboxes[i_img, i_object] = [x, y, w, h] # store coordinates # Lets plot one example of generated image: i = 0 plt.imshow(imgs[i].T, cmap='Greys', interpolation='none', origin='lower', extent=[0, img_size, 0, img_size]) for bbox in bboxes[i]: plt.gca().add_patch(matplotlib.patches.Rectangle((bbox[0], bbox[1]), bbox[2], bbox[3], ec='r', fc='none')) ## Obs: # - The transpose was done for using properly both plt functions # - extent is the size of the image # - ec is the color of the border of the bounding box # - fc is to avoid any coloured background of the bounding box # Display plot: # plt.show() # Reshape (stack rows horizontally) and normalize the image data to mean 0 and std 1: X = (imgs.reshape(num_imgs, -1) - np.mean(imgs)) / np.std(imgs) X.shape, np.mean(X), np.std(X) # Normalize x, y, w, h by img_size, so that all values are between 0 and 1: # Important: Do not shift to negative values (e.g. by setting to mean 0) #----------- because the IOU calculation needs positive w and h y = bboxes.reshape(num_imgs, -1) / img_size y.shape, np.mean(y), np.std(y) # Split training and test: i = int(0.8 * num_imgs) train_X = X[:i] test_X = X[i:] train_y = y[:i] test_y = y[i:] test_imgs = imgs[i:] test_bboxes = bboxes[i:] # Build the model: model = Sequential([Dense(200, input_dim=X.shape[-1]), Activation('relu'), Dropout(0.2), Dense(y.shape[-1])]) model.compile('adadelta', 'mse') # Fit the model: tic = time.time() model.fit(train_X, train_y,nb_epoch=30, validation_data=(test_X, test_y), verbose=2) toc = time.time() - tic print(toc) # Predict bounding boxes on the test images: pred_y = model.predict(test_X) pred_bboxes = pred_y * img_size pred_bboxes = pred_bboxes.reshape(len(pred_bboxes), num_objects, -1) pred_bboxes.shape # Function to define the intersection over the union of the bounding boxes pair: def IOU(bbox1, bbox2): '''Calculate overlap between two bounding boxes [x, y, w, h] as the area of intersection over the area of unity''' x1, y1, w1, h1 = bbox1[0], bbox1[1], bbox1[2], bbox1[3] x2, y2, w2, h2 = bbox2[0], bbox2[1], bbox2[2], bbox2[3] w_I = min(x1 + w1, x2 + w2) - max(x1, x2) h_I = min(y1 + h1, y2 + h2) - max(y1, y2) if w_I <= 0 or h_I <= 0: # no overlap return 0 else: I = w_I * h_I U = w1 * h1 + w2 * h2 - I return I / U # Show a few images and predicted bounding boxes from the test dataset. os.chdir('/workdir/jp2476/repo/diversity-proj/files') plt.figure(figsize=(12, 3)) for i_subplot in range(1, 5): plt.subplot(1, 4, i_subplot) i = np.random.randint(len(test_imgs)) plt.imshow(test_imgs[i].T, cmap='Greys', interpolation='none', origin='lower', extent=[0, img_size, 0, img_size]) for pred_bbox, train_bbox in zip(pred_bboxes[i], test_bboxes[i]): plt.gca().add_patch(matplotlib.patches.Rectangle((pred_bbox[0], pred_bbox[1]), pred_bbox[2], pred_bbox[3], ec='r', fc='none')) plt.annotate('IOU: {:.2f}'.format(IOU(pred_bbox, train_bbox)), (pred_bbox[0], pred_bbox[1]+pred_bbox[3]+0.2), color='r') # plt.savefig("simple_detection.pdf", dpi=150) # plt.savefig("simple_detection.png", dpi=150) plt.show() plt.clf() # Calculate the mean IOU (overlap) between the predicted and expected bounding boxes on the test dataset: summed_IOU = 0. for pred_bbox, test_bbox in zip(pred_bboxes.reshape(-1, 4), test_bboxes.reshape(-1, 4)): summed_IOU += IOU(pred_bbox, test_bbox) mean_IOU = summed_IOU / len(pred_bboxes) mean_IOU #-------------------------------------------Two Rectangle dection---------------------------------------------# ## Adapted from https://github.com/jrieke/shape-detection by <NAME> # Import libraries: import numpy as np import matplotlib.pyplot as plt import matplotlib import time import os # Import tensorflow to use GPUs on keras: import tensorflow as tf # Set keras with GPUs import keras config = tf.ConfigProto( device_count = {'GPU': 1 , 'CPU': 12} ) sess = tf.Session(config=config) keras.backend.set_session(sess) # Import keras tools: from keras.models import Sequential from keras.layers import Dense, Activation, Dropout from keras.optimizers import SGD # Create images with random rectangles and bounding boxes: num_imgs = 50000 # Image parameters for simulation: img_size = 8 min_rect_size = 1 max_rect_size = 4 num_objects = 2 # Initialize objects: bboxes = np.zeros((num_imgs, num_objects, 4)) imgs = np.zeros((num_imgs, img_size, img_size)) # Generate images and bounding boxes: for i_img in range(num_imgs): for i_object in range(num_objects): w, h = np.random.randint(min_rect_size, max_rect_size, size=2) x = np.random.randint(0, img_size - w) y = np.random.randint(0, img_size - h) imgs[i_img, x:x+w, y:y+h] = 1. bboxes[i_img, i_object] = [x, y, w, h] # Get shapes: imgs.shape, bboxes.shape # Plot one example of generated images: i = 0 plt.imshow(imgs[i].T, cmap='Greys', interpolation='none', origin='lower', extent=[0, img_size, 0, img_size]) for bbox in bboxes[i]: plt.gca().add_patch(matplotlib.patches.Rectangle((bbox[0], bbox[1]), bbox[2], bbox[3], ec='r', fc='none')) # plt.show() # Reshape and normalize the data to mean 0 and std 1: X = (imgs.reshape(num_imgs, -1) - np.mean(imgs)) / np.std(imgs) X.shape, np.mean(X), np.std(X) # Normalize x, y, w, h by img_size, so that all values are between 0 and 1: # Important: Do not shift to negative values (e.g. by setting to mean 0), #---------- because the IOU calculation needs positive w and h y = bboxes.reshape(num_imgs, -1) / img_size y.shape, np.mean(y), np.std(y) # Function to define the intersection over the union of the bounding boxes pair: def IOU(bbox1, bbox2): '''Calculate overlap between two bounding boxes [x, y, w, h] as the area of intersection over the area of unity''' x1, y1, w1, h1 = bbox1[0], bbox1[1], bbox1[2], bbox1[3] x2, y2, w2, h2 = bbox2[0], bbox2[1], bbox2[2], bbox2[3] w_I = min(x1 + w1, x2 + w2) - max(x1, x2) h_I = min(y1 + h1, y2 + h2) - max(y1, y2) if w_I <= 0 or h_I <= 0: # no overlap return 0 else: I = w_I * h_I U = w1 * h1 + w2 * h2 - I return I / U # Split training and test. i = int(0.8 * num_imgs) train_X = X[:i] test_X = X[i:] train_y = y[:i] test_y = y[i:] test_imgs = imgs[i:] test_bboxes = bboxes[i:] # Build the model. from keras.models import Sequential from keras.layers import Dense, Activation, Dropout from keras.optimizers import SGD model = Sequential([ Dense(256, input_dim=X.shape[-1]), Activation('relu'), Dropout(0.4), Dense(y.shape[-1]) ]) model.compile('adadelta', 'mse') # Flip bboxes during training: # Note: The validation loss is always quite big here because we don't flip the bounding boxes for #------ the validation data # Define the distance between the two bounding boxes: def distance(bbox1, bbox2): return np.sqrt(np.sum(np.square(bbox1[:2] - bbox2[:2]))) # Parameters to fit the model: num_epochs = 50 flipped = np.zeros((len(train_y), num_epochs)) ious_epoch = np.zeros((len(train_y), num_epochs)) dists_epoch = np.zeros((len(train_y), num_epochs)) mses_epoch = np.zeros((len(train_y), num_epochs)) # Training the model: for epoch in range(num_epochs): # Print the current epoch: print('Epoch', epoch) # Fit the model: model.fit(train_X, train_y, nb_epoch=1, validation_data=(test_X, test_y), verbose=2) # Get the output from the neural net: hat_y = model.predict(train_X) for i, (hat_bboxes, train_bboxes) in enumerate(zip(hat_y, train_y)): # Flip the training data: flipped_train_bboxes = np.concatenate([train_bboxes[4:], train_bboxes[:4]]) # Compute the mean-squared error for non-flipped and flipped data points: mse = np.mean(np.square(hat_bboxes - train_bboxes)) mse_flipped = np.mean(np.square(hat_bboxes - flipped_train_bboxes)) # Compute the IOU for each variation: iou = IOU(hat_bboxes[:4], train_bboxes[:4]) + IOU(hat_bboxes[4:], train_bboxes[4:]) iou_flipped = IOU(hat_bboxes[:4], flipped_train_bboxes[:4]) + IOU(hat_bboxes[4:], flipped_train_bboxes[4:]) # Compute the distance for each variation: dist = distance(hat_bboxes[:4], train_bboxes[:4]) + distance(hat_bboxes[4:], train_bboxes[4:]) dist_flipped = distance(hat_bboxes[:4], flipped_train_bboxes[:4]) + distance(hat_bboxes[4:], flipped_train_bboxes[4:]) # Store stats: if mse_flipped < mse: # you can also use iou or dist here train_y[i] = flipped_train_bboxes flipped[i, epoch] = 1 mses_epoch[i, epoch] = mse_flipped ious_epoch[i, epoch] = iou_flipped / 2. dists_epoch[i, epoch] = dist_flipped / 2. else: mses_epoch[i, epoch] = mse ious_epoch[i, epoch] = iou / 2. dists_epoch[i, epoch] = dist / 2. print('Flipped {} training samples ({} %)'.format(np.sum(flipped[:, epoch]), np.mean(flipped[:, epoch]) * 100.)) print('Mean IOU: {}'.format(
np.mean(ious_epoch[:, epoch])
numpy.mean
# -*- coding: utf-8 -*- """ Created on Sat Aug 3 14:10:12 2019 @author: Dominic """ from numba import njit, float64, int64 from scipy import integrate from math import exp, log, pi import numpy as np # I USE NUMPY FOR EXP, LOG AND SQRT AS THEY HANDLE IMAGINARY PARTS from ..finutils.FinGlobalVariables import gDaysInYear from ..products.equity.FinEquityOption import FinEquityOptionTypes from ..finutils.FinMath import norminvcdf ########################################################################## # Heston Process # dS = rS dt + sqrt(V) * S * dz # dV = kappa(theta-V) dt + sigma sqrt(V) dz # corr(dV,dS) = rho dt # Rewritten as # dS = rS dt + sqrt(V) * S * (rhohat dz1 + rho dz2) # dV = kappa(theta-V) dt + sigma sqrt(V) dz2 # where rhohat = sqrt(1-rho*rho) ########################################################################## # TODO - DECIDE WHETHER TO OO MODEL # TODO - NEEDS CHECKING FOR MC CONVERGENCE ########################################################################## from enum import Enum class FinHestonNumericalScheme(Enum): EULER = 1 EULERLOG = 2 QUADEXP = 3 ########################################################################## @njit(float64[:, :](float64, float64, float64, float64, float64, float64, float64, float64, float64, float64, int64, int64, int64), fastmath=True) def getPaths( s0, r, q, v0, kappa, theta, sigma, rho, t, dt, numPaths, seed, scheme): np.random.seed(seed) numSteps = int(t / dt) sPaths = np.zeros(shape=(numPaths, numSteps)) sPaths[:, 0] = s0 sdt = np.sqrt(dt) rhohat = np.sqrt(1.0 - rho * rho) sigma2 = sigma * sigma if scheme == FinHestonNumericalScheme.EULER.value: # Basic scheme to first order with truncation on variance for iPath in range(0, numPaths): s = s0 v = v0 for iStep in range(1, numSteps): z1 = np.random.normal(0.0, 1.0) * sdt z2 = np.random.normal(0.0, 1.0) * sdt zV = z1 zS = rho * z1 + rhohat * z2 vplus = max(v, 0.0) rtvplus = np.sqrt(vplus) v += kappa * (theta - vplus) * dt + sigma * \ rtvplus * zV + 0.25 * sigma2 * (zV * zV - dt) s += (r - q) * s * dt + rtvplus * s * \ zS + 0.5 * s * vplus * (zV * zV - dt) sPaths[iPath, iStep] = s elif scheme == FinHestonNumericalScheme.EULERLOG.value: # Basic scheme to first order with truncation on variance for iPath in range(0, numPaths): x = log(s0) v = v0 for iStep in range(1, numSteps): zV =
np.random.normal(0.0, 1.0)
numpy.random.normal
import abc import numpy as np import scipy.stats as spst import scipy.optimize as spop class AssetAllocABC(abc.ABC): n_asset = 1 rho = None sigma = np.array([1.0]) ret = np.array([0.0]) cor_m = np.eye(1) cov_m = np.eye(1) longshort = np.array([1], dtype=np.int8) def __init__(self, sigma=None, cor=None, cov=None, ret=None, longshort=1): """ Args: sigma: asset volatilities of `n_asset` assets. (n_asset, ) array cor: asset correlation. If matrix with shape (n_asset, n_asset), used as it is. If scalar, correlation matrix is constructed with all same off-diagonal values. cov: asset covariance ret: expected return longshort: long/short constraint. 1 for long-only, -1 for short, 0 for no constraint """ if cov is None: # when sigma and cor are given self.sigma = np.atleast_1d(sigma) self.n_asset = len(self.sigma) if self.n_asset == 1: raise ValueError(f"The number of assets should be more than one.") if np.isscalar(cor): self.cor_m = cor * np.ones((self.n_asset, self.n_asset)) \ + (1 - cor) * np.eye(self.n_asset) self.rho = cor else: assert cor.shape == (self.n_asset, self.n_asset) self.cor_m = cor if self.n_asset == 2: self.rho = cor[0, 1] self.cov_m = self.sigma * self.cor_m * sigma[:, None] else: # When covariance is given directly self.n_asset = cov.shape[0] self.cov_m = cov self.sigma = np.sqrt(np.diag(cov)) self.cor_m = cov.copy() self.cor_m /= self.sigma[:, None] self.cor_m /= self.sigma if ret is not None: self.ret = ret * np.ones(self.n_asset) if longshort is None: self.longshort = np.full(self.n_asset, 1, dtype=np.int8) # long-only elif np.isscalar(longshort): self.longshort = np.full(self.n_asset,
np.sign(longshort)
numpy.sign
# coding=utf-8 # Copyright (C) 2020 NumS Development Team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import Tuple, Iterator import itertools import numpy as np import scipy.special from nums.core.settings import np_ufunc_map # pylint: disable = no-member def get_uop_output_type(op_name, dtype): a = np.array(1, dtype=dtype) result_dtype = np.__getattribute__(op_name)(a).dtype return np.__getattribute__(str(result_dtype)) def get_bop_output_type(op_name, dtype_a, dtype_b): a = np.array(1, dtype=dtype_a) b = np.array(2, dtype=dtype_b) op_name = np_ufunc_map.get(op_name, op_name) try: dtype = np.__getattribute__(op_name)(a, b).dtype return np.__getattribute__(str(dtype)) except Exception as _: dtype = scipy.special.__getattribute__(op_name)(a, b).dtype return np.__getattribute__(str(dtype)) def is_int(val): return isinstance(val, (int, np.int, np.int8, np.int16, np.int32, np.int64)) def get_reduce_output_type(op_name, dtype): a = np.array([0, 1], dtype=dtype) dtype = np.__getattribute__(op_name)(a).dtype return np.__getattribute__(str(dtype)) def shape_from_block_array(arr: np.ndarray): grid_shape = arr.shape num_axes = len(arr.shape) shape = np.zeros(num_axes, dtype=np.int) for j in range(num_axes): pos = [[0]] * num_axes pos[j] = range(grid_shape[j]) j_iter = list(itertools.product(*pos)) for j_access in j_iter: shape[j] += arr[j_access].shape[j] return tuple(shape) def broadcast(a_shape, b_shape): a_view = np.lib.stride_tricks.broadcast_to(0, a_shape) b_view = np.lib.stride_tricks.broadcast_to(0, b_shape) return np.broadcast(a_view, b_view) def broadcast_block_shape(a_shape, b_shape, a_block_shape): # Starting from last block shape dim and # map each shape dim to block shape dim as already defined, # and for the rest of dims, set block shape to 1. result_shape = broadcast(a_shape, b_shape).shape result_block_shape = [] a_block_shape_r = list(reversed(a_block_shape)) for i, _ in enumerate(reversed(result_shape)): if i < len(a_block_shape_r): result_block_shape.append(a_block_shape_r[i]) else: result_block_shape.append(1) return tuple(reversed(result_block_shape)) def broadcast_shape(a_shape, b_shape): return broadcast(a_shape, b_shape).shape def can_broadcast_shapes(a_shape, b_shape): try: assert broadcast_shape(a_shape, b_shape) is not None return True except ValueError as _: return False def broadcast_shape_to(from_shape, to_shape): # Enforce broadcasting rules from an # array of references to 0 with shape from_shape. from_view = np.lib.stride_tricks.broadcast_to(0, from_shape) return np.lib.stride_tricks.broadcast_to(from_view, to_shape) def can_broadcast_shape_to(from_shape, to_shape): # See: https://numpy.org/devdocs/user/theory.broadcasting.html try: broadcast_shape_to(from_shape, to_shape) return True except ValueError as _: return False def broadcast_shape_to_alt(from_shape, to_shape): # This is heavily tested with shapes up to length 5. from_num_axes = len(from_shape) to_num_axes = len(to_shape) result_shape = [] if to_num_axes < from_num_axes: raise ValueError("Input shape has more dimensions than allowed by the axis remapping.") if to_num_axes == 0 and from_shape != 0: raise ValueError("Cannot broadcast non-scalar shape to scalar shape ().") from_shape_r = list(reversed(from_shape)) to_shape_r = list(reversed(to_shape)) for i, from_dim in enumerate(from_shape_r): to_dim = to_shape_r[i] if from_dim == 1: result_shape.append(to_dim) elif to_dim == from_dim: result_shape.append(to_dim) else: raise ValueError("Cannot broadcast %s to %s." % (str(from_shape), str(to_shape))) return tuple(reversed(result_shape + to_shape_r[from_num_axes:])) def is_array_like(obj): return isinstance(obj, (tuple, list, np.ndarray)) def block_shape_from_subscript(subscript: tuple, block_shape: tuple): new_block_shape = [] for i, obj in enumerate(subscript): if isinstance(obj, slice): new_block_shape.append(block_shape[i]) elif isinstance(obj, (int, np.intp)): continue else: raise NotImplementedError("No support for advanced indexing.") return tuple(new_block_shape) def get_slices(total_size, batch_size, order, reverse_blocks=False): assert order in (-1, 1) if order > 0: if reverse_blocks: result = list(reversed(list(range(total_size, 0, -batch_size)) + [0])) else: result = list(range(0, total_size, batch_size)) + [total_size] return list(map(lambda s: slice(*s, order), zip(*(result[:-1], result[1:])))) else: if reverse_blocks: # If reverse order blocks are not multiples of axis dimension, # then the last block is smaller than block size and should be # the first block. result = list(reversed(list(range(-total_size-1, -1, batch_size)) + [-1])) else: result = list(range(-1, -total_size - 1, -batch_size)) + [-total_size - 1] return list(map(lambda s: slice(*s, order), zip(*(result[:-1], result[1:])))) class OrderedGrid(object): def __init__(self, shape: Tuple, block_shape: Tuple, order: Tuple, block_order=None): if block_order is not None: assert len(block_order) == len(shape) self.shape = tuple(shape) self.block_shape = tuple(np.min([shape, block_shape], axis=0)) self.order = tuple(order) self.grid_shape = [] self.grid_slices = [] for i in range(len(self.shape)): dim = self.shape[i] block_dim = block_shape[i] axis_order = order[i] reverse_blocks = False if block_order is not None: reverse_blocks = block_order[i] == -1 axis_slices = get_slices(dim, block_dim, axis_order, reverse_blocks) self.grid_slices.append(axis_slices) self.grid_shape.append(len(axis_slices)) self.grid_shape = tuple(self.grid_shape) # Assumes C-style ordering. # We add len(shape) to allow for axis consisting of the actual slices. self.slices = np.array(list(itertools.product(*self.grid_slices)), dtype=slice).reshape(tuple(list(self.grid_shape) + [len(shape)])) def index_iterator(self) -> Iterator[Tuple]: if 0 in self.shape: return [] return itertools.product(*map(range, self.grid_shape)) def idx2addr(index: tuple, shape: tuple): strides = [np.product(shape[i:]) for i in range(1, len(shape))] + [1] addr: int = sum(np.array(index) * strides) return addr def addr2idx(addr: int, shape: tuple): strides = [
np.product(shape[i:])
numpy.product
#!/usr/bin/env python """ GeoData.py Created on Thu Jul 17 12:46:46 2014 @author: <NAME> """ from __future__ import division,absolute_import from six import integer_types,string_types #import os #import time import posixpath from copy import deepcopy from datetime import datetime import numpy as np import scipy as sp import scipy.interpolate as spinterp from scipy.spatial import Delaunay import tables from pandas import DataFrame import pdb from warnings import warn # from . import CoordTransforms as CT from .utilityfuncs import read_h5_main VARNAMES = ['data','coordnames','dataloc','sensorloc','times'] class GeoData(object): '''This class will hold the information for geophysical data. Variables data - This is a dictionary with strings for keys only. The strings are the given names of the data. coordnames - A string that holds the type of coordinate system. dataloc - A numpy array that holds the locations of the samples sensorloc - A numpy array with the WGS coordinates of the sensor. times - A numpy array that is holding the times associated with the measurements.''' def __init__(self,readmethod,inputs): if isinstance(readmethod,string_types): (self.data,self.coordnames,self.dataloc,self.sensorloc,self.times) = inputs else: '''This will create an instance of the GeoData class by giving it a read method and the inputs in a tuple''' (self.data,self.coordnames,self.dataloc,self.sensorloc,self.times) = readmethod(*inputs) # Assert that the data types are correct numerics = (np.ndarray,integer_types,float) assert isinstance(self.data,dict),"data needs to be a dictionary" assert isinstance(self.coordnames,str), "coordnames needs to be a string" assert isinstance(self.dataloc,numerics),"dataloc needs to be a numpy array" assert isinstance(self.sensorloc,numerics),"sensorloc needs to be a numpy array" assert isinstance(self.times,numerics),"times needs to be a numpy array" self.times = timerepair(self.times) # Make sure the times vector is sorted if not self.issatellite(): timestemp = self.times[:,0] sortvec = sp.argsort(timestemp) self.times=self.times[sortvec] for ikey in self.datanames(): self.data[ikey]=self.data[ikey][:,sortvec] def datanames(self): '''Returns the data names in a list.''' return self.data.keys() def write_h5(self,filename): '''Writes out the structured h5 files for the class. inputs filename - The filename of the output.''' with tables.openFile(filename, mode = "w", title = "GeoData Out") as h5file: # get the names of all the variables set in the init function varnames = self.__dict__.keys() vardict = self.__dict__ try: # XXX only allow 1 level of dictionaries, do not allow for dictionary of dictionaries. # Make group for each dictionary for cvar in varnames: #group = h5file.create_group(posixpath.sep, cvar,cvar +'dictionary') if isinstance(vardict[cvar],dict): # Check if dictionary dictkeys = vardict[cvar].keys() group2 = h5file.create_group('/',cvar,cvar+' dictionary') for ikeys in dictkeys: h5file.create_array(group2,ikeys,vardict[cvar][ikeys])#,'Static array') else: if isinstance(vardict[cvar],string_types): vardict[cvar] =
np.string_(vardict[cvar])
numpy.string_
import cv2 from PIL import Image import urllib.request,io, time import numpy as np from matplotlib import pyplot as plt def normalize(v): norm = np.linalg.norm(v) if norm == 0: return v return v / norm def randcolors(elemlist): for elem in elemlist: yield elem, tuple(int(x) for x in list(np.random.choice(range(256), size=3))) nfeatures = 2000 fastTreshold = 5 path = io.BytesIO(urllib.request.urlopen('http://10.0.0.128/capture').read()) previmg = np.array(Image.open(path).convert('RGB')) previmg = cv2.rotate(previmg[:,:,::-1], cv2.ROTATE_90_CLOCKWISE) # RBG to BGR img = previmg while 1: previmg = img path = io.BytesIO(urllib.request.urlopen('http://10.0.0.128/capture').read()) img = np.array(Image.open(path).convert('RGB')) img = cv2.rotate(img[:,:,::-1], cv2.ROTATE_90_CLOCKWISE) # RBG to BGR # cv2.imshow('capture', img) # k = cv2.waitKey(1) & 0xFF # if k == 27: # break # continue orb = cv2.ORB_create(nfeatures=nfeatures, fastThreshold=fastTreshold) kp1, des1 = orb.detectAndCompute(previmg, None) kp2, des2 = orb.detectAndCompute(img, None) if len(kp1) == 0 or len(kp2) == 0: continue desc_matcher = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=False) matches = desc_matcher.match(des1,des2) matches = sorted(matches, key = lambda x:x.distance) if len(matches) < nfeatures / 2 and fastTreshold > 3: fastTreshold -= 1 print('fastTreshold-- (' + str(fastTreshold) + ')') if len(matches) == nfeatures: fastTreshold += 1 print('fastTreshold++ (' + str(fastTreshold) + ')') vectors = [np.subtract(kp1[m.queryIdx].pt, kp2[m.trainIdx].pt) for m in matches] median = normalize(np.median(vectors, axis=0)) rated = np.array([ (m, v, (np.dot(normalize(v), median) if
np.any(v)
numpy.any
# 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])
numpy.array
import os import tensorflow as tf import matplotlib.pyplot as plt import random import pandas as pd import numpy as np import keras.initializers import keras.optimizers from networkx import Graph, find_cliques from sklearn.metrics import roc_curve, auc from keras.layers import Concatenate, Input, Embedding, Lambda, Activation, BatchNormalization from keras.layers.core import Dense, Dropout, Reshape from keras.models import load_model, model_from_json, model_from_yaml, Model from keras.utils.vis_utils import plot_model from keras.callbacks import TensorBoard from .datasets import DataSet from .importing_modules import * class NeuralNetworkConfig: def __init__(self, categorical_input: str="cat_input", continuous_input: str="cont_input", output: str="output", reshaped_output: str="reshaped_output", noisy_layer: str="noisy", kernel_initializer: str="uniform", hidden: str = "hidden", reshaped: str="reshaped", dropout: str="dropout", merge: str="merge", activation: str="relu", output_activation: str="sigmoid", batch_normalization: bool=False): self.kernel_initializer = kernel_initializer self.activation = activation self.output_activation = output_activation self.cont_input = continuous_input self.cat_input = categorical_input self.hidden = hidden self.noisy_layer = noisy_layer self.reshaped = reshaped self.merge = merge self.dropout = dropout self.output = output self.reshaped_output = reshaped_output self.batch_normalization = batch_normalization class NeuralNetwork: def __init__(self, model): self.__model = model def get_model(self): return self.__model @classmethod def from_file(cls, from_file: str): model = load_model(from_file) return cls(model) def get_layer(self, name): return self.__model.get_layer(name) def get_weights(self): return self.__model.get_weights() def set_weights(self, weights): self.__model.set_weights(weights) def get_weights_for_layer(self, feature): return self.__model.get_layer(feature).get_weights() def get_weights_with_name(self): model = self.__model names = [layer.name for layer in model.layers] weights = [] for name in names: weights.append(model.get_layer(name).get_weights()) return dict(zip(names, weights)) def set_weights_by_name(self, weights): for name, weight in weights.items(): self.__model.get_layer(name).set_weights(weight) def save_plot(self, to_file='model_plot.svg', shapes=False, layer_names=False): if to_file: plot_model(self.__model, to_file=to_file, show_shapes=shapes, show_layer_names=layer_names) def compile(self, loss='binary_crossentropy', lr=0.001): optimizer=keras.optimizers.Adam(lr=lr) self.__model.compile(loss=loss, optimizer=optimizer, metrics=['accuracy']) def export(self, to_file): if to_file: name, ext = os.path.splitext(to_file) if ext == '.h5': self.__model.save(to_file) elif ext == '.json': model_json = self.__model.to_json() with(to_file, 'w') as json_file: json_file.write(model_json) elif ext == '.yaml': model_yaml = self.__model.to_yaml() with(to_file, 'w') as yaml_file: yaml_file.write(model_yaml) class DenseNeuralNetwork(NeuralNetwork): @classmethod def from_scratch(cls, config: NeuralNetworkConfig, dataset, hidden_units: int, embedding_size: int = 10, dropout_rate: float = 0.0, output_units=1, embedding_layers_trainable=True): categorical_data = dataset.get_data(without_resulting_feature=True).select_dtypes(include='category') continuous_features = dataset.get_data(without_resulting_feature=True).select_dtypes( exclude='category').columns.size if isinstance(categorical_data, pd.DataFrame): categorical_data_categories = {} for column in categorical_data: categorical_data_categories[column] = categorical_data[column].cat.categories.size categorical_data = categorical_data_categories model = DenseNeuralNetwork._build(config, categorical_data, continuous_features, hidden_units, embedding_size, dropout_rate, output_units, embedding_layers_trainable) return cls(model) @staticmethod def _build(config, categorical_data_categories, continuous_features: int, hidden_units: int, embedding_size: int, dropout_rate, output_units: int, embedding_layers_trainable): # create input layer for continuous data continuous_input = Input(shape=(continuous_features,), name=config.cont_input) reshaped_continuous_input = Reshape((1, continuous_features), name=config.reshaped)(continuous_input) # create input layers complemented by embedding layers to handle categorical features embedding_layers = [] categorical_inputs = [] for feature, size in categorical_data_categories.items(): categorical_input = Input((1,), name=config.cat_input + "_" + feature) categorical_inputs.append(categorical_input) embedding_layer = Embedding(size, embedding_size, name=feature, trainable=embedding_layers_trainable)( categorical_input) embedding_layers.append(embedding_layer) # merge all inputs merge_layer = Concatenate(name=config.merge)(embedding_layers + [reshaped_continuous_input]) # hidden layers hidden_layer = Dense(hidden_units, kernel_initializer=config.kernel_initializer, name=config.hidden)(merge_layer) if config.batch_normalization: hidden_layer = BatchNormalization()(hidden_layer) hidden_layer = Activation(config.activation)(hidden_layer) dropout_layer = Dropout(dropout_rate, name=config.dropout)(hidden_layer) # output_layer output_layer = Dense(output_units, name=config.output)(dropout_layer) output_layer = Activation(config.output_activation)(output_layer) # add reshape layer since output should be vector output_layer = Reshape((1,), name=config.reshaped_output)(output_layer) # create final model model = Model(inputs=categorical_inputs + [continuous_input], outputs=output_layer) return model class OptimizedNeuralNetwork(NeuralNetwork): @classmethod def from_scratch(cls, config: NeuralNetworkConfig, dataset: DataSet, correlation_info: list, embedding_size: int=10, dropout_rate: float=0.0, output_units=1): flatten_correlation = [item for sublist in correlation_info for item in sublist] features = dataset.get_data(without_resulting_feature=True).columns if not all(elem in features for elem in flatten_correlation): return None diff = list(set(features) - set(flatten_correlation)) diff = [[item] for item in diff] correlation_info.extend(diff) categorical_data = dataset.get_data(without_resulting_feature=True).select_dtypes(include='category') continuous_features = dataset.get_data(without_resulting_feature=True).select_dtypes(exclude='category').columns if isinstance(categorical_data, pd.DataFrame): categorical_data_categories = {} for column in categorical_data: categorical_data_categories[column] = categorical_data[column].cat.categories.size categorical_data = categorical_data_categories model = OptimizedNeuralNetwork._build(config, categorical_data, continuous_features, correlation_info, embedding_size, dropout_rate, output_units) return cls(model) @staticmethod def _build(config: NeuralNetworkConfig, categorical_data_categories: dict, continuous_features: list, correlation_info: list,embedding_size: int, dropout_rate: float, output_units: int): feature_layers = {} hidden_layers = [] inputs = [] for feature, size in categorical_data_categories.items(): categorical_input = Input((1,), name=config.cat_input + "_" + feature) inputs.append(categorical_input) embedding_layer = Embedding(size, embedding_size, name=feature)(categorical_input) feature_layers[feature] = embedding_layer for feature in continuous_features: continuous_input = Input((1,), name=config.cont_input + "_" + feature) inputs.append(continuous_input) reshaped_continuous_input = Reshape((1, 1), name=feature)(continuous_input) feature_layers[feature] = reshaped_continuous_input for couple in correlation_info: coupled_layers = [feature_layers[feature] for feature in couple] if len(couple) > 1: merge_layer = Concatenate()(coupled_layers) hidden_layer = Dense(1, kernel_initializer=config.kernel_initializer)(merge_layer) if config.batch_normalization: hidden_layer = BatchNormalization()(hidden_layer) hidden_layer = Activation(config.activation)(hidden_layer) else: hidden_layer = Dense(1, kernel_initializer=config.kernel_initializer)(coupled_layers[0]) if config.batch_normalization: hidden_layer = BatchNormalization()(hidden_layer) hidden_layer = Activation(config.activation)(hidden_layer) hidden_layers.append(hidden_layer) merge_layer = Concatenate()(hidden_layers) dropout_layer = Dropout(dropout_rate, name=config.dropout)(merge_layer) # output_layer output_layer = Dense(1, name=config.output)(dropout_layer) output_layer = Activation(config.output_activation)(output_layer) # add reshape layer since output should be vector output_layer = Reshape((output_units,), name=config.reshaped_output)(output_layer) # create final model model = Model(inputs=inputs, outputs=output_layer) return model class Trainer: def __init__(self, nnet: NeuralNetwork, training_dataset, training_target, batch_size=32, epochs=1000): self.__nnet = nnet self.__training_dataset = training_dataset self.__training_target = training_target self.__batch_size = batch_size self.__epochs = epochs self.__score = None self._preprocess_dataset() def _preprocess_dataset(self): categorical_data = DataSet.dataframe_to_series(self.__training_dataset.get_data(without_resulting_feature=True).select_dtypes(include='category')) if isinstance(self.__nnet, OptimizedNeuralNetwork): continuous_data = DataSet.dataframe_to_series(self.__training_dataset.get_data(without_resulting_feature=True).select_dtypes(exclude='category')) self.__training_dataset = [*categorical_data, *continuous_data] else: continuous_data = self.__training_dataset.get_data().select_dtypes(exclude='category').values self.__training_dataset = [*categorical_data, continuous_data] def train(self, verbose=1): tensorboard = TensorBoard(log_dir="./logs") self.__nnet.get_model().fit(self.__training_dataset, self.__training_target, batch_size=self.__batch_size, epochs=self.__epochs, verbose=verbose, shuffle=False, callbacks=[tensorboard]) def evaluate(self, verbose=1): self.__score = self.__nnet.get_model().evaluate(self.__training_dataset, self.__training_target, batch_size=self.__batch_size, verbose=verbose) def get_score(self): return self.__score class Predictor: def __init__(self, nnet: NeuralNetwork, dataset: DataSet): self._nnet = nnet self._dataset = dataset self._score = {} self._prediction = [] self._preprocess() def _preprocess(self): categorical_data = DataSet.dataframe_to_series(self._dataset.get_data().select_dtypes(include='category')) if isinstance(self._nnet, OptimizedNeuralNetwork): continuous_data = DataSet.dataframe_to_series(self._dataset.get_data().select_dtypes(exclude='category')) self._dataset = [*categorical_data, *continuous_data] else: continuous_data = self._dataset.get_data().select_dtypes(exclude='category').values self._dataset = [*categorical_data, continuous_data] def predict(self): self._prediction = self._nnet.get_model().predict(self._dataset).flatten() return self._prediction def evaluate(self, real_values, show_plot: bool = False): if len(self._prediction) > 0: rounded_pred = np.round(self._prediction) tp = np.sum(np.logical_and(rounded_pred == 1, real_values == 1)) tn = np.sum(np.logical_and(rounded_pred == 0, real_values == 0)) fp = np.sum(np.logical_and(rounded_pred == 1, real_values == 0)) fn = np.sum(
np.logical_and(rounded_pred == 0, real_values == 1)
numpy.logical_and
import sys import tensorflow as tf import pdb import numpy as np import myParams import GTools as GT import scipy.io import h5py import time FLAGS = tf.app.flags.FLAGS def setup_inputs(sess, filenames, image_size=None, capacity_factor=3, TestStuff=False): batch_size=myParams.myDict['batch_size'] channelsIn=myParams.myDict['channelsIn'] channelsOut=myParams.myDict['channelsOut'] DataH=myParams.myDict['DataH'] DataW=myParams.myDict['DataW'] LabelsH=myParams.myDict['LabelsH'] LabelsW=myParams.myDict['LabelsW'] if myParams.myDict['InputMode'] == 'I2I_ApplySens': print('I2I loading labels ' + time.strftime("%Y-%m-%d %H:%M:%S")) DatasetMatFN=myParams.myDict['LabelsMatFN'] f = h5py.File(DatasetMatFN, 'r') nToLoad=myParams.myDict['nToLoad'] LoadAndRunOnData=myParams.myDict['LoadAndRunOnData']>0 if LoadAndRunOnData: nToLoad=3 labels=f['Data'][1:nToLoad] print('Loaded images ' + time.strftime("%Y-%m-%d %H:%M:%S")) SensFN='/media/a/H2/home/a/gUM/ESensCC128.mat' SensCC=scipy.io.loadmat(SensFN) Sens=SensCC['ESensCC128'] SensMsk=SensCC['MskS'] SensMsk=np.reshape(SensMsk,(SensMsk.shape[0],SensMsk.shape[1],1)) def ConcatCOnDim(X,dim): return tf.cast(tf.concat([tf.real(X),tf.imag(X)],axis=dim),tf.float32) def myrot90(X): return tf.transpose(X, perm=[1,0,2]) with tf.device('/gpu:0'): TFL = tf.constant(np.int32(labels)) Idx=tf.random_uniform([1],minval=0,maxval=TFL.shape[0],dtype=tf.int32) labelR=tf.slice(TFL,[Idx[0],0,0,0],[1,-1,-1,1]) labelI=tf.slice(TFL,[Idx[0],0,0,1],[1,-1,-1,1]) labelR=tf.cast(labelR,tf.complex64) labelI=tf.cast(labelI,tf.complex64) label=tf.cast((labelR + 1j*labelI)/30000.0, tf.complex64) myParams.myDict['channelsOut']=1 myParams.myDict['LabelsH']=labels.shape[1] myParams.myDict['LabelsW']=labels.shape[2] myParams.myDict['DataH']=labels.shape[1] myParams.myDict['DataW']=labels.shape[2] label = tf.reshape(label, [LabelsH, LabelsW, 1]) label = tf.image.random_flip_left_right(label) label = tf.image.random_flip_up_down(label) u1=tf.random_uniform([1]) label=tf.cond(u1[0]<0.5, lambda: tf.identity(label), lambda: myrot90(label)) TFMsk = tf.constant(np.complex64(SensMsk)) TFSens = tf.constant(np.complex64(Sens)) label=tf.multiply(label,TFMsk) feature=label # label=ConcatCOnDim(label,2) label = tf.cast(tf.abs(label),tf.float32) feature=tf.multiply(feature,TFSens) feature=ConcatCOnDim(feature,2) features, labels = tf.train.batch([feature, label],batch_size=batch_size,num_threads=4,capacity = capacity_factor*batch_size,name='labels_and_features') tf.train.start_queue_runners(sess=sess) return features, labels if myParams.myDict['InputMode'] == 'I2I_B0': print('I2I loading labels ' + time.strftime("%Y-%m-%d %H:%M:%S")) DatasetMatFN=myParams.myDict['LabelsMatFN'] f = h5py.File(DatasetMatFN, 'r') nToLoad=myParams.myDict['nToLoad'] LoadAndRunOnData=myParams.myDict['LoadAndRunOnData']>0 if LoadAndRunOnData: nToLoad=3 labels=f['Data'][1:nToLoad] LMin=np.float32(f['Min']) LRange=np.float32(f['Range']) print('Min, Range: %f,%f' % (LMin,LRange)) print('Loaded images ' + time.strftime("%Y-%m-%d %H:%M:%S")) print('I2I loading features ' + time.strftime("%Y-%m-%d %H:%M:%S")) DatasetMatFN=myParams.myDict['FeaturesMatFN'] f = h5py.File(DatasetMatFN, 'r') features=f['Data'][1:nToLoad] FMin=np.float32(f['Min']) FRange=np.float32(f['Range']) print('Min, Range: %f,%f' % (FMin,FRange)) print('Loaded featuress ' + time.strftime("%Y-%m-%d %H:%M:%S")) TFL = tf.constant(np.int16(labels)) TFF = tf.constant(np.int16(features)) Idx=tf.random_uniform([1],minval=0,maxval=TFL.shape[0],dtype=tf.int32) label=tf.slice(TFL,[Idx[0],0,0],[1,-1,-1,]) feature=tf.slice(TFF,[Idx[0],0,0,0],[1,-1,-1,-1]) label = tf.cast(label, tf.float32) feature = tf.cast(feature, tf.float32) label=(label*LRange/30000.0)+LMin feature=(feature*FRange/30000.0)+FMin if labels.ndim==4: label = tf.reshape(label, [LabelsH, LabelsW, TFL.shape[3]]) else: label = tf.reshape(label, [LabelsH, LabelsW, 1]) if features.ndim==4: feature = tf.reshape(feature, [LabelsH, LabelsW, TFF.shape[3]]) else: feature = tf.reshape(feature, [LabelsH, LabelsW, 1]) features, labels = tf.train.batch([feature, label],batch_size=batch_size,num_threads=4,capacity = capacity_factor*batch_size,name='labels_and_features') tf.train.start_queue_runners(sess=sess) return features, labels if myParams.myDict['InputMode'] == 'I2I': print('I2I loading labels ' + time.strftime("%Y-%m-%d %H:%M:%S")) DatasetMatFN=myParams.myDict['LabelsMatFN'] # DatasetMatFN='/media/a/H2/home/a/gUM/GRE_U1.4_Labels.mat' f = h5py.File(DatasetMatFN, 'r') nToLoad=myParams.myDict['nToLoad'] LoadAndRunOnData=myParams.myDict['LoadAndRunOnData']>0 if LoadAndRunOnData: nToLoad=3 labels=f['labels'][1:nToLoad] print('Loaded images ' + time.strftime("%Y-%m-%d %H:%M:%S")) print('I2I loading features ' + time.strftime("%Y-%m-%d %H:%M:%S")) DatasetMatFN=myParams.myDict['FeaturesMatFN'] # DatasetMatFN='/media/a/H2/home/a/gUM/GRE_U1.4_Features.mat' f = h5py.File(DatasetMatFN, 'r') features=f['features'][1:nToLoad] print('Loaded featuress ' + time.strftime("%Y-%m-%d %H:%M:%S")) TFL = tf.constant(np.int16(labels)) TFF = tf.constant(np.int16(features)) Idx=tf.random_uniform([1],minval=0,maxval=TFL.shape[0],dtype=tf.int32) # label=tf.slice(TFL,[Idx[0],0,0],[1,-1,-1]) label=tf.slice(TFL,[Idx[0],0,0,0],[1,-1,-1,-1]) feature=tf.slice(TFF,[Idx[0],0,0,0],[1,-1,-1,-1]) label = tf.cast(label, tf.float32) feature = tf.cast(feature, tf.float32) if labels.ndim==4: label = tf.reshape(label, [LabelsH, LabelsW, TFL.shape[3]]) else: label = tf.reshape(label, [LabelsH, LabelsW, 1]) if features.ndim==4: feature = tf.reshape(feature, [LabelsH, LabelsW, TFF.shape[3]]) else: feature = tf.reshape(feature, [LabelsH, LabelsW, 1]) features, labels = tf.train.batch([feature, label],batch_size=batch_size,num_threads=4,capacity = capacity_factor*batch_size,name='labels_and_features') tf.train.start_queue_runners(sess=sess) return features, labels if myParams.myDict['InputMode'] == 'RegridTry3FMB': BaseTSDataP=myParams.myDict['BaseTSDataP'] BaseNUFTDataP=myParams.myDict['BaseNUFTDataP'] B0Data=scipy.io.loadmat(BaseTSDataP + 'B0TS.mat') TSBFA=B0Data['TSBFA'] TSCA=B0Data['TSCA'] TSBFB=B0Data['TSBFB'] TSCB=B0Data['TSCB'] SensCC=scipy.io.loadmat(BaseTSDataP + 'SensCC1.mat') SensA=SensCC['SensCCA'] SensMskA=SensCC['SensMskA'] SensB=SensCC['SensCCB'] SensMskB=SensCC['SensMskB'] SensMskA=np.reshape(SensMskA,(SensMskA.shape[0],SensMskA.shape[1],1)) SensMskB=np.reshape(SensMskB,(SensMskB.shape[0],SensMskB.shape[1],1)) TFMskA = tf.constant(np.complex64(SensMskA)) TFMskB = tf.constant(np.complex64(SensMskB)) print('loading images ' + time.strftime("%Y-%m-%d %H:%M:%S")) # f = h5py.File('/media/a/H1/HCPData_256x256_int16.mat', 'r') DatasetMatFN=myParams.myDict['DatasetMatFN'] f = h5py.File(DatasetMatFN, 'r') nToLoad=myParams.myDict['nToLoad'] # nToLoad=10000 LoadAndRunOnData=myParams.myDict['LoadAndRunOnData']>0 if LoadAndRunOnData: nToLoad=3 I=f['HCPData'][1:nToLoad] print('Loaded images ' + time.strftime("%Y-%m-%d %H:%M:%S")) H=LabelsH W=LabelsW TFI = tf.constant(np.int16(I)) IdxA=tf.random_uniform([1],minval=0,maxval=I.shape[0],dtype=tf.int32) IdxB=tf.random_uniform([1],minval=0,maxval=I.shape[0],dtype=tf.int32) featureA=tf.slice(TFI,[IdxA[0],0,0],[1,-1,-1]) featureB=tf.slice(TFI,[IdxB[0],0,0],[1,-1,-1]) featureA=tf.transpose(featureA, perm=[1,2,0]) featureB=tf.transpose(featureB, perm=[1,2,0]) featureA = tf.image.random_flip_left_right(featureA) featureA = tf.image.random_flip_up_down(featureA) u1=tf.random_uniform([1]) featureA=tf.cond(u1[0]<0.5, lambda: tf.identity(featureA), lambda: tf.image.rot90(featureA)) featureB = tf.image.random_flip_left_right(featureB) featureB = tf.image.random_flip_up_down(featureB) u1=tf.random_uniform([1]) featureB=tf.cond(u1[0]<0.5, lambda: tf.identity(featureB), lambda: tf.image.rot90(featureB)) featureA = tf.random_crop(featureA, [H, W, 1]) featureB = tf.random_crop(featureB, [H, W, 1]) featureA = tf.cast(featureA, tf.int32) featureB = tf.cast(featureB, tf.int32) mxA=tf.maximum(tf.reduce_max(featureA),1) mxB=tf.maximum(tf.reduce_max(featureB),1) featureA = tf.cast(featureA/mxA, tf.complex64) featureB = tf.cast(featureB/mxB, tf.complex64) featureA=tf.multiply(featureA,TFMskA) featureB=tf.multiply(featureB,TFMskB) LFac=myParams.myDict['RandomPhaseLinearFac'] QFac=myParams.myDict['RandomPhaseQuadraticFac'] SFac=myParams.myDict['RandomPhaseScaleFac'] QA=GT.TFGenerateRandomSinPhase(H, W,LFac,QFac,SFac) # (nx=100,ny=120,LFac=5,QFac=0.1,SFac=2): QB=GT.TFGenerateRandomSinPhase(H, W,LFac,QFac,SFac) CurIWithPhaseA=featureA*tf.reshape(QA,[H,W,1]) CurIWithPhaseB=featureB*tf.reshape(QB,[H,W,1]) NUFTData=scipy.io.loadmat(BaseNUFTDataP + 'TrajForNUFT.mat') Kd=NUFTData['Kd'] P=NUFTData['P'] SN=NUFTData['SN'] Trajm2=NUFTData['Trajm2'] nTraj=Trajm2.shape[1] nCh=SensA.shape[2] nTSC=TSCA.shape[2] # ggg Arrived till here. CAIPI supposed to be into TSB anyway SNcA,paddings,sp_R,sp_I,TSBFXA=GT.TF_TSNUFFT_Prepare(SN,SensA,TSCA,TSBFA,Kd,P) SNcB,paddings,sp_R,sp_I,TSBFXB=GT.TF_TSNUFFT_Prepare(SN,SensB,TSCB,TSBFB,Kd,P) def ConcatCI(X): return tf.concat([tf.real(X),tf.imag(X)],axis=0) def ConcatCIOn2(X): return tf.concat([tf.real(X),tf.imag(X)],axis=2) if myParams.myDict['BankSize']>0: BankSize=myParams.myDict['BankSize'] BankK=myParams.myDict['BankK'] label_indexes = tf.constant(np.int32(np.arange(0,BankSize)),dtype=tf.int32) BankK_indexes = tf.constant(np.int32(np.arange(0,BankSize*BankK)),dtype=tf.int32) Bankdataset = tf.data.Dataset.from_tensor_slices(label_indexes) Bankdataset = Bankdataset.repeat(count=None) Bankiter = Bankdataset.make_one_shot_iterator() label_index = Bankiter.get_next() label_index=tf.cast(label_index,tf.int32) label_index=label_index*2 BankKdataset = tf.data.Dataset.from_tensor_slices(BankK_indexes) BankKdataset = BankKdataset.repeat(count=None) BankKiter = BankKdataset.make_one_shot_iterator() label_indexK = BankKiter.get_next() label_indexK=tf.cast(label_indexK,tf.int32) label_indexK=label_indexK*2 IdxAX=tf.random_uniform([1],minval=0,maxval=BankSize,dtype=tf.int32) IdxBX=tf.random_uniform([1],minval=0,maxval=BankSize,dtype=tf.int32) with tf.device('/gpu:0'): OnlyTakeFromBank=tf.greater(label_indexK,label_index) with tf.variable_scope("aaa", reuse=True): Bank=tf.get_variable("Bank",dtype=tf.float32) LBank=tf.get_variable("LBank",dtype=tf.float32) def f2(): return tf.scatter_nd_update(Bank,[[label_index],[label_index+1]], [ConcatCI(tf.reshape(tf.transpose(GT.TF_TSNUFFT_Run(CurIWithPhaseA,SNcA,paddings,nTraj,nTSC,nCh,sp_R,sp_I,TSBFXA), perm=[1,0]),[nTraj*nCh,1,1])),ConcatCI(tf.reshape(tf.transpose(GT.TF_TSNUFFT_Run(CurIWithPhaseB,SNcB,paddings,nTraj,nTSC,nCh,sp_R,sp_I,TSBFXB), perm=[1,0]),[nTraj*nCh,1,1]))]) def f2L(): return tf.scatter_nd_update(LBank,[[label_index],[label_index+1]], [ConcatCIOn2(CurIWithPhaseA),ConcatCIOn2(CurIWithPhaseB)]) Bank = tf.cond(OnlyTakeFromBank, lambda: tf.identity(Bank), f2) LBank = tf.cond(OnlyTakeFromBank, lambda: tf.identity(LBank), f2L) IdxAF = tf.cond(OnlyTakeFromBank, lambda: tf.identity(IdxAX[0]*2), lambda: tf.identity(label_index)) IdxBF = tf.cond(OnlyTakeFromBank, lambda: tf.identity(IdxBX[0]*2+1), lambda: tf.identity(label_index+1)) # Take from bank in any case featureAX = tf.slice(Bank,[IdxAF,0,0,0],[1,-1,-1,-1]) featureAX = tf.reshape(featureAX, [DataH, 1, 1]) featureBX = tf.slice(Bank,[IdxBF,0,0,0],[1,-1,-1,-1]) featureBX = tf.reshape(featureBX, [DataH, 1, 1]) featureX=featureAX+featureBX # That's MB labelAX = tf.slice(LBank,[IdxAF,0,0,0],[1,-1,-1,-1]) labelAX = tf.reshape(labelAX, [H, W, 2]) labelBX = tf.slice(LBank,[IdxBF,0,0,0],[1,-1,-1,-1]) labelBX = tf.reshape(labelBX, [H, W, 2]) labelX = tf.concat([labelAX,labelBX],axis=1); features, labels = tf.train.batch([featureX, labelX],batch_size=batch_size,num_threads=4,capacity = capacity_factor*batch_size,name='labels_and_features') else: featureA=GT.TF_TSNUFFT_Run(CurIWithPhaseA,SNcA,paddings,nTraj,nTSC,nCh,sp_R,sp_I,TSBFXA) featureB=GT.TF_TSNUFFT_Run(CurIWithPhaseB,SNcB,paddings,nTraj,nTSC,nCh,sp_R,sp_I,TSBFXB) feature=featureA+featureB # That's MB feature=tf.transpose(feature, perm=[1,0]) F=tf.reshape(feature,[nTraj*nCh,1,1]) feature=ConcatCI(F) CurIWithPhase=tf.concat([CurIWithPhaseA,CurIWithPhaseB],axis=1); label=tf.concat([tf.real(CurIWithPhase),tf.imag(CurIWithPhase)],axis=2) features, labels = tf.train.batch([feature, label],batch_size=batch_size,num_threads=4,capacity = capacity_factor*batch_size,name='labels_and_features') tf.train.start_queue_runners(sess=sess) return features, labels if myParams.myDict['InputMode'] == 'RegridTry3F': BaseTSDataP=myParams.myDict['BaseTSDataP'] BaseNUFTDataP=myParams.myDict['BaseNUFTDataP'] B0Data=scipy.io.loadmat(BaseTSDataP + 'B0TS.mat') # Sens=B0Data['Sens'] TSBF=B0Data['TSBF'] TSC=B0Data['TSC'] SensCC=scipy.io.loadmat(BaseTSDataP + 'SensCC1.mat') Sens=SensCC['SensCC'] SensMsk=SensCC['SensMsk'] SensMsk=np.reshape(SensMsk,(SensMsk.shape[0],SensMsk.shape[1],1)) TFMsk = tf.constant(np.complex64(SensMsk)) print('loading images ' + time.strftime("%Y-%m-%d %H:%M:%S")) # I=scipy.io.loadmat('/media/a/H1/First3kIm256x256Magint16.mat') # I=I['First3kIm256x256Magint16'] DatasetMatFN=myParams.myDict['DatasetMatFN'] # f = h5py.File('/media/a/H1/HCPData_256x256_int16.mat', 'r') f = h5py.File(DatasetMatFN, 'r') # nToLoad=10000 nToLoad=myParams.myDict['nToLoad'] LoadAndRunOnData=myParams.myDict['LoadAndRunOnData']>0 if LoadAndRunOnData: nToLoad=3 I=f['HCPData'][1:nToLoad] print('Loaded images ' + time.strftime("%Y-%m-%d %H:%M:%S")) # I=scipy.io.loadmat('/media/a/H1/First1kIm256x256Magint16.mat') # I=I['First1kIm256x256Magint16'] H=LabelsH W=LabelsW TFI = tf.constant(np.int16(I)) Idx=tf.random_uniform([1],minval=0,maxval=I.shape[0],dtype=tf.int32) feature=tf.slice(TFI,[Idx[0],0,0],[1,-1,-1]) feature=tf.transpose(feature, perm=[1,2,0]) feature = tf.image.random_flip_left_right(feature) feature = tf.image.random_flip_up_down(feature) # u1 = tf.distributions.Uniform(low=0.0, high=1.0) u1=tf.random_uniform([1]) feature=tf.cond(u1[0]<0.5, lambda: tf.identity(feature), lambda: tf.image.rot90(feature)) # tf.image.rot90( image, k=1, name=None) # MYGlobalStep = tf.Variable(0, trainable=False, name='Myglobal_step') # MYGlobalStep = MYGlobalStep+1 # feature=tf.cond(MYGlobalStep>0, lambda: tf.identity(feature), lambda: tf.identity(feature)) # feature = tf.Print(feature,[MYGlobalStep,],message='MYGlobalStep:') # image = tf.image.random_saturation(image, .95, 1.05) # image = tf.image.random_brightness(image, .05) #image = tf.image.random_contrast(image, .95, 1.05) feature = tf.random_crop(feature, [H, W, 1]) feature = tf.cast(feature, tf.int32) mx=tf.reduce_max(feature) mx=tf.maximum(mx,1) feature = tf.cast(feature/mx, tf.complex64) feature=tf.multiply(feature,TFMsk) Q=GT.TFGenerateRandomSinPhase(H, W) CurIWithPhase=feature*tf.reshape(Q,[H,W,1]) label=tf.concat([tf.real(CurIWithPhase),tf.imag(CurIWithPhase)],axis=2) NUFTData=scipy.io.loadmat(BaseNUFTDataP + 'TrajForNUFT.mat') Kd=NUFTData['Kd'] P=NUFTData['P'] SN=NUFTData['SN'] Trajm2=NUFTData['Trajm2'] nTraj=Trajm2.shape[1] nCh=Sens.shape[2] nTSC=TSC.shape[2] SNc,paddings,sp_R,sp_I,TSBFX=GT.TF_TSNUFFT_Prepare(SN,Sens,TSC,TSBF,Kd,P) # feature=GT.TF_TSNUFFT_Run(CurIWithPhase,SNc,paddings,nTraj,nTSC,nCh,sp_R,sp_I,TSBFX) # feature=tf.transpose(feature, perm=[1,0]) # F=tf.reshape(feature,[nTraj*nCh,1,1]) # feature=tf.concat([tf.real(F),tf.imag(F)],axis=0) def ConcatCI(X): return tf.concat([tf.real(X),tf.imag(X)],axis=0) # feature=ConcatCI(F) # feature=ConcatCI(tf.reshape(tf.transpose(GT.TF_TSNUFFT_Run(CurIWithPhase,SNc,paddings,nTraj,nTSC,nCh,sp_R,sp_I,TSBFX), perm=[1,0]),[nTraj*nCh,1,1])) # ggg Signal Bank stuff: if myParams.myDict['BankSize']>0: BankSize=myParams.myDict['BankSize'] BankK=myParams.myDict['BankK'] label_indexes = tf.constant(np.int32(np.arange(0,BankSize)),dtype=tf.int32) BankK_indexes = tf.constant(np.int32(np.arange(0,BankSize*BankK)),dtype=tf.int32) Bankdataset = tf.data.Dataset.from_tensor_slices(label_indexes) Bankdataset = Bankdataset.repeat(count=None) Bankiter = Bankdataset.make_one_shot_iterator() label_index = Bankiter.get_next() label_index=tf.cast(label_index,tf.int32) BankKdataset = tf.data.Dataset.from_tensor_slices(BankK_indexes) BankKdataset = BankKdataset.repeat(count=None) BankKiter = BankKdataset.make_one_shot_iterator() label_indexK = BankKiter.get_next() label_indexK=tf.cast(label_indexK,tf.int32) with tf.device('/gpu:0'): OnlyTakeFromBank=tf.greater(label_indexK,label_index) with tf.variable_scope("aaa", reuse=True): Bank=tf.get_variable("Bank",dtype=tf.float32) LBank=tf.get_variable("LBank",dtype=tf.float32) def f2(): return tf.scatter_nd_update(Bank,[[label_index]], [ConcatCI(tf.reshape(tf.transpose(GT.TF_TSNUFFT_Run(CurIWithPhase,SNc,paddings,nTraj,nTSC,nCh,sp_R,sp_I,TSBFX), perm=[1,0]),[nTraj*nCh,1,1]))]) def f2L(): return tf.scatter_nd_update(LBank,[[label_index]], [label]) Bank = tf.cond(OnlyTakeFromBank, lambda: tf.identity(Bank), f2) LBank = tf.cond(OnlyTakeFromBank, lambda: tf.identity(LBank), f2L) # Take from bank in any case featureX = tf.slice(Bank,[label_index,0,0,0],[1,-1,-1,-1]) featureX = tf.reshape(featureX, [DataH, 1, 1]) # featureX = tf.Print(featureX,[label_index,label_indexK],message='Taking from bank:') labelX = tf.slice(LBank,[label_index,0,0,0],[1,-1,-1,-1]) labelX = tf.reshape(labelX, [H, W, 2]) features, labels = tf.train.batch([featureX, labelX],batch_size=batch_size,num_threads=4,capacity = capacity_factor*batch_size,name='labels_and_features') # feature = tf.cond(TakeFromBank, lambda: tf.identity(Bfeature), lambda: tf.identity(Afeature)) # label = tf.cond(TakeFromBank, lambda: tf.identity(Blabel), lambda: tf.identity(Alabel)) else: feature=ConcatCI(tf.reshape(tf.transpose(GT.TF_TSNUFFT_Run(CurIWithPhase,SNc,paddings,nTraj,nTSC,nCh,sp_R,sp_I,TSBFX), perm=[1,0]),[nTraj*nCh,1,1])) features, labels = tf.train.batch([feature, label],batch_size=batch_size,num_threads=4,capacity = capacity_factor*batch_size,name='labels_and_features') # ggg end Signal Bank stuff: tf.train.start_queue_runners(sess=sess) return features, labels if myParams.myDict['InputMode'] == 'RegridTry3M': Msk=scipy.io.loadmat('/media/a/DATA/meas_MID244_gBP_VD11_U19_G35S155_4min_FID22439/Sli08/Msk.mat') Msk=Msk['Msk'] TFMsk = tf.constant(Msk) FN='/media/a/H1/meas_MID244_gBP_VD11_U19_G35S155_4min_FID22439/AllData_Sli8_6k.mat' if TestStuff: print('setup_inputs Test') ChunkSize=100 ChunkSizeL=400 FN='/media/a/H1/meas_MID244_gBP_VD11_U19_G35S155_4min_FID22439/AllData_Sli8_100.mat' else: print('setup_inputs Train') ChunkSize=1000 ChunkSizeL=4000 f = h5py.File(FN, 'r') print('loading Data ' + time.strftime("%Y-%m-%d %H:%M:%S")) I=f['AllDatax'][:] print('Loaded labels ' + time.strftime("%Y-%m-%d %H:%M:%S")) f.close() I=I.astype(np.float32) f = h5py.File('/media/a/H1/AllImWithPhaseComplexSingle_h5.mat', 'r') print('Loading labels ' + time.strftime("%Y-%m-%d %H:%M:%S")) L=f['AllLh5'][0:(ChunkSizeL)] print('Loaded labels ' + time.strftime("%Y-%m-%d %H:%M:%S")) f.close() L=L.astype(np.float32) TFI = tf.constant(I[0:ChunkSize]) TFIb = tf.constant(I[(ChunkSize):(2*ChunkSize)]) TFIc = tf.constant(I[(2*ChunkSize):(3*ChunkSize)]) TFId = tf.constant(I[(3*ChunkSize):(4*ChunkSize)]) TFL = tf.constant(L) # place = tf.placeholder(tf.float32, shape=(DataH, DataW, channelsIn)) # placeL = tf.placeholder(tf.float32, shape=(LabelsH, LabelsW, channelsOut)) Idx=tf.random_uniform([1],minval=0,maxval=ChunkSizeL,dtype=tf.int32) def f1(): return tf.cond(Idx[0]<ChunkSize, lambda: tf.slice(TFI,[Idx[0],0],[1,-1]), lambda: tf.slice(TFIb,[Idx[0]-ChunkSize,0],[1,-1])) def f2(): return tf.cond(Idx[0]<(3*ChunkSize), lambda: tf.slice(TFIc,[Idx[0]-2*ChunkSize,0],[1,-1]), lambda: tf.slice(TFId,[Idx[0]-3*ChunkSize,0],[1,-1])) feature=tf.cond(Idx[0]<(2*ChunkSize), f1, f2) # feature=tf.cond(Idx[0]<ChunkSize, lambda: tf.slice(TFI,[Idx[0],0],[1,-1]), lambda: tf.slice(TFIb,[Idx[0]-ChunkSize,0],[1,-1])) # feature=tf.slice(TFI,[Idx[0],0],[1,-1]) # feature = tmp.assign(place) feature = tf.reshape(feature, [DataH, DataW, channelsIn]) feature = tf.cast(feature, tf.float32) labels = tf.slice(TFL,[Idx[0],0,0,0],[1,-1,-1,-1]) # feature = tmpL.assign(placeL) labels = tf.reshape(labels, [LabelsH, LabelsW, channelsOut]) label = tf.cast(labels, tf.float32) label=tf.multiply(label,TFMsk) # Using asynchronous queues features, labels = tf.train.batch([feature, label], batch_size=batch_size, num_threads=4, capacity = capacity_factor*batch_size, name='labels_and_features') tf.train.start_queue_runners(sess=sess) return features, labels if myParams.myDict['InputMode'] == 'SPEN_Local': SR=scipy.io.loadmat('/media/a/H1/SR.mat') SR=SR['SR'] SR=np.reshape(SR,[DataH,DataH,1]) SR=np.transpose(SR, (2,0,1)) SR_TF=tf.constant(SR) # I=scipy.io.loadmat('/media/a/H1/First1kIm256x256Magint16.mat') # I=I['First1kIm256x256Magint16'] I=scipy.io.loadmat('/media/a/H1/First3kIm256x256Magint16.mat') I=I['First3kIm256x256Magint16'] TFI = tf.constant(np.float32(I)) Idx=tf.random_uniform([1],minval=0,maxval=3000,dtype=tf.int32) feature=tf.slice(TFI,[Idx[0],0,0],[1,-1,-1]) feature=tf.transpose(feature, perm=[1,2,0]) feature = tf.random_crop(feature, [DataH, DataW, 1]) mx=tf.reduce_max(feature) mx=tf.maximum(mx,1) feature = tf.cast(feature/mx, tf.complex64) Q=GT.TFGenerateRandomSinPhase(DataH, DataW) CurIWithPhase=feature*tf.reshape(Q,[DataH,DataW,1]) label=tf.concat([tf.real(CurIWithPhase),tf.imag(CurIWithPhase)],axis=2) P=tf.transpose(CurIWithPhase, perm=[2,1,0]) F=tf.matmul(P,SR_TF) F=tf.transpose(F, perm=[2,1,0]) SPENLocalFactor=myParams.myDict['SPENLocalFactor'] F=GT.ExpandWithCopiesOn2(F,DataH,SPENLocalFactor) feature=tf.concat([tf.real(F),tf.imag(F)],axis=2) features, labels = tf.train.batch([feature, label],batch_size=batch_size,num_threads=4,capacity = capacity_factor*batch_size,name='labels_and_features') tf.train.start_queue_runners(sess=sess) return features, labels if myParams.myDict['InputMode'] == 'SPEN_FC': SR=scipy.io.loadmat('/media/a/H1/SR.mat') SR=SR['SR'] SR=np.reshape(SR,[DataH,DataH,1]) SR=np.transpose(SR, (2,0,1)) SR_TF=tf.constant(SR) I=scipy.io.loadmat('/media/a/H1/First1kIm256x256Magint16.mat') I=I['First1kIm256x256Magint16'] TFI = tf.constant(
np.float32(I)
numpy.float32
import numpy as np from . import box # NOQA from . import Geometry # NOQA from . import GeometryType, lib from .decorators import multithreading_enabled, requires_geos, UnsupportedGEOSOperation __all__ = [ "difference", "intersection", "intersection_all", "symmetric_difference", "symmetric_difference_all", "union", "union_all", "coverage_union", "coverage_union_all", ] @multithreading_enabled def difference(a, b, grid_size=None, **kwargs): """Returns the part of geometry A that does not intersect with geometry B. If grid_size is nonzero, input coordinates will be snapped to a precision grid of that size and resulting coordinates will be snapped to that same grid. If 0, this operation will use double precision coordinates. If None, the highest precision of the inputs will be used, which may be previously set using set_precision. Note: returned geometry does not have precision set unless specified previously by set_precision. Parameters ---------- a : Geometry or array_like b : Geometry or array_like grid_size : float, optional Precision grid size; requires GEOS >= 3.9.0. Will use the highest precision of the inputs by default. **kwargs For other keyword-only arguments, see the `NumPy ufunc docs <https://numpy.org/doc/stable/reference/ufuncs.html#ufuncs-kwargs>`_. See also -------- set_precision Examples -------- >>> from shapely.constructive import normalize >>> line = Geometry("LINESTRING (0 0, 2 2)") >>> difference(line, Geometry("LINESTRING (1 1, 3 3)")) <pygeos.Geometry LINESTRING (0 0, 1 1)> >>> difference(line, Geometry("LINESTRING EMPTY")) <pygeos.Geometry LINESTRING (0 0, 2 2)> >>> difference(line, None) is None True >>> box1 = box(0, 0, 2, 2) >>> box2 = box(1, 1, 3, 3) >>> normalize(difference(box1, box2)) <pygeos.Geometry POLYGON ((0 0, 0 2, 1 2, 1 1, 2 1, 2 0, 0 0))> >>> box1 = box(0.1, 0.2, 2.1, 2.1) >>> difference(box1, box2, grid_size=1) # doctest: +SKIP <pygeos.Geometry POLYGON ((0 0, 0 2, 1 2, 1 1, 2 1, 2 0, 0 0))> """ if grid_size is not None: if lib.geos_version < (3, 9, 0): raise UnsupportedGEOSOperation("grid_size parameter requires GEOS >= 3.9.0") if not np.isscalar(grid_size): raise ValueError("grid_size parameter only accepts scalar values") return lib.difference_prec(a, b, grid_size, **kwargs) return lib.difference(a, b, **kwargs) @multithreading_enabled def intersection(a, b, grid_size=None, **kwargs): """Returns the geometry that is shared between input geometries. If grid_size is nonzero, input coordinates will be snapped to a precision grid of that size and resulting coordinates will be snapped to that same grid. If 0, this operation will use double precision coordinates. If None, the highest precision of the inputs will be used, which may be previously set using set_precision. Note: returned geometry does not have precision set unless specified previously by set_precision. Parameters ---------- a : Geometry or array_like b : Geometry or array_like grid_size : float, optional Precision grid size; requires GEOS >= 3.9.0. Will use the highest precision of the inputs by default. **kwargs For other keyword-only arguments, see the `NumPy ufunc docs <https://numpy.org/doc/stable/reference/ufuncs.html#ufuncs-kwargs>`_. See also -------- intersection_all set_precision Examples -------- >>> from shapely.constructive import normalize >>> line = Geometry("LINESTRING(0 0, 2 2)") >>> intersection(line, Geometry("LINESTRING(1 1, 3 3)")) <pygeos.Geometry LINESTRING (1 1, 2 2)> >>> box1 = box(0, 0, 2, 2) >>> box2 = box(1, 1, 3, 3) >>> normalize(intersection(box1, box2)) <pygeos.Geometry POLYGON ((1 1, 1 2, 2 2, 2 1, 1 1))> >>> box1 = box(0.1, 0.2, 2.1, 2.1) >>> intersection(box1, box2, grid_size=1) # doctest: +SKIP <pygeos.Geometry POLYGON ((1 1, 1 2, 2 2, 2 1, 1 1))> """ if grid_size is not None: if lib.geos_version < (3, 9, 0): raise UnsupportedGEOSOperation("grid_size parameter requires GEOS >= 3.9.0") if not np.isscalar(grid_size): raise ValueError("grid_size parameter only accepts scalar values") return lib.intersection_prec(a, b, grid_size, **kwargs) return lib.intersection(a, b, **kwargs) @multithreading_enabled def intersection_all(geometries, axis=None, **kwargs): """Returns the intersection of multiple geometries. This function ignores None values when other Geometry elements are present. If all elements of the given axis are None, None is returned. Parameters ---------- geometries : array_like axis : int, optional Axis along which the operation is performed. The default (None) performs the operation over all axes, returning a scalar value. Axis may be negative, in which case it counts from the last to the first axis. **kwargs For other keyword-only arguments, see the `NumPy ufunc.reduce docs <https://numpy.org/doc/stable/reference/generated/numpy.ufunc.reduce.html#numpy.ufunc.reduce>`_. See also -------- intersection Examples -------- >>> line_1 = Geometry("LINESTRING(0 0, 2 2)") >>> line_2 = Geometry("LINESTRING(1 1, 3 3)") >>> intersection_all([line_1, line_2]) <pygeos.Geometry LINESTRING (1 1, 2 2)> >>> intersection_all([[line_1, line_2, None]], axis=1).tolist() [<pygeos.Geometry LINESTRING (1 1, 2 2)>] """ return lib.intersection.reduce(geometries, axis=axis, **kwargs) @multithreading_enabled def symmetric_difference(a, b, grid_size=None, **kwargs): """Returns the geometry that represents the portions of input geometries that do not intersect. If grid_size is nonzero, input coordinates will be snapped to a precision grid of that size and resulting coordinates will be snapped to that same grid. If 0, this operation will use double precision coordinates. If None, the highest precision of the inputs will be used, which may be previously set using set_precision. Note: returned geometry does not have precision set unless specified previously by set_precision. Parameters ---------- a : Geometry or array_like b : Geometry or array_like grid_size : float, optional Precision grid size; requires GEOS >= 3.9.0. Will use the highest precision of the inputs by default. **kwargs For other keyword-only arguments, see the `NumPy ufunc docs <https://numpy.org/doc/stable/reference/ufuncs.html#ufuncs-kwargs>`_. See also -------- symmetric_difference_all set_precision Examples -------- >>> from shapely.constructive import normalize >>> line = Geometry("LINESTRING(0 0, 2 2)") >>> symmetric_difference(line, Geometry("LINESTRING(1 1, 3 3)")) <pygeos.Geometry MULTILINESTRING ((0 0, 1 1), (2 2, 3 3))> >>> box1 = box(0, 0, 2, 2) >>> box2 = box(1, 1, 3, 3) >>> normalize(symmetric_difference(box1, box2)) <pygeos.Geometry MULTIPOLYGON (((1 2, 1 3, 3 3, 3 1, 2 1, 2 2, 1 2)), ((0 0,...> >>> box1 = box(0.1, 0.2, 2.1, 2.1) >>> symmetric_difference(box1, box2, grid_size=1) # doctest: +SKIP <pygeos.Geometry MULTIPOLYGON (((1 2, 1 3, 3 3, 3 1, 2 1, 2 2, 1 2)), ((0 0,...> """ if grid_size is not None: if lib.geos_version < (3, 9, 0): raise UnsupportedGEOSOperation("grid_size parameter requires GEOS >= 3.9.0") if not np.isscalar(grid_size): raise ValueError("grid_size parameter only accepts scalar values") return lib.symmetric_difference_prec(a, b, grid_size, **kwargs) return lib.symmetric_difference(a, b, **kwargs) @multithreading_enabled def symmetric_difference_all(geometries, axis=None, **kwargs): """Returns the symmetric difference of multiple geometries. This function ignores None values when other Geometry elements are present. If all elements of the given axis are None, None is returned. Parameters ---------- geometries : array_like axis : int, optional Axis along which the operation is performed. The default (None) performs the operation over all axes, returning a scalar value. Axis may be negative, in which case it counts from the last to the first axis. **kwargs For other keyword-only arguments, see the `NumPy ufunc.reduce docs <https://numpy.org/doc/stable/reference/generated/numpy.ufunc.reduce.html#numpy.ufunc.reduce>`_. See also -------- symmetric_difference Examples -------- >>> line_1 = Geometry("LINESTRING(0 0, 2 2)") >>> line_2 = Geometry("LINESTRING(1 1, 3 3)") >>> symmetric_difference_all([line_1, line_2]) <pygeos.Geometry MULTILINESTRING ((0 0, 1 1), (2 2, 3 3))> >>> symmetric_difference_all([[line_1, line_2, None]], axis=1).tolist() [<pygeos.Geometry MULTILINESTRING ((0 0, 1 1), (2 2, 3 3))>] """ return lib.symmetric_difference.reduce(geometries, axis=axis, **kwargs) @multithreading_enabled def union(a, b, grid_size=None, **kwargs): """Merges geometries into one. If grid_size is nonzero, input coordinates will be snapped to a precision grid of that size and resulting coordinates will be snapped to that same grid. If 0, this operation will use double precision coordinates. If None, the highest precision of the inputs will be used, which may be previously set using set_precision. Note: returned geometry does not have precision set unless specified previously by set_precision. Parameters ---------- a : Geometry or array_like b : Geometry or array_like grid_size : float, optional Precision grid size; requires GEOS >= 3.9.0. Will use the highest precision of the inputs by default. **kwargs For other keyword-only arguments, see the `NumPy ufunc docs <https://numpy.org/doc/stable/reference/ufuncs.html#ufuncs-kwargs>`_. See also -------- union_all set_precision Examples -------- >>> from shapely.constructive import normalize >>> line = Geometry("LINESTRING(0 0, 2 2)") >>> union(line, Geometry("LINESTRING(2 2, 3 3)")) <pygeos.Geometry MULTILINESTRING ((0 0, 2 2), (2 2, 3 3))> >>> union(line, None) is None True >>> box1 = box(0, 0, 2, 2) >>> box2 = box(1, 1, 3, 3) >>> normalize(union(box1, box2)) <pygeos.Geometry POLYGON ((0 0, 0 2, 1 2, 1 3, 3 3, 3 1, 2 1, 2 0, 0 0))> >>> box1 = box(0.1, 0.2, 2.1, 2.1) >>> union(box1, box2, grid_size=1) # doctest: +SKIP <pygeos.Geometry POLYGON ((0 0, 0 2, 1 2, 1 3, 3 3, 3 1, 2 1, 2 0, 0 0))> """ if grid_size is not None: if lib.geos_version < (3, 9, 0): raise UnsupportedGEOSOperation("grid_size parameter requires GEOS >= 3.9.0") if not np.isscalar(grid_size): raise ValueError("grid_size parameter only accepts scalar values") return lib.union_prec(a, b, grid_size, **kwargs) return lib.union(a, b, **kwargs) @multithreading_enabled def union_all(geometries, grid_size=None, axis=None, **kwargs): """Returns the union of multiple geometries. This function ignores None values when other Geometry elements are present. If all elements of the given axis are None, None is returned. If grid_size is nonzero, input coordinates will be snapped to a precision grid of that size and resulting coordinates will be snapped to that same grid. If 0, this operation will use double precision coordinates. If None, the highest precision of the inputs will be used, which may be previously set using set_precision. Note: returned geometry does not have precision set unless specified previously by set_precision. Parameters ---------- geometries : array_like grid_size : float, optional Precision grid size; requires GEOS >= 3.9.0. Will use the highest precision of the inputs by default. axis : int, optional Axis along which the operation is performed. The default (None) performs the operation over all axes, returning a scalar value. Axis may be negative, in which case it counts from the last to the first axis. **kwargs For other keyword-only arguments, see the `NumPy ufunc docs <https://numpy.org/doc/stable/reference/ufuncs.html#ufuncs-kwargs>`_. See also -------- union set_precision Examples -------- >>> from shapely.constructive import normalize >>> line_1 = Geometry("LINESTRING(0 0, 2 2)") >>> line_2 = Geometry("LINESTRING(2 2, 3 3)") >>> union_all([line_1, line_2]) <pygeos.Geometry MULTILINESTRING ((0 0, 2 2), (2 2, 3 3))> >>> union_all([[line_1, line_2, None]], axis=1).tolist() [<pygeos.Geometry MULTILINESTRING ((0 0, 2 2), (2 2, 3 3))>] >>> box1 = box(0, 0, 2, 2) >>> box2 = box(1, 1, 3, 3) >>> normalize(union_all([box1, box2])) <pygeos.Geometry POLYGON ((0 0, 0 2, 1 2, 1 3, 3 3, 3 1, 2 1, 2 0, 0 0))> >>> box1 = box(0.1, 0.2, 2.1, 2.1) >>> union_all([box1, box2], grid_size=1) # doctest: +SKIP <pygeos.Geometry POLYGON ((0 0, 0 2, 1 2, 1 3, 3 3, 3 1, 2 1, 2 0, 0 0))> """ # for union_all, GEOS provides an efficient route through first creating # GeometryCollections # first roll the aggregation axis backwards geometries = np.asarray(geometries) if axis is None: geometries = geometries.ravel() else: geometries = np.rollaxis( np.asarray(geometries), axis=axis, start=geometries.ndim ) # create_collection acts on the inner axis collections = lib.create_collection(geometries, GeometryType.GEOMETRYCOLLECTION) if grid_size is not None: if lib.geos_version < (3, 9, 0): raise UnsupportedGEOSOperation("grid_size parameter requires GEOS >= 3.9.0") if not
np.isscalar(grid_size)
numpy.isscalar
import loader as ld import fun_basicas as fun import pandas as pd import matplotlib.pyplot as plt import numpy as np import scipy.optimize as opt from scipy.optimize import minimize def coste(theta1, theta2, X, Y, num_etiquetas): # Y preparada A1, A2, h = forward_prop(X, theta1, theta2) sum1 = Y * np.log(h) sum2 = (1 - Y) *
np.log(1 - h + 1e-6)
numpy.log
############## music generation with 3 layer LSTM ###################### # # Distributed under the MIT license by <NAME> ######################################################################## import numpy as np import matplotlib import matplotlib.pyplot as plt import matplotlib.cm as cm import math import copy as cp from copy import deepcopy import pickle as pkl import time import os import theano #typical 2x speed up for small network, 400x600x600 net ~6x speed up from theano import tensor as T, function, printing from theano.sandbox.rng_mrg import MRG_RandomStreams as RandomStreams import theano.sandbox.cuda as cuda from random import shuffle #from theano.compile.nanguardmode import NanGuardMode import LSTMmusicMB from LSTMmusicMB import RNN4Music # midi utility scripts should be installed in ./midi/utils.py import midi.MidiOutStream import midi.MidiInStream import midi.MidiInFile import midi.MidiToText from midi.utils import midiread from midi.utils import midiwrite # set plot sizes if this code is copied to ipython/jupyter notebook import pylab pylab.rcParams['figure.figsize'] = (20, 5) np.set_printoptions(threshold='nan') def main(): #--- import data ---# sizeOfMiniBatch = 5 #how many tunes per miniBatch noOfEpoch = 100 noOfEpochPerMB = 2 lengthOfMB = 100 sparseParam = np.float32(0.01) #increases with no. of cells path = './Piano-midi.de/train-individual/hpps' #path = './Piano-midi.de/train' files = os.listdir(path) assert len(files) > 0, 'Training set is empty!' \ ' (did you download the data files?)' #pitch range is from 21 to 109 dataset = [midiread((path + "/" + f), (21, 109),0.3).piano_roll.astype(theano.config.floatX) for f in files] #check number of notes for each tune: print(str([np.array(dataset[n]).shape[0] for n in np.arange(np.array(dataset).shape[0])])) # set "silent" to zero in 1-hot format for k in np.arange(np.array(dataset).shape[0]): for n in np.arange(0,np.array(dataset[k]).shape[0],1): if np.sum(dataset[k][n], dtype=theano.config.floatX) == 0 : dataset[k][n][0] = np.float32(1.0) #--- training with data ---# myRNN4Music = RNN4Music(h1_length=176, h2_length=176, h3_length=176, io_length=88, R1=np.float32(0.001), R2=np.float32(0.001), R3=
np.float32(0.001)
numpy.float32
import numpy import math from scipy.interpolate import InterpolatedUnivariateSpline as interpolate from scipy.integrate import simps import sys sys.path.append("/global/homes/c/chmodi/Programs/Py_codes/modules/") import cosmology as cosmo_lib class s_cross(): def __init__(self, power_file, M, L, R = 0., H0 = 100.): self.M = M self.L = L self.ktrue, self.ptrue = numpy.loadtxt(power_file, unpack = True) self.H0 = H0 self.R = R self.rhoc = 3 * H0**2 /(8 * math.pi * 43.007) self.rhom = self.rhoc*M self.cosmo = cosmo_lib.Cosmology(M= M, L = L) self.masses = 10**numpy.arange(9, 18, 0.01) self.sigma = numpy.zeros_like(self.masses) self.calc_sigma() def calc_sigma(self): M = self.masses for foo in range(len(M)): self.sigma[foo] = self.sigmasq(M[foo])**0.5 def tophat(self, k, R): kr = k*R wt = 3 * (numpy.sin(kr)/kr -
numpy.cos(kr)
numpy.cos
"""Description of Pd2d class.""" __author__ = 'ikibalin' __version__ = "2020_08_19" from warnings import warn import numpy from typing import List, NoReturn from cryspy.A_functions_base.function_2_crystallography_base import \ calc_cos_ang from cryspy.A_functions_base.matrix_operations import calc_m1_m2_m1t from cryspy.A_functions_base.unit_cell import calc_matrix_t from cryspy.A_functions_base.powder_diffraction_const_wavelength import \ calc_ttheta_phi_by_gamma_nu from cryspy.B_parent_classes.cl_1_item import ItemN from cryspy.B_parent_classes.cl_2_loop import LoopN from cryspy.B_parent_classes.cl_3_data import DataN from cryspy.B_parent_classes.preocedures import take_items_by_class from cryspy.C_item_loop_classes.cl_1_setup import Setup from cryspy.C_item_loop_classes.cl_1_diffrn_radiation import \ DiffrnRadiation from cryspy.C_item_loop_classes.cl_1_extinction import Extinction from cryspy.C_item_loop_classes.cl_1_phase import PhaseL from cryspy.C_item_loop_classes.cl_1_pd_peak import PdPeakL from cryspy.C_item_loop_classes.cl_1_refln import ReflnL from cryspy.C_item_loop_classes.cl_1_refln_susceptibility import \ ReflnSusceptibilityL from cryspy.C_item_loop_classes.cl_1_refine_ls import RefineLs from cryspy.C_item_loop_classes.cl_1_pd2d_background import \ Pd2dBackground from cryspy.C_item_loop_classes.cl_1_pd2d_instr_reflex_asymmetry import\ Pd2dInstrReflexAsymmetry from cryspy.C_item_loop_classes.cl_1_pd2d_instr_resolution import \ Pd2dInstrResolution from cryspy.C_item_loop_classes.cl_1_pd2d_meas import Pd2dMeas from cryspy.C_item_loop_classes.cl_1_pd2d_proc import Pd2dProc from cryspy.C_item_loop_classes.cl_1_pd2d_peak import Pd2dPeakL from cryspy.C_item_loop_classes.cl_1_chi2 import Chi2 from cryspy.C_item_loop_classes.cl_1_range import Range from cryspy.C_item_loop_classes.cl_1_texture import TextureL from cryspy.C_item_loop_classes.cl_1_exclude import ExcludeL from cryspy.E_data_classes.cl_1_crystal import Crystal na = numpy.newaxis class Pd2d(DataN): """ Powder diffraction experiment with polarized or unpolarized neutrons (2d). Data items in the DIFFRN category record details about 2d powder diffraction measurements. Methods ------- - calc_iint_u_d_flip_ratio - calc_fr - calc_fm_perp_loc - calc_chi_sq - params_to_cif - data_to_cif - calc_to_cif - estimate_FM Attributes ---------- - setup (mandatory) - pd2d_instr_resolution (mandatory) - phase (mandatory) - pd2d_background (mandatory) - pd_meas (mandatory) - diffrn_radiation - chi2 - range - extinction - pd2d_instr_reflex_asymmetry - texture - exclude - pd2d_proc - pd2d_peak - refine_ls - refln_#phase_name - refln_susceptibility_#phase_name """ CLASSES_MANDATORY = (Pd2dInstrResolution, PhaseL, DiffrnRadiation, Setup, Range, Pd2dBackground, Pd2dMeas) CLASSES_OPTIONAL = (Extinction, ExcludeL, Chi2, Pd2dInstrReflexAsymmetry, TextureL, RefineLs, ReflnL, ReflnSusceptibilityL, Pd2dPeakL, Pd2dProc, PdPeakL) # CLASSES_INTERNAL = () CLASSES = CLASSES_MANDATORY + CLASSES_OPTIONAL PREFIX = "pd2d" # default values for the parameters D_DEFAULT = {} def __init__(self, data_name=None, **kwargs) -> NoReturn: super(Pd2d, self).__init__() self.__dict__["items"] = [] self.__dict__["data_name"] = data_name for key, attr in self.D_DEFAULT.items(): setattr(self, key, attr) for key, attr in kwargs.items(): setattr(self, key, attr) def calc_profile(self, tth, phi, l_crystal: List[Crystal], l_peak_in=None, l_refln_in=None, l_refln_susceptibility_in=None, l_dd_in=None, flag_internal: bool = True): """Calculate intensity for the given diffraction angle.""" proc = Pd2dProc() # it is output proc.ttheta = tth proc.phi = phi background = self.pd2d_background int_bkgd = background.interpolate_by_points(tth, phi) proc.intensity_bkg_calc = int_bkgd tth_rad = tth*numpy.pi/180. phi_rad = phi*numpy.pi/180. cos_theta_1d = numpy.cos(0.5*tth_rad) sin_phi_1d = numpy.sin(phi_rad) setup = self.setup wavelength = setup.wavelength diffrn_radiation = self.diffrn_radiation if setup.offset_phi is None: setup.offset_phi = 0. phi_0 = setup.offset_phi phi_rad = (phi-phi_0)*numpy.pi/180. sin_phi_1d = numpy.sin(phi_rad) p_u = float(diffrn_radiation.polarization) p_d = (2.*float(diffrn_radiation.efficiency)-1.)*p_u tth_min = tth.min() tth_max = tth.max()+3. if tth_max > 180.: tth_max = 180. sthovl_min = numpy.sin(0.5*tth_min*numpy.pi/180.)/wavelength sthovl_max = numpy.sin(0.5*tth_max*numpy.pi/180.)/wavelength res_u_2d = numpy.zeros((tth.shape[0], phi.shape[0]), dtype=float) res_d_2d = numpy.zeros((tth.shape[0], phi.shape[0]), dtype=float) try: texture = self.texture h_ax, k_ax = float(texture.h_ax[0]), float(texture.k_ax[0]) # FIXME l_ax = float(texture.l_ax[0]) g_1, g_2 = float(texture.g_1[0]), float(texture.g_2[0]) except AttributeError: texture = None phase = self.phase _h = len(phase.label) if l_peak_in is None: l_peak_in = len(phase.label) * [None] else: if _h != len(l_peak_in): l_peak_in = len(phase.label) * [None] if l_refln_in is None: l_refln_in = len(phase.label) * [None] else: if _h != len(l_refln_in): l_refln_in = len(phase.label) * [None] if l_refln_susceptibility_in is None: l_refln_susceptibility_in = len(phase.label) * [None] else: if _h != len(l_refln_susceptibility_in): l_refln_susceptibility_in = len(phase.label) * [None] if l_dd_in is None: l_dd_in = len(phase.label) * [None] else: if _h != len(l_dd_in): l_dd_in = len(phase.label) * [None] l_peak, l_dd_out = [], [] l_refln, l_refln_s = [], [] for item_phase, peak_in, refln_in, refln_susceptibility_in, dd_in in \ zip(phase.items, l_peak_in, l_refln_in, l_refln_susceptibility_in, l_dd_in): phase_label = item_phase.label phase_scale = item_phase.scale try: phase_igsize = item_phase.igsize if phase_igsize is None: phase_igsize = 0. # temporary solution except AttributeError: phase_igsize = 0. try: phase_u = item_phase.u if phase_u is None: phase_u = 0. # temporary solution except AttributeError: phase_u = 0. try: phase_v = item_phase.v if phase_v is None: phase_v = 0. # temporary solution except AttributeError: phase_v = 0. try: phase_w = item_phase.w if phase_w is None: phase_w = 0. # temporary solution except AttributeError: phase_w = 0. try: phase_x = item_phase.x if phase_x is None: phase_x = 0. # temporary solution except AttributeError: phase_x = 0. try: phase_y = item_phase.y if phase_y is None: phase_y = 0. # temporary solution except AttributeError: phase_y = 0. dd_out = {} for i_crystal, crystal in enumerate(l_crystal): if crystal.data_name.lower() == phase_label.lower(): ind_cry = i_crystal break if ind_cry is None: warn(f"Crystal with name '{phase_label:}' is not found.", UserWarning) return crystal = l_crystal[ind_cry] cell = crystal.cell # space_group = crystal.space_group if peak_in is not None: index_h = peak_in.numpy_index_h index_k = peak_in.numpy_index_k index_l = peak_in.numpy_index_l mult = peak_in.numpy_index_mult else: if texture is None: ind_hkl_mult = crystal.calc_hkl(sthovl_min, sthovl_max) else: ind_hkl_mult = crystal.calc_hkl_in_range(sthovl_min, sthovl_max) index_h, index_k, index_l, mult = ind_hkl_mult[0], ind_hkl_mult[1], ind_hkl_mult[2], ind_hkl_mult[3] peak = Pd2dPeakL(loop_name=phase_label) peak.numpy_index_h = index_h peak.numpy_index_k = index_k peak.numpy_index_l = index_l peak.numpy_index_mult = mult peak.numpy_to_items() cond_1 = len(crystal.get_variable_names()) == 0 cond_2 = (peak_in is not None) & (refln_in is not None) if (cond_1 & cond_2): f_nucl_sq = peak_in.numpy_f_nucl_sq f_m_p_sin_sq = peak_in.numpy_f_m_p_sin_sq f_m_p_cos_sq = peak_in.numpy_f_m_p_cos_sq cross_sin = peak_in.numpy_cross_sin refln = refln_in refln_s = refln_susceptibility_in else: f_nucl_sq, f_m_p_sin_sq, f_m_p_cos_sq, cross_sin, refln, \ refln_s = self.calc_for_iint(index_h, index_k, index_l, crystal) refln.loop_name = phase_label refln_s.loop_name = phase_label l_refln.append(refln) l_refln_s.append(refln_s) peak.numpy_f_nucl_sq = f_nucl_sq peak.numpy_f_m_p_sin_sq = f_m_p_sin_sq peak.numpy_f_m_p_cos_sq = f_m_p_cos_sq peak.numpy_cross_sin = cross_sin cond_1 = dd_in is not None cond_2 = ((len(crystal.get_variable_names()) == 0) & (not(diffrn_radiation.polarization_refinement)) & (not(diffrn_radiation.efficiency_refinement))) if cond_1 & cond_2: iint_u_3d, iint_d_3d = dd_in["iint_u_3d"], dd_in["iint_d_3d"] cos_theta_3d = dd_in["cos_theta_3d"] sin_phi_3d = dd_in["sin_phi_3d"] else: cos_theta_3d, sin_phi_3d, mult_f_n_3d = numpy.meshgrid( cos_theta_1d, sin_phi_1d, mult*f_nucl_sq, indexing="ij") mult_f_m_c_3d = numpy.meshgrid( tth_rad, phi_rad, mult*f_m_p_cos_sq, indexing="ij")[2] hh_u_s_3d = numpy.meshgrid( tth_rad, phi_rad, mult*(f_m_p_sin_sq+p_u*cross_sin), indexing="ij")[2] hh_d_s_3d = numpy.meshgrid( tth_rad, phi_rad, mult*(f_m_p_sin_sq-p_d*cross_sin), indexing="ij")[2] c_a_sq_3d = (cos_theta_3d * sin_phi_3d)**2 s_a_sq_3d = 1.-c_a_sq_3d iint_u_3d = (mult_f_n_3d + hh_u_s_3d*s_a_sq_3d + mult_f_m_c_3d*c_a_sq_3d) iint_d_3d = (mult_f_n_3d + hh_d_s_3d*s_a_sq_3d + mult_f_m_c_3d*c_a_sq_3d) dd_out["cos_theta_3d"] = cos_theta_3d dd_out["sin_phi_3d"] = sin_phi_3d dd_out["iint_u_3d"] = iint_u_3d dd_out["iint_d_3d"] = iint_d_3d sthovl_hkl = cell.calc_sthovl(index_h, index_k, index_l) tth_hkl_rad = numpy.where(sthovl_hkl*wavelength < 1., 2.*numpy.arcsin(sthovl_hkl*wavelength), numpy.pi) tth_hkl = tth_hkl_rad*180./numpy.pi cond_1 = dd_in is not None flag_phase_uvwxy_ref = ( item_phase.igsize_refinement | item_phase.u_refinement | item_phase.v_refinement | item_phase.w_refinement | item_phase.x_refinement | item_phase.y_refinement) cond_2 = ((not(flag_phase_uvwxy_ref)) & (not(self.pd2d_instr_resolution.is_variables())) & (not(setup.is_variables()))) if cond_1 & cond_2: profile_3d, tth_zs = dd_in["profile_3d"], dd_in["tth_zs"] h_pv = dd_in["h_pv"] else: profile_3d, tth_zs, h_pv = self.calc_shape_profile( tth, phi, tth_hkl, phase_igsize=phase_igsize, phase_u=phase_u, phase_v=phase_v, phase_w=phase_w, phase_x=phase_x, phase_y=phase_y) dd_out["profile_3d"] = profile_3d dd_out["tth_zs"] = tth_zs dd_out["h_pv"] = h_pv peak.numpy_ttheta = tth_hkl + setup.offset_ttheta peak.width_ttheta = h_pv peak.numpy_to_items() # texture if texture is not None: cond_1 = dd_in is not None cond_2 = ((not(setup.offset_phi_refinement))) if cond_1 & cond_2: cos_alpha_ang_3d = dd_in["cos_alpha_ang_3d"] sin_alpha_ang_3d = dd_in["sin_alpha_ang_3d"] else: cos_alpha_ang_3d = cos_theta_3d * sin_phi_3d sin_alpha_ang_3d = numpy.sqrt(1.-cos_alpha_ang_3d**2) dd_out["cos_alpha_ang_3d"] = cos_alpha_ang_3d dd_out["sin_alpha_ang_3d"] = sin_alpha_ang_3d cond_2 = (cond_2 & (not(texture.is_variables())) & (not(cell.is_variables()))) if cond_1 & cond_2: texture_3d = dd_in["texture_3d"] else: cos_alpha_ax = calc_cos_ang(cell, h_ax, k_ax, l_ax, index_h, index_k, index_l) c_help = 1.-cos_alpha_ax**2 c_help[c_help < 0.] = 0. sin_alpha_ax = numpy.sqrt(c_help) cos_alpha_ax_3d = numpy.meshgrid(tth, phi, cos_alpha_ax, indexing="ij")[2] sin_alpha_ax_3d = numpy.meshgrid(tth, phi, sin_alpha_ax, indexing="ij")[2] cos_alpha_3d = cos_alpha_ax_3d*cos_alpha_ang_3d + \ sin_alpha_ax_3d*sin_alpha_ang_3d texture_3d = g_2 + (1.-g_2) * \ (1./g_1 + (g_1**2-1./g_1)*cos_alpha_3d**2)**(-1.5) dd_out["texture_3d"] = texture_3d profile_3d = profile_3d*texture_3d res_u_3d = profile_3d*iint_u_3d res_d_3d = profile_3d*iint_d_3d # 0.5 to have the same meaning for scale factor as in FullProf res_u_2d += 0.5*phase_scale*res_u_3d.sum(axis=2) res_d_2d += 0.5*phase_scale*res_d_3d.sum(axis=2) l_peak.append(peak) l_dd_out.append(dd_out) proc.ttheta_corrected = tth_zs proc.intensity_plus_net = res_u_2d proc.intensity_minus_net = res_d_2d proc.intensity_plus_total = res_u_2d+int_bkgd proc.intensity_minus_total = res_d_2d+int_bkgd if flag_internal: if background.is_variables(): background.form_ttheta_phi_intensity() proc.form_ttheta_phi_intensity_plus_net() proc.form_ttheta_phi_intensity_minus_net() proc.form_ttheta_phi_intensity_plus_total() proc.form_ttheta_phi_intensity_minus_total() l_calc_objs = l_refln + l_refln_s + l_peak l_calc_objs.append(proc) self.add_items(l_calc_objs) return proc, l_peak, l_refln, l_dd_out def calc_chi_sq(self, l_crystal, flag_internal: bool = True): """ Calculate chi square. Arguments --------- - l_crystal: a list of Crystal objects of cryspy library - flag_internal: a flag to calculate internal objects (default is True) Output arguments ---------------- - chi_sq_val: chi square of flip ratio (Sum_i ((y_e_i - y_m_i) / sigma_i)**2) - n: number of measured reflections """ meas = self.pd2d_meas tth = meas.ttheta phi = meas.phi int_u_exp = meas.intensity_plus sint_u_exp = meas.intensity_plus_sigma int_d_exp = meas.intensity_minus sint_d_exp = meas.intensity_minus_sigma l_peak_in, l_refln_in = [], [] l_refln_susceptibility_in = [] l_dd_in = [] flag_1 = not(flag_internal) try: dd = self.dd flag_2 = True except AttributeError: flag_2 = False if (flag_1 & flag_2): for phase_item in self.phase.items: crystal = None for cryst in l_crystal: if cryst.data_name.lower() == phase_item.label.lower(): crystal = cryst break attr_peak = f"pd2d_peak_{crystal.data_name:}" attr_refln = f"refln_{crystal.data_name:}" attr_refln_s = f"refln_susceptibility_{crystal.data_name:}" l_peak_in.append(getattr(self, attr_peak)) l_refln_in.append(getattr(self, attr_refln)) l_refln_susceptibility_in.append(getattr(self, attr_refln_s)) cond_tth_in = numpy.ones(tth.size, dtype=bool) cond_phi_in = numpy.ones(phi.size, dtype=bool) try: range_ = self.range cond_tth_in = numpy.logical_and(cond_tth_in, tth >= range_.ttheta_min) cond_tth_in = numpy.logical_and(cond_tth_in, tth <= range_.ttheta_max) cond_phi_in = numpy.logical_and(cond_phi_in, phi >= range_.phi_min) cond_phi_in = numpy.logical_and(cond_phi_in, phi <= range_.phi_max) except AttributeError: pass # cond_1_in, cond_2_in = numpy.meshgrid(cond_tth_in, cond_phi_in, # indexing="ij") # cond_in = numpy.logical_and(cond_1_in, cond_2_in) tth_in = tth[cond_tth_in] phi_in = phi[cond_phi_in] int_u_exp_in = int_u_exp[cond_tth_in, :][:, cond_phi_in] sint_u_exp_in = sint_u_exp[cond_tth_in, :][:, cond_phi_in] int_d_exp_in = int_d_exp[cond_tth_in, :][:, cond_phi_in] sint_d_exp_in = sint_d_exp[cond_tth_in, :][:, cond_phi_in] proc, l_peak, l_refln, l_dd_out = self.calc_profile( tth_in, phi_in, l_crystal, l_peak_in=l_peak_in, l_refln_in=l_refln_in, l_refln_susceptibility_in=l_refln_susceptibility_in, l_dd_in=l_dd_in, flag_internal=flag_internal) proc.intensity_plus = int_u_exp_in proc.intensity_plus_sigma = sint_u_exp_in proc.intensity_minus = int_d_exp_in proc.intensity_minus_sigma = sint_d_exp_in # self.proc = proc # self.peaks = l_peak # self.reflns = l_refln self.dd = l_dd_out int_u_mod = proc.intensity_plus_total int_d_mod = proc.intensity_minus_total sint_sum_exp_in = (sint_u_exp_in**2 + sint_d_exp_in**2)**0.5 chi_sq_u = ((int_u_mod-int_u_exp_in)/sint_u_exp_in)**2 chi_sq_d = ((int_d_mod-int_d_exp_in)/sint_d_exp_in)**2 chi_sq_sum = ((int_u_mod+int_d_mod-int_u_exp_in-int_d_exp_in) / sint_sum_exp_in)**2 chi_sq_dif = ((int_u_mod-int_d_mod-int_u_exp_in+int_d_exp_in) / sint_sum_exp_in)**2 cond_u = numpy.logical_not(numpy.isnan(chi_sq_u)) cond_d = numpy.logical_not(numpy.isnan(chi_sq_d)) cond_sum = numpy.logical_not(numpy.isnan(chi_sq_sum)) cond_dif = numpy.logical_not(numpy.isnan(chi_sq_dif)) # exclude region try: exclude = self.exclude l_excl_tth_min = exclude.numpy_ttheta_min l_excl_tth_max = exclude.numpy_ttheta_max l_excl_phi_min = exclude.numpy_phi_min l_excl_phi_max = exclude.numpy_phi_max for excl_tth_min, excl_tth_max, excl_phi_min, excl_phi_max in \ zip(l_excl_tth_min, l_excl_tth_max, l_excl_phi_min, l_excl_phi_max): cond_1 = numpy.logical_or(tth_in < 1.*excl_tth_min, tth_in > 1.*excl_tth_max) cond_2 = numpy.logical_or(phi_in < 1.*excl_phi_min, phi_in > 1.*excl_phi_max) cond_11, cond_22 = numpy.meshgrid(cond_1, cond_2, indexing="ij") cond_12 = numpy.logical_or(cond_11, cond_22) cond_u = numpy.logical_and(cond_u, cond_12) cond_d = numpy.logical_and(cond_d, cond_12) cond_sum = numpy.logical_and(cond_sum, cond_12) except AttributeError: pass chi_sq_u_val = (chi_sq_u[cond_u]).sum() n_u = cond_u.sum() chi_sq_d_val = (chi_sq_d[cond_d]).sum() n_d = cond_d.sum() chi_sq_sum_val = (chi_sq_sum[cond_sum]).sum() n_sum = cond_sum.sum() chi_sq_dif_val = (chi_sq_dif[cond_dif]).sum() n_dif = cond_dif.sum() chi2 = self.chi2 flag_u = chi2.up flag_d = chi2.down flag_sum = chi2.sum flag_dif = chi2.diff chi_sq_val = (int(flag_u)*chi_sq_u_val + int(flag_d)*chi_sq_d_val + int(flag_sum)*chi_sq_sum_val + int(flag_dif)*chi_sq_dif_val) n = (int(flag_u)*n_u + int(flag_d)*n_d + int(flag_sum)*n_sum + int(flag_dif)*n_dif) # print(f"chi_sq_val/n: {chi_sq_val/n:.2f} \ # chi_sq_val: {chi_sq_val: .2f}") # d_exp_out = {"chi_sq_val": chi_sq_val, "n": n} # d_exp_out.update(d_exp_prof_out) if flag_internal: refine_ls = RefineLs(number_reflns=n, goodness_of_fit_all=chi_sq_val/float(n), weighting_scheme="sigma") self.refine_ls = refine_ls proc.form_ttheta_phi_intensity_bkg_calc() proc.form_ttheta_phi_intensity_plus() proc.form_ttheta_phi_intensity_plus_sigma() proc.form_ttheta_phi_intensity_minus() proc.form_ttheta_phi_intensity_minus_sigma() return chi_sq_val, n def calc_for_iint(self, index_h, index_k, index_l, crystal, flag_internal: bool = True): """Calculate the integral intensity for h, k, l reflections.""" index_hkl = numpy.stack([index_h, index_k, index_l], axis=0) setup = self.setup field = float(setup.field) refln = crystal.calc_refln(index_hkl) f_nucl = refln.numpy_f_calc f_nucl_sq = abs(f_nucl*f_nucl.conjugate()) refln_s = crystal.calc_refln_susceptibility(index_hkl) sft_11 = refln_s.numpy_chi_11_calc sft_12 = refln_s.numpy_chi_12_calc sft_13 = refln_s.numpy_chi_13_calc sft_21 = refln_s.numpy_chi_21_calc sft_22 = refln_s.numpy_chi_22_calc sft_23 = refln_s.numpy_chi_23_calc sft_31 = refln_s.numpy_chi_31_calc sft_32 = refln_s.numpy_chi_32_calc sft_33 = refln_s.numpy_chi_33_calc _ij = numpy.stack([sft_11, sft_12, sft_13, sft_21, sft_22, sft_23, sft_31, sft_32, sft_33], axis=0) cell = crystal.cell unit_cell_parameters = cell.get_unit_cell_parameters() t_ij = calc_matrix_t(index_hkl, unit_cell_parameters, flag_unit_cell_parameters=False)[0] #SIGMA = T CHI T^-1 = T chi T^T (because T is rotation matrix, therefore T^-1 = T^T) th_ij = calc_m1_m2_m1t(t_ij, _ij)[0] th_11, th_12, th_13, th_22, th_23 = th_ij[0], th_ij[1], th_ij[2], th_ij[4], th_ij[5] # f_m_p_sin_sq = (field**2)*abs(0.5*(th_11*th_11.conjugate()+\ # th_22*th_22.conjugate())+th_12*th_12.conjugate()) # f_m_p_cos_sq = (field**2)*abs(th_13*th_13.conjugate()+\ # th_23*th_23.conjugate()) # f_m_p_field = 0.5*field*(th_11+th_22) f_m_p_sin_sq = abs(0.5 * (th_11 * th_11.conjugate()+th_22 * th_22.conjugate())+th_12 * th_12.conjugate()) f_m_p_cos_sq = abs(th_13 * th_13.conjugate() + th_23 * th_23.conjugate()) f_m_p_field = 0.5 * (th_11+th_22) cross_sin = 2. * (f_nucl.real * f_m_p_field.real + f_nucl.imag * f_m_p_field.imag) return f_nucl_sq, f_m_p_sin_sq, f_m_p_cos_sq, cross_sin, refln, refln_s def _gauss_pd(self, tth_2d): """One dimensional gauss powder diffraction.""" ag, bg = self.ag, self.bg val_1 = bg*tth_2d**2 val_2 = numpy.where(val_1 < 5., numpy.exp(-val_1), 0.) self.gauss_pd = ag*val_2 def _lor_pd(self, tth_2d): """One dimensional lorentz powder diffraction.""" al, bl = self.al, self.bl self.lor_pd = al*1./(1.+bl*tth_2d**2) def calc_shape_profile( self, tth, phi, tth_hkl, phase_igsize: float = 0., phase_u: float = 0., phase_v: float = 0., phase_w: float = 0., phase_x: float = 0., phase_y: float = 0.): """ Calculate profile in the range ttheta. For reflections placed on ttheta_hkl with i_g parameter by default equal to zero tth, phi, tth_hkl in degrees """ setup = self.setup zero_shift = float(setup.offset_ttheta) tth_zs = tth-zero_shift resolution = self.pd2d_instr_resolution h_pv, eta, h_g, h_l, a_g, b_g, a_l, b_l = resolution.calc_resolution( tth_hkl, phase_igsize=phase_igsize, phase_u=phase_u, phase_v=phase_v, phase_w=phase_w, phase_x=phase_x, phase_y=phase_y) tth_3d, phi_3d, tth_hkl_3d = numpy.meshgrid(tth_zs, phi, tth_hkl, indexing="ij") self.ag = numpy.meshgrid(tth_zs, phi, a_g, indexing="ij")[2] self.bg = numpy.meshgrid(tth_zs, phi, b_g, indexing="ij")[2] self.al = numpy.meshgrid(tth_zs, phi, a_l, indexing="ij")[2] self.bl = numpy.meshgrid(tth_zs, phi, b_l, indexing="ij")[2] eta_3d = numpy.meshgrid(tth_zs, phi, eta, indexing="ij")[2] self.eta = eta_3d self._gauss_pd(tth_3d-tth_hkl_3d) self._lor_pd(tth_3d-tth_hkl_3d) g_pd2d_3d = self.gauss_pd l_pd2d_3d = self.lor_pd np_shape_3d = eta_3d * l_pd2d_3d + (1.-eta_3d) * g_pd2d_3d asymmetry = self.pd2d_instr_reflex_asymmetry np_ass_2d = asymmetry.calc_asymmetry(tth_zs, tth_hkl, h_pv) np_ass_3d = np_ass_2d[:, numpy.newaxis, :] * numpy.ones( phi.size, dtype=float)[numpy.newaxis, :, numpy.newaxis] # Lorentz factor tth_rad = tth_zs*numpy.pi/180. np_lor_1d = 1./(numpy.sin(tth_rad)*numpy.sin(0.5*tth_rad)) np_lor_3d = numpy.meshgrid(np_lor_1d, phi, tth_hkl, indexing="ij")[0] profile_3d = np_shape_3d*np_ass_3d*np_lor_3d return profile_3d, tth_zs, h_pv def params_to_cif(self, separator="_", flag: bool = False, flag_minimal: bool = True) -> str: """Save parameters to cif format.""" ls_out = [] l_cls = (Pd2dBackground, Pd2dInstrResolution, PhaseL, DiffrnRadiation, Setup, Range, Chi2, Extinction, ExcludeL, Pd2dInstrReflexAsymmetry, TextureL) l_obj = [item for item in self.items if type(item) in l_cls] l_itemn = [item for item in l_obj if isinstance(item, ItemN)] l_loopn = [item for item in l_obj if isinstance(item, LoopN)] ls_out.extend([_.to_cif(separator=separator)+"\n" for _ in l_itemn]) ls_out.extend([_.to_cif(separator=separator)+"\n" for _ in l_loopn]) return "\n".join(ls_out) def data_to_cif(self, separator="_", flag: bool = False, flag_minimal: bool = True) -> str: """Save data to cif format.""" ls_out = [] l_cls = (Pd2dMeas, ) l_obj = [item for item in self.items if type(item) in l_cls] l_itemn = [item for item in l_obj if isinstance(item, ItemN)] l_loopn = [item for item in l_obj if isinstance(item, LoopN)] ls_out.extend([_.to_cif(separator=separator)+"\n" for _ in l_itemn]) ls_out.extend([_.to_cif(separator=separator)+"\n" for _ in l_loopn]) return "\n".join(ls_out) def calc_to_cif(self, separator="_", flag=False, flag_minimal=True) -> str: """Save calculations to cif format.""" ls_out = [] l_cls = (RefineLs, ReflnL, ReflnSusceptibilityL, Pd2dPeakL, Pd2dProc) l_obj = [item for item in self.items if type(item) in l_cls] l_itemn = [item for item in l_obj if isinstance(item, ItemN)] l_loopn = [item for item in l_obj if isinstance(item, LoopN)] ls_out.extend([_.to_cif(separator=separator)+"\n" for _ in l_itemn]) ls_out.extend([_.to_cif(separator=separator)+"\n" for _ in l_loopn]) return "\n".join(ls_out) def apply_constraints(self): """Apply constraints.""" pass def plots(self): if self.is_attribute("pd2d_proc"): pd2d_proc = self.pd2d_proc fig = pd2d_proc.plot_gamma_nu()[0] l_pd_peak = [item for item in self.items if isinstance(item, PdPeakL)] [ax1, ax2] = fig.axes[:2] gamma_min, gamma_max = ax1.get_xlim() nu_min, nu_max = ax1.get_ylim() for pd_peak in l_pd_peak: if pd_peak.is_attribute("gamma"): index_h = numpy.array(pd_peak.index_h, dtype=int) index_k = numpy.array(pd_peak.index_k, dtype=int) index_l = numpy.array(pd_peak.index_l, dtype=int) gamma = numpy.array(pd_peak.gamma, dtype=float) nu = numpy.array(pd_peak.nu, dtype=float) flag_gn = numpy.logical_and( numpy.logical_and(gamma>=gamma_min, gamma<=gamma_max), numpy.logical_and(nu>=nu_min, nu<=nu_max)) if (pd_peak.is_attribute("intensity_plus") and pd_peak.is_attribute("intensity_minus")): i_plus = numpy.array(pd_peak.intensity_plus, dtype=float) i_minus = numpy.array(pd_peak.intensity_minus, dtype=float) inv_lf = numpy.sin(gamma*numpy.pi/180)*numpy.sin(0.5*gamma*numpy.pi/180) i_sum = numpy.abs(i_plus*flag_gn+i_minus*flag_gn) i_difference = numpy.abs(i_plus*flag_gn-i_minus*flag_gn) flag_i_plus = (i_sum-i_sum.min()) > 0.01 * (i_sum.max() - i_sum.min()) flag_i_difference = i_difference > 0.01 * i_difference.max() flag_i = numpy.logical_or(flag_i_plus, flag_i_difference) flag_gn = numpy.logical_and(flag_gn, flag_i) ax1.plot(gamma[flag_gn], 0.5*(nu[flag_gn]+nu_max), "k.", alpha=0.3) ax2.plot(gamma[flag_gn], 0.5*(nu[flag_gn]+nu_max), "k.", alpha=0.3) ax1.plot(gamma[flag_gn], nu_min+0.5*(-nu[flag_gn]+nu_max), "k.", alpha=0.3) ax2.plot(gamma[flag_gn], nu_min+0.5*(-nu[flag_gn]+nu_max), "k.", alpha=0.3) if (pd_peak.is_attribute("intensity_plus") and pd_peak.is_attribute("intensity_minus")): i_plus = numpy.array(pd_peak.intensity_plus, dtype=float) i_minus = numpy.array(pd_peak.intensity_minus, dtype=float) inv_lf = numpy.sin(gamma*numpy.pi/180)*numpy.sin(0.5*gamma*numpy.pi/180) i_sum = numpy.abs(i_plus*flag_gn+i_minus*flag_gn) i_difference = numpy.abs(i_plus*flag_gn-i_minus*flag_gn) flag_i_plus = (i_sum-i_sum.min()) > 0.2 * (i_sum.max() - i_sum.min()) flag_i_difference = i_difference > 0.2 * i_difference.max() flag_i = numpy.logical_or(flag_i_plus, flag_i_difference) flag_gn = numpy.logical_and(flag_gn, flag_i) l_gn = [] for i_h, i_k, i_l, i_g, i_n in zip( index_h[flag_gn], index_k[flag_gn], index_l[flag_gn], gamma[flag_gn], nu[flag_gn]): if not((i_g, i_n) in l_gn): s_text = f"({i_h:}{i_k:}{i_l:})" ax1.text(i_g, 0.5*(+i_n+nu_max), s_text, alpha=0.5, color="k") ax2.text(i_g, 0.5*(+i_n+nu_max), s_text, alpha=0.5, color="k") ax1.text(i_g, 0.5*(-i_n+nu_max)+nu_min, s_text, alpha=0.5, color="k") ax2.text(i_g, 0.5*(-i_n+nu_max)+nu_min, s_text, alpha=0.5, color="k") l_gn.append((i_g, i_n)) return [(fig, ax1), ] if self.is_attribute("chi2"): flag_up = self.chi2.up flag_down = self.chi2.down flag_sum = self.chi2.sum flag_diff = self.chi2.diff else: flag_up, flag_down, flag_sum = False, False, True flag_diff = False if flag_sum: fig_s, ax_s = pd2d_proc.plot_projection_sum() ax_s.set_title(self.data_name + " - "+ax_s.title.get_text()) y_min_s, y_max_s = ax_s.get_ylim() y_dist_s = y_max_s-y_min_s y_step_s = 0. if flag_diff: fig_d, ax_d = pd2d_proc.plot_projection_diff() ax_d.set_title(self.data_name + " - "+ax_d.title.get_text()) y_min_d, y_max_d = ax_d.get_ylim() y_dist_d = y_max_d-y_min_d y_step_d = 0. for item in self.items: if isinstance(item, Pd2dPeakL): np_tth = item.numpy_ttheta if flag_sum: ax_s.plot(np_tth, 0.*np_tth+y_min_s-y_step_s, "|", label=item.loop_name) y_step_s += 0.05*y_dist_s if flag_diff: ax_d.plot(np_tth, 0.*np_tth+y_min_d-y_step_d, "|", label=item.loop_name) y_step_d += 0.05*y_dist_d res = [] if flag_sum: ax_s.legend(loc='upper right') res.append((fig_s, ax_s)) if flag_diff: ax_d.legend(loc='upper right') res.append((fig_d, ax_d)) return res elif self.is_attribute("pd2d_meas"): return self.pd2d_meas.plots() return [] def get_dictionary(self): """Form dictionary. See documentation moduel CrysPy using Jupyter notebook. """ self.form_object() ddict = {} setup, pd2d_meas, resolution = None, None, None pd2d_background, range_, exclude = None, None, None asymmetry, diffrn_radiation = None, None phase, texture, chi2 = None, None, None l_obj = take_items_by_class(self, (Setup, )) if len(l_obj) > 0: setup = l_obj[0] l_obj = take_items_by_class(self, (Pd2dMeas, )) if len(l_obj) > 0: pd2d_meas = l_obj[0] l_obj = take_items_by_class(self, (Pd2dInstrResolution, )) if len(l_obj) > 0: resolution = l_obj[0] l_obj = take_items_by_class(self, (Pd2dBackground, )) if len(l_obj) > 0: pd2d_background = l_obj[0] l_obj = take_items_by_class(self, (Range, )) if len(l_obj) > 0: range_ = l_obj[0] l_obj = take_items_by_class(self, (ExcludeL, )) if len(l_obj) > 0: exclude = l_obj[0] l_obj = take_items_by_class(self, (Pd2dInstrReflexAsymmetry, )) if len(l_obj) > 0: asymmetry = l_obj[0] l_obj = take_items_by_class(self, (DiffrnRadiation, )) if len(l_obj) > 0: diffrn_radiation = l_obj[0] l_obj = take_items_by_class(self, (PhaseL, )) if len(l_obj) > 0: phase = l_obj[0] l_obj = take_items_by_class(self, (TextureL, )) if len(l_obj) > 0: texture = l_obj[0] l_obj = take_items_by_class(self, (Chi2, )) if len(l_obj) > 0: chi2 = l_obj[0] ddict["name"] = self.data_name ddict["type_name"] = self.get_name() if setup is not None: ddict["magnetic_field"] = numpy.array([setup.field], dtype=float) ddict["wavelength"] = numpy.array([setup.wavelength], dtype=float) ddict["flags_wavelength"] =
numpy.array([setup.wavelength_refinement], dtype=bool)
numpy.array
import os import time import numpy as np import configparser from PIL import Image import matplotlib.pyplot as plt from matplotlib.pyplot import figure # Puzzles Type puz = "Houses" config = configparser.ConfigParser() config.read(puz + '/Cards/Cards.ini') num_of_cards = len(config.sections()) # Create Tiles sides = [] colors = [] num_colors = [] tiles = np.zeros([num_of_cards, 3, 3]) for i in range(num_of_cards): for j in range(4): temp = config['Card_' + str(i+1)]['loc' + str(j+1)] temp = temp.split(' ') temp_side = temp[1] if temp_side not in sides: sides.append(temp_side) temp_color = temp[0] if temp_color not in colors: colors.append(temp_color) num_colors.append(len(colors)) if j==0: for c, color in enumerate(colors): if temp_color==color: tiles[i][0][1] = num_colors[c] if temp_side==sides[0]: tiles[i][0][1] = -1 * tiles[i][0][1] break; elif j==1: for c, color in enumerate(colors): if temp_color==color: tiles[i][1][0] = num_colors[c] if temp_side==sides[0]: tiles[i][1][0] = -1 * tiles[i][1][0] break; elif j==2: for c, color in enumerate(colors): if temp_color==color: tiles[i][1][2] = num_colors[c] if temp_side==sides[0]: tiles[i][1][2] = -1 * tiles[i][1][2] break; elif j==3: for c, color in enumerate(colors): if temp_color==color: tiles[i][2][1] = num_colors[c] if temp_side==sides[0]: tiles[i][2][1] = -1 * tiles[i][2][1] break; # Rotate {tile} 90 degrees {rotations} times def turn_tile(tile, rotations): new_tile = np.zeros([tile.shape[0], tile.shape[1]]) for r in range(rotations): new_tile[0][1] = tile[1][0] new_tile[1][0] = tile[2][1] new_tile[1][2] = tile[0][1] new_tile[2][1] = tile[1][2] tile[:][:] = new_tile[:][:] return tile # Find identical Cards double_cards = [] for i in range(tiles.shape[0]-1): for j in range(i+1, tiles.shape[0]): rot = 0 tile_to_check = np.array(tiles[i]) while rot<4: if ((tile_to_check[0][1]==tiles[j][0][1]) and (tile_to_check[1][0]==tiles[j][1][0]) and (tile_to_check[1][2]==tiles[j][1][2]) and (tile_to_check[2][1]==tiles[j][2][1])): double_cards.append(np.array([i+1, j+1])) rot = rot + 1 turn_tile(tile_to_check, rot) # Check if the combination is legal def is_legal(tiles, position, tile, turn, sol_tiles, sol_turns): # Positions = | 0 | 1 | 2 | # | 3 | 4 | 5 | # | 6 | 7 | 8 | if position==0: return True elif position==1: tile1 = turn_tile(np.array(tiles[tile]), turn) tile0 = turn_tile(np.array(tiles[sol_tiles[0]-1]), sol_turns[0]) if tile1[1][0]+tile0[1][2]==0: return True elif position==2: tile2 = turn_tile(np.array(tiles[tile]), turn) tile1 = turn_tile(np.array(tiles[sol_tiles[1]-1]), sol_turns[1]) if tile2[1][0]+tile1[1][2]==0: return True elif position==3: tile3 = turn_tile(np.array(tiles[tile]), turn) tile0 = turn_tile(
np.array(tiles[sol_tiles[0]-1])
numpy.array
""" Created on Mon Feb 22 15:52:51 2021 @author: <NAME> """ import pandas as pd import numpy as np import os import pickle import calendar import time import warnings from pyproj import Transformer import networkx as nx import matplotlib as mpl import matplotlib.pyplot as plt from requests import get import dataframe_key def compile_chicago_stations(): """ Reads data files containing information about docking stations in Chicago and compiles the data into a dataframe. The dataframe is then saved as a pickle for further use. The relevant files can be found at: https://divvy-tripdata.s3.amazonaws.com/index.html https://data.cityofchicago.org/Transportation/Divvy-Bicycle-Stations-All-Map/bk89-9dk7 Raises ------ FileNotFoundError Raised if no data files containing station data are found. Returns ------- stat_df : pandas DataFrame Dataframe of all docking station information. """ try: with open('./python_variables/Chicago_stations.pickle', 'rb') as file: stat_df = pickle.load(file) except FileNotFoundError as exc: print('No pickle found. Creating pickle...') stat_files = [file for file in os.listdir('data') if 'Divvy_Stations' in file] col_list = ['id', 'name', 'latitude', 'longitude'] key = {'ID':'id', 'Station Name':'name', 'Latitude':'latitude','Longitude':'longitude'} try: stat_df = pd.read_csv( 'data/Divvy_Bicycle_Stations_-_All_-_Map.csv').rename(columns = key) stat_df = stat_df[col_list] except FileNotFoundError: stat_df = pd.DataFrame(columns = col_list) for file in stat_files: df = pd.read_csv(f'./data/{file}')[col_list] stat_df = pd.concat([stat_df, df], sort = False) if stat_df.size == 0: raise FileNotFoundError( 'No data files containing station data found. Please read the docstring for more information.') from exc stat_df.drop_duplicates(subset = 'name', inplace = True) with open('./python_variables/Chicago_stations.pickle', 'wb') as file: pickle.dump(stat_df, file) print('Pickle loaded') return stat_df def get_JC_blacklist(): """ Constructs/updates a blacklist of stations in Jersey City area. The blacklist is created using historical biketrip datasets for the area. Use only if you know what you are doing. The relevant files can be found at: https://www.citibikenyc.com/system-data Raises ------ FileNotFoundError Raised if no Jersey City dataset is found. Returns ------- blacklist : list List of IDs of the Jersey City docking stations. """ try: with open('./python_variables/JC_blacklist', 'rb') as file: blacklist = pickle.load(file) except FileNotFoundError: print('No previous blacklist found. Creating blacklist...') blacklist = set() JC_files = [file for file in os.listdir('data') if 'JC' in file] if len(JC_files) == 0: raise FileNotFoundError( 'No JC files found. Please have a JC file in the data directory to create/update blacklist.') for file in JC_files: df = pd.read_csv('data/' + file) df = df.rename(columns = dataframe_key.get_key('nyc')) JC_start_stat_indices = df.loc[df['start_stat_long'] < 74.02] JC_end_stat_indices = df.loc[df['end_stat_long'] < 74.02] stat_IDs = set( df['start_stat_id'][JC_start_stat_indices]) | set(df['end_stat_id'][JC_end_stat_indices]) blacklist = blacklist | stat_IDs with open('./python_variables/JC_blacklist', 'wb') as file: pickle.dump(blacklist, file) print('Blacklist updated') return blacklist def days_index(df): """ Find indices of daily trips. Parameters ---------- df : pandas DataFrame Dataframe containing bikeshare trip data with columns that have been renamed to the common key. Returns ------- d_i : dict Contains the indices of the first trip per day. """ days = df['start_dt'].dt.day d_i = [(days == i).idxmax() for i in range(1, max(days)+1)] return dict(zip(range(1, max(days)+1), d_i)) def pickle_data(df, city, year, month): """ Generate pickle of days' starting indices. Parameters ---------- df : pandas DataFrame bikeshare trip data with columns that have been renamed to the common key. city : str The identification of the city. For a list of supported cities, see the documentation for the Data class. year : int The year of interest in YYYY format. month : int The month of interest in MM format. Returns ------- d : dict Contains the indices of the first trip per day. """ d = days_index(df) with open(f'./python_variables/day_index_{city}{year:d}{month:02d}.pickle', 'wb') as file: pickle.dump(d, file) return d def get_data(city, year, month, blacklist=None): """ Read data from csv files. Parameters ---------- city : str The identification of the city. For a list of supported cities, see the documentation for the Data class. year : int The year of interest in YYYY format. month : int The month of interest in MM format. blacklist : list, optional List of IDs of stations to remove. Default is None. Returns ------- df : pandas DataFrame Dataframe containing bikeshare trip data. days : dict Contains the indices of the first trip per day. """ supported_cities = ['nyc', 'sfran', 'sjose', 'washDC', 'chic', 'london', 'oslo', 'edinburgh', 'bergen', 'buenos_aires', 'madrid', 'mexico', 'taipei'] # Remember to update this list if city not in supported_cities: raise ValueError("This city is not currently supported. Supported cities are {}".format(supported_cities)) # Make folder for dataframes if not found if not os.path.exists('python_variables/big_data'): os.makedirs('python_variables/big_data') try: with open(f'./python_variables/big_data/{city}{year:d}{month:02d}_dataframe_blcklst={blacklist}.pickle', 'rb') as file: df = pickle.load(file) print('Pickle loaded') except FileNotFoundError: print('No dataframe pickle found. Pickling dataframe...') if city == "nyc": try: df = pd.read_csv(f'./data/{year:d}{month:02d}-citibike-tripdata.csv') except FileNotFoundError as exc: raise FileNotFoundError('No trip data found. All relevant files can be found at https://www.citibikenyc.com/system-data') from exc df = df.rename(columns = dataframe_key.get_key(city)) try: with open('./python_variables/JC_blacklist', 'rb') as file: JC_blacklist = pickle.load(file) df = df[~df['start_stat_id'].isin(JC_blacklist)] df = df[~df['end_stat_id'].isin(JC_blacklist)] except FileNotFoundError: print('No JC blacklist found. Continuing...') df.dropna(inplace=True) df.reset_index(inplace = True, drop = True) df['start_dt'] = pd.to_datetime(df['start_t']) df['end_dt'] = pd.to_datetime(df['end_t']) elif city == "washDC": try: df = pd.read_csv(f'./data/{year:d}{month:02d}-capitalbikeshare-tripdata.csv') except FileNotFoundError as exc: raise FileNotFoundError('No trip data found. All relevant files can be found at https://www.capitalbikeshare.com/system-data') from exc df = df.rename(columns = dataframe_key.get_key(city)) df['start_stat_lat'] = '' df['start_stat_long'] = '' df['end_stat_lat'] = '' df['end_stat_long'] = '' stat_df = pd.read_csv('data/Capital_Bike_Share_Locations.csv') for _ , stat in stat_df.iterrows(): start_matches = np.where(df['start_stat_id'] == stat['TERMINAL_NUMBER']) end_matches = np.where(df['end_stat_id'] == stat['TERMINAL_NUMBER']) df.at[start_matches[0], 'start_stat_lat'] = stat['LATITUDE'] df.at[start_matches[0], 'start_stat_long'] = stat['LONGITUDE'] df.at[end_matches[0], 'end_stat_lat'] = stat['LATITUDE'] df.at[end_matches[0], 'end_stat_long'] = stat['LONGITUDE'] df.replace('', np.nan, inplace = True) df.dropna(inplace=True) max_lat = 38.961029 min_lat = 38.792686 max_long= -76.909415 min_long= -77.139396 df = df.iloc[np.where( (df['start_stat_lat'] < max_lat) & (df['start_stat_lat'] > min_lat) & (df['start_stat_long'] < max_long) & (df['start_stat_long'] > min_long))] df = df.iloc[np.where( (df['end_stat_lat'] < max_lat) & (df['end_stat_lat'] > min_lat) & (df['end_stat_long'] < max_long) & (df['end_stat_long'] > min_long))] df.reset_index(inplace = True, drop = True) df['start_dt'] = pd.to_datetime(df['start_t']) df['end_dt'] = pd.to_datetime(df['end_t']) elif city == "chic": q = int(np.ceil(month/3)) try: df = pd.read_csv(f'./data/Divvy_Trips_{year:d}_Q{q}.csv') except FileNotFoundError as exc: raise FileNotFoundError('No trip data found. All relevant files can be found at https://www.divvybikes.com/system-data') from exc df = df.rename(columns = dataframe_key.get_key(city)) n_days = calendar.monthrange(year, month)[1] df = df.iloc[np.where(df['start_t'] > f'{year:d}-{month:02d}-01 00:00:00')] df = df.iloc[np.where(df['start_t'] < f'{year:d}-{month:02d}-{n_days} 23:59:59')] df.reset_index(inplace = True, drop = True) df['start_stat_lat'] = '' df['start_stat_long'] = '' df['end_stat_lat'] = '' df['end_stat_long'] = '' try: with open('./python_variables/Chicago_stations.pickle', 'rb') as file: stat_df = pickle.load(file) except FileNotFoundError as exc: compile_chicago_stations() with open('./python_variables/Chicago_stations.pickle', 'rb') as file: stat_df = pickle.load(file) for _, stat in stat_df.iterrows(): start_matches = np.where(df['start_stat_name'] == stat['name']) end_matches = np.where(df['end_stat_name'] == stat['name']) df.at[start_matches[0], 'start_stat_lat'] = stat['latitude'] df.at[start_matches[0], 'start_stat_long'] = stat['longitude'] df.at[end_matches[0], 'end_stat_lat'] = stat['latitude'] df.at[end_matches[0], 'end_stat_long'] = stat['longitude'] df.replace('', np.nan, inplace = True) df.dropna(subset = ['start_stat_lat', 'start_stat_long', 'end_stat_lat', 'end_stat_long'], inplace = True) df.reset_index(inplace = True, drop = True) df['start_dt'] = pd.to_datetime(df['start_t']) df['end_dt'] = pd.to_datetime(df['end_t']) df['duration'] = df['duration'].str.replace(',', '').astype(float) elif city == "sfran": try: df = pd.read_csv(f'./data/{year:d}{month:02d}-baywheels-tripdata.csv') except FileNotFoundError as exc: raise FileNotFoundError('No trip data found. All relevant files can be found at https://www.lyft.com/bikes/bay-wheels/system-data') from exc df = df.rename(columns = dataframe_key.get_key(city)) df.dropna(inplace=True) df = df.iloc[np.where(df['start_stat_lat'] > 37.593220)] df = df.iloc[np.where(df['end_stat_lat'] > 37.593220)] df.sort_values(by = 'start_t', inplace = True) df.reset_index(inplace = True, drop = True) df['start_dt'] = pd.to_datetime(df['start_t']) df['end_dt'] = pd.to_datetime(df['end_t']) elif city == "sjose": try: df = pd.read_csv(f'./data/{year:d}{month:02d}-baywheels-tripdata.csv') except FileNotFoundError as exc: raise FileNotFoundError('No trip data found. All relevant files can be found at https://www.lyft.com/bikes/bay-wheels/system-data') from exc df = df.rename(columns = dataframe_key.get_key(city)) df.dropna(inplace=True) df = df.iloc[np.where(df['start_stat_lat'] < 37.593220)] df = df.iloc[np.where(df['end_stat_lat'] < 37.593220)] df.sort_values(by = 'start_t', inplace = True) df.reset_index(inplace = True, drop = True) df['start_dt'] = pd.to_datetime(df['start_t']) df['end_dt'] = pd.to_datetime(df['end_t']) elif city == "london": month_dict = {1:'Jan', 2:'Feb', 3:'Mar', 4:'Apr', 5:'May', 6:'Jun', 7:'Jul', 8:'Aug', 9:'Sep', 10:'Oct', 11:'Nov', 12:'Dec'} data_files = [file for file in os.listdir('data') if 'JourneyDataExtract' in file] data_files = [file for file in data_files if '{}'.format(year) and '{}'.format(month_dict[month]) in file] if len(data_files) == 0: raise FileNotFoundError('No London data for {}. {} found. All relevant files can be found at https://cycling.data.tfl.gov.uk/.'.format(month_dict[month], year)) if isinstance(data_files, str): warnings.warn('Only one data file found. Please check that you have all available data.') df = pd.read_csv('./data/' + data_files[0]) for file in data_files[1:]: df_temp = pd.read_csv('./data/' + file) df = pd.concat([df, df_temp], sort = False) df.rename(columns = dataframe_key.get_key(city), inplace = True) n_days = calendar.monthrange(year, month)[1] df = df.iloc[np.where(df['start_t'] >= f'01/{month:02d}/{year} 00:00')] df = df.iloc[np.where(df['start_t'] <= f'{n_days}/{month:02d}/{year} 23:59')] df.sort_values(by = 'start_t', inplace = True) df.reset_index(inplace = True) df['start_t'] = pd.to_datetime(df['start_t'], format = '%d/%m/%Y %H:%M').astype(str) df['end_t'] = pd.to_datetime(df['end_t'], format = '%d/%m/%Y %H:%M').astype(str) stat_df = pd.read_csv('./data/london_stations.csv') stat_df.at[np.where(stat_df['station_id'] == 502)[0][0], 'latitude'] = 51.53341 df['start_stat_lat'] = '' df['start_stat_long'] = '' df['end_stat_lat'] = '' df['end_stat_long'] = '' for _ , stat in stat_df.iterrows(): start_matches = np.where(df['start_stat_name'] == stat['station_name']) end_matches = np.where(df['end_stat_name'] == stat['station_name']) df.at[start_matches[0], 'start_stat_lat'] = stat['latitude'] df.at[start_matches[0], 'start_stat_long'] = stat['longitude'] df.at[end_matches[0], 'end_stat_lat'] = stat['latitude'] df.at[end_matches[0], 'end_stat_long'] = stat['longitude'] df.replace('', np.nan, inplace = True) df.dropna(inplace = True) df.reset_index(inplace = True, drop = True) df['start_dt'] = pd.to_datetime(df['start_t']) df['end_dt'] = pd.to_datetime(df['end_t']) df = df[df.start_dt.dt.month == month] df.reset_index(inplace = True, drop = True) elif city == "oslo": try: df = pd.read_csv(f'./data/{year:d}{month:02d}-oslo.csv') except FileNotFoundError as exc: raise FileNotFoundError('No trip data found. All relevant files can be found at https://oslobysykkel.no/en/open-data/historical') from exc df = df.rename(columns = dataframe_key.get_key(city)) df.dropna(inplace=True) df.reset_index(inplace = True, drop = True) df['start_dt'] = pd.to_datetime(df['start_t']) df['end_dt'] = pd.to_datetime(df['end_t']) elif city == "edinburgh": try: df = pd.read_csv(f'./data/{year:d}{month:02d}-edinburgh.csv') except FileNotFoundError as exc: raise FileNotFoundError('No trip data found. All relevant files can be found at https://edinburghcyclehire.com/open-data/historical') from exc df = df.rename(columns = dataframe_key.get_key(city)) df.dropna(inplace=True) df.reset_index(inplace = True, drop = True) df['start_dt'] = pd.to_datetime(df['start_t']) df['end_dt'] = pd.to_datetime(df['end_t']) elif city == "bergen": try: df = pd.read_csv(f'./data/{year:d}{month:02d}-bergen.csv') except FileNotFoundError as exc: raise FileNotFoundError('No trip data found. All relevant files can be found at https://bergenbysykkel.no/en/open-data/historical') from exc df = df.rename(columns = dataframe_key.get_key(city)) df.dropna(inplace=True) df.reset_index(inplace = True, drop = True) df['start_dt'] = pd.to_datetime(df['start_t']) df['end_dt'] = pd.to_datetime(df['end_t']) elif city == "buenos_aires": try: df_year = pd.read_csv(f"./data/recorridos-realizados-{year:d}.csv") except FileNotFoundError as exc: raise FileNotFoundError('No trip data found. All relevant files can be found at https://data.buenosaires.gob.ar/dataset/bicicletas-publicas') from exc df_year = df_year.rename(columns = dataframe_key.get_key(city)) #df_year['month'] = pd.to_datetime(df_year['fecha_origen_recorrido']).dt.month df_year['month'] = pd.to_datetime(df_year['start_t']).dt.month df = df_year.loc[df_year.month == month] df.sort_values(by=['start_t'], inplace=True) df.reset_index(inplace = True, drop = True) df['start_dt'] = pd.to_datetime(df['start_t']) df['end_dt'] = pd.to_datetime(df['end_t']) elif city == "madrid": try: df = pd.read_json(f"./data/{year:d}{month:02d}_movements.json", lines=True) except FileNotFoundError as exc: raise FileNotFoundError('No trip data found. All relevant files can be found at https://opendata.emtmadrid.es/Datos-estaticos/Datos-generales-(1)') from exc try: df_pre = pd.read_json(f"./data/{year:d}{(month-1):02d}_movements.json", lines=True) except FileNotFoundError as exc: raise FileNotFoundError('No trip data found. All relevant files can be found at https://opendata.emtmadrid.es/Datos-estaticos/Datos-generales-(1)') from exc df = df.rename(columns = dataframe_key.get_key(city)) df_pre = df_pre.rename(columns = dataframe_key.get_key(city)) df['start_dt'] = pd.to_datetime(df['start_t'], format = '%Y-%m-%dT%H:%M:%SZ') + pd.DateOffset(hours=2) df_pre['start_dt'] = pd.to_datetime(df_pre['start_t'], format = '%Y-%m-%dT%H:%M:%SZ') + pd.DateOffset(hours=2) df = df[df['start_dt'].dt.month == 9] df_pre = df_pre[df_pre['start_dt'].dt.month == 9] df = pd.concat((df_pre, df)) df['start_t'] = df['start_dt'].astype(str) df['end_dt'] = df['start_dt'] + pd.to_timedelta(df['duration'], unit='s') #df['end_t'] = pd.to_datetime(df['end_dt']).astype(str) _ , stations = pd.read_json( f"./data/{year:d}{month:02d}_stations_madrid.json", lines=True).iloc[-1] stations = pd.DataFrame(stations) name_dict = dict(zip(stations['id'], stations['name'])) long_dict = dict(zip(stations['id'], stations['longitude'].astype(float))) lat_dict = dict(zip(stations['id'], stations['latitude'].astype(float))) addr_dict = dict(zip(stations['id'], stations['address'])) df['start_stat_name'] = df['start_stat_id'].map(name_dict) df['start_stat_lat'] = df['start_stat_id'].map(lat_dict) df['start_stat_long'] = df['start_stat_id'].map(long_dict) df['start_stat_desc'] = df['start_stat_id'].map(addr_dict) df['end_stat_name'] = df['end_stat_id'].map(name_dict) df['end_stat_lat'] = df['end_stat_id'].map(lat_dict) df['end_stat_long'] = df['end_stat_id'].map(long_dict) df['end_stat_desc'] = df['end_stat_id'].map(addr_dict) df.reset_index(inplace = True, drop = True) elif city == "mexico": try: df = pd.read_csv(f"./data/{year:d}-{month:02d}-mexico.csv") except FileNotFoundError as exc: raise FileNotFoundError('No trip data found. All relevant files can be found at https://www.ecobici.cdmx.gob.mx/en/informacion-del-servicio/open-data') from exc df.rename(columns = dataframe_key.get_key(city), inplace=True) df['start_dt'] = pd.to_datetime(df['start_date'] + df['start_time'], format='%d/%m/%Y%H:%M:%S') df['end_dt'] = pd.to_datetime(df['end_date'] + df['end_time'], format='%d/%m/%Y%H:%M:%S') df.drop(['start_date','start_time','end_date','end_time'], axis=1, inplace=True) df['duration'] = (df['end_dt'] - df['start_dt']).dt.total_seconds() df['start_t'] = df['start_dt'].astype(str) stations = pd.DataFrame(pd.read_json("./data/stations_mexico.json", lines=True)['stations'][0]) name_dict = dict(zip(stations['id'], stations['address'])) locations = stations['location'].apply(pd.Series) long_dict = dict(zip(stations['id'], locations['lon'].astype(float))) lat_dict = dict(zip(stations['id'], locations['lat'].astype(float))) type_dict = dict(zip(stations['id'], stations['stationType'])) df['start_stat_name'] = df['start_stat_id'].map(name_dict) df['start_stat_lat'] = df['start_stat_id'].map(lat_dict) df['start_stat_long'] = df['start_stat_id'].map(long_dict) df['end_stat_name'] = df['end_stat_id'].map(name_dict) df['end_stat_lat'] = df['end_stat_id'].map(lat_dict) df['end_stat_long'] = df['end_stat_id'].map(long_dict) df['station_type'] = df['end_stat_id'].map(type_dict) df.dropna(inplace=True) df = df[df.start_dt.dt.month == 9] df.sort_values(by=['start_dt'], inplace=True) df.reset_index(inplace = True, drop = True) elif city == "taipei": colnames = ['start_t', 'start_stat_name_zh', 'end_t', 'end_stat_name_zh', 'duration'] try: df = pd.read_csv(f"./data/{year:d}{month:02d}-taipei.csv", usecols=range(5), names=colnames) except FileNotFoundError as exc: raise FileNotFoundError('No trip data found. All relevant data can be found at https://data.taipei/#/ and https://drive.google.com/drive/folders/1QsROgp8AcER6qkTJDxpuV8Mt1Dy6lGQO') from exc # Update names of stations df.replace(to_replace='信義杭州路口(中華電信總公司', value='信義杭州路口(中華電信總公司)', inplace=True) df.replace(to_replace='捷運科技大樓站', value='捷運科技大樓站(台北教育大學)', inplace=True) df.replace(to_replace='?公公園', value='瑠公公園', inplace=True) df.replace(to_replace='饒河夜市', value='饒河夜市(八德路側)', inplace=True) df.replace(to_replace='捷運大坪林站(3號出口)', value='捷運大坪林站(1號出口)', inplace=True) df.replace(to_replace='新明路321巷口', value='新明路262巷口', inplace=True) df['start_dt'] = pd.to_datetime(df['start_t'], format='%Y-%m-%d %H:%M:%S') df['end_dt'] = pd.to_datetime(df['end_t'], format='%Y-%m-%d %H:%M:%S') df['duration'] = pd.to_timedelta(df.duration).dt.total_seconds() try: stations = pd.DataFrame.from_dict( list(pd.read_json("./data/YouBikeTP.json")['retVal'])) except FileNotFoundError as exc: raise FileNotFoundError('No station data found. The data can be found at https://tcgbusfs.blob.core.windows.net/blobyoubike/YouBikeTP.json') from exc stations['sno'] = stations['sno'].astype(int) stations['lat'] = stations['lat'].astype(float) stations['lng'] = stations['lng'].astype(float) id_dict = dict(zip(stations['sna'], stations['sno'])) # stations_ntpc = pd.read_csv("./data/stations_new_taipei.csv") # stations_ntpc['sno'] = stations_ntpc['sno'].astype(int) # stations_ntpc['lat'] = stations_ntpc['lat'].astype(float) # stations_ntpc['lng'] = stations_ntpc['lng'].astype(float) # id_dict_ntpc = dict(zip(stations_ntpc['sna'], stations_ntpc['sno'])) # id_dict = {**id_dict_tp, **id_dict_ntpc} df['start_stat_id'] = df['start_stat_name_zh'].map(id_dict) df['end_stat_id'] = df['end_stat_name_zh'].map(id_dict) name_dict = dict(zip(stations['sno'], stations['snaen'])) long_dict = dict(zip(stations['sno'], stations['lng'])) lat_dict = dict(zip(stations['sno'], stations['lat'])) addr_dict = dict(zip(stations['sno'], stations['aren'])) # name_dict_ntpc = dict(zip(stations_ntpc['sno'], stations_ntpc['snaen'])) # long_dict_ntpc = dict(zip(stations_ntpc['sno'], stations_ntpc['lng'])) # lat_dict_ntpc = dict(zip(stations_ntpc['sno'], stations_ntpc['lat'])) # addr_dict_ntpc = dict(zip(stations_ntpc['sno'], stations_ntpc['aren'])) # name_dict = {**name_dict_tp, **name_dict_ntpc} # long_dict = {**long_dict_tp, **long_dict_ntpc} # lat_dict = {**lat_dict_tp, **lat_dict_ntpc} # addr_dict = {**addr_dict_tp, **addr_dict_ntpc} df['start_stat_name'] = df['start_stat_id'].map(name_dict) df['start_stat_lat'] = df['start_stat_id'].map(lat_dict) df['start_stat_long'] = df['start_stat_id'].map(long_dict) df['start_stat_desc'] = df['start_stat_id'].map(addr_dict) df['end_stat_name'] = df['end_stat_id'].map(name_dict) df['end_stat_lat'] = df['end_stat_id'].map(lat_dict) df['end_stat_long'] = df['end_stat_id'].map(long_dict) df['end_stat_desc'] = df['end_stat_id'].map(addr_dict) #df_nan = df[df.isna().any(axis=1)] df.dropna(inplace=True) df.sort_values(by=['start_dt'], inplace=True) df.reset_index(inplace=True, drop = True) if blacklist: df = df[~df['start_stat_id'].isin(blacklist)] df = df[~df['end_stat_id'].isin(blacklist)] with open(f'./python_variables/big_data/{city}{year:d}{month:02d}_dataframe_blcklst={blacklist}.pickle', 'wb') as file: pickle.dump(df, file) print('Pickling done.') try: with open(f'./python_variables/day_index_{city}{year:d}{month:02d}.pickle', 'rb') as file: days = pickle.load(file) except FileNotFoundError: print("Pickle does not exist. Pickling day indices...") days = pickle_data(df, city, year, month) print("Pickling done.") print(f"Data loaded: {city}{year:d}{month:02d}") return df, days def station_locations(df, id_index): """ Creates a dictionary with station IDs as keys and locations as values. Parameters ---------- df : pandas DataFrame Bikeshare trip data. id_index : dict Maps station ID (arbitrary integer) to the range from 0 to number of stations Returns ------- locations : dict key : station index (returned from id_index) value : tuple (longitude, latitude) """ # Create Dictionary Station : Position locations = dict() for e in id_index.keys(): if df[df['start_stat_id'] == e]['start_stat_lat'].shape[0]: locations[id_index[e]] = (df[df['start_stat_id'] == e]['start_stat_long'].iloc[0], df[df['start_stat_id'] == e]['start_stat_lat'].iloc[0]) else: locations[id_index[e]] = (df[df['end_stat_id'] == e]['end_stat_long'].iloc[0], df[df['end_stat_id'] == e]['end_stat_lat'].iloc[0]) return locations def station_names(df, id_index): """ Creates a dictionary with station IDs as keys and station names as values. Parameters ---------- df : pandas DataFrame Bikeshare trip data. id_index : dict Maps station ID (arbitrary integer) to the range from 0 to number of stations Returns ------- names : dict key : station index (returned from id_index) value : string containing station name """ # Create Dictionary Station : Names names = dict() for e in id_index.keys(): if df[df['start_stat_id'] == e]['start_stat_name'].shape[0]: names[id_index[e]] = df[df['start_stat_id'] == e]['start_stat_name'].iloc[0] else: names[id_index[e]] = df[df['end_stat_id'] == e]['end_stat_name'].iloc[0] return names def diradjacency(df, city, year, month, day_index, days, stations, threshold=1, remove_self_loops=True): """ Calculate the directed adjacency matrix for the network. Parameters ---------- df : pandas DataFrame bikesharing data. city : str The identification of the city. For a list of supported cities, see the documentation for the Data class. year : int The year of interest in YYYY format. month : int The month of interest in MM format. day_index : list Indices of the first trip per day. days : iterable Days in consideration. stations : Stat class Station class containing station information. threshold : int, optional Threshold for weights. If an edge has a weight below the threshold then the weight is set to zero. The default threshold is 1. remove_self_loops : bool, optional Does not count trips which start and end at the same station if True. The default is True. Returns ------- d_adj : ndarray Array containing the directed adjacency matrix. """ try: # If Pickle exists, load it with open(f'./python_variables/directedadjacency_{city}{year:d}{month:02d}{tuple(days)}thr_{threshold:d}.pickle', 'rb') as file: d_adj = pickle.load(file) print("Pickle loaded") except FileNotFoundError: # If not, calculate weighted adjacency matrix and create Pickle print(f"Pickle does not exist. Pickling directed adjacency matrix: directedadjacency_{city}{year:d}{month:02d}{tuple(days)}thr_{threshold:d}.pickle...") d_adj = np.zeros((stations.n_tot, stations.n_tot)) for day in days: if day is max(days): for _, row in df.iloc[day_index[day]:].iterrows(): d_adj[stations.id_index[row['start_stat_id']], stations.id_index[row['end_stat_id']]] += 1 print('Day {} loaded...'.format(day)) else: for _, row in df.iloc[day_index[day]:day_index[day+1]].iterrows(): d_adj[stations.id_index[row['start_stat_id']], stations.id_index[row['end_stat_id']]] += 1 print('Day {} loaded...'.format(day)) d_adj[d_adj <= threshold] = 0 if remove_self_loops: for i in range(stations.n_tot): d_adj[i, i] = 0 with open(f'./python_variables/directedadjacency_{city}{year:d}{month:02d}{tuple(days)}thr_{threshold:d}.pickle', 'wb') as file: pickle.dump(d_adj, file) print("Pickling done.") return d_adj def get_degree_matrix(adj): """ Computes the degree matrix of the network. Parameters ---------- adj : ndarray Adjacency matrix. Returns ------- deg_matrix: ndarray The degree matrix. """ deg_matrix = np.zeros_like(adj) for i in range(len(adj)): deg_matrix[i,i] = np.sum(adj[[i],:]) return deg_matrix def data_pickle_load(city, year, month): """ Load data from a Data class object pickle. See Data.pickle_dump Parameters ---------- city : str The identification of the city. For a list of supported cities, see the documentation for the Data class. year : int The year of interest in YYYY format. month : int The month of interest in MM format. Returns ------- object of Data class """ with open(f'./python_variables/big_data/data_{city}{year:d}{month:02d}.pickle', 'rb') as file: return pickle.load(file) def adjacency(df, n_tot, id_index, threshold=1, remove_self_loops=True): """ Calculate the weighted adjacency matrix for the network assuming an undirected graph. Parameters ---------- df : pandas DataFrame Contains the data over which the adjacency matrix is calculated. n_tot : int Number of stations. id_index : dict Translates station id to an index starting from 0. threshold : int, optional Threshold for weights. If an edge has a weight below the threshold then the weight is set to zero. The default threshold is 1. remove_self_loops : bool, optional Does not count trips which start and end at the same station if True. The default is True. Returns ------- adj : ndarray Adjacency matrix of the network. """ adj = np.zeros((n_tot, n_tot)) si = df['start_stat_id'].map(id_index) ei = df['end_stat_id'].map(id_index) #start_stat_index = id_index(df['start_stat_id']) for i, j in zip(si, ei): adj[i, j] += 1 adj = adj + adj.T adj[adj <= threshold] = 0 if remove_self_loops: for i in range(n_tot): adj[i, i] = 0 return adj def PageRank(adj, d=0.85, iterations=100, initialisation="rdm"): """ Calculates the PageRank of each vertex in a graph. Parameters ---------- adj : ndarray Directed and weighted adjacency matrix. d : float, optional Dampening factor. The default is 0.85. iterations : int, optional The amount of iterations we run the PageRank algortihm. The default is 100. initialisation : str, optional Determines if we have random initialisation or 1/n initialisation. The default is "rdm". Returns ------- v : ndarray contains the PageRank of each vertex. """ N = adj.shape[0] weightlist = [] for i in range(N): weight = 0 for n in range(N): weight += adj[i,n] weightlist.append(weight) if initialisation == "rdm": v = np.random.rand(N, 1) v = v / np.linalg.norm(v, 1) else: # Uniform initialisation v = np.linspace(1/N, 1/N, N) for i in range(iterations): for n in range(N): if weightlist[n] != 0: v[n] = v[n]/weightlist[n] v = (1 - d)/(N+1) + d * adj @ v return v def get_elevation(lat, long, dataset="mapzen"): """ Finds the elevation for a specific coordinate. Elevation data is taken from https://www.opentopodata.org/ Parameters ---------- lat : float or iterable Latitude or iterable containing latitudes. long : float or iterable Longitude or iterable containing longitudes. dataset : str, optional Dataset used for elevation data. The default is "mapzen". Returns ------- elevation : ndarray Array containing elevations. """ if lat is None or long is None: return None elevation = np.array([]) if isinstance(long, float): query = (f'https://api.opentopodata.org/v1/{dataset}?locations=' f'{lat},{long}') print(query) # Request with a timeout for slow responses r = get(query, timeout = 60) # Only get the json response in case of 200 or 201 if r.status_code == 200 or r.status_code == 201: elevation = pd.json_normalize(r.json(), 'results')['elevation'] else: # if it is a list or iterable i = 100 for n in range(0, len(long), i): lo = long[n:n+i] la = lat[n:n+i] loc_string = f'https://api.opentopodata.org/v1/{dataset}?locations=' for at, ong in zip(la, lo): loc_string = loc_string + f"{at},{ong}|" loc_string = loc_string[:-1] query = (loc_string) r = get(query, timeout = 60) # Only get the json response in case of 200 or 201 if r.status_code == 200 or r.status_code == 201: elevation = np.append(elevation, np.array(pd.json_normalize(r.json(), 'results')['elevation']) ) return elevation def get_weather(city, year, month): """ Get weather data for the given city, year and month. Parameters ---------- city : str The identification of the city. For a list of supported cities, see the documentation for the Data class. year : int The year of interest in YYYY format. month : int The month of interest in MM format. Returns ------- request : str DESCRIPTION. rain : DESCRIPTION. """ cities = ['chic', 'london', 'madrid', 'mexico', 'nyc', 'sfran', 'taipei', 'washDC'] if city in cities: name_dict = {'chic':'Chicago', 'london':'London', 'madrid':'Madrid', 'mexico':'Mexico City', 'nyc':'New York City', 'sfran':'San Francisco', 'taipei':'Taipei', 'washDC':'Washington DC'} city = name_dict[city] n_days = calendar.monthrange(year, month)[1] tp = 1 query = (f"http://api.worldweatheronline.com/premium/v1/past-weather.ashx?" f"key=7886f8387f8c4c0484f83623210305&q={city}&format=json&date={year}-{month}-01&enddate={year}-{month}-{n_days}&tp={tp}")# Request with a timeout for slow responses r = get(query, timeout = 60) # Only get the json response in case of 200 or 201 if r.status_code == 200 or r.status_code == 201: result = r.json()['data'] request = result['request'] weather = pd.DataFrame(result['weather']) hourweather = [pd.DataFrame(i) for i in weather['hourly']] for day, wea in zip(weather['date'], hourweather): wea['day'] = day[-2:] hweather = pd.concat(hourweather) hweather.reset_index(inplace=True) hweather['hour'] = (hweather['time'].astype(int)//100).astype(str) hweather['precipMM'] = hweather['precipMM'].astype(float) hweather['time_dt'] = pd.to_datetime( str(year) + str(month) + hweather['day'] + hweather['hour'], format='%Y%m%d%H') hweather['day'] = hweather['day'].astype(int) hweather['hour'] = hweather['hour'].astype(int) hweather['desc'] = pd.DataFrame(hweather['weatherDesc'].explode().tolist()) rain = hweather[['day', 'hour', 'time_dt', 'precipMM', 'tempC', 'windspeedKmph', 'desc']] return request, rain def TotalVariation(adj, cutoff): """ Calculates the total variation of given graph with the degree as the signal. Parameters ---------- adj : ndarray Adjacency matrix. threshold : float Threshold for when the signal is high or low frequency. Returns ------- filterarray : ndarray Binary array. 1 indicates low frequency and 0 indicates high frequency. """ n = len(adj) Lambda, u = np.linalg.eig(adj) Lambda_max = np.max(abs(Lambda)) W_tilde = adj * 1/Lambda_max T = np.zeros(n) filterarray = np.zeros(n) for m in range(n): T[m] = np.linalg.norm(u[:,m] - (W_tilde @ u[:,m]), ord = 1) if T[m] < cutoff: filterarray[m] = 1 return filterarray def subframe(filterarray, df, id_index, low): """ Creates a lowpass- or highpass-filtered dataframe Parameters ---------- filterarray : ndarray Binary array. 1 indicates low frequency and 0 indicates high frequency. df : pandas dataframe Original city data dataframe. low : Logival, optional Tells us if the filtered dataframe will be low or high frequency. The default is True. Returns ------- df_done : pandas dataframe Filtered pandas dataframe. """ filtered_positions = np.argwhere(filterarray == 1) l = len(filtered_positions) filtered_positions = filtered_positions.reshape(l) if low: df_filtered = df[df['start_stat_id'].map(id_index).isin(filtered_positions)] df_done = df_filtered[df_filtered['end_stat_id'].map(id_index).isin(filtered_positions)] else: df_filtered = df[~df['start_stat_id'].map(id_index).isin(filtered_positions)] df_done = df_filtered[~df_filtered['end_stat_id'].map(id_index).isin(filtered_positions)] return df_done def adjacency_filtered(df, day_index, days, n_tot, id_index, threshold=1, remove_self_loops=True): """ Calculate weighted adjacency matrix (undirected) Parameters ---------- days : tuple Tuple of days in consideration. threshold : int, optional Threshold for weights. If an edge has a weight below the threshold then the weight is set to zero. The default threshold is 1. remove_self_loops : bool, optional Does not count trips which start and end at the same station if True. The default is True. Returns ------- adj : ndarray Adjacency matrix of the network. """ adj = np.zeros((n_tot, n_tot)) si = df['start_stat_id'].map(id_index) ei = df['end_stat_id'].map(id_index) for day in days: if day is max(days): for i, j in zip(si[day_index[day]:], ei[day_index[day]:]): adj[i, j] += 1 adj[j, i] += 1 else: for i, j in zip(si[day_index[day]:day_index[day+1]], ei[day_index[day]:day_index[day+1]]): adj[i, j] += 1 adj[j, i] += 1 adj[adj <= threshold] = 0 if remove_self_loops == True: for i in range(n_tot): adj[i, i] = 0 return adj def coverage(g, p): """ Calculates the covergae of the partition. Parameters ---------- g : networkx graph class graph of the data. p : dictionary tells which verticies belongs to which communities. Returns ------- float the coverage of our partition. """ d_i = dict(zip(np.arange(g.number_of_nodes()), list(g.nodes()))) n = g.number_of_nodes() ad = nx.adjacency_matrix(g) p_sum = np.sum(ad) / 2 num = 0 for i in range(n): for j in range(i + 1, n): if p[d_i[i]] == p[d_i[j]]: num += ad[i, j] return num / p_sum def distance(lat1, lon1, lat2, lon2): """ Calculates the distance between two coordiantes. Parameters ---------- lat1 : float Latitude of first coordinate. lon1 : float Longitude of first coordinate. lat2 : float Latitude of second coordinate. lon2 : float Longitude of second coordinate. Returns ------- res : float Distance between the two coordinates. """ r = 6371000 phi1 = np.radians(lat1) phi2 = np.radians(lat2) delta_phi = np.radians(lat2 - lat1) delta_lambda = np.radians(lon2 - lon1) a =
np.sin(delta_phi / 2)
numpy.sin
"""Most utility functions here has been adopted from: https://github.com/guillaumegenthial/sequence_tagging/blob/master/model/data_utils.py """ import numpy as np import os import math # shared global variables to be imported from model also UNK = "$UNK$" NUM = "$NUM$" NONE = "O" # read the word importance scores class AnnotationDataset(object): def __init__(self, filename, processing_word=None): self.filename = filename self.processing_word = processing_word self.length = None def __iter__(self): with open(self.filename) as f: words, tags = [], [] for line in f: line = line.strip() if (len(line) == 0): if len(words) != 0: yield words, tags words, tags = [], [] else: ls = line.split(' ') word, tag = ls[0], ls[-1] if self.processing_word is not None: word = self.processing_word(word) words += [word] tags += [tag] def __len__(self): if self.length is None: self.length = 0 for _ in self: self.length += 1 return self.length def get_vocabs(datasets): print("Building vocab...") vocab_words = set() vocab_tags = set() for dataset in datasets: for words, tags in dataset: vocab_words.update(words) vocab_tags.update(tags) print("- done. {} tokens".format(len(vocab_words))) return vocab_words, vocab_tags def get_char_vocab(dataset): vocab_char = set() for words, _ in dataset: for word in words: vocab_char.update(word) return vocab_char def get_glove_vocab(filename): print("Building vocab...") vocab = set() with open(filename) as f: for line in f: word = line.strip().split(' ')[0] vocab.add(word) print("- done. {} tokens".format(len(vocab))) return vocab def get_google_vocab(filename): from gensim.models import Word2Vec model = Word2Vec.load_word2vec_format(filename, binary=True) print ("Building vocab...") vocab = set(model.vocab.keys()) print ("- done. {} tokens".format(len(vocab))) return model, vocab def get_senna_vocab(filename): print ("Building vocab...") vocab = set() with open(filename) as f: for line in f: word = line.strip() vocab.add(word) print ("- done. {} tokens".format(len(vocab))) return vocab def write_vocab(vocab, filename): print("Writing vocab...") with open(filename, "w") as f: for i, word in enumerate(vocab): if i != len(vocab) - 1: f.write("{}\n".format(word)) else: f.write(word) print("- done. {} tokens".format(len(vocab))) def load_vocab(filename): try: d = dict() with open(filename) as f: for idx, word in enumerate(f): word = word.strip() d[word] = idx except IOError: raise MyIOError(filename) return d def export_trimmed_glove_vectors(vocab, glove_filename, trimmed_filename, dim): embeddings = np.zeros([len(vocab), dim]) with open(glove_filename) as f: for line in f: line = line.strip().split(' ') word = line[0] embedding = [float(x) for x in line[1:]] if word in vocab: word_idx = vocab[word] embeddings[word_idx] = np.asarray(embedding) np.savez_compressed(trimmed_filename, embeddings=embeddings) def export_trimmed_google_vectors(vocab, google_model, trimmed_filename, dim, random): embeddings = np.asarray(random.normal(loc=0.0, scale=0.1, size= [len(vocab), dim]), dtype=np.float32) for word in google_model.vocab.keys(): if word in vocab: word_idx = vocab[word] embedding = google_model[word] embeddings[word_idx] = np.asarray(embedding) np.savez_compressed(trimmed_filename, embeddings=embeddings) def export_trimmed_senna_vectors(vocab, vocab_emb, senna_filename, trimmed_filename, dim): embeddings = np.zeros([len(vocab), dim]) vocab_emb = list(vocab_emb) with open(senna_filename) as f: for i, line in enumerate(f): line = line.strip().split(' ') word = vocab_emb[i] embedding = map(float, line) if word in vocab: word_idx = vocab[word] embeddings[word_idx] = np.asarray(embedding)
np.savez_compressed(trimmed_filename, embeddings=embeddings)
numpy.savez_compressed